author
int64
658
755k
date
stringlengths
19
19
timezone
int64
-46,800
43.2k
hash
stringlengths
40
40
message
stringlengths
5
490
mods
list
language
stringclasses
20 values
license
stringclasses
3 values
repo
stringlengths
5
68
original_message
stringlengths
12
491
129,187
20.12.2019 17:27:17
18,000
8b4425d64c980079e4f58e543221797b2bde1179
[lib] logOut should never reject or take longer than 500ms
[ { "change_type": "MODIFY", "old_path": "lib/actions/user-actions.js", "new_path": "lib/actions/user-actions.js", "diff": "@@ -24,6 +24,7 @@ import type { UserSearchResult } from '../types/search-types';\nimport threadWatcher from '../shared/thread-watcher';\nimport { getConfig } from '../utils/config';\n+import sleep from '../utils/sleep';\nconst logOutActionTypes = Object.freeze({\nstarted: \"LOG_OUT_STARTED\",\n@@ -33,10 +34,18 @@ const logOutActionTypes = Object.freeze({\nasync function logOut(\nfetchJSON: FetchJSON,\n): Promise<LogOutResult> {\n- const response = await fetchJSON('log_out', {});\n- return {\n- currentUserInfo: response.currentUserInfo,\n- };\n+ let response = null;\n+ try {\n+ response = await Promise.race([\n+ fetchJSON('log_out', {}),\n+ (async () => {\n+ await sleep(500);\n+ throw new Error('log_out took more than 500ms');\n+ })(),\n+ ]);\n+ } catch { }\n+ const currentUserInfo = response ? response.currentUserInfo : null;\n+ return { currentUserInfo };\n}\nconst deleteAccountActionTypes = Object.freeze({\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/user-reducer.js", "new_path": "lib/reducers/user-reducer.js", "diff": "@@ -56,7 +56,7 @@ function reduceCurrentUserInfo(\n}\n} else if (\naction.type === setNewSessionActionType &&\n- action.payload.sessionChange.cookieInvalidated\n+ action.payload.sessionChange.currentUserInfo\n) {\nconst { sessionChange } = action.payload;\nif (!_isEqual(sessionChange.currentUserInfo)(state)) {\n" }, { "change_type": "MODIFY", "old_path": "lib/types/account-types.js", "new_path": "lib/types/account-types.js", "diff": "@@ -26,7 +26,7 @@ export type ResetPasswordRequest = {|\n|};\nexport type LogOutResult = {|\n- currentUserInfo: LoggedOutUserInfo,\n+ currentUserInfo: ?LoggedOutUserInfo,\n|};\nexport type LogOutResponse = {|\n" }, { "change_type": "MODIFY", "old_path": "lib/types/session-types.js", "new_path": "lib/types/session-types.js", "diff": "@@ -64,6 +64,7 @@ export type ServerSessionChange = {|\nexport type ClientSessionChange = {|\ncookieInvalidated: false,\n+ currentUserInfo?: ?CurrentUserInfo,\nsessionID?: null | string,\ncookie?: string,\n|} | {|\n" }, { "change_type": "MODIFY", "old_path": "lib/utils/fetch-json.js", "new_path": "lib/utils/fetch-json.js", "diff": "@@ -11,6 +11,7 @@ import type {\nClientSessionChange,\n} from '../types/session-types';\nimport type { ConnectionStatus } from '../types/socket-types';\n+import type { CurrentUserInfo } from '../types/user-types';\nimport invariant from 'invariant';\nimport _map from 'lodash/fp/map';\n@@ -37,6 +38,7 @@ export type FetchJSONOptions = $Shape<{|\nexport type FetchJSONServerResponse = $Shape<{|\ncookieChange: ServerSessionChange,\n+ currentUserInfo?: ?CurrentUserInfo,\nerror: string,\npayload: Object,\n|}>;\n@@ -161,17 +163,22 @@ async function fetchJSON(\n}\n}\n- const { cookieChange, error, payload } = json;\n+ const { cookieChange, error, payload, currentUserInfo } = json;\nconst sessionChange: ?ServerSessionChange = cookieChange;\nif (sessionChange) {\nconst { threadInfos, userInfos, ...rest } = sessionChange;\n- if (rest.cookieInvalidated) {\n- const maybeReplacement = await cookieInvalidationRecovery(rest);\n+ const clientSessionChange = rest.cookieInvalidated\n+ ? rest\n+ : { cookieInvalidated: false, currentUserInfo, ...rest };\n+ if (clientSessionChange.cookieInvalidated) {\n+ const maybeReplacement = await cookieInvalidationRecovery(\n+ clientSessionChange,\n+ );\nif (maybeReplacement) {\nreturn await maybeReplacement(endpoint, input, options);\n}\n}\n- setNewSession(rest, error);\n+ setNewSession(clientSessionChange, error);\n}\nif (error) {\n" }, { "change_type": "MODIFY", "old_path": "lib/utils/sanitization.js", "new_path": "lib/utils/sanitization.js", "diff": "@@ -17,7 +17,7 @@ function sanitizeAction(action: BaseAction): BaseAction {\ntype: \"SET_NEW_SESSION\",\npayload: {\n...action.payload,\n- sessionChange: { ...rest },\n+ sessionChange: { cookieInvalidated: true, ...rest },\n},\n};\n} else {\n@@ -26,7 +26,7 @@ function sanitizeAction(action: BaseAction): BaseAction {\ntype: \"SET_NEW_SESSION\",\npayload: {\n...action.payload,\n- sessionChange: { ...rest },\n+ sessionChange: { cookieInvalidated: false, ...rest },\n},\n};\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[lib] logOut should never reject or take longer than 500ms
129,187
20.12.2019 17:36:39
18,000
75ba179813d831a270d5bea1a5eeea8000c672f0
[lib] Don't try to openSocket on native unless user cookie available
[ { "change_type": "MODIFY", "old_path": "lib/socket/socket.react.js", "new_path": "lib/socket/socket.react.js", "diff": "@@ -140,7 +140,11 @@ class Socket extends React.PureComponent<Props, State> {\n}\nopenSocket(newStatus: ConnectionStatus) {\n- if (this.props.frozen) {\n+ if (\n+ this.props.frozen ||\n+ (getConfig().platformDetails.platform !== \"web\" &&\n+ (!this.props.cookie || !this.props.cookie.startsWith(\"user=\")))\n+ ) {\nreturn;\n}\nif (this.socket) {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[lib] Don't try to openSocket on native unless user cookie available
129,187
20.12.2019 17:54:51
18,000
c99a64b145c351f0efc5a6aef9d6dcc14c5f6395
[lib] deleteAccount should never reject or take longer than 500ms
[ { "change_type": "MODIFY", "old_path": "lib/actions/user-actions.js", "new_path": "lib/actions/user-actions.js", "diff": "@@ -57,10 +57,18 @@ async function deleteAccount(\nfetchJSON: FetchJSON,\npassword: string,\n): Promise<LogOutResult> {\n- const response = await fetchJSON('delete_account', { password });\n- return {\n- currentUserInfo: response.currentUserInfo,\n- };\n+ let response = null;\n+ try {\n+ response = await Promise.race([\n+ fetchJSON('delete_account', { password }),\n+ (async () => {\n+ await sleep(500);\n+ throw new Error('delete_account took more than 500ms');\n+ })(),\n+ ]);\n+ } catch { }\n+ const currentUserInfo = response ? response.currentUserInfo : null;\n+ return { currentUserInfo };\n}\nconst registerActionTypes = Object.freeze({\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[lib] deleteAccount should never reject or take longer than 500ms
129,187
22.12.2019 15:37:10
18,000
91ab59a3c4fec3c0e9d5c1e21ff9427b1caf9c24
Pass currentUserInfo into action-utils
[ { "change_type": "MODIFY", "old_path": "lib/utils/action-utils.js", "new_path": "lib/utils/action-utils.js", "diff": "@@ -9,7 +9,11 @@ import type {\nimport type { LoadingOptions, LoadingInfo } from '../types/loading-types';\nimport type { FetchJSON, FetchJSONOptions } from './fetch-json';\nimport type { RawThreadInfo } from '../types/thread-types';\n-import type { UserInfo, LoggedOutUserInfo } from '../types/user-types';\n+import type {\n+ UserInfo,\n+ LoggedOutUserInfo,\n+ CurrentUserInfo,\n+} from '../types/user-types';\nimport type {\nLogInActionSource,\nLogInStartingPayload,\n@@ -245,9 +249,10 @@ function bindCookieAndUtilsIntoFetchJSON(params: BindServerCallsParams): FetchJS\ncookie,\nurlPrefix,\nsessionID,\n- loggedIn,\n+ currentUserInfo,\nconnectionStatus,\n} = params;\n+ const loggedIn = !!(currentUserInfo && !currentUserInfo.anonymous && true);\nconst boundSetNewSession = setNewSession.bind(null, dispatch);\n// This function gets called before fetchJSON sends a request, to make sure\n// that we're not in the middle of trying to recover an invalidated cookie\n@@ -284,6 +289,7 @@ function bindCookieAndUtilsIntoFetchJSON(params: BindServerCallsParams): FetchJS\n...params,\ncookie: newSessionChange.cookie,\nsessionID: newSessionChange.sessionID,\n+ currentUserInfo: newSessionChange.currentUserInfo,\n})\n: null;\nfor (const func of currentWaitingCalls) {\n@@ -340,7 +346,7 @@ type BindServerCallsParams = {|\ncookie: ?string,\nurlPrefix: string,\nsessionID: ?string,\n- loggedIn: bool,\n+ currentUserInfo: ?CurrentUserInfo,\nconnectionStatus: ConnectionStatus,\n|};\n@@ -358,14 +364,14 @@ const baseCreateBoundServerCallsSelector = (actionFunc: ActionFunc) => {\n(state: BindServerCallsParams) => state.cookie,\n(state: BindServerCallsParams) => state.urlPrefix,\n(state: BindServerCallsParams) => state.sessionID,\n- (state: BindServerCallsParams) => state.loggedIn,\n+ (state: BindServerCallsParams) => state.currentUserInfo,\n(state: BindServerCallsParams) => state.connectionStatus,\n(\ndispatch: Dispatch,\ncookie: ?string,\nurlPrefix: string,\nsessionID: ?string,\n- loggedIn: bool,\n+ currentUserInfo: ?CurrentUserInfo,\nconnectionStatus: ConnectionStatus,\n) => {\nconst boundFetchJSON = bindCookieAndUtilsIntoFetchJSON({\n@@ -373,7 +379,7 @@ const baseCreateBoundServerCallsSelector = (actionFunc: ActionFunc) => {\ncookie,\nurlPrefix,\nsessionID,\n- loggedIn,\n+ currentUserInfo,\nconnectionStatus,\n});\nreturn (...rest: $FlowFixMe) => actionFunc(boundFetchJSON, ...rest);\n@@ -395,7 +401,7 @@ function bindServerCalls(serverCalls: ServerCalls) {\ncookie: ?string,\nurlPrefix: string,\nsessionID: ?string,\n- currentUserInfoLoggedIn: bool,\n+ currentUserInfo: ?CurrentUserInfo,\nconnectionStatus: ConnectionStatus,\n},\ndispatchProps: Object,\n@@ -407,7 +413,7 @@ function bindServerCalls(serverCalls: ServerCalls) {\ncookie,\nurlPrefix,\nsessionID,\n- currentUserInfoLoggedIn: loggedIn,\n+ currentUserInfo,\nconnectionStatus,\n} = stateProps;\nconst boundServerCalls = _mapValues(\n@@ -417,7 +423,7 @@ function bindServerCalls(serverCalls: ServerCalls) {\ncookie,\nurlPrefix,\nsessionID,\n- loggedIn,\n+ currentUserInfo,\nconnectionStatus,\n}),\n)(serverCalls);\n" }, { "change_type": "MODIFY", "old_path": "lib/utils/redux-utils.js", "new_path": "lib/utils/redux-utils.js", "diff": "@@ -6,6 +6,7 @@ import {\ntype ConnectionStatus,\nconnectionStatusPropType,\n} from '../types/socket-types';\n+import { type CurrentUserInfo, currentUserPropType } from '../types/user-types';\nimport { connect as reactReduxConnect } from 'react-redux';\nimport invariant from 'invariant';\n@@ -21,7 +22,7 @@ export type ServerCallState = {|\ncookie: ?string,\nurlPrefix: string,\nsessionID: ?string,\n- currentUserInfoLoggedIn: bool,\n+ currentUserInfo: ?CurrentUserInfo,\nconnectionStatus: ConnectionStatus,\n|};\n@@ -29,7 +30,7 @@ const serverCallStatePropType = PropTypes.shape({\ncookie: PropTypes.string,\nurlPrefix: PropTypes.string.isRequired,\nsessionID: PropTypes.string,\n- currentUserInfoLoggedIn: PropTypes.bool.isRequired,\n+ currentUserInfo: currentUserPropType,\nconnectionStatus: connectionStatusPropType.isRequired,\n});\n@@ -39,20 +40,19 @@ const serverCallStateSelector: (\n(state: AppState) => state.cookie,\n(state: AppState) => state.urlPrefix,\n(state: AppState) => state.sessionID,\n- (state: AppState) =>\n- !!(state.currentUserInfo && !state.currentUserInfo.anonymous && true),\n+ (state: AppState) => state.currentUserInfo,\n(state: AppState) => state.connection.status,\n(\ncookie: ?string,\nurlPrefix: string,\nsessionID: ?string,\n- currentUserInfoLoggedIn: bool,\n+ currentUserInfo: ?CurrentUserInfo,\nconnectionStatus: ConnectionStatus,\n) => ({\ncookie,\nurlPrefix,\nsessionID,\n- currentUserInfoLoggedIn,\n+ currentUserInfo,\nconnectionStatus,\n}),\n);\n@@ -71,7 +71,7 @@ function connect<S: AppState, OP: Object, SP: Object>(\ncookie: ?string,\nurlPrefix: string,\nsessionID: ?string,\n- currentUserInfoLoggedIn: bool,\n+ currentUserInfo: ?CurrentUserInfo,\nconnectionStatus: ConnectionStatus,\n} => ({\n...mapStateToProps(state, ownProps),\n@@ -83,7 +83,7 @@ function connect<S: AppState, OP: Object, SP: Object>(\ncookie: ?string,\nurlPrefix: string,\nsessionID: ?string,\n- currentUserInfoLoggedIn: bool,\n+ currentUserInfo: ?CurrentUserInfo,\nconnectionStatus: ConnectionStatus,\n} => ({\n// $FlowFixMe\n" }, { "change_type": "MODIFY", "old_path": "native/navigation/tooltip.react.js", "new_path": "native/navigation/tooltip.react.js", "diff": "@@ -415,7 +415,7 @@ function createTooltip<\ncookie,\nurlPrefix,\nsessionID,\n- currentUserInfoLoggedIn: loggedIn,\n+ currentUserInfo,\nconnectionStatus,\n} = this.props.serverCallState;\nreturn createBoundServerCallsSelector(serverCall)({\n@@ -423,7 +423,7 @@ function createTooltip<\ncookie,\nurlPrefix,\nsessionID,\n- loggedIn,\n+ currentUserInfo,\nconnectionStatus,\n});\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Pass currentUserInfo into action-utils
129,187
22.12.2019 16:58:49
18,000
bf7a030e7ecbd78e5c553a79867c0cbcffd3d94a
account-regexes.js -> account-utils.js
[ { "change_type": "RENAME", "old_path": "lib/shared/account-regexes.js", "new_path": "lib/shared/account-utils.js", "diff": "" }, { "change_type": "MODIFY", "old_path": "native/account/forgot-password-panel.react.js", "new_path": "native/account/forgot-password-panel.react.js", "diff": "@@ -26,7 +26,7 @@ import { connect } from 'lib/utils/redux-utils';\nimport {\nvalidUsernameRegex,\nvalidEmailRegex,\n-} from 'lib/shared/account-regexes';\n+} from 'lib/shared/account-utils';\nimport {\nTextInput,\n" }, { "change_type": "MODIFY", "old_path": "native/account/log-in-panel.react.js", "new_path": "native/account/log-in-panel.react.js", "diff": "@@ -31,7 +31,7 @@ import PropTypes from 'prop-types';\nimport {\nvalidUsernameRegex,\nvalidEmailRegex,\n-} from 'lib/shared/account-regexes';\n+} from 'lib/shared/account-utils';\nimport { connect } from 'lib/utils/redux-utils';\nimport {\nlogInActionTypes,\n" }, { "change_type": "MODIFY", "old_path": "native/account/register-panel.react.js", "new_path": "native/account/register-panel.react.js", "diff": "@@ -34,7 +34,7 @@ import { createLoadingStatusSelector } from 'lib/selectors/loading-selectors';\nimport {\nvalidUsernameRegex,\nvalidEmailRegex,\n-} from 'lib/shared/account-regexes';\n+} from 'lib/shared/account-utils';\nimport { TextInput } from './modal-components.react';\nimport {\n" }, { "change_type": "MODIFY", "old_path": "native/more/edit-email.react.js", "new_path": "native/more/edit-email.react.js", "diff": "@@ -29,7 +29,7 @@ import {\nchangeUserSettingsActionTypes,\nchangeUserSettings,\n} from 'lib/actions/user-actions';\n-import { validEmailRegex } from 'lib/shared/account-regexes';\n+import { validEmailRegex } from 'lib/shared/account-utils';\nimport { createLoadingStatusSelector } from 'lib/selectors/loading-selectors';\nimport Button from '../components/button.react';\n" }, { "change_type": "MODIFY", "old_path": "server/src/creators/account-creator.js", "new_path": "server/src/creators/account-creator.js", "diff": "@@ -13,7 +13,7 @@ import bcrypt from 'twin-bcrypt';\nimport {\nvalidUsernameRegex,\nvalidEmailRegex,\n-} from 'lib/shared/account-regexes';\n+} from 'lib/shared/account-utils';\nimport { ServerError } from 'lib/utils/errors';\nimport { values } from 'lib/utils/objects';\nimport ashoat from 'lib/facts/ashoat';\n" }, { "change_type": "MODIFY", "old_path": "server/src/updaters/account-updaters.js", "new_path": "server/src/updaters/account-updaters.js", "diff": "@@ -11,7 +11,7 @@ import { updateTypes } from 'lib/types/update-types';\nimport bcrypt from 'twin-bcrypt';\n-import { validEmailRegex } from 'lib/shared/account-regexes';\n+import { validEmailRegex } from 'lib/shared/account-utils';\nimport { promiseAll } from 'lib/utils/promises';\nimport { ServerError } from 'lib/utils/errors';\nimport { verifyField } from 'lib/types/verify-types';\n" }, { "change_type": "MODIFY", "old_path": "web/modals/account/forgot-password-modal.react.js", "new_path": "web/modals/account/forgot-password-modal.react.js", "diff": "@@ -10,7 +10,7 @@ import PropTypes from 'prop-types';\nimport {\nvalidUsernameRegex,\nvalidEmailRegex,\n-} from 'lib/shared/account-regexes';\n+} from 'lib/shared/account-utils';\nimport { connect } from 'lib/utils/redux-utils';\nimport {\nforgotPasswordActionTypes,\n" }, { "change_type": "MODIFY", "old_path": "web/modals/account/log-in-modal.react.js", "new_path": "web/modals/account/log-in-modal.react.js", "diff": "@@ -16,7 +16,7 @@ import PropTypes from 'prop-types';\nimport {\nvalidUsernameRegex,\nvalidEmailRegex,\n-} from 'lib/shared/account-regexes';\n+} from 'lib/shared/account-utils';\nimport { connect } from 'lib/utils/redux-utils';\nimport { logInActionTypes, logIn } from 'lib/actions/user-actions';\nimport { createLoadingStatusSelector } from 'lib/selectors/loading-selectors';\n" }, { "change_type": "MODIFY", "old_path": "web/modals/account/register-modal.react.js", "new_path": "web/modals/account/register-modal.react.js", "diff": "@@ -16,7 +16,7 @@ import PropTypes from 'prop-types';\nimport {\nvalidUsernameRegex,\nvalidEmailRegex,\n-} from 'lib/shared/account-regexes';\n+} from 'lib/shared/account-utils';\nimport { connect } from 'lib/utils/redux-utils';\nimport { registerActionTypes, register } from 'lib/actions/user-actions';\nimport { createLoadingStatusSelector } from 'lib/selectors/loading-selectors';\n" }, { "change_type": "MODIFY", "old_path": "web/modals/account/user-settings-modal.react.js", "new_path": "web/modals/account/user-settings-modal.react.js", "diff": "@@ -14,7 +14,7 @@ import invariant from 'invariant';\nimport classNames from 'classnames';\nimport PropTypes from 'prop-types';\n-import { validEmailRegex } from 'lib/shared/account-regexes';\n+import { validEmailRegex } from 'lib/shared/account-utils';\nimport {\ndeleteAccountActionTypes,\ndeleteAccount,\n" }, { "change_type": "MODIFY", "old_path": "web/splash/splash.react.js", "new_path": "web/splash/splash.react.js", "diff": "@@ -13,7 +13,7 @@ import * as React from 'react';\nimport PropTypes from 'prop-types';\nimport invariant from 'invariant';\n-import { validEmailRegex } from 'lib/shared/account-regexes';\n+import { validEmailRegex } from 'lib/shared/account-utils';\nimport { connect } from 'lib/utils/redux-utils';\nimport {\nrequestAccessActionTypes,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
account-regexes.js -> account-utils.js
129,187
22.12.2019 17:14:48
18,000
62f3ab3d30db373c44813bffaa14dce62f682985
Ignore expired session downgrades in SET_NEW_SESSION
[ { "change_type": "MODIFY", "old_path": "lib/shared/account-utils.js", "new_path": "lib/shared/account-utils.js", "diff": "// @flow\n+import type { CurrentUserInfo } from '../types/user-types';\n+\nconst validUsernameRegex = /^[a-zA-Z0-9-_]+$/;\nconst validEmailRegex = new RegExp(\n/^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+/.source +\n@@ -7,4 +9,25 @@ const validEmailRegex = new RegExp(\n/(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/.source\n);\n-export { validUsernameRegex, validEmailRegex }\n+function invalidSessionDowngrade(\n+ currentCurrentUserInfo: ?CurrentUserInfo,\n+ actionCurrentUserInfo: ?CurrentUserInfo,\n+ requestCurrentUserInfo: ?CurrentUserInfo,\n+): bool {\n+ // If this action represents a session downgrade - oldState has a loggedIn\n+ // currentUserInfo, but the action has an anonymous one - then it is only\n+ // valid if the currentUserInfo used for the request matches what oldState\n+ // currently has. If the currentUserInfo in Redux has changed since the\n+ // request, and is currently loggedIn, then the session downgrade does not\n+ // apply to it. In this case we will simply swallow the action.\n+ return !!(\n+ currentCurrentUserInfo &&\n+ !currentCurrentUserInfo.anonymous &&\n+ actionCurrentUserInfo &&\n+ actionCurrentUserInfo.anonymous &&\n+ (!requestCurrentUserInfo ||\n+ requestCurrentUserInfo.id !== currentCurrentUserInfo.id)\n+ );\n+}\n+\n+export { validUsernameRegex, validEmailRegex, invalidSessionDowngrade };\n" }, { "change_type": "MODIFY", "old_path": "lib/types/session-types.js", "new_path": "lib/types/session-types.js", "diff": "@@ -76,6 +76,7 @@ export type ClientSessionChange = {|\nexport type SetSessionPayload = {|\nsessionChange: ClientSessionChange,\n+ requestCurrentUserInfo: ?CurrentUserInfo,\nerror: ?string,\n|};\n" }, { "change_type": "MODIFY", "old_path": "lib/utils/action-utils.js", "new_path": "lib/utils/action-utils.js", "diff": "@@ -159,11 +159,12 @@ const setNewSessionActionType = \"SET_NEW_SESSION\";\nfunction setNewSession(\ndispatch: Dispatch,\nsessionChange: ClientSessionChange,\n+ requestCurrentUserInfo: ?CurrentUserInfo,\nerror: ?string,\n) {\ndispatch({\ntype: setNewSessionActionType,\n- payload: { sessionChange, error },\n+ payload: { sessionChange, requestCurrentUserInfo, error },\n});\n}\n@@ -194,7 +195,7 @@ async function fetchNewCookieFromNativeCredentials(\nerror: ?string,\n) => {\nnewSessionChange = sessionChange;\n- setNewSession(dispatch, sessionChange, error);\n+ setNewSession(dispatch, sessionChange, null, error);\n};\ntry {\nconst result = await fetchJSON(\n@@ -253,7 +254,15 @@ function bindCookieAndUtilsIntoFetchJSON(params: BindServerCallsParams): FetchJS\nconnectionStatus,\n} = params;\nconst loggedIn = !!(currentUserInfo && !currentUserInfo.anonymous && true);\n- const boundSetNewSession = setNewSession.bind(null, dispatch);\n+ const boundSetNewSession = (\n+ sessionChange: ClientSessionChange,\n+ error: ?string,\n+ ) => setNewSession(\n+ dispatch,\n+ sessionChange,\n+ currentUserInfo,\n+ error,\n+ );\n// This function gets called before fetchJSON sends a request, to make sure\n// that we're not in the middle of trying to recover an invalidated cookie\nconst waitIfCookieInvalidated = () => {\n" }, { "change_type": "MODIFY", "old_path": "native/redux/redux-setup.js", "new_path": "native/redux/redux-setup.js", "diff": "@@ -68,6 +68,7 @@ import {\n} from 'lib/actions/message-actions';\nimport { reduxLoggerMiddleware } from 'lib/utils/redux-logger';\nimport { getConfig } from 'lib/utils/config';\n+import { invalidSessionDowngrade } from 'lib/shared/account-utils';\nimport { activeThreadSelector } from '../selectors/nav-selectors';\nimport {\n@@ -190,6 +191,16 @@ function chatRouteFromNavInfo(navInfo: NavInfo): NavigationStateRoute {\n}\nfunction reducer(state: AppState = defaultState, action: *) {\n+ if (\n+ action.type === setNewSessionActionType &&\n+ invalidSessionDowngrade(\n+ state.currentUserInfo,\n+ action.payload.sessionChange.currentUserInfo,\n+ action.payload.requestCurrentUserInfo,\n+ )\n+ ) {\n+ return state;\n+ }\nif (\naction.type === recordAndroidNotificationActionType ||\naction.type === clearAndroidNotificationsActionType ||\n" }, { "change_type": "MODIFY", "old_path": "web/redux-setup.js", "new_path": "web/redux-setup.js", "diff": "@@ -22,6 +22,7 @@ import {\ndeleteThreadActionTypes,\n} from 'lib/actions/thread-actions';\nimport { mostRecentReadThreadSelector } from 'lib/selectors/thread-selectors';\n+import { invalidSessionDowngrade } from 'lib/shared/account-utils';\nimport { activeThreadSelector } from './selectors/nav-selectors';\n@@ -97,9 +98,14 @@ export function reducer(oldState: AppState | void, action: Action) {\nwindowDimensions: action.payload,\n},\n);\n+ } else if (action.type === setNewSessionActionType) {\n+ if (invalidSessionDowngrade(\n+ oldState.currentUserInfo,\n+ action.payload.sessionChange.currentUserInfo,\n+ action.payload.requestCurrentUserInfo,\n+ )) {\n+ return oldState;\n}\n-\n- if (action.type === setNewSessionActionType) {\nstate = {\n...state,\nsessionID: action.payload.sessionChange.sessionID,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Ignore expired session downgrades in SET_NEW_SESSION
129,187
22.12.2019 17:31:18
18,000
175bca27b0d5282e5f467612aae139c50793f268
Ignore expired session downgrades in socket SET_NEW_SESSION
[ { "change_type": "MODIFY", "old_path": "lib/socket/socket.react.js", "new_path": "lib/socket/socket.react.js", "diff": "@@ -38,6 +38,7 @@ import type {\n} from '../utils/action-utils';\nimport type { LogOutResult } from '../types/account-types';\nimport type { CalendarQuery } from '../types/entry-types';\n+import { type CurrentUserInfo, currentUserPropType } from '../types/user-types';\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\n@@ -89,6 +90,7 @@ type Props = {|\ncurrentCalendarQuery: () => CalendarQuery,\nhasWiFi: bool,\nfrozen: bool,\n+ currentUserInfo: ?CurrentUserInfo,\n// Redux dispatch functions\ndispatch: Dispatch,\ndispatchActionPayload: DispatchActionPayload,\n@@ -115,6 +117,7 @@ class Socket extends React.PureComponent<Props, State> {\ncurrentCalendarQuery: PropTypes.func.isRequired,\nhasWiFi: PropTypes.bool.isRequired,\nfrozen: PropTypes.bool.isRequired,\n+ currentUserInfo: currentUserPropType,\ndispatch: PropTypes.func.isRequired,\ndispatchActionPayload: PropTypes.func.isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\n@@ -131,6 +134,7 @@ class Socket extends React.PureComponent<Props, State> {\ninitialPlatformDetailsSent = getConfig().platformDetails.platform === \"web\";\nreopenConnectionAfterClosing = false;\ninvalidationRecoveryInProgress = false;\n+ initializedWithCurrentUserInfo: ?CurrentUserInfo;\nconstructor(props: Props) {\nsuper(props);\n@@ -446,6 +450,7 @@ class Socket extends React.PureComponent<Props, State> {\nsetNewSessionActionType,\n{\nsessionChange: { cookieInvalidated: true, currentUserInfo, cookie },\n+ requestCurrentUserInfo: this.initializedWithCurrentUserInfo,\nerror: null,\n},\n);\n@@ -525,6 +530,7 @@ class Socket extends React.PureComponent<Props, State> {\nsessionIdentification,\n},\n};\n+ this.initializedWithCurrentUserInfo = this.props.currentUserInfo;\nthis.sendMessage(initialMessage);\npromises.stateSyncMessage = inflightRequests.fetchResponse(\n@@ -558,6 +564,7 @@ class Socket extends React.PureComponent<Props, State> {\nsetNewSessionActionType,\n{\nsessionChange: { cookieInvalidated: false, sessionID },\n+ requestCurrentUserInfo: this.initializedWithCurrentUserInfo,\nerror: null,\n},\n);\n" }, { "change_type": "MODIFY", "old_path": "native/socket.react.js", "new_path": "native/socket.react.js", "diff": "@@ -37,6 +37,7 @@ export default connect(\ncurrentCalendarQuery: nativeCalendarQuery(state),\nhasWiFi: state.connectivity.hasWiFi,\nfrozen: state.frozen,\n+ currentUserInfo: state.currentUserInfo,\n};\n},\n{ logOut },\n" }, { "change_type": "MODIFY", "old_path": "web/socket.react.js", "new_path": "web/socket.react.js", "diff": "@@ -36,6 +36,7 @@ export default connect(\ncurrentCalendarQuery: webCalendarQuery(state),\nhasWiFi: true,\nfrozen: false,\n+ currentUserInfo: state.currentUserInfo,\n};\n},\n{ logOut },\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Ignore expired session downgrades in socket SET_NEW_SESSION
129,187
22.12.2019 18:07:04
18,000
8acf5e4000a3b9a22fb9d8fbdf1c8355997997c2
Ignore expired session downgrades in LOG_OUT_SUCCESS and DELETE_ACCOUNT_SUCCESS
[ { "change_type": "MODIFY", "old_path": "lib/actions/user-actions.js", "new_path": "lib/actions/user-actions.js", "diff": "@@ -5,7 +5,11 @@ import {\nverifyField,\ntype HandleVerificationCodeResult,\n} from '../types/verify-types';\n-import type { UserInfo, AccountUpdate } from '../types/user-types';\n+import type {\n+ UserInfo,\n+ AccountUpdate,\n+ CurrentUserInfo,\n+} from '../types/user-types';\nimport type {\nChangeUserSettingsResult,\nLogOutResult,\n@@ -33,6 +37,7 @@ const logOutActionTypes = Object.freeze({\n});\nasync function logOut(\nfetchJSON: FetchJSON,\n+ requestCurrentUserInfo: ?CurrentUserInfo,\n): Promise<LogOutResult> {\nlet response = null;\ntry {\n@@ -45,7 +50,7 @@ async function logOut(\n]);\n} catch { }\nconst currentUserInfo = response ? response.currentUserInfo : null;\n- return { currentUserInfo };\n+ return { currentUserInfo, requestCurrentUserInfo };\n}\nconst deleteAccountActionTypes = Object.freeze({\n@@ -56,6 +61,7 @@ const deleteAccountActionTypes = Object.freeze({\nasync function deleteAccount(\nfetchJSON: FetchJSON,\npassword: string,\n+ requestCurrentUserInfo: ?CurrentUserInfo,\n): Promise<LogOutResult> {\nlet response = null;\ntry {\n@@ -68,7 +74,7 @@ async function deleteAccount(\n]);\n} catch { }\nconst currentUserInfo = response ? response.currentUserInfo : null;\n- return { currentUserInfo };\n+ return { currentUserInfo, requestCurrentUserInfo };\n}\nconst registerActionTypes = Object.freeze({\n" }, { "change_type": "MODIFY", "old_path": "lib/socket/socket.react.js", "new_path": "lib/socket/socket.react.js", "diff": "@@ -96,7 +96,7 @@ type Props = {|\ndispatchActionPayload: DispatchActionPayload,\ndispatchActionPromise: DispatchActionPromise,\n// async functions that hit server APIs\n- logOut: () => Promise<LogOutResult>,\n+ logOut: (requestCurrentUserInfo: ?CurrentUserInfo) => Promise<LogOutResult>,\n|};\ntype State = {|\ninflightRequests: ?InflightRequests,\n@@ -457,7 +457,7 @@ class Socket extends React.PureComponent<Props, State> {\n} else if (!recoverySessionChange) {\nthis.props.dispatchActionPromise(\nlogOutActionTypes,\n- this.props.logOut(),\n+ this.props.logOut(this.props.currentUserInfo),\n);\n}\nthis.invalidationRecoveryInProgress = false;\n@@ -611,7 +611,7 @@ class Socket extends React.PureComponent<Props, State> {\nif (e.message === \"not_logged_in\") {\nthis.props.dispatchActionPromise(\nlogOutActionTypes,\n- this.props.logOut(),\n+ this.props.logOut(this.props.currentUserInfo),\n);\n} else if (this.socket) {\nthis.socket.close();\n" }, { "change_type": "MODIFY", "old_path": "lib/types/account-types.js", "new_path": "lib/types/account-types.js", "diff": "@@ -5,6 +5,7 @@ import type {\nUserInfo,\nLoggedOutUserInfo,\nLoggedInUserInfo,\n+ CurrentUserInfo,\n} from './user-types';\nimport type {\nCalendarQuery,\n@@ -27,6 +28,7 @@ export type ResetPasswordRequest = {|\nexport type LogOutResult = {|\ncurrentUserInfo: ?LoggedOutUserInfo,\n+ requestCurrentUserInfo: ?CurrentUserInfo,\n|};\nexport type LogOutResponse = {|\n" }, { "change_type": "MODIFY", "old_path": "lib/types/user-types.js", "new_path": "lib/types/user-types.js", "diff": "@@ -49,7 +49,7 @@ export type LoggedOutUserInfo = {|\nexport type CurrentUserInfo = LoggedInUserInfo | LoggedOutUserInfo;\n-export const currentUserPropType = PropTypes.oneOf([\n+export const currentUserPropType = PropTypes.oneOfType([\nPropTypes.shape({\nid: PropTypes.string.isRequired,\nusername: PropTypes.string.isRequired,\n" }, { "change_type": "MODIFY", "old_path": "native/crash.react.js", "new_path": "native/crash.react.js", "diff": "@@ -9,6 +9,10 @@ import type { DispatchActionPromise } from 'lib/utils/action-utils';\nimport type { AppState } from './redux/redux-setup';\nimport type { ErrorData } from 'lib/types/report-types';\nimport type { LogOutResult } from 'lib/types/account-types';\n+import {\n+ type CurrentUserInfo,\n+ currentUserPropType,\n+} from 'lib/types/user-types';\nimport * as React from 'react';\nimport {\n@@ -44,13 +48,15 @@ const errorTitles = [\ntype Props = {\nerrorData: $ReadOnlyArray<ErrorData>,\n+ // Redux state\n+ currentUserInfo: ?CurrentUserInfo,\n// Redux dispatch functions\ndispatchActionPromise: DispatchActionPromise,\n// async functions that hit server APIs\nsendReport: (\nrequest: ClientReportCreationRequest,\n) => Promise<ReportCreationResponse>,\n- logOut: () => Promise<LogOutResult>,\n+ logOut: (requestCurrentUserInfo: ?CurrentUserInfo) => Promise<LogOutResult>,\n};\ntype State = {|\nerrorReportID: ?string,\n@@ -65,6 +71,7 @@ class Crash extends React.PureComponent<Props, State> {\ncomponentStack: PropTypes.string.isRequired,\n}),\n})).isRequired,\n+ currentUserInfo: currentUserPropType,\ndispatchActionPromise: PropTypes.func.isRequired,\nsendReport: PropTypes.func.isRequired,\nlogOut: PropTypes.func.isRequired,\n@@ -188,7 +195,7 @@ class Crash extends React.PureComponent<Props, State> {\nasync logOutAndExit() {\ntry {\n- await this.props.logOut();\n+ await this.props.logOut(this.props.currentUserInfo);\n} catch (e) { }\ngetPersistor().purge();\nExitApp.exitApp();\n@@ -269,6 +276,8 @@ const styles = StyleSheet.create({\n});\nexport default connect(\n- undefined,\n+ (state: AppState) => ({\n+ currentUserInfo: state.currentUserInfo,\n+ }),\n{ sendReport, logOut },\n)(Crash);\n" }, { "change_type": "MODIFY", "old_path": "native/more/delete-account.react.js", "new_path": "native/more/delete-account.react.js", "diff": "@@ -8,6 +8,10 @@ import { loadingStatusPropType } from 'lib/types/loading-types';\nimport type { LogOutResult } from 'lib/types/account-types';\nimport { type GlobalTheme, globalThemePropType } from '../types/themes';\nimport type { Styles } from '../types/styles';\n+import {\n+ type CurrentUserInfo,\n+ currentUserPropType,\n+} from 'lib/types/user-types';\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\n@@ -39,13 +43,16 @@ type Props = {|\nnavigation: NavigationScreenProp<*>,\n// Redux state\nloadingStatus: LoadingStatus,\n- username: ?string,\n+ currentUserInfo: ?CurrentUserInfo,\nactiveTheme: ?GlobalTheme,\nstyles: Styles,\n// Redux dispatch functions\ndispatchActionPromise: DispatchActionPromise,\n// async functions that hit server APIs\n- deleteAccount: (password: string) => Promise<LogOutResult>,\n+ deleteAccount: (\n+ password: string,\n+ requestCurrentUserInfo: ?CurrentUserInfo,\n+ ) => Promise<LogOutResult>,\n|};\ntype State = {|\npassword: string,\n@@ -58,7 +65,7 @@ class DeleteAccount extends React.PureComponent<Props, State> {\nnavigate: PropTypes.func.isRequired,\n}).isRequired,\nloadingStatus: loadingStatusPropType.isRequired,\n- username: PropTypes.string,\n+ currentUserInfo: currentUserPropType,\nactiveTheme: globalThemePropType,\nstyles: PropTypes.objectOf(PropTypes.object).isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\n@@ -99,6 +106,12 @@ class DeleteAccount extends React.PureComponent<Props, State> {\n}\n}\n+ get username() {\n+ return this.props.currentUserInfo && !this.props.currentUserInfo.anonymous\n+ ? this.props.currentUserInfo.username\n+ : undefined;\n+ }\n+\nrender() {\nlet onePasswordButton = null;\nif (this.state.onePasswordSupported) {\n@@ -186,10 +199,13 @@ class DeleteAccount extends React.PureComponent<Props, State> {\nasync deleteAccount() {\ntry {\n- if (this.props.username) {\n- await deleteNativeCredentialsFor(this.props.username);\n+ if (this.username) {\n+ await deleteNativeCredentialsFor(this.username);\n}\n- const result = await this.props.deleteAccount(this.state.password);\n+ const result = await this.props.deleteAccount(\n+ this.state.password,\n+ this.props.currentUserInfo,\n+ );\nreturn result;\n} catch (e) {\nif (e.message === 'invalid_credentials') {\n@@ -293,9 +309,7 @@ const loadingStatusSelector = createLoadingStatusSelector(\nexport default connect(\n(state: AppState) => ({\nloadingStatus: loadingStatusSelector(state),\n- username: state.currentUserInfo && !state.currentUserInfo.anonymous\n- ? state.currentUserInfo.username\n- : undefined,\n+ currentUserInfo: state.currentUserInfo,\nactiveTheme: state.globalThemeInfo.activeTheme,\nstyles: stylesSelector(state),\n}),\n" }, { "change_type": "MODIFY", "old_path": "native/more/more-screen.react.js", "new_path": "native/more/more-screen.react.js", "diff": "@@ -10,6 +10,10 @@ import type { LoadingStatus } from 'lib/types/loading-types';\nimport { loadingStatusPropType } from 'lib/types/loading-types';\nimport type { Styles } from '../types/styles';\nimport { type Colors, colorsPropType } from '../themes/colors';\n+import {\n+ type CurrentUserInfo,\n+ currentUserPropType,\n+} from 'lib/types/user-types';\nimport * as React from 'react';\nimport {\n@@ -53,16 +57,14 @@ import { colorsSelector, styleSelector } from '../themes/colors';\ntype Props = {\nnavigation: NavigationScreenProp<*>,\n// Redux state\n- username: ?string,\n- email: ?string,\n- emailVerified: ?bool,\n+ currentUserInfo: ?CurrentUserInfo,\nresendVerificationLoadingStatus: LoadingStatus,\ncolors: Colors,\nstyles: Styles,\n// Redux dispatch functions\ndispatchActionPromise: DispatchActionPromise,\n// async functions that hit server APIs\n- logOut: () => Promise<LogOutResult>,\n+ logOut: (requestCurrentUserInfo: ?CurrentUserInfo) => Promise<LogOutResult>,\nresendVerificationEmail: () => Promise<void>,\n};\nclass MoreScreen extends React.PureComponent<Props> {\n@@ -71,9 +73,7 @@ class MoreScreen extends React.PureComponent<Props> {\nnavigation: PropTypes.shape({\nnavigate: PropTypes.func.isRequired,\n}).isRequired,\n- username: PropTypes.string,\n- email: PropTypes.string,\n- emailVerified: PropTypes.bool,\n+ currentUserInfo: currentUserPropType,\nresendVerificationLoadingStatus: loadingStatusPropType.isRequired,\ncolors: colorsPropType.isRequired,\nstyles: PropTypes.objectOf(PropTypes.object).isRequired,\n@@ -85,10 +85,29 @@ class MoreScreen extends React.PureComponent<Props> {\nheaderTitle: \"More\",\n};\n+ get username() {\n+ return this.props.currentUserInfo && !this.props.currentUserInfo.anonymous\n+ ? this.props.currentUserInfo.username\n+ : undefined;\n+ }\n+\n+ get email() {\n+ return this.props.currentUserInfo && !this.props.currentUserInfo.anonymous\n+ ? this.props.currentUserInfo.email\n+ : undefined;\n+ }\n+\n+ get emailVerified() {\n+ return this.props.currentUserInfo && !this.props.currentUserInfo.anonymous\n+ ? this.props.currentUserInfo.emailVerified\n+ : undefined;\n+ }\n+\nrender() {\n- let emailVerified = null;\n- if (this.props.emailVerified === true) {\n- emailVerified = (\n+ const { emailVerified } = this;\n+ let emailVerifiedNode = null;\n+ if (emailVerified === true) {\n+ emailVerifiedNode = (\n<Text style={[\nthis.props.styles.verification,\nthis.props.styles.verificationText,\n@@ -97,7 +116,7 @@ class MoreScreen extends React.PureComponent<Props> {\nVerified\n</Text>\n);\n- } else if (this.props.emailVerified === false) {\n+ } else if (emailVerified === false) {\nlet resendVerificationEmailSpinner;\nif (this.props.resendVerificationLoadingStatus === \"loading\") {\nresendVerificationEmailSpinner = (\n@@ -107,7 +126,7 @@ class MoreScreen extends React.PureComponent<Props> {\n/>\n);\n}\n- emailVerified = (\n+ emailVerifiedNode = (\n<View style={this.props.styles.verification}>\n<Text style={[\nthis.props.styles.verificationText,\n@@ -147,7 +166,7 @@ class MoreScreen extends React.PureComponent<Props> {\n<Text style={this.props.styles.label} numberOfLines={1}>\n{\"Logged in as \"}\n<Text style={this.props.styles.username}>\n- {this.props.username}\n+ {this.username}\n</Text>\n</Text>\n<Button onPress={this.onPressLogOut}>\n@@ -161,9 +180,9 @@ class MoreScreen extends React.PureComponent<Props> {\n<Text style={this.props.styles.label}>Email</Text>\n<View style={this.props.styles.content}>\n<Text style={this.props.styles.value} numberOfLines={1}>\n- {this.props.email}\n+ {this.email}\n</Text>\n- {emailVerified}\n+ {emailVerifiedNode}\n</View>\n<EditSettingButton\nonPress={this.onPressEditEmail}\n@@ -275,7 +294,7 @@ class MoreScreen extends React.PureComponent<Props> {\nlogOutButKeepNativeCredentialsWrapper = () => {\nthis.props.dispatchActionPromise(\nlogOutActionTypes,\n- this.props.logOut(),\n+ this.logOut(),\n);\n}\n@@ -286,11 +305,15 @@ class MoreScreen extends React.PureComponent<Props> {\n);\n}\n+ logOut() {\n+ return this.props.logOut(this.props.currentUserInfo);\n+ }\n+\nasync logOutAndDeleteNativeCredentials() {\n- const username = this.props.username;\n+ const { username } = this;\ninvariant(username, \"can't log out if not logged in\");\nawait deleteNativeCredentialsFor(username);\n- return await this.props.logOut();\n+ return await this.logOut();\n}\nonPressResendVerificationEmail = () => {\n@@ -469,15 +492,7 @@ const resendVerificationLoadingStatusSelector = createLoadingStatusSelector(\nexport default connect(\n(state: AppState) => ({\n- username: state.currentUserInfo && !state.currentUserInfo.anonymous\n- ? state.currentUserInfo.username\n- : undefined,\n- email: state.currentUserInfo && !state.currentUserInfo.anonymous\n- ? state.currentUserInfo.email\n- : undefined,\n- emailVerified: state.currentUserInfo && !state.currentUserInfo.anonymous\n- ? state.currentUserInfo.emailVerified\n- : undefined,\n+ currentUserInfo: state.currentUserInfo,\nresendVerificationLoadingStatus:\nresendVerificationLoadingStatusSelector(state),\ncolors: colorsSelector(state),\n" }, { "change_type": "MODIFY", "old_path": "native/redux/redux-setup.js", "new_path": "native/redux/redux-setup.js", "diff": "@@ -69,6 +69,10 @@ import {\nimport { reduxLoggerMiddleware } from 'lib/utils/redux-logger';\nimport { getConfig } from 'lib/utils/config';\nimport { invalidSessionDowngrade } from 'lib/shared/account-utils';\n+import {\n+ logOutActionTypes,\n+ deleteAccountActionTypes,\n+} from 'lib/actions/user-actions';\nimport { activeThreadSelector } from '../selectors/nav-selectors';\nimport {\n@@ -192,12 +196,27 @@ function chatRouteFromNavInfo(navInfo: NavInfo): NavigationStateRoute {\nfunction reducer(state: AppState = defaultState, action: *) {\nif (\n- action.type === setNewSessionActionType &&\n+ (action.type === setNewSessionActionType &&\ninvalidSessionDowngrade(\nstate.currentUserInfo,\naction.payload.sessionChange.currentUserInfo,\naction.payload.requestCurrentUserInfo,\n)\n+ ) ||\n+ (action.type === logOutActionTypes.success &&\n+ invalidSessionDowngrade(\n+ state.currentUserInfo,\n+ action.payload.currentUserInfo,\n+ action.payload.requestCurrentUserInfo,\n+ )\n+ ) ||\n+ (action.type === deleteAccountActionTypes.success &&\n+ invalidSessionDowngrade(\n+ state.currentUserInfo,\n+ action.payload.currentUserInfo,\n+ action.payload.requestCurrentUserInfo,\n+ )\n+ )\n) {\nreturn state;\n}\n" }, { "change_type": "MODIFY", "old_path": "web/account-bar.react.js", "new_path": "web/account-bar.react.js", "diff": "@@ -4,6 +4,10 @@ import type { AppState } from './redux-setup';\nimport type { DispatchActionPromise } from 'lib/utils/action-utils';\nimport type { ThreadInfo } from 'lib/types/thread-types';\nimport type { LogOutResult } from 'lib/types/account-types';\n+import {\n+ type CurrentUserInfo,\n+ currentUserPropType,\n+} from 'lib/types/user-types';\nimport * as React from 'react';\nimport invariant from 'invariant';\n@@ -22,12 +26,11 @@ import { htmlTargetFromEvent } from './vector-utils';\ntype Props = {|\nsetModal: (modal: ?React.Node) => void,\n// Redux state\n- loggedIn: bool,\n- username: ?string,\n+ currentUserInfo: ?CurrentUserInfo,\n// Redux dispatch functions\ndispatchActionPromise: DispatchActionPromise,\n// async functions that hit server APIs\n- logOut: () => Promise<LogOutResult>,\n+ logOut: (requestCurrentUserInfo: ?CurrentUserInfo) => Promise<LogOutResult>,\n|};\ntype State = {|\nexpanded: bool,\n@@ -36,8 +39,7 @@ class AccountBar extends React.PureComponent<Props, State> {\nstatic propTypes = {\nsetModal: PropTypes.func.isRequired,\n- loggedIn: PropTypes.bool.isRequired,\n- username: PropTypes.string,\n+ currentUserInfo: currentUserPropType,\ndispatchActionPromise: PropTypes.func.isRequired,\nlogOut: PropTypes.func.isRequired,\n};\n@@ -53,8 +55,19 @@ class AccountBar extends React.PureComponent<Props, State> {\n}\n}\n+ get loggedIn() {\n+ return !!(this.props.currentUserInfo &&\n+ !this.props.currentUserInfo.anonymous && true);\n+ }\n+\n+ get username() {\n+ return this.props.currentUserInfo && !this.props.currentUserInfo.anonymous\n+ ? this.props.currentUserInfo.username\n+ : undefined;\n+ }\n+\nrender() {\n- if (!this.props.loggedIn) {\n+ if (!this.loggedIn) {\nreturn (\n<div className={css['account-bar']}>\n<div className={css['account-button']}>\n@@ -101,7 +114,7 @@ class AccountBar extends React.PureComponent<Props, State> {\n<div className={css['account-bar']} onMouseDown={this.onMouseDown}>\n<div className={css['account-button']}>\n<span>{\"logged in as \"}</span>\n- <span className={css['username']}>{this.props.username}</span>\n+ <span className={css['username']}>{this.username}</span>\n{caret}\n</div>\n{menu}\n@@ -143,7 +156,10 @@ class AccountBar extends React.PureComponent<Props, State> {\nonLogOut = (event: SyntheticEvent<HTMLAnchorElement>) => {\nevent.preventDefault();\n- this.props.dispatchActionPromise(logOutActionTypes, this.props.logOut());\n+ this.props.dispatchActionPromise(\n+ logOutActionTypes,\n+ this.props.logOut(this.props.currentUserInfo),\n+ );\nthis.setState({ expanded: false });\n}\n@@ -167,11 +183,7 @@ class AccountBar extends React.PureComponent<Props, State> {\nexport default connect(\n(state: AppState) => ({\n- loggedIn: !!(state.currentUserInfo &&\n- !state.currentUserInfo.anonymous && true),\n- username: state.currentUserInfo && !state.currentUserInfo.anonymous\n- ? state.currentUserInfo.username\n- : undefined,\n+ currentUserInfo: state.currentUserInfo,\n}),\n{ logOut },\n)(AccountBar);\n" }, { "change_type": "MODIFY", "old_path": "web/modals/account/user-settings-modal.react.js", "new_path": "web/modals/account/user-settings-modal.react.js", "diff": "import type { AppState } from '../../redux-setup';\nimport type { DispatchActionPromise } from 'lib/utils/action-utils';\nimport type { ThreadInfo } from 'lib/types/thread-types';\n-import type { AccountUpdate } from 'lib/types/user-types';\n+import {\n+ type AccountUpdate,\n+ type CurrentUserInfo,\n+ currentUserPropType,\n+} from 'lib/types/user-types';\nimport type {\nLogOutResult,\nChangeUserSettingsResult,\n@@ -61,21 +65,22 @@ class Tab extends React.PureComponent<TabProps> {\ntype Props = {\nsetModal: (modal: ?React.Node) => void,\n// Redux state\n- username: string,\n- email: string,\n- emailVerified: bool,\n+ currentUserInfo: ?CurrentUserInfo,\ninputDisabled: bool,\n// Redux dispatch functions\ndispatchActionPromise: DispatchActionPromise,\n// async functions that hit server APIs\n- deleteAccount: (password: string) => Promise<LogOutResult>,\n+ deleteAccount: (\n+ password: string,\n+ requestCurrentUserInfo: ?CurrentUserInfo,\n+ ) => Promise<LogOutResult>,\nchangeUserSettings: (\naccountUpdate: AccountUpdate,\n) => Promise<ChangeUserSettingsResult>,\nresendVerificationEmail: () => Promise<void>,\n};\ntype State = {\n- email: string,\n+ email: ?string,\nemailVerified: ?bool,\nnewPassword: string,\nconfirmNewPassword: string,\n@@ -86,6 +91,15 @@ type State = {\nclass UserSettingsModal extends React.PureComponent<Props, State> {\n+ static propTypes = {\n+ setModal: PropTypes.func.isRequired,\n+ currentUserInfo: currentUserPropType,\n+ inputDisabled: PropTypes.bool.isRequired,\n+ dispatchActionPromise: PropTypes.func.isRequired,\n+ deleteAccount: PropTypes.func.isRequired,\n+ changeUserSettings: PropTypes.func.isRequired,\n+ resendVerificationEmail: PropTypes.func.isRequired,\n+ };\nemailInput: ?HTMLInputElement;\nnewPasswordInput: ?HTMLInputElement;\ncurrentPasswordInput: ?HTMLInputElement;\n@@ -93,8 +107,8 @@ class UserSettingsModal extends React.PureComponent<Props, State> {\nconstructor(props: Props) {\nsuper(props);\nthis.state = {\n- email: props.email,\n- emailVerified: props.emailVerified,\n+ email: this.email,\n+ emailVerified: this.emailVerified,\nnewPassword: \"\",\nconfirmNewPassword: \"\",\ncurrentPassword: \"\",\n@@ -108,6 +122,24 @@ class UserSettingsModal extends React.PureComponent<Props, State> {\nthis.emailInput.focus();\n}\n+ get username() {\n+ return this.props.currentUserInfo && !this.props.currentUserInfo.anonymous\n+ ? this.props.currentUserInfo.username\n+ : undefined;\n+ }\n+\n+ get email() {\n+ return this.props.currentUserInfo && !this.props.currentUserInfo.anonymous\n+ ? this.props.currentUserInfo.email\n+ : undefined;\n+ }\n+\n+ get emailVerified() {\n+ return this.props.currentUserInfo && !this.props.currentUserInfo.anonymous\n+ ? this.props.currentUserInfo.emailVerified\n+ : undefined;\n+ }\n+\nrender() {\nlet mainContent = null;\nif (this.state.currentTabType === \"general\") {\n@@ -133,7 +165,7 @@ class UserSettingsModal extends React.PureComponent<Props, State> {\n<div>\n<div className={css['form-text']}>\n<div className={css['form-title']}>Username</div>\n- <div className={css['form-content']}>{this.props.username}</div>\n+ <div className={css['form-content']}>{this.username}</div>\n</div>\n<div>\n<div className={css['form-title']}>Email</div>\n@@ -279,8 +311,8 @@ class UserSettingsModal extends React.PureComponent<Props, State> {\ninvariant(target instanceof HTMLInputElement, \"target not input\");\nthis.setState({\nemail: target.value,\n- emailVerified: target.value === this.props.email\n- ? this.props.emailVerified\n+ emailVerified: target.value === this.email\n+ ? this.emailVerified\n: null,\n});\n}\n@@ -337,7 +369,8 @@ class UserSettingsModal extends React.PureComponent<Props, State> {\nreturn;\n}\n- if (this.state.email.search(validEmailRegex) === -1) {\n+ const { email } = this.state;\n+ if (!email || email.search(validEmailRegex) === -1) {\nthis.setState(\n{\nemail: \"\",\n@@ -354,12 +387,11 @@ class UserSettingsModal extends React.PureComponent<Props, State> {\nthis.props.dispatchActionPromise(\nchangeUserSettingsActionTypes,\n- this.changeUserSettingsAction(),\n+ this.changeUserSettingsAction(email),\n);\n}\n- async changeUserSettingsAction() {\n- const email = this.state.email;\n+ async changeUserSettingsAction(email: string) {\ntry {\nconst result = await this.props.changeUserSettings({\nupdatedFields: {\n@@ -368,7 +400,7 @@ class UserSettingsModal extends React.PureComponent<Props, State> {\n},\ncurrentPassword: this.state.currentPassword,\n});\n- if (email !== this.props.email) {\n+ if (email !== this.email) {\nthis.props.setModal(<VerifyEmailModal onClose={this.clearModal} />);\n} else {\nthis.clearModal();\n@@ -392,8 +424,8 @@ class UserSettingsModal extends React.PureComponent<Props, State> {\n} else if (e.message === 'email_taken') {\nthis.setState(\n{\n- email: this.props.email,\n- emailVerified: this.props.emailVerified,\n+ email: this.email,\n+ emailVerified: this.emailVerified,\nerrorMessage: \"email already taken\",\ncurrentTabType: \"general\",\n},\n@@ -405,8 +437,8 @@ class UserSettingsModal extends React.PureComponent<Props, State> {\n} else {\nthis.setState(\n{\n- email: this.props.email,\n- emailVerified: this.props.emailVerified,\n+ email: this.email,\n+ emailVerified: this.emailVerified,\nnewPassword: \"\",\nconfirmNewPassword: \"\",\ncurrentPassword: \"\",\n@@ -435,6 +467,7 @@ class UserSettingsModal extends React.PureComponent<Props, State> {\ntry {\nconst response = await this.props.deleteAccount(\nthis.state.currentPassword,\n+ this.props.currentUserInfo,\n);\nthis.clearModal();\nreturn response;\n@@ -465,18 +498,6 @@ class UserSettingsModal extends React.PureComponent<Props, State> {\n}\n-UserSettingsModal.propTypes = {\n- setModal: PropTypes.func.isRequired,\n- username: PropTypes.string.isRequired,\n- email: PropTypes.string.isRequired,\n- emailVerified: PropTypes.bool.isRequired,\n- inputDisabled: PropTypes.bool.isRequired,\n- dispatchActionPromise: PropTypes.func.isRequired,\n- deleteAccount: PropTypes.func.isRequired,\n- changeUserSettings: PropTypes.func.isRequired,\n- resendVerificationEmail: PropTypes.func.isRequired,\n-};\n-\nconst deleteAccountLoadingStatusSelector\n= createLoadingStatusSelector(deleteAccountActionTypes);\nconst changeUserSettingsLoadingStatusSelector\n@@ -486,15 +507,7 @@ const resendVerificationEmailLoadingStatusSelector\nexport default connect(\n(state: AppState) => ({\n- username: state.currentUserInfo && !state.currentUserInfo.anonymous\n- ? state.currentUserInfo.username\n- : undefined,\n- email: state.currentUserInfo && !state.currentUserInfo.anonymous\n- ? state.currentUserInfo.email\n- : undefined,\n- emailVerified: state.currentUserInfo && !state.currentUserInfo.anonymous\n- ? state.currentUserInfo.emailVerified\n- : undefined,\n+ currentUserInfo: state.currentUserInfo,\ninputDisabled: deleteAccountLoadingStatusSelector(state) === \"loading\" ||\nchangeUserSettingsLoadingStatusSelector(state) === \"loading\" ||\nresendVerificationEmailLoadingStatusSelector(state) === \"loading\",\n" }, { "change_type": "MODIFY", "old_path": "web/redux-setup.js", "new_path": "web/redux-setup.js", "diff": "@@ -23,6 +23,10 @@ import {\n} from 'lib/actions/thread-actions';\nimport { mostRecentReadThreadSelector } from 'lib/selectors/thread-selectors';\nimport { invalidSessionDowngrade } from 'lib/shared/account-utils';\n+import {\n+ logOutActionTypes,\n+ deleteAccountActionTypes,\n+} from 'lib/actions/user-actions';\nimport { activeThreadSelector } from './selectors/nav-selectors';\n@@ -110,6 +114,23 @@ export function reducer(oldState: AppState | void, action: Action) {\n...state,\nsessionID: action.payload.sessionChange.sessionID,\n};\n+ } else if (\n+ (action.type === logOutActionTypes.success &&\n+ invalidSessionDowngrade(\n+ oldState.currentUserInfo,\n+ action.payload.currentUserInfo,\n+ action.payload.requestCurrentUserInfo,\n+ )\n+ ) ||\n+ (action.type === deleteAccountActionTypes.success &&\n+ invalidSessionDowngrade(\n+ oldState.currentUserInfo,\n+ action.payload.currentUserInfo,\n+ action.payload.requestCurrentUserInfo,\n+ )\n+ )\n+ ) {\n+ return oldState;\n}\nreturn validateState(oldState, baseReducer(state, action));\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Ignore expired session downgrades in LOG_OUT_SUCCESS and DELETE_ACCOUNT_SUCCESS
129,187
23.12.2019 15:57:26
18,000
14fd7255066fcb881022e56ae6f9d4b128cb65f1
[lib] Fix notif text for multimedia sent to group chat
[ { "change_type": "MODIFY", "old_path": "lib/shared/notif-utils.js", "new_path": "lib/shared/notif-utils.js", "diff": "@@ -418,7 +418,7 @@ function fullNotifTextsForMessageInfo(\nbody = `sent you ${contentString}`;\nmerged = body;\n} else {\n- body = `${userString} send ${contentString}`;\n+ body = `sent ${contentString}`;\nconst threadName = notifThreadName(threadInfo);\nmerged = `${body} to ${threadName}`;\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[lib] Fix notif text for multimedia sent to group chat
129,187
23.12.2019 19:01:55
18,000
e9f8413c66a9196139e250c4423075ef39459057
[native] Rename to webpack.config.cjs New version of Node isn't cool with `require(web/webpack.config.js)`
[ { "change_type": "MODIFY", "old_path": "web/package.json", "new_path": "web/package.json", "diff": "\"license\": \"BSD-3-Clause\",\n\"scripts\": {\n\"clean\": \"rm -rf dist/ && rm -rf node_modules/\",\n- \"dev\": \"yarn concurrently --names=\\\"NODESSR,BROWSER\\\" -c \\\"bgBlue.bold,bgMagenta.bold\\\" \\\"yarn webpack --config-name=server --watch\\\" \\\"yarn webpack-dev-server --hot --config-name=browser\\\"\",\n- \"prod\": \"yarn webpack --env prod --progress\",\n+ \"dev\": \"yarn concurrently --names=\\\"NODESSR,BROWSER\\\" -c \\\"bgBlue.bold,bgMagenta.bold\\\" \\\"yarn webpack --config webpack.config.cjs --config-name=server --watch\\\" \\\"yarn webpack-dev-server --hot --config webpack.config.cjs --config-name=browser\\\"\",\n+ \"prod\": \"yarn webpack --config webpack.config.cjs --env prod --progress\",\n\"flow\": \"yarn flow; test $? -eq 0 -o $? -eq 2\"\n},\n\"devDependencies\": {\n" }, { "change_type": "RENAME", "old_path": "web/webpack.config.js", "new_path": "web/webpack.config.cjs", "diff": "" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Rename to webpack.config.cjs New version of Node isn't cool with `require(web/webpack.config.js)`
129,187
24.12.2019 12:56:26
18,000
c55d892fcc631023f051042786474022469b8ee7
Compare cookie and sessionID when determining if session downgrade is invalid
[ { "change_type": "MODIFY", "old_path": "lib/actions/user-actions.js", "new_path": "lib/actions/user-actions.js", "diff": "@@ -5,11 +5,7 @@ import {\nverifyField,\ntype HandleVerificationCodeResult,\n} from '../types/verify-types';\n-import type {\n- UserInfo,\n- AccountUpdate,\n- CurrentUserInfo,\n-} from '../types/user-types';\n+import type { UserInfo, AccountUpdate } from '../types/user-types';\nimport type {\nChangeUserSettingsResult,\nLogOutResult,\n@@ -25,6 +21,7 @@ import type {\nSubscriptionUpdateResult,\n} from '../types/subscription-types';\nimport type { UserSearchResult } from '../types/search-types';\n+import type { PreRequestUserState } from '../types/session-types';\nimport threadWatcher from '../shared/thread-watcher';\nimport { getConfig } from '../utils/config';\n@@ -37,7 +34,7 @@ const logOutActionTypes = Object.freeze({\n});\nasync function logOut(\nfetchJSON: FetchJSON,\n- requestCurrentUserInfo: ?CurrentUserInfo,\n+ preRequestUserState: PreRequestUserState,\n): Promise<LogOutResult> {\nlet response = null;\ntry {\n@@ -50,7 +47,7 @@ async function logOut(\n]);\n} catch { }\nconst currentUserInfo = response ? response.currentUserInfo : null;\n- return { currentUserInfo, requestCurrentUserInfo };\n+ return { currentUserInfo, preRequestUserState };\n}\nconst deleteAccountActionTypes = Object.freeze({\n@@ -61,7 +58,7 @@ const deleteAccountActionTypes = Object.freeze({\nasync function deleteAccount(\nfetchJSON: FetchJSON,\npassword: string,\n- requestCurrentUserInfo: ?CurrentUserInfo,\n+ preRequestUserState: PreRequestUserState,\n): Promise<LogOutResult> {\nlet response = null;\ntry {\n@@ -74,7 +71,7 @@ async function deleteAccount(\n]);\n} catch { }\nconst currentUserInfo = response ? response.currentUserInfo : null;\n- return { currentUserInfo, requestCurrentUserInfo };\n+ return { currentUserInfo, preRequestUserState };\n}\nconst registerActionTypes = Object.freeze({\n" }, { "change_type": "MODIFY", "old_path": "lib/selectors/account-selectors.js", "new_path": "lib/selectors/account-selectors.js", "diff": "@@ -4,6 +4,8 @@ import type { AppState } from '../types/redux-types';\nimport type { CalendarQuery } from '../types/entry-types';\nimport type { LogInExtraInfo } from '../types/account-types';\nimport { isDeviceType, assertDeviceType } from '../types/device-types';\n+import type { CurrentUserInfo } from '../types/user-types';\n+import type { PreRequestUserState } from '../types/session-types';\nimport { createSelector } from 'reselect';\n@@ -32,6 +34,20 @@ const logInExtraInfoSelector: (\n},\n);\n+const preRequestUserStateSelector: (\n+ state: AppState,\n+) => PreRequestUserState = createSelector(\n+ (state: AppState) => state.currentUserInfo,\n+ (state: AppState) => state.cookie,\n+ (state: AppState) => state.sessionID,\n+ (currentUserInfo: ?CurrentUserInfo, cookie: ?string, sessionID: ?string) => ({\n+ currentUserInfo,\n+ cookie,\n+ sessionID,\n+ })\n+);\n+\nexport {\nlogInExtraInfoSelector,\n+ preRequestUserStateSelector,\n};\n" }, { "change_type": "MODIFY", "old_path": "lib/shared/account-utils.js", "new_path": "lib/shared/account-utils.js", "diff": "// @flow\n+import type { AppState } from '../types/redux-types';\nimport type { CurrentUserInfo } from '../types/user-types';\n+import type { PreRequestUserState } from '../types/session-types';\nconst validUsernameRegex = /^[a-zA-Z0-9-_]+$/;\nconst validEmailRegex = new RegExp(\n@@ -10,9 +12,9 @@ const validEmailRegex = new RegExp(\n);\nfunction invalidSessionDowngrade(\n- currentCurrentUserInfo: ?CurrentUserInfo,\n+ currentReduxState: AppState,\nactionCurrentUserInfo: ?CurrentUserInfo,\n- requestCurrentUserInfo: ?CurrentUserInfo,\n+ preRequestUserState: ?PreRequestUserState,\n): bool {\n// If this action represents a session downgrade - oldState has a loggedIn\n// currentUserInfo, but the action has an anonymous one - then it is only\n@@ -20,13 +22,17 @@ function invalidSessionDowngrade(\n// currently has. If the currentUserInfo in Redux has changed since the\n// request, and is currently loggedIn, then the session downgrade does not\n// apply to it. In this case we will simply swallow the action.\n+ const currentCurrentUserInfo = currentReduxState.currentUserInfo;\nreturn !!(\ncurrentCurrentUserInfo &&\n!currentCurrentUserInfo.anonymous &&\nactionCurrentUserInfo &&\nactionCurrentUserInfo.anonymous &&\n- (!requestCurrentUserInfo ||\n- requestCurrentUserInfo.id !== currentCurrentUserInfo.id)\n+ preRequestUserState &&\n+ (!preRequestUserState.currentUserInfo ||\n+ preRequestUserState.currentUserInfo.id !== currentCurrentUserInfo.id ||\n+ preRequestUserState.cookie !== currentReduxState.cookie ||\n+ preRequestUserState.sessionID !== currentReduxState.sessionID)\n);\n}\n" }, { "change_type": "MODIFY", "old_path": "lib/socket/socket.react.js", "new_path": "lib/socket/socket.react.js", "diff": "@@ -9,6 +9,8 @@ import {\ntype SessionState,\ntype SessionIdentification,\nsessionIdentificationPropType,\n+ type PreRequestUserState,\n+ preRequestUserStatePropType,\n} from '../types/session-types';\nimport {\nclientSocketMessageTypes,\n@@ -38,7 +40,6 @@ import type {\n} from '../utils/action-utils';\nimport type { LogOutResult } from '../types/account-types';\nimport type { CalendarQuery } from '../types/entry-types';\n-import { type CurrentUserInfo, currentUserPropType } from '../types/user-types';\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\n@@ -90,13 +91,13 @@ type Props = {|\ncurrentCalendarQuery: () => CalendarQuery,\nhasWiFi: bool,\nfrozen: bool,\n- currentUserInfo: ?CurrentUserInfo,\n+ preRequestUserState: PreRequestUserState,\n// Redux dispatch functions\ndispatch: Dispatch,\ndispatchActionPayload: DispatchActionPayload,\ndispatchActionPromise: DispatchActionPromise,\n// async functions that hit server APIs\n- logOut: (requestCurrentUserInfo: ?CurrentUserInfo) => Promise<LogOutResult>,\n+ logOut: (preRequestUserState: PreRequestUserState) => Promise<LogOutResult>,\n|};\ntype State = {|\ninflightRequests: ?InflightRequests,\n@@ -117,7 +118,7 @@ class Socket extends React.PureComponent<Props, State> {\ncurrentCalendarQuery: PropTypes.func.isRequired,\nhasWiFi: PropTypes.bool.isRequired,\nfrozen: PropTypes.bool.isRequired,\n- currentUserInfo: currentUserPropType,\n+ preRequestUserState: preRequestUserStatePropType.isRequired,\ndispatch: PropTypes.func.isRequired,\ndispatchActionPayload: PropTypes.func.isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\n@@ -134,7 +135,7 @@ class Socket extends React.PureComponent<Props, State> {\ninitialPlatformDetailsSent = getConfig().platformDetails.platform === \"web\";\nreopenConnectionAfterClosing = false;\ninvalidationRecoveryInProgress = false;\n- initializedWithCurrentUserInfo: ?CurrentUserInfo;\n+ initializedWithUserState: ?PreRequestUserState;\nconstructor(props: Props) {\nsuper(props);\n@@ -450,14 +451,14 @@ class Socket extends React.PureComponent<Props, State> {\nsetNewSessionActionType,\n{\nsessionChange: { cookieInvalidated: true, currentUserInfo, cookie },\n- requestCurrentUserInfo: this.initializedWithCurrentUserInfo,\n+ preRequestUserState: this.initializedWithUserState,\nerror: null,\n},\n);\n} else if (!recoverySessionChange) {\nthis.props.dispatchActionPromise(\nlogOutActionTypes,\n- this.props.logOut(this.props.currentUserInfo),\n+ this.props.logOut(this.props.preRequestUserState),\n);\n}\nthis.invalidationRecoveryInProgress = false;\n@@ -530,7 +531,7 @@ class Socket extends React.PureComponent<Props, State> {\nsessionIdentification,\n},\n};\n- this.initializedWithCurrentUserInfo = this.props.currentUserInfo;\n+ this.initializedWithUserState = this.props.preRequestUserState;\nthis.sendMessage(initialMessage);\npromises.stateSyncMessage = inflightRequests.fetchResponse(\n@@ -560,11 +561,15 @@ class Socket extends React.PureComponent<Props, State> {\n{ ...actionPayload, calendarQuery: sessionState.calendarQuery },\n);\nif (sessionID !== null && sessionID !== undefined) {\n+ invariant(\n+ this.initializedWithUserState,\n+ \"initializedWithUserState should be set when state sync received\",\n+ );\nthis.props.dispatchActionPayload(\nsetNewSessionActionType,\n{\nsessionChange: { cookieInvalidated: false, sessionID },\n- requestCurrentUserInfo: this.initializedWithCurrentUserInfo,\n+ preRequestUserState: this.initializedWithUserState,\nerror: null,\n},\n);\n@@ -611,7 +616,7 @@ class Socket extends React.PureComponent<Props, State> {\nif (e.message === \"not_logged_in\") {\nthis.props.dispatchActionPromise(\nlogOutActionTypes,\n- this.props.logOut(this.props.currentUserInfo),\n+ this.props.logOut(this.props.preRequestUserState),\n);\n} else if (this.socket) {\nthis.socket.close();\n" }, { "change_type": "MODIFY", "old_path": "lib/types/account-types.js", "new_path": "lib/types/account-types.js", "diff": "@@ -5,7 +5,6 @@ import type {\nUserInfo,\nLoggedOutUserInfo,\nLoggedInUserInfo,\n- CurrentUserInfo,\n} from './user-types';\nimport type {\nCalendarQuery,\n@@ -21,6 +20,7 @@ import type {\nPlatformDetails,\nDeviceType,\n} from './device-types';\n+import type { PreRequestUserState } from './session-types';\nexport type ResetPasswordRequest = {|\nusernameOrEmail: string,\n@@ -28,7 +28,7 @@ export type ResetPasswordRequest = {|\nexport type LogOutResult = {|\ncurrentUserInfo: ?LoggedOutUserInfo,\n- requestCurrentUserInfo: ?CurrentUserInfo,\n+ preRequestUserState: PreRequestUserState,\n|};\nexport type LogOutResponse = {|\n" }, { "change_type": "MODIFY", "old_path": "lib/types/session-types.js", "new_path": "lib/types/session-types.js", "diff": "// @flow\nimport type { RawThreadInfo } from './thread-types';\n-import type {\n- UserInfo,\n- CurrentUserInfo,\n- LoggedOutUserInfo,\n+import {\n+ type UserInfo,\n+ type CurrentUserInfo,\n+ type LoggedOutUserInfo,\n+ currentUserPropType,\n} from './user-types';\nimport type { CalendarQuery } from './entry-types';\n@@ -74,9 +75,21 @@ export type ClientSessionChange = {|\ncookie?: string,\n|};\n+export type PreRequestUserState = {|\n+ currentUserInfo: ?CurrentUserInfo,\n+ cookie: ?string,\n+ sessionID: ?string,\n+|};\n+\n+export const preRequestUserStatePropType = PropTypes.shape({\n+ currentUserInfo: currentUserPropType,\n+ cookie: PropTypes.string,\n+ sessionID: PropTypes.string,\n+});\n+\nexport type SetSessionPayload = {|\nsessionChange: ClientSessionChange,\n- requestCurrentUserInfo: ?CurrentUserInfo,\n+ preRequestUserState: ?PreRequestUserState,\nerror: ?string,\n|};\n" }, { "change_type": "MODIFY", "old_path": "lib/utils/action-utils.js", "new_path": "lib/utils/action-utils.js", "diff": "@@ -20,7 +20,10 @@ import type {\nLogInResult,\n} from '../types/account-types';\nimport type { Endpoint, SocketAPIHandler } from '../types/endpoints';\n-import type { ClientSessionChange } from '../types/session-types';\n+import type {\n+ ClientSessionChange,\n+ PreRequestUserState,\n+} from '../types/session-types';\nimport type { ConnectionStatus } from '../types/socket-types';\nimport invariant from 'invariant';\n@@ -159,12 +162,12 @@ const setNewSessionActionType = \"SET_NEW_SESSION\";\nfunction setNewSession(\ndispatch: Dispatch,\nsessionChange: ClientSessionChange,\n- requestCurrentUserInfo: ?CurrentUserInfo,\n+ preRequestUserState: ?PreRequestUserState,\nerror: ?string,\n) {\ndispatch({\ntype: setNewSessionActionType,\n- payload: { sessionChange, requestCurrentUserInfo, error },\n+ payload: { sessionChange, preRequestUserState, error },\n});\n}\n@@ -260,7 +263,7 @@ function bindCookieAndUtilsIntoFetchJSON(params: BindServerCallsParams): FetchJS\n) => setNewSession(\ndispatch,\nsessionChange,\n- currentUserInfo,\n+ { currentUserInfo, cookie, sessionID },\nerror,\n);\n// This function gets called before fetchJSON sends a request, to make sure\n" }, { "change_type": "MODIFY", "old_path": "native/crash.react.js", "new_path": "native/crash.react.js", "diff": "@@ -10,9 +10,9 @@ import type { AppState } from './redux/redux-setup';\nimport type { ErrorData } from 'lib/types/report-types';\nimport type { LogOutResult } from 'lib/types/account-types';\nimport {\n- type CurrentUserInfo,\n- currentUserPropType,\n-} from 'lib/types/user-types';\n+ type PreRequestUserState,\n+ preRequestUserStatePropType,\n+} from 'lib/types/session-types';\nimport * as React from 'react';\nimport {\n@@ -36,6 +36,7 @@ import sleep from 'lib/utils/sleep';\nimport { reduxLogger } from 'lib/utils/redux-logger';\nimport { logOutActionTypes, logOut } from 'lib/actions/user-actions';\nimport { sanitizeAction, sanitizeState } from 'lib/utils/sanitization';\n+import { preRequestUserStateSelector } from 'lib/selectors/account-selectors';\nimport Button from './components/button.react';\nimport { store } from './redux/redux-setup';\n@@ -49,14 +50,14 @@ const errorTitles = [\ntype Props = {\nerrorData: $ReadOnlyArray<ErrorData>,\n// Redux state\n- currentUserInfo: ?CurrentUserInfo,\n+ preRequestUserState: PreRequestUserState,\n// Redux dispatch functions\ndispatchActionPromise: DispatchActionPromise,\n// async functions that hit server APIs\nsendReport: (\nrequest: ClientReportCreationRequest,\n) => Promise<ReportCreationResponse>,\n- logOut: (requestCurrentUserInfo: ?CurrentUserInfo) => Promise<LogOutResult>,\n+ logOut: (preRequestUserState: PreRequestUserState) => Promise<LogOutResult>,\n};\ntype State = {|\nerrorReportID: ?string,\n@@ -71,7 +72,7 @@ class Crash extends React.PureComponent<Props, State> {\ncomponentStack: PropTypes.string.isRequired,\n}),\n})).isRequired,\n- currentUserInfo: currentUserPropType,\n+ preRequestUserState: preRequestUserStatePropType.isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\nsendReport: PropTypes.func.isRequired,\nlogOut: PropTypes.func.isRequired,\n@@ -195,7 +196,7 @@ class Crash extends React.PureComponent<Props, State> {\nasync logOutAndExit() {\ntry {\n- await this.props.logOut(this.props.currentUserInfo);\n+ await this.props.logOut(this.props.preRequestUserState);\n} catch (e) { }\ngetPersistor().purge();\nExitApp.exitApp();\n@@ -277,7 +278,7 @@ const styles = StyleSheet.create({\nexport default connect(\n(state: AppState) => ({\n- currentUserInfo: state.currentUserInfo,\n+ preRequestUserState: preRequestUserStateSelector(state),\n}),\n{ sendReport, logOut },\n)(Crash);\n" }, { "change_type": "MODIFY", "old_path": "native/more/delete-account.react.js", "new_path": "native/more/delete-account.react.js", "diff": "@@ -9,9 +9,9 @@ import type { LogOutResult } from 'lib/types/account-types';\nimport { type GlobalTheme, globalThemePropType } from '../types/themes';\nimport type { Styles } from '../types/styles';\nimport {\n- type CurrentUserInfo,\n- currentUserPropType,\n-} from 'lib/types/user-types';\n+ type PreRequestUserState,\n+ preRequestUserStatePropType,\n+} from 'lib/types/session-types';\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\n@@ -33,6 +33,7 @@ import {\ndeleteAccount,\n} from 'lib/actions/user-actions';\nimport { createLoadingStatusSelector } from 'lib/selectors/loading-selectors';\n+import { preRequestUserStateSelector } from 'lib/selectors/account-selectors';\nimport Button from '../components/button.react';\nimport OnePasswordButton from '../components/one-password-button.react';\n@@ -43,7 +44,8 @@ type Props = {|\nnavigation: NavigationScreenProp<*>,\n// Redux state\nloadingStatus: LoadingStatus,\n- currentUserInfo: ?CurrentUserInfo,\n+ username: ?string,\n+ preRequestUserState: PreRequestUserState,\nactiveTheme: ?GlobalTheme,\nstyles: Styles,\n// Redux dispatch functions\n@@ -51,7 +53,7 @@ type Props = {|\n// async functions that hit server APIs\ndeleteAccount: (\npassword: string,\n- requestCurrentUserInfo: ?CurrentUserInfo,\n+ preRequestUserState: PreRequestUserState,\n) => Promise<LogOutResult>,\n|};\ntype State = {|\n@@ -65,7 +67,8 @@ class DeleteAccount extends React.PureComponent<Props, State> {\nnavigate: PropTypes.func.isRequired,\n}).isRequired,\nloadingStatus: loadingStatusPropType.isRequired,\n- currentUserInfo: currentUserPropType,\n+ username: PropTypes.string,\n+ preRequestUserState: preRequestUserStatePropType.isRequired,\nactiveTheme: globalThemePropType,\nstyles: PropTypes.objectOf(PropTypes.object).isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\n@@ -106,12 +109,6 @@ class DeleteAccount extends React.PureComponent<Props, State> {\n}\n}\n- get username() {\n- return this.props.currentUserInfo && !this.props.currentUserInfo.anonymous\n- ? this.props.currentUserInfo.username\n- : undefined;\n- }\n-\nrender() {\nlet onePasswordButton = null;\nif (this.state.onePasswordSupported) {\n@@ -199,12 +196,12 @@ class DeleteAccount extends React.PureComponent<Props, State> {\nasync deleteAccount() {\ntry {\n- if (this.username) {\n- await deleteNativeCredentialsFor(this.username);\n+ if (this.props.username) {\n+ await deleteNativeCredentialsFor(this.props.username);\n}\nconst result = await this.props.deleteAccount(\nthis.state.password,\n- this.props.currentUserInfo,\n+ this.props.preRequestUserState,\n);\nreturn result;\n} catch (e) {\n@@ -309,7 +306,10 @@ const loadingStatusSelector = createLoadingStatusSelector(\nexport default connect(\n(state: AppState) => ({\nloadingStatus: loadingStatusSelector(state),\n- currentUserInfo: state.currentUserInfo,\n+ username: state.currentUserInfo && !state.currentUserInfo.anonymous\n+ ? state.currentUserInfo.username\n+ : undefined,\n+ preRequestUserState: preRequestUserStateSelector(state),\nactiveTheme: state.globalThemeInfo.activeTheme,\nstyles: stylesSelector(state),\n}),\n" }, { "change_type": "MODIFY", "old_path": "native/more/more-screen.react.js", "new_path": "native/more/more-screen.react.js", "diff": "@@ -14,6 +14,10 @@ import {\ntype CurrentUserInfo,\ncurrentUserPropType,\n} from 'lib/types/user-types';\n+import {\n+ type PreRequestUserState,\n+ preRequestUserStatePropType,\n+} from 'lib/types/session-types';\nimport * as React from 'react';\nimport {\n@@ -37,6 +41,7 @@ import {\nresendVerificationEmail,\n} from 'lib/actions/user-actions';\nimport { createLoadingStatusSelector } from 'lib/selectors/loading-selectors';\n+import { preRequestUserStateSelector } from 'lib/selectors/account-selectors';\nimport {\ngetNativeSharedWebCredentials,\n@@ -58,13 +63,14 @@ type Props = {\nnavigation: NavigationScreenProp<*>,\n// Redux state\ncurrentUserInfo: ?CurrentUserInfo,\n+ preRequestUserState: PreRequestUserState,\nresendVerificationLoadingStatus: LoadingStatus,\ncolors: Colors,\nstyles: Styles,\n// Redux dispatch functions\ndispatchActionPromise: DispatchActionPromise,\n// async functions that hit server APIs\n- logOut: (requestCurrentUserInfo: ?CurrentUserInfo) => Promise<LogOutResult>,\n+ logOut: (preRequestUserState: PreRequestUserState) => Promise<LogOutResult>,\nresendVerificationEmail: () => Promise<void>,\n};\nclass MoreScreen extends React.PureComponent<Props> {\n@@ -74,6 +80,7 @@ class MoreScreen extends React.PureComponent<Props> {\nnavigate: PropTypes.func.isRequired,\n}).isRequired,\ncurrentUserInfo: currentUserPropType,\n+ preRequestUserState: preRequestUserStatePropType.isRequired,\nresendVerificationLoadingStatus: loadingStatusPropType.isRequired,\ncolors: colorsPropType.isRequired,\nstyles: PropTypes.objectOf(PropTypes.object).isRequired,\n@@ -306,7 +313,7 @@ class MoreScreen extends React.PureComponent<Props> {\n}\nlogOut() {\n- return this.props.logOut(this.props.currentUserInfo);\n+ return this.props.logOut(this.props.preRequestUserState);\n}\nasync logOutAndDeleteNativeCredentials() {\n@@ -493,6 +500,7 @@ const resendVerificationLoadingStatusSelector = createLoadingStatusSelector(\nexport default connect(\n(state: AppState) => ({\ncurrentUserInfo: state.currentUserInfo,\n+ preRequestUserState: preRequestUserStateSelector(state),\nresendVerificationLoadingStatus:\nresendVerificationLoadingStatusSelector(state),\ncolors: colorsSelector(state),\n" }, { "change_type": "MODIFY", "old_path": "native/redux/redux-setup.js", "new_path": "native/redux/redux-setup.js", "diff": "@@ -40,7 +40,7 @@ import {\n} from '../types/camera';\nimport type { Orientations } from 'react-native-orientation-locker';\n-import React from 'react';\n+import * as React from 'react';\nimport invariant from 'invariant';\nimport thunk from 'redux-thunk';\nimport {\n@@ -198,23 +198,23 @@ function reducer(state: AppState = defaultState, action: *) {\nif (\n(action.type === setNewSessionActionType &&\ninvalidSessionDowngrade(\n- state.currentUserInfo,\n+ state,\naction.payload.sessionChange.currentUserInfo,\n- action.payload.requestCurrentUserInfo,\n+ action.payload.preRequestUserState,\n)\n) ||\n(action.type === logOutActionTypes.success &&\ninvalidSessionDowngrade(\n- state.currentUserInfo,\n+ state,\naction.payload.currentUserInfo,\n- action.payload.requestCurrentUserInfo,\n+ action.payload.preRequestUserState,\n)\n) ||\n(action.type === deleteAccountActionTypes.success &&\ninvalidSessionDowngrade(\n- state.currentUserInfo,\n+ state,\naction.payload.currentUserInfo,\n- action.payload.requestCurrentUserInfo,\n+ action.payload.preRequestUserState,\n)\n)\n) {\n" }, { "change_type": "MODIFY", "old_path": "native/socket.react.js", "new_path": "native/socket.react.js", "diff": "@@ -5,6 +5,7 @@ import type { AppState } from './redux/redux-setup';\nimport { connect } from 'lib/utils/redux-utils';\nimport { logOut } from 'lib/actions/user-actions';\nimport Socket from 'lib/socket/socket.react';\n+import { preRequestUserStateSelector } from 'lib/selectors/account-selectors';\nimport {\nopenSocketSelector,\n@@ -37,7 +38,7 @@ export default connect(\ncurrentCalendarQuery: nativeCalendarQuery(state),\nhasWiFi: state.connectivity.hasWiFi,\nfrozen: state.frozen,\n- currentUserInfo: state.currentUserInfo,\n+ preRequestUserState: preRequestUserStateSelector(state),\n};\n},\n{ logOut },\n" }, { "change_type": "MODIFY", "old_path": "web/account-bar.react.js", "new_path": "web/account-bar.react.js", "diff": "@@ -8,6 +8,10 @@ import {\ntype CurrentUserInfo,\ncurrentUserPropType,\n} from 'lib/types/user-types';\n+import {\n+ type PreRequestUserState,\n+ preRequestUserStatePropType,\n+} from 'lib/types/session-types';\nimport * as React from 'react';\nimport invariant from 'invariant';\n@@ -15,6 +19,7 @@ import PropTypes from 'prop-types';\nimport { logOut, logOutActionTypes } from 'lib/actions/user-actions';\nimport { connect } from 'lib/utils/redux-utils';\n+import { preRequestUserStateSelector } from 'lib/selectors/account-selectors';\nimport css from './style.css';\nimport LogInModal from './modals/account/log-in-modal.react';\n@@ -27,10 +32,11 @@ type Props = {|\nsetModal: (modal: ?React.Node) => void,\n// Redux state\ncurrentUserInfo: ?CurrentUserInfo,\n+ preRequestUserState: PreRequestUserState,\n// Redux dispatch functions\ndispatchActionPromise: DispatchActionPromise,\n// async functions that hit server APIs\n- logOut: (requestCurrentUserInfo: ?CurrentUserInfo) => Promise<LogOutResult>,\n+ logOut: (preRequestUserState: PreRequestUserState) => Promise<LogOutResult>,\n|};\ntype State = {|\nexpanded: bool,\n@@ -40,6 +46,7 @@ class AccountBar extends React.PureComponent<Props, State> {\nstatic propTypes = {\nsetModal: PropTypes.func.isRequired,\ncurrentUserInfo: currentUserPropType,\n+ preRequestUserState: preRequestUserStatePropType.isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\nlogOut: PropTypes.func.isRequired,\n};\n@@ -158,7 +165,7 @@ class AccountBar extends React.PureComponent<Props, State> {\nevent.preventDefault();\nthis.props.dispatchActionPromise(\nlogOutActionTypes,\n- this.props.logOut(this.props.currentUserInfo),\n+ this.props.logOut(this.props.preRequestUserState),\n);\nthis.setState({ expanded: false });\n}\n@@ -184,6 +191,7 @@ class AccountBar extends React.PureComponent<Props, State> {\nexport default connect(\n(state: AppState) => ({\ncurrentUserInfo: state.currentUserInfo,\n+ preRequestUserState: preRequestUserStateSelector(state),\n}),\n{ logOut },\n)(AccountBar);\n" }, { "change_type": "MODIFY", "old_path": "web/modals/account/user-settings-modal.react.js", "new_path": "web/modals/account/user-settings-modal.react.js", "diff": "@@ -12,6 +12,10 @@ import type {\nLogOutResult,\nChangeUserSettingsResult,\n} from 'lib/types/account-types';\n+import {\n+ type PreRequestUserState,\n+ preRequestUserStatePropType,\n+} from 'lib/types/session-types';\nimport * as React from 'react';\nimport invariant from 'invariant';\n@@ -29,6 +33,7 @@ import {\n} from 'lib/actions/user-actions';\nimport { connect } from 'lib/utils/redux-utils';\nimport { createLoadingStatusSelector } from 'lib/selectors/loading-selectors';\n+import { preRequestUserStateSelector } from 'lib/selectors/account-selectors';\nimport css from '../../style.css';\nimport Modal from '../modal.react';\n@@ -66,13 +71,14 @@ type Props = {\nsetModal: (modal: ?React.Node) => void,\n// Redux state\ncurrentUserInfo: ?CurrentUserInfo,\n+ preRequestUserState: PreRequestUserState,\ninputDisabled: bool,\n// Redux dispatch functions\ndispatchActionPromise: DispatchActionPromise,\n// async functions that hit server APIs\ndeleteAccount: (\npassword: string,\n- requestCurrentUserInfo: ?CurrentUserInfo,\n+ preRequestUserState: PreRequestUserState,\n) => Promise<LogOutResult>,\nchangeUserSettings: (\naccountUpdate: AccountUpdate,\n@@ -94,6 +100,7 @@ class UserSettingsModal extends React.PureComponent<Props, State> {\nstatic propTypes = {\nsetModal: PropTypes.func.isRequired,\ncurrentUserInfo: currentUserPropType,\n+ preRequestUserState: preRequestUserStatePropType.isRequired,\ninputDisabled: PropTypes.bool.isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\ndeleteAccount: PropTypes.func.isRequired,\n@@ -467,7 +474,7 @@ class UserSettingsModal extends React.PureComponent<Props, State> {\ntry {\nconst response = await this.props.deleteAccount(\nthis.state.currentPassword,\n- this.props.currentUserInfo,\n+ this.props.preRequestUserState,\n);\nthis.clearModal();\nreturn response;\n@@ -508,6 +515,7 @@ const resendVerificationEmailLoadingStatusSelector\nexport default connect(\n(state: AppState) => ({\ncurrentUserInfo: state.currentUserInfo,\n+ preRequestUserState: preRequestUserStateSelector(state),\ninputDisabled: deleteAccountLoadingStatusSelector(state) === \"loading\" ||\nchangeUserSettingsLoadingStatusSelector(state) === \"loading\" ||\nresendVerificationEmailLoadingStatusSelector(state) === \"loading\",\n" }, { "change_type": "MODIFY", "old_path": "web/redux-setup.js", "new_path": "web/redux-setup.js", "diff": "@@ -104,9 +104,9 @@ export function reducer(oldState: AppState | void, action: Action) {\n);\n} else if (action.type === setNewSessionActionType) {\nif (invalidSessionDowngrade(\n- oldState.currentUserInfo,\n+ oldState,\naction.payload.sessionChange.currentUserInfo,\n- action.payload.requestCurrentUserInfo,\n+ action.payload.preRequestUserState,\n)) {\nreturn oldState;\n}\n@@ -117,16 +117,16 @@ export function reducer(oldState: AppState | void, action: Action) {\n} else if (\n(action.type === logOutActionTypes.success &&\ninvalidSessionDowngrade(\n- oldState.currentUserInfo,\n+ oldState,\naction.payload.currentUserInfo,\n- action.payload.requestCurrentUserInfo,\n+ action.payload.preRequestUserState,\n)\n) ||\n(action.type === deleteAccountActionTypes.success &&\ninvalidSessionDowngrade(\n- oldState.currentUserInfo,\n+ oldState,\naction.payload.currentUserInfo,\n- action.payload.requestCurrentUserInfo,\n+ action.payload.preRequestUserState,\n)\n)\n) {\n" }, { "change_type": "MODIFY", "old_path": "web/socket.react.js", "new_path": "web/socket.react.js", "diff": "@@ -5,6 +5,7 @@ import type { AppState } from './redux-setup';\nimport { connect } from 'lib/utils/redux-utils';\nimport { logOut } from 'lib/actions/user-actions';\nimport Socket from 'lib/socket/socket.react';\n+import { preRequestUserStateSelector } from 'lib/selectors/account-selectors';\nimport {\nopenSocketSelector,\n@@ -36,7 +37,7 @@ export default connect(\ncurrentCalendarQuery: webCalendarQuery(state),\nhasWiFi: true,\nfrozen: false,\n- currentUserInfo: state.currentUserInfo,\n+ preRequestUserState: preRequestUserStateSelector(state),\n};\n},\n{ logOut },\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Compare cookie and sessionID when determining if session downgrade is invalid
129,187
24.12.2019 18:21:15
18,000
84e9bfa5a26a56fe62031fbb577365357dbe3cb1
[native] Hide MediaGalleryKeyboard when ChatInputState unmounts
[ { "change_type": "MODIFY", "old_path": "native/keyboard/keyboard-input-host.react.js", "new_path": "native/keyboard/keyboard-input-host.react.js", "diff": "@@ -26,11 +26,13 @@ import { styleSelector } from '../themes/colors';\nimport {\nmediaGalleryKeyboardName,\n} from '../media/media-gallery-keyboard.react';\n+import { activeMessageListSelector } from '../selectors/nav-selectors';\ntype Props = {|\ntextInputRef: ?TextInput,\n// Redux state\nstyles: Styles,\n+ activeMessageList: ?string,\n// withKeyboardState\nkeyboardState: ?KeyboardState,\n// withChatInput\n@@ -41,10 +43,20 @@ class KeyboardInputHost extends React.PureComponent<Props> {\nstatic propTypes = {\ntextInputRef: PropTypes.instanceOf(TextInput),\nstyles: PropTypes.objectOf(PropTypes.object).isRequired,\n+ activeMessageList: PropTypes.string,\nkeyboardState: keyboardStatePropType,\nchatInputState: chatInputStatePropType,\n};\n+ componentDidUpdate(prevProps: Props) {\n+ if (\n+ prevProps.activeMessageList &&\n+ this.props.activeMessageList !== prevProps.activeMessageList\n+ ) {\n+ this.hideMediaGallery();\n+ }\n+ }\n+\nstatic mediaGalleryOpen(props: Props) {\nconst { keyboardState } = props;\nreturn !!(keyboardState && keyboardState.mediaGalleryOpen);\n@@ -120,4 +132,5 @@ const stylesSelector = styleSelector(styles);\nexport default connect((state: AppState) => ({\nstyles: stylesSelector(state),\n+ activeMessageList: activeMessageListSelector(state),\n}))(withKeyboardState(withChatInputState(KeyboardInputHost)));\n" }, { "change_type": "MODIFY", "old_path": "native/keyboard/keyboard-state-container.react.js", "new_path": "native/keyboard/keyboard-state-container.react.js", "diff": "@@ -64,6 +64,7 @@ class KeyboardStateContainer extends React.PureComponent<Props, State> {\ndismissKeyboard = () => {\nKeyboardUtils.dismiss();\n+ this.hideMediaGallery();\n}\ndismissKeyboardIfShowing = () => {\n" }, { "change_type": "MODIFY", "old_path": "native/selectors/nav-selectors.js", "new_path": "native/selectors/nav-selectors.js", "diff": "@@ -125,9 +125,10 @@ const lightboxTransitioningSelector: (state: AppState) => bool = createSelector(\n},\n);\n-const activeThreadSelector: (state: AppState) => ?string = createSelector(\n- (state: AppState) => state.navInfo.navigationState,\n- (navigationState: NavigationState): ?string => {\n+function activeThread(\n+ navigationState: NavigationState,\n+ validRouteNames: $ReadOnlyArray<string>,\n+): ?string {\nlet rootIndex = navigationState.index;\nlet currentRootSubroute = navigationState.routes[rootIndex];\nwhile (currentRootSubroute.routeName !== AppRouteName) {\n@@ -151,14 +152,26 @@ const activeThreadSelector: (state: AppState) => ?string = createSelector(\n}\nconst chatRoute = assertNavigationRouteNotLeafNode(currentTabSubroute);\nconst currentChatSubroute = chatRoute.routes[chatRoute.index];\n- if (\n- currentChatSubroute.routeName !== MessageListRouteName &&\n- currentChatSubroute.routeName !== ThreadSettingsRouteName\n- ) {\n+ if (!validRouteNames.includes(currentChatSubroute.routeName)) {\nreturn null;\n}\nreturn getThreadIDFromParams(currentChatSubroute);\n- },\n+}\n+\n+const activeThreadSelector: (state: AppState) => ?string = createSelector(\n+ (state: AppState) => state.navInfo.navigationState,\n+ (navigationState: NavigationState): ?string => activeThread(\n+ navigationState,\n+ [ MessageListRouteName, ThreadSettingsRouteName ],\n+ ),\n+);\n+\n+const activeMessageListSelector: (state: AppState) => ?string = createSelector(\n+ (state: AppState) => state.navInfo.navigationState,\n+ (navigationState: NavigationState): ?string => activeThread(\n+ navigationState,\n+ [ MessageListRouteName ],\n+ ),\n);\nconst appCanRespondToBackButtonSelector: (\n@@ -233,6 +246,7 @@ export {\nbackgroundIsDarkSelector,\nlightboxTransitioningSelector,\nactiveThreadSelector,\n+ activeMessageListSelector,\nappCanRespondToBackButtonSelector,\ncalendarActiveSelector,\nnativeCalendarQuery,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Hide MediaGalleryKeyboard when ChatInputState unmounts
129,187
26.12.2019 13:26:44
18,000
c1e0d69723c869968c985ab4b3071f5221ae218a
[lib] Don't persist queuedActivityUpdates until persisting navInfo
[ { "change_type": "MODIFY", "old_path": "lib/reducers/connection-reducer.js", "new_path": "lib/reducers/connection-reducer.js", "diff": "@@ -105,6 +105,9 @@ export default function reduceConnectionInfo(\nreturn {\n...action.payload.connection,\nstatus: \"connecting\",\n+ queuedActivityUpdates: action.payload.navInfo\n+ ? action.payload.connection.queuedActivityUpdates\n+ : [],\nlateResponses: [],\nshowDisconnectedBar: false,\n};\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[lib] Don't persist queuedActivityUpdates until persisting navInfo
129,187
26.12.2019 13:42:07
18,000
8b7fcabd9afb1808fdc325a7f537e0f8c1ac0d71
[native] Don't set unread to false in validateState for background action types (Unless it's clear that the app is in the foreground)
[ { "change_type": "MODIFY", "old_path": "native/redux/action-types.js", "new_path": "native/redux/action-types.js", "diff": "// @flow\n+import { saveMessagesActionType } from 'lib/actions/message-actions';\n+\nexport const handleURLActionType = \"HANDLE_URL\";\nexport const navigateToAppActionType = \"NAVIGATE_TO_APP\";\nexport const resetUserStateActionType = \"RESET_USER_STATE\";\n@@ -16,3 +18,9 @@ export const updateConnectivityActiveType = \"UPDATE_CONNECTIVITY\";\nexport const updateThemeInfoActionType = \"UPDATE_THEME_INFO\";\nexport const updateDeviceCameraInfoActionType = \"UPDATE_DEVICE_CAMERA_INFO\";\nexport const updateDeviceOrientationActionType = \"UPDATE_DEVICE_ORIENTATION\";\n+\n+export const backgroundActionTypes: Set<string> = new Set([\n+ saveMessagesActionType,\n+ recordAndroidNotificationActionType,\n+ rescindAndroidNotificationActionType,\n+]);\n" }, { "change_type": "MODIFY", "old_path": "native/redux/redux-setup.js", "new_path": "native/redux/redux-setup.js", "diff": "@@ -62,10 +62,7 @@ import {\nimport Orientation from 'react-native-orientation-locker';\nimport baseReducer from 'lib/reducers/master-reducer';\n-import {\n- sendTextMessageActionTypes,\n- saveMessagesActionType,\n-} from 'lib/actions/message-actions';\n+import { sendTextMessageActionTypes } from 'lib/actions/message-actions';\nimport { reduxLoggerMiddleware } from 'lib/utils/redux-logger';\nimport { getConfig } from 'lib/utils/config';\nimport { invalidSessionDowngrade } from 'lib/shared/account-utils';\n@@ -86,6 +83,7 @@ import {\nupdateThemeInfoActionType,\nupdateDeviceCameraInfoActionType,\nupdateDeviceOrientationActionType,\n+ backgroundActionTypes,\n} from './action-types';\nimport {\ndefaultNavInfo,\n@@ -395,7 +393,7 @@ function validateState(\nactiveThread &&\n(NativeAppState.currentState === \"active\" ||\n(appLastBecameInactive + 10000 < Date.now() &&\n- action.type !== saveMessagesActionType)) &&\n+ !backgroundActionTypes.has(action.type))) &&\nstate.threadStore.threadInfos[activeThread].currentUser.unread\n) {\n// Makes sure a currently focused thread is never unread. Note that we\n@@ -403,8 +401,8 @@ function validateState(\n// changed to inactive more than 10 seconds ago. This is because there is a\n// delay when NativeAppState is updating in response to a foreground, and\n// actions don't get processed more than 10 seconds after a backgrounding\n- // anyways. However we don't consider this for saveMessagesActionType, since\n- // that action can be expected to happen while the app is backgrounded.\n+ // anyways. However we don't consider this for action types that can be\n+ // expected to happen while the app is backgrounded.\nstate = {\n...state,\nthreadStore: {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Don't set unread to false in validateState for background action types (Unless it's clear that the app is in the foreground)
129,187
16.01.2020 13:59:08
-32,400
6daacd841ca6aa309008b3b44f71001477d2c5c9
[web] Don't upload any files in a batch if one fails validation
[ { "change_type": "MODIFY", "old_path": "web/chat/chat-input-state-container.react.js", "new_path": "web/chat/chat-input-state-container.react.js", "diff": "@@ -343,13 +343,16 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\nasync appendFiles(threadID: string, files: $ReadOnlyArray<File>) {\nconst validationResults = await Promise.all(files.map(validateFile));\nconst newUploads = [];\n+ const { setModal } = this.props;\nfor (let result of validationResults) {\nif (!result) {\n- continue;\n+ setModal(<InvalidUploadModal setModal={setModal} />);\n+ return;\n}\nconst { file, mediaType, dimensions } = result;\nif (!dimensions) {\n- continue;\n+ setModal(<InvalidUploadModal setModal={setModal} />);\n+ return;\n}\nnewUploads.push({\nlocalID: `localUpload${nextLocalUploadID++}`,\n@@ -366,7 +369,6 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\n});\n}\nif (newUploads.length === 0) {\n- const { setModal } = this.props;\nsetModal(<InvalidUploadModal setModal={setModal} />);\nreturn;\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[web] Don't upload any files in a batch if one fails validation
129,187
16.01.2020 13:59:31
-32,400
1f3680da0125400f1a8f85621e3510bad7c73ec8
[server] Maintain own list of valid MIME types
[ { "change_type": "MODIFY", "old_path": "server/src/uploads/media-utils.js", "new_path": "server/src/uploads/media-utils.js", "diff": "@@ -8,6 +8,12 @@ import { fileInfoFromData } from 'lib/utils/file-utils';\nconst fiveMegabytes = 5 * 1024 * 1024;\n+const allowedMimeTypes = new Set([\n+ \"image/png\",\n+ \"image/jpeg\",\n+ \"image/gif\",\n+]);\n+\nasync function validateAndConvert(\ninitialBuffer: Buffer,\ninitialName: string,\n@@ -19,7 +25,7 @@ async function validateAndConvert(\n}\nconst { mime } = fileInfo;\n- if (mime === \"image/heic\") {\n+ if (!allowedMimeTypes.has(mime)) {\n// This should've gotten converted on the client\nreturn null;\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Maintain own list of valid MIME types
129,187
16.01.2020 14:00:00
-32,400
6cf94203aaa7f181b4d6432b281d9026409250b2
[web] Maintain own list of valid MIME types
[ { "change_type": "MODIFY", "old_path": "web/utils/media-utils.js", "new_path": "web/utils/media-utils.js", "diff": "import type { MediaType, Dimensions } from 'lib/types/media-types';\n-import {\n- fileInfoFromData,\n- mimeTypesToMediaTypes,\n-} from 'lib/utils/file-utils';\n+import { fileInfoFromData } from 'lib/utils/file-utils';\nfunction blobToArrayBuffer(blob: Blob): Promise<ArrayBuffer> {\nconst fileReader = new FileReader();\n@@ -48,6 +45,9 @@ async function validateFile(file: File): Promise<?FileValidationResult> {\nreturn null;\n}\nconst { name, mime, mediaType } = fileInfo;\n+ if (!allowedMimeTypes.has(mime)) {\n+ return null;\n+ }\nlet dimensions = null;\nif (mediaType === \"photo\") {\ndimensions = await getPhotoDimensions(file);\n@@ -58,7 +58,13 @@ async function validateFile(file: File): Promise<?FileValidationResult> {\nreturn { file: fixedFile, mediaType, dimensions };\n}\n-const allowedMimeTypeString = Object.keys(mimeTypesToMediaTypes).join(',');\n+const allowedMimeTypeArray = [\n+ \"image/png\",\n+ \"image/jpeg\",\n+ \"image/gif\",\n+];\n+const allowedMimeTypes = new Set(allowedMimeTypeArray);\n+const allowedMimeTypeString = allowedMimeTypeArray.join(',');\nfunction preloadImage(uri: string): Promise<Dimensions> {\nreturn new Promise((resolve, reject) => {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[web] Maintain own list of valid MIME types
129,187
16.01.2020 14:39:39
-32,400
1d0d69190c33db6e4e0872a4a61850a5b75680a8
[native] react-native-progress@^4.0.3
[ { "change_type": "MODIFY", "old_path": "native/ios/Podfile", "new_path": "native/ios/Podfile", "diff": "@@ -16,7 +16,6 @@ target 'SquadCal' do\npod 'React-RCTText', :path => '../../node_modules/react-native/Libraries/Text'\npod 'React-RCTVibration', :path => '../../node_modules/react-native/Libraries/Vibration'\npod 'React-RCTWebSocket', :path => '../../node_modules/react-native/Libraries/WebSocket'\n- pod 'React-ART', :path => '../../node_modules/react-native/Libraries/ART'\npod 'React-cxxreact', :path => '../../node_modules/react-native/ReactCommon/cxxreact'\npod 'React-jsi', :path => '../../node_modules/react-native/ReactCommon/jsi'\n" }, { "change_type": "MODIFY", "old_path": "native/ios/Podfile.lock", "new_path": "native/ios/Podfile.lock", "diff": "@@ -42,8 +42,6 @@ PODS:\n- React-RCTText (= 0.60.6)\n- React-RCTVibration (= 0.60.6)\n- React-RCTWebSocket (= 0.60.6)\n- - React-ART (0.60.6):\n- - React-Core (= 0.60.6)\n- React-Core (0.60.6):\n- Folly (= 2018.10.22.00)\n- React-cxxreact (= 0.60.6)\n@@ -136,6 +134,8 @@ PODS:\n- React-Core (= 0.60.6)\n- React-RCTWebSocket (0.60.6):\n- React-Core (= 0.60.6)\n+ - ReactNativeART (1.1.2):\n+ - React\n- ReactNativeDarkMode (0.2.0-rc.1):\n- React\n- ReactNativeKeyboardInput (6.0.0):\n@@ -177,7 +177,6 @@ DEPENDENCIES:\n- lottie-ios (from `../../node_modules/lottie-ios`)\n- lottie-react-native (from `../../node_modules/lottie-react-native`)\n- React (from `../../node_modules/react-native/`)\n- - React-ART (from `../../node_modules/react-native/Libraries/ART`)\n- React-Core (from `../../node_modules/react-native/React`)\n- React-cxxreact (from `../../node_modules/react-native/ReactCommon/cxxreact`)\n- React-DevSupport (from `../../node_modules/react-native/React`)\n@@ -206,6 +205,7 @@ DEPENDENCIES:\n- React-RCTText (from `../../node_modules/react-native/Libraries/Text`)\n- React-RCTVibration (from `../../node_modules/react-native/Libraries/Vibration`)\n- React-RCTWebSocket (from `../../node_modules/react-native/Libraries/WebSocket`)\n+ - \"ReactNativeART (from `../../node_modules/@react-native-community/art`)\"\n- ReactNativeDarkMode (from `../../node_modules/react-native-dark-mode`)\n- ReactNativeKeyboardInput (from `../../node_modules/react-native-keyboard-input`)\n- \"RNCAsyncStorage (from `../../node_modules/@react-native-community/async-storage`)\"\n@@ -220,7 +220,7 @@ DEPENDENCIES:\n- yoga (from `../../node_modules/react-native/ReactCommon/yoga`)\nSPEC REPOS:\n- https://github.com/cocoapods/specs.git:\n+ https://github.com/CocoaPods/Specs.git:\n- 1PasswordExtension\n- boost-for-react-native\n- DVAssetLoaderDelegate\n@@ -245,8 +245,6 @@ EXTERNAL SOURCES:\n:path: \"../../node_modules/lottie-react-native\"\nReact:\n:path: \"../../node_modules/react-native/\"\n- React-ART:\n- :path: \"../../node_modules/react-native/Libraries/ART\"\nReact-Core:\n:path: \"../../node_modules/react-native/React\"\nReact-cxxreact:\n@@ -303,6 +301,8 @@ EXTERNAL SOURCES:\n:path: \"../../node_modules/react-native/Libraries/Vibration\"\nReact-RCTWebSocket:\n:path: \"../../node_modules/react-native/Libraries/WebSocket\"\n+ ReactNativeART:\n+ :path: \"../../node_modules/@react-native-community/art\"\nReactNativeDarkMode:\n:path: \"../../node_modules/react-native-dark-mode\"\nReactNativeKeyboardInput:\n@@ -341,7 +341,6 @@ SPEC CHECKSUMS:\nlottie-react-native: b123a79529cc732201091f585c62c89bb4747252\nmobile-ffmpeg-min: 05ebe3998721155274ae50466b5223d3637a92ab\nReact: 68e7f8dfc27729eade18423072a143120f2f32ab\n- React-ART: b5b51652ddd2096f23c3c045ce4f4309b2aafcf6\nReact-Core: fc9dace551f6c8c1007dd2d3cb1bc10c90a01d3e\nReact-cxxreact: abe59014fce932d41a08bf1aa5dcad9ca8f0a2c5\nReact-DevSupport: b0da2fd9ad4ffb25561bf2a328ab84f78f871bdd\n@@ -370,6 +369,7 @@ SPEC CHECKSUMS:\nReact-RCTText: d91537e29e38dc69cf09cbca0875cf5dc7402da6\nReact-RCTVibration: 7655d72dfb919dd6d8e135ca108a5a2bd9fcd7b4\nReact-RCTWebSocket: 7cd2c8d0f8ddd680dc76404defba7ab1f56b83af\n+ ReactNativeART: c580fba2f7d188d8fa4418ce78db8130654ed10f\nReactNativeDarkMode: 88317ff05ba95fd063dd347ad32f8c4cefd3166c\nReactNativeKeyboardInput: c37e26821519869993b3b61844350feb9177ff37\nRNCAsyncStorage: 60a80e72d95bf02a01cace55d3697d9724f0d77f\n@@ -386,6 +386,6 @@ SPEC CHECKSUMS:\nSPTPersistentCache: df36ea46762d7cf026502bbb86a8b79d0080dff4\nyoga: 5079887aa3e4c62142d6bcee493022643ee4d730\n-PODFILE CHECKSUM: bef973e63f300f7e85c0d1f71f5d64ee8926e9e4\n+PODFILE CHECKSUM: edddd963d5b3cf05676bab073f5e73501d9b163f\n-COCOAPODS: 1.7.5\n+COCOAPODS: 1.8.4\n" }, { "change_type": "MODIFY", "old_path": "native/package.json", "new_path": "native/package.json", "diff": "\"react-test-renderer\": \"16.8.6\"\n},\n\"dependencies\": {\n+ \"@react-native-community/art\": \"^1.1.2\",\n\"@react-native-community/async-storage\": \"^1.6.1\",\n\"@react-native-community/cameraroll\": \"^1.3.0\",\n\"@react-native-community/netinfo\": \"^4.4.0\",\n\"react-native-notifications\": \"git+https://git@github.com/ashoat/react-native-notifications.git\",\n\"react-native-onepassword\": \"git+https://git@github.com/DriveWealth/react-native-onepassword.git#aed794d8c6f0f2560b62a0012449abf6f1b3576c\",\n\"react-native-orientation-locker\": \"^1.1.6\",\n- \"react-native-progress\": \"git+https://git@github.com/oblador/react-native-progress.git#984c9f2232d5c1a3f9c5481633d34ed6bc6ca476\",\n+ \"react-native-progress\": \"^4.0.3\",\n\"react-native-reanimated\": \"^1.3.0\",\n\"react-native-screens\": \"1.0.0-alpha.17\",\n\"react-native-segmented-control-tab\": \"^3.2.1\",\n" }, { "change_type": "MODIFY", "old_path": "yarn.lock", "new_path": "yarn.lock", "diff": "resolved \"https://registry.yarnpkg.com/@protobufjs/utf8/-/utf8-1.1.0.tgz#a777360b5b39a1a2e5106f8e858f2fd2d060c570\"\nintegrity sha1-p3c2C1s5oaLlEG+OhY8v0tBgxXA=\n+\"@react-native-community/art@^1.0.3\", \"@react-native-community/art@^1.1.2\":\n+ version \"1.1.2\"\n+ resolved \"https://registry.yarnpkg.com/@react-native-community/art/-/art-1.1.2.tgz#8d365ad5a12f83a0570ef83590f883a201f8e723\"\n+ integrity sha512-KCPWdrdkjMOjUjKjYhJUt628mjf+SyoopXPztFbPvSpMl6jI9Qs8fnxnrt8ITKJvt7Xy7K7y6Cn/Q5h1GgIwjQ==\n+ dependencies:\n+ art \"^0.10.3\"\n+ invariant \"^2.2.4\"\n+ prop-types \"^15.7.2\"\n+\n\"@react-native-community/async-storage@^1.6.1\":\nversion \"1.6.2\"\nresolved \"https://registry.yarnpkg.com/@react-native-community/async-storage/-/async-storage-1.6.2.tgz#a19ca7149c4dfe8216f2330e6b1ebfe2d075ef92\"\n@@ -2202,7 +2211,7 @@ arrify@^2.0.0:\nresolved \"https://registry.yarnpkg.com/arrify/-/arrify-2.0.1.tgz#c9655e9331e0abcd588d2a7cad7e9956f66701fa\"\nintegrity sha512-3duEwti880xqi4eAMN8AyR4a0ByT90zoYdLlevfrvU43vb0YZwZVfxOgxWrLXXXpyugL0hNZc9G6BiB5B3nUug==\n-art@^0.10.0:\n+art@^0.10.0, art@^0.10.3:\nversion \"0.10.3\"\nresolved \"https://registry.yarnpkg.com/art/-/art-0.10.3.tgz#b01d84a968ccce6208df55a733838c96caeeaea2\"\nintegrity sha512-HXwbdofRTiJT6qZX/FnchtldzJjS3vkLJxQilc3Xj+ma2MXjY4UAyQ0ls1XZYVnDvVIBiFZbC6QsvtW86TD6tQ==\n@@ -10162,10 +10171,12 @@ react-native-orientation-locker@^1.1.6:\nresolved \"https://registry.yarnpkg.com/react-native-orientation-locker/-/react-native-orientation-locker-1.1.6.tgz#7d66a62cdbf4dd1548522efe69a4e04af5daf929\"\nintegrity sha512-yXTC8KmKfhuEAh+gCOcehx0v4IjYapV0lJ6W1muafoISvxMsT+Cizzy+Iz78hQywVZTJNB/Xusl7WMXev7OxDQ==\n-\"react-native-progress@git+https://git@github.com/oblador/react-native-progress.git#984c9f2232d5c1a3f9c5481633d34ed6bc6ca476\":\n- version \"3.6.0\"\n- resolved \"git+https://git@github.com/oblador/react-native-progress.git#984c9f2232d5c1a3f9c5481633d34ed6bc6ca476\"\n+react-native-progress@^4.0.3:\n+ version \"4.0.3\"\n+ resolved \"https://registry.yarnpkg.com/react-native-progress/-/react-native-progress-4.0.3.tgz#0020a9ce9fa5cb14c7aac8f993b31f27a7ff2150\"\n+ integrity sha512-UMjY9W82bU/NLJ2PxkQ3rZFHZPzVTwKowuOfO1bWEainuyjAXwlcZdyQnZxuqIgHrLkZpg9ppdu+g2mflT86ZQ==\ndependencies:\n+ \"@react-native-community/art\" \"^1.0.3\"\nprop-types \"^15.7.2\"\nreact-native-reanimated@^1.3.0:\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] react-native-progress@^4.0.3
129,187
17.01.2020 16:00:33
-32,400
4239663a8374ad14c2d53590cbd31fbfc1b3509f
[native] Don't upload any files in a batch if one fails validation And show a message when the failure happens
[ { "change_type": "MODIFY", "old_path": "native/chat/chat-input-state-container.react.js", "new_path": "native/chat/chat-input-state-container.react.js", "diff": "@@ -43,6 +43,7 @@ import { createMediaMessageInfo } from 'lib/shared/message-utils';\nimport { ChatInputStateContext } from './chat-input-state';\nimport { validateMedia, convertMedia } from '../utils/media-utils';\n+import { displayActionResultModal } from '../navigation/action-result-modal';\nlet nextLocalUploadID = 0;\ntype MediaInfo = {|\n@@ -289,8 +290,7 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\n// Since we filter our MIME types in our calls to CameraRoll,\n// this should never be triggered\nconsole.log('unexpected MIME type found');\n- }\n- if (mediaInfos.length === 0) {\n+ displayActionResultModal(\"unsupported media type :(\");\nreturn;\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Don't upload any files in a batch if one fails validation And show a message when the failure happens
129,187
28.01.2020 13:41:00
28,800
236308ea40e3b8ec68463f65983153960780e53a
[native] Keep Dimensions together in ClientImageInfo
[ { "change_type": "MODIFY", "old_path": "native/chat/chat-input-state-container.react.js", "new_path": "native/chat/chat-input-state-container.react.js", "diff": "@@ -582,14 +582,14 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\nretryMedia.map(singleMedia => {\nif (singleMedia.type === \"photo\") {\nconst { dimensions, uri } = singleMedia;\n- return { type: \"photo\", ...dimensions, uri };\n+ return { type: \"photo\", dimensions, uri };\n} else {\nconst { dimensions, uri, filename } = singleMedia;\ninvariant(\nfilename,\n\"filename should be set on locally created Video\",\n);\n- return { type: \"video\", ...dimensions, uri, filename };\n+ return { type: \"video\", dimensions, uri, filename };\n}\n});\nconst validationResults = await Promise.all(\n" }, { "change_type": "MODIFY", "old_path": "native/keyboard/keyboard-state-container.react.js", "new_path": "native/keyboard/keyboard-state-container.react.js", "diff": "// @flow\n-import type { GalleryMediaInfo } from '../media/media-gallery-media.react';\n-\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport { KeyboardUtils } from 'react-native-keyboard-input';\n" }, { "change_type": "MODIFY", "old_path": "native/media/camera-modal.react.js", "new_path": "native/media/camera-modal.react.js", "diff": "@@ -954,8 +954,7 @@ class CameraModal extends React.PureComponent<Props, State> {\nconst pendingImageInfo = {\nuri,\n- width,\n- height,\n+ dimensions: { width, height },\ntype: \"photo\",\nunlinkURIAfterRemoving: true,\n};\n" }, { "change_type": "MODIFY", "old_path": "native/media/media-gallery-keyboard.react.js", "new_path": "native/media/media-gallery-keyboard.react.js", "diff": "@@ -264,16 +264,14 @@ class MediaGalleryKeyboard extends React.PureComponent<Props, State> {\nif (isVideo) {\nreturn {\ntype: \"video\",\n- height,\n- width,\n+ dimensions: { height, width },\nuri,\nfilename,\n};\n} else {\nreturn {\ntype: \"photo\",\n- height,\n- width,\n+ dimensions: { height, width },\nuri,\n};\n}\n" }, { "change_type": "MODIFY", "old_path": "native/media/media-gallery-media.react.js", "new_path": "native/media/media-gallery-media.react.js", "diff": "// @flow\n-import { mediaTypePropType } from 'lib/types/media-types';\n+import {\n+ mediaTypePropType,\n+ type Dimensions,\n+ dimensionsPropType,\n+} from 'lib/types/media-types';\nimport type { ViewStyle, ImageStyle } from '../types/styles';\nimport { type Colors, colorsPropType } from '../themes/colors';\n@@ -33,14 +37,12 @@ export type GalleryMediaInfo =\n| {|\ntype: \"photo\",\nuri: string,\n- height: number,\n- width: number,\n+ dimensions: Dimensions,\n|}\n| {|\ntype: \"video\",\nuri: string,\n- height: number,\n- width: number,\n+ dimensions: Dimensions,\nfilename: string,\n|};\nconst animatedSpec = {\n@@ -69,8 +71,7 @@ class MediaGalleryMedia extends React.PureComponent<Props> {\nstatic propTypes = {\nmediaInfo: PropTypes.shape({\n- height: PropTypes.number.isRequired,\n- width: PropTypes.number.isRequired,\n+ dimensions: dimensionsPropType.isRequired,\ntype: mediaTypePropType.isRequired,\nuri: PropTypes.string.isRequired,\nfilename: PropTypes.string,\n@@ -207,7 +208,7 @@ class MediaGalleryMedia extends React.PureComponent<Props> {\nrender() {\nconst { mediaInfo, containerHeight } = this.props;\n- const { uri, width, height, type } = mediaInfo;\n+ const { uri, dimensions: { width, height }, type } = mediaInfo;\nconst active = MediaGalleryMedia.isActive(this.props);\nconst dimensionsStyle = {\nheight: containerHeight,\n" }, { "change_type": "MODIFY", "old_path": "native/utils/media-utils.js", "new_path": "native/utils/media-utils.js", "diff": "@@ -51,24 +51,20 @@ type ValidateMediaInput =\n| {\ntype: \"photo\",\nuri: string,\n- height: number,\n- width: number,\n+ dimensions: Dimensions,\n...\n}\n| {\ntype: \"video\",\nuri: string,\n- height: number,\n- width: number,\n+ dimensions: Dimensions,\nfilename: string,\n...\n};\nasync function validateMedia(\nmediaInfo: ValidateMediaInput,\n): Promise<?MediaValidationResult> {\n- const { height, width } = mediaInfo;\n- const dimensions = { height, width };\n- const { uri, type } = mediaInfo;\n+ const { dimensions, uri, type } = mediaInfo;\nif (mediaInfo.type === \"video\") {\nconst { filename } = mediaInfo;\nreturn { mediaType: \"video\", uri, dimensions, filename };\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Keep Dimensions together in ClientImageInfo
129,187
28.01.2020 13:49:19
28,800
5669dcfa57a95d31619e1f5c6df7488b5a6aa748
[native] ClientImageInfo -> ClientMediaInfo
[ { "change_type": "MODIFY", "old_path": "native/chat/chat-input-state-container.react.js", "new_path": "native/chat/chat-input-state-container.react.js", "diff": "import type {\nPendingMultimediaUploads,\n- ClientImageInfo,\n+ ClientMediaInfo,\n} from './chat-input-state';\nimport type { AppState } from '../redux/redux-setup';\nimport type {\n@@ -267,16 +267,16 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\nsendMultimediaMessage = async (\nthreadID: string,\n- inputImageInfos: $ReadOnlyArray<ClientImageInfo>,\n+ inputMediaInfos: $ReadOnlyArray<ClientMediaInfo>,\n) => {\nconst urisToUnlink = new Set(\n- inputImageInfos.filter(\n+ inputMediaInfos.filter(\ninputImageInfo => !!inputImageInfo.unlinkURIAfterRemoving,\n).map(inputImageInfo => inputImageInfo.uri),\n);\nconst validationResults = await Promise.all(\n- inputImageInfos.map(validateMedia),\n+ inputMediaInfos.map(validateMedia),\n);\nconst mediaInfos = validationResults.filter(Boolean).map(\nvalidationResult => ({\n" }, { "change_type": "MODIFY", "old_path": "native/chat/chat-input-state.js", "new_path": "native/chat/chat-input-state.js", "diff": "@@ -10,7 +10,7 @@ export type PendingMultimediaUpload = {|\nprogressPercent: number,\n|};\n-export type ClientImageInfo = {|\n+export type ClientMediaInfo = {|\n...GalleryMediaInfo,\nunlinkURIAfterRemoving?: bool,\n|};\n@@ -40,7 +40,7 @@ export type ChatInputState = {|\npendingUploads: PendingMultimediaUploads,\nsendMultimediaMessage: (\nthreadID: string,\n- imageInfos: $ReadOnlyArray<ClientImageInfo>,\n+ mediaInfos: $ReadOnlyArray<ClientMediaInfo>,\n) => Promise<void>,\nmessageHasUploadFailure: (localMessageID: string) => bool,\nretryMultimediaMessage: (localMessageID: string) => Promise<void>,\n" }, { "change_type": "MODIFY", "old_path": "native/media/camera-modal.react.js", "new_path": "native/media/camera-modal.react.js", "diff": "@@ -19,7 +19,7 @@ import {\ntype ChatInputState,\nchatInputStatePropType,\nwithChatInputState,\n- type ClientImageInfo,\n+ type ClientMediaInfo,\n} from '../chat/chat-input-state';\nimport type { ViewStyle } from '../types/styles';\n@@ -265,7 +265,7 @@ type State = {|\nflashMode: number,\nautoFocusPointOfInterest: ?{| x: number, y: number, autoExposure?: bool |},\nstagingMode: bool,\n- pendingImageInfo: ?ClientImageInfo,\n+ pendingMediaInfo: ?ClientMediaInfo,\n|};\nclass CameraModal extends React.PureComponent<Props, State> {\n@@ -346,7 +346,7 @@ class CameraModal extends React.PureComponent<Props, State> {\nflashMode: RNCamera.Constants.FlashMode.off,\nautoFocusPointOfInterest: undefined,\nstagingMode: false,\n- pendingImageInfo: undefined,\n+ pendingMediaInfo: undefined,\n};\nconst { position } = props;\n@@ -623,22 +623,22 @@ class CameraModal extends React.PureComponent<Props, State> {\nthis.stagingModeProgress.setValue(0);\n}\n- if (this.state.pendingImageInfo && !prevState.pendingImageInfo) {\n+ if (this.state.pendingMediaInfo && !prevState.pendingMediaInfo) {\ntiming(\nthis.sendButtonProgress,\n{ ...stagingModeAnimationConfig, toValue: 1 },\n).start();\n- } else if (!this.state.pendingImageInfo && prevState.pendingImageInfo) {\n- CameraModal.cleanUpPendingImageInfo(prevState.pendingImageInfo);\n+ } else if (!this.state.pendingMediaInfo && prevState.pendingMediaInfo) {\n+ CameraModal.cleanUpPendingImageInfo(prevState.pendingMediaInfo);\nthis.sendButtonProgress.setValue(0);\n}\n}\n- static async cleanUpPendingImageInfo(pendingImageInfo: ClientImageInfo) {\n- if (!pendingImageInfo.unlinkURIAfterRemoving) {\n+ static async cleanUpPendingImageInfo(pendingMediaInfo: ClientMediaInfo) {\n+ if (!pendingMediaInfo.unlinkURIAfterRemoving) {\nreturn;\n}\n- const path = pathFromURI(pendingImageInfo.uri);\n+ const path = pathFromURI(pendingMediaInfo.uri);\nif (!path) {\nreturn;\n}\n@@ -693,9 +693,9 @@ class CameraModal extends React.PureComponent<Props, State> {\nrenderStagingView() {\nlet image = null;\n- const { pendingImageInfo } = this.state;\n- if (pendingImageInfo) {\n- const imageSource = { uri: pendingImageInfo.uri };\n+ const { pendingMediaInfo } = this.state;\n+ if (pendingMediaInfo) {\n+ const imageSource = { uri: pendingMediaInfo.uri };\nimage = <Image source={imageSource} style={styles.stagingImage} />;\n} else {\nimage = <ContentLoading fillType=\"flex\" colors={colors.dark} />;\n@@ -715,7 +715,7 @@ class CameraModal extends React.PureComponent<Props, State> {\n</TouchableOpacity>\n<SendMediaButton\nonPress={this.sendPhoto}\n- pointerEvents={pendingImageInfo ? 'auto' : 'none'}\n+ pointerEvents={pendingMediaInfo ? 'auto' : 'none'}\ncontainerStyle={styles.sendButtonContainer}\nstyle={this.sendButtonStyle}\n/>\n@@ -952,7 +952,7 @@ class CameraModal extends React.PureComponent<Props, State> {\n`unable to parse filename out of react-native-camera URI ${uri}`,\n);\n- const pendingImageInfo = {\n+ const pendingMediaInfo = {\nuri,\ndimensions: { width, height },\ntype: \"photo\",\n@@ -960,15 +960,15 @@ class CameraModal extends React.PureComponent<Props, State> {\n};\nthis.setState({\n- pendingImageInfo,\n+ pendingMediaInfo,\nzoom: 0,\nautoFocusPointOfInterest: undefined,\n});\n}\nsendPhoto = async () => {\n- const { pendingImageInfo } = this.state;\n- if (!pendingImageInfo) {\n+ const { pendingMediaInfo } = this.state;\n+ if (!pendingMediaInfo) {\nreturn;\n}\nconst { chatInputState } = this.props;\n@@ -976,9 +976,9 @@ class CameraModal extends React.PureComponent<Props, State> {\nthis.close();\nchatInputState.sendMultimediaMessage(\nthis.props.navigation.state.params.threadID,\n- [ pendingImageInfo ],\n+ [ pendingMediaInfo ],\n);\n- saveImage({ uri: pendingImageInfo.uri, type: \"photo\" });\n+ saveImage({ uri: pendingMediaInfo.uri, type: \"photo\" });\n}\nclearPendingImage = () => {\n@@ -986,7 +986,7 @@ class CameraModal extends React.PureComponent<Props, State> {\nthis.camera.resumePreview();\nthis.setState({\nstagingMode: false,\n- pendingImageInfo: undefined,\n+ pendingMediaInfo: undefined,\n});\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] ClientImageInfo -> ClientMediaInfo
129,187
28.01.2020 15:37:40
28,800
bc70783568ef4ed10d530ff4cd04313546f7e750
[native] Kill GalleryMediaInfo and ValidateMediaInput
[ { "change_type": "MODIFY", "old_path": "native/chat/chat-input-state-container.react.js", "new_path": "native/chat/chat-input-state-container.react.js", "diff": "@@ -20,7 +20,6 @@ import {\ntype RawMediaMessageInfo,\n} from 'lib/types/message-types';\nimport type { MediaValidationResult } from '../utils/media-utils';\n-import type { GalleryMediaInfo } from '../media/media-gallery-media.react';\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\n@@ -578,7 +577,7 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\n},\n}));\n- const galleryMediaInfos: GalleryMediaInfo[] =\n+ const galleryMediaInfos: ClientMediaInfo[] =\nretryMedia.map(singleMedia => {\nif (singleMedia.type === \"photo\") {\nconst { dimensions, uri } = singleMedia;\n" }, { "change_type": "MODIFY", "old_path": "native/chat/chat-input-state.js", "new_path": "native/chat/chat-input-state.js", "diff": "// @flow\n-import type { GalleryMediaInfo } from '../media/media-gallery-media.react';\n+import { type Dimensions, dimensionsPropType } from 'lib/types/media-types';\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\n@@ -10,11 +10,37 @@ export type PendingMultimediaUpload = {|\nprogressPercent: number,\n|};\n-export type ClientMediaInfo = {|\n- ...GalleryMediaInfo,\n+export type ClientMediaInfo =\n+ | {|\n+ type: \"photo\",\n+ uri: string,\n+ dimensions: Dimensions,\nunlinkURIAfterRemoving?: bool,\n+ |}\n+ | {|\n+ type: \"video\",\n+ uri: string,\n+ dimensions: Dimensions,\n+ unlinkURIAfterRemoving?: bool,\n+ filename: string,\n|};\n+export const clientMediaInfoPropType = PropTypes.oneOf([\n+ PropTypes.shape({\n+ type: PropTypes.oneOf([ \"photo\" ]).isRequired,\n+ uri: PropTypes.string.isRequired,\n+ dimensions: dimensionsPropType.isRequired,\n+ unlinkURIAfterRemoving: PropTypes.bool,\n+ }),\n+ PropTypes.shape({\n+ type: PropTypes.oneOf([ \"video\" ]).isRequired,\n+ uri: PropTypes.string.isRequired,\n+ dimensions: dimensionsPropType.isRequired,\n+ unlinkURIAfterRemoving: PropTypes.bool,\n+ filename: PropTypes.string.isRequired,\n+ }),\n+]);\n+\nconst pendingMultimediaUploadPropType = PropTypes.shape({\nfailed: PropTypes.string,\nprogressPercent: PropTypes.number.isRequired,\n" }, { "change_type": "MODIFY", "old_path": "native/keyboard/keyboard-input-host.react.js", "new_path": "native/keyboard/keyboard-input-host.react.js", "diff": "@@ -6,13 +6,13 @@ import {\ntype ChatInputState,\nchatInputStatePropType,\nwithChatInputState,\n+ type ClientMediaInfo,\n} from '../chat/chat-input-state';\nimport {\ntype KeyboardState,\nkeyboardStatePropType,\nwithKeyboardState,\n} from '../keyboard/keyboard-state';\n-import type { GalleryMediaInfo } from '../media/media-gallery-media.react';\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\n@@ -80,7 +80,7 @@ class KeyboardInputHost extends React.PureComponent<Props> {\nonMediaGalleryItemSelected = (\nkeyboardName: string,\n- mediaInfos: $ReadOnlyArray<GalleryMediaInfo>,\n+ mediaInfos: $ReadOnlyArray<ClientMediaInfo>,\n) => {\nconst { keyboardState } = this.props;\ninvariant(\n" }, { "change_type": "MODIFY", "old_path": "native/media/media-gallery-keyboard.react.js", "new_path": "native/media/media-gallery-keyboard.react.js", "diff": "// @flow\n-import type { GalleryMediaInfo } from './media-gallery-media.react';\nimport type { AppState } from '../redux/redux-setup';\nimport { type Dimensions, dimensionsPropType } from 'lib/types/media-types';\nimport type { ViewToken } from 'react-native/Libraries/Lists/ViewabilityHelper';\nimport type { ViewStyle, Styles } from '../types/styles';\nimport { type Colors, colorsPropType } from '../themes/colors';\n+import type { ClientMediaInfo } from '../chat/chat-input-state';\nimport * as React from 'react';\nimport {\n@@ -53,7 +53,7 @@ type Props = {|\nstyles: Styles,\n|};\ntype State = {|\n- mediaInfos: ?$ReadOnlyArray<GalleryMediaInfo>,\n+ mediaInfos: ?$ReadOnlyArray<ClientMediaInfo>,\nerror: ?string,\ncontainerHeight: ?number,\n// null means end reached; undefined means no fetch yet\n@@ -328,7 +328,7 @@ class MediaGalleryKeyboard extends React.PureComponent<Props, State> {\nreturn !!this.state.queuedMediaURIs;\n}\n- renderItem = (row: { item: GalleryMediaInfo }) => {\n+ renderItem = (row: { item: ClientMediaInfo }) => {\nconst { containerHeight, queuedMediaURIs } = this.state;\ninvariant(containerHeight, \"should be set\");\nconst { uri } = row.item;\n@@ -354,7 +354,7 @@ class MediaGalleryKeyboard extends React.PureComponent<Props, State> {\nreturn <View style={this.props.styles.separator} />;\n}\n- static keyExtractor(item: GalleryMediaInfo) {\n+ static keyExtractor(item: ClientMediaInfo) {\nreturn item.uri;\n}\n@@ -445,7 +445,7 @@ class MediaGalleryKeyboard extends React.PureComponent<Props, State> {\nthis.viewableIndices = viewableIndices;\n}\n- setMediaQueued = (mediaInfo: GalleryMediaInfo, isQueued: bool) => {\n+ setMediaQueued = (mediaInfo: ClientMediaInfo, isQueued: bool) => {\nthis.setState((prevState: State) => {\nconst prevQueuedMediaURIs = prevState.queuedMediaURIs\n? [ ...prevState.queuedMediaURIs ]\n@@ -472,7 +472,7 @@ class MediaGalleryKeyboard extends React.PureComponent<Props, State> {\n});\n}\n- setFocus = (mediaInfo: GalleryMediaInfo, isFocused: bool) => {\n+ setFocus = (mediaInfo: ClientMediaInfo, isFocused: bool) => {\nconst { uri } = mediaInfo;\nif (isFocused) {\nthis.setState({ focusedMediaURI: uri });\n@@ -481,7 +481,7 @@ class MediaGalleryKeyboard extends React.PureComponent<Props, State> {\n}\n}\n- sendSingleMedia = (mediaInfo: GalleryMediaInfo) => {\n+ sendSingleMedia = (mediaInfo: ClientMediaInfo) => {\nthis.sendMedia([ mediaInfo ]);\n}\n@@ -502,7 +502,7 @@ class MediaGalleryKeyboard extends React.PureComponent<Props, State> {\nthis.sendMedia(queuedMediaInfos);\n}\n- sendMedia(mediaInfos: $ReadOnlyArray<GalleryMediaInfo>) {\n+ sendMedia(mediaInfos: $ReadOnlyArray<ClientMediaInfo>) {\nif (this.mediaSelected) {\nreturn;\n}\n" }, { "change_type": "MODIFY", "old_path": "native/media/media-gallery-media.react.js", "new_path": "native/media/media-gallery-media.react.js", "diff": "// @flow\n-import {\n- mediaTypePropType,\n- type Dimensions,\n- dimensionsPropType,\n-} from 'lib/types/media-types';\nimport type { ViewStyle, ImageStyle } from '../types/styles';\nimport { type Colors, colorsPropType } from '../themes/colors';\n+import {\n+ type ClientMediaInfo,\n+ clientMediaInfoPropType,\n+} from '../chat/chat-input-state';\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\n@@ -33,18 +32,6 @@ from 'react-native-reanimated';\nimport invariant from 'invariant';\nimport Video from 'react-native-video';\n-export type GalleryMediaInfo =\n- | {|\n- type: \"photo\",\n- uri: string,\n- dimensions: Dimensions,\n- |}\n- | {|\n- type: \"video\",\n- uri: string,\n- dimensions: Dimensions,\n- filename: string,\n- |};\nconst animatedSpec = {\nduration: 400,\neasing: Easing.inOut(Easing.ease),\n@@ -56,26 +43,21 @@ const reanimatedSpec = {\n};\ntype Props = {|\n- mediaInfo: GalleryMediaInfo,\n+ mediaInfo: ClientMediaInfo,\ncontainerHeight: number,\nqueueModeActive: bool,\nisQueued: bool,\n- setMediaQueued: (media: GalleryMediaInfo, isQueued: bool) => void,\n- sendMedia: (media: GalleryMediaInfo) => void,\n+ setMediaQueued: (media: ClientMediaInfo, isQueued: bool) => void,\n+ sendMedia: (media: ClientMediaInfo) => void,\nisFocused: bool,\n- setFocus: (media: GalleryMediaInfo, isFocused: bool) => void,\n+ setFocus: (media: ClientMediaInfo, isFocused: bool) => void,\nscreenWidth: number,\ncolors: Colors,\n|};\nclass MediaGalleryMedia extends React.PureComponent<Props> {\nstatic propTypes = {\n- mediaInfo: PropTypes.shape({\n- dimensions: dimensionsPropType.isRequired,\n- type: mediaTypePropType.isRequired,\n- uri: PropTypes.string.isRequired,\n- filename: PropTypes.string,\n- }).isRequired,\n+ mediaInfo: clientMediaInfoPropType.isRequired,\ncontainerHeight: PropTypes.number.isRequired,\nqueueModeActive: PropTypes.bool.isRequired,\nisQueued: PropTypes.bool.isRequired,\n" }, { "change_type": "MODIFY", "old_path": "native/utils/media-utils.js", "new_path": "native/utils/media-utils.js", "diff": "// @flow\nimport type { Dimensions, MediaType } from 'lib/types/media-types';\n+import type { ClientMediaInfo } from '../chat/chat-input-state';\nimport { Platform, Image } from 'react-native';\nimport base64 from 'base-64';\n@@ -47,22 +48,8 @@ export type MediaValidationResult =\ndimensions: Dimensions,\nfilename: string,\n|};\n-type ValidateMediaInput =\n- | {\n- type: \"photo\",\n- uri: string,\n- dimensions: Dimensions,\n- ...\n- }\n- | {\n- type: \"video\",\n- uri: string,\n- dimensions: Dimensions,\n- filename: string,\n- ...\n- };\nasync function validateMedia(\n- mediaInfo: ValidateMediaInput,\n+ mediaInfo: ClientMediaInfo,\n): Promise<?MediaValidationResult> {\nconst { dimensions, uri, type } = mediaInfo;\nif (mediaInfo.type === \"video\") {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Kill GalleryMediaInfo and ValidateMediaInput
129,187
28.01.2020 16:53:30
28,800
2bb1f1cd22f3b680e5a191ae04bdae8b55d7ba90
[native] Pass filename through stack for photo too For upcoming improved logging
[ { "change_type": "MODIFY", "old_path": "lib/types/media-types.js", "new_path": "lib/types/media-types.js", "diff": "@@ -19,6 +19,8 @@ export type Image = {|\nuri: string,\ntype: \"photo\",\ndimensions: Dimensions,\n+ // stored on native only during creation in case retry needed after state lost\n+ filename?: string,\n|};\nexport type Video = {|\n" }, { "change_type": "MODIFY", "old_path": "native/chat/chat-input-state-container.react.js", "new_path": "native/chat/chat-input-state-container.react.js", "diff": "@@ -319,16 +319,17 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\nconst media = mediaInfos.map(\n({ localID, validationResult }) => {\n// This conditional is for Flow\n- if (validationResult.mediaType === \"photo\") {\n- const { uri, dimensions, mediaType } = validationResult;\n+ if (validationResult.type === \"photo\") {\n+ const { uri, dimensions, filename } = validationResult;\nreturn {\nid: localID,\nuri,\ntype: \"photo\",\ndimensions,\n+ filename,\n};\n} else {\n- const { uri, dimensions, mediaType, filename } = validationResult;\n+ const { uri, dimensions, filename } = validationResult;\nreturn {\nid: localID,\nuri,\n@@ -580,8 +581,12 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\nconst galleryMediaInfos: ClientMediaInfo[] =\nretryMedia.map(singleMedia => {\nif (singleMedia.type === \"photo\") {\n- const { dimensions, uri } = singleMedia;\n- return { type: \"photo\", dimensions, uri };\n+ const { dimensions, uri, filename } = singleMedia;\n+ invariant(\n+ filename,\n+ \"filename should be set on locally created Video\",\n+ );\n+ return { type: \"photo\", dimensions, uri, filename };\n} else {\nconst { dimensions, uri, filename } = singleMedia;\ninvariant(\n" }, { "change_type": "MODIFY", "old_path": "native/chat/chat-input-state.js", "new_path": "native/chat/chat-input-state.js", "diff": "@@ -10,34 +10,40 @@ export type PendingMultimediaUpload = {|\nprogressPercent: number,\n|};\n-export type ClientMediaInfo =\n- | {|\n+export type ClientPhotoInfo = {|\ntype: \"photo\",\nuri: string,\ndimensions: Dimensions,\n+ filename: string,\nunlinkURIAfterRemoving?: bool,\n- |}\n- | {|\n+|};\n+\n+export type ClientVideoInfo = {|\ntype: \"video\",\nuri: string,\ndimensions: Dimensions,\n- unlinkURIAfterRemoving?: bool,\nfilename: string,\n+ unlinkURIAfterRemoving?: bool,\n|};\n+export type ClientMediaInfo =\n+ | ClientPhotoInfo\n+ | ClientVideoInfo;\n+\nexport const clientMediaInfoPropType = PropTypes.oneOf([\nPropTypes.shape({\ntype: PropTypes.oneOf([ \"photo\" ]).isRequired,\nuri: PropTypes.string.isRequired,\ndimensions: dimensionsPropType.isRequired,\n+ filename: PropTypes.string.isRequired,\nunlinkURIAfterRemoving: PropTypes.bool,\n}),\nPropTypes.shape({\ntype: PropTypes.oneOf([ \"video\" ]).isRequired,\nuri: PropTypes.string.isRequired,\ndimensions: dimensionsPropType.isRequired,\n- unlinkURIAfterRemoving: PropTypes.bool,\nfilename: PropTypes.string.isRequired,\n+ unlinkURIAfterRemoving: PropTypes.bool,\n}),\n]);\n" }, { "change_type": "MODIFY", "old_path": "native/keyboard/keyboard-input-host.react.js", "new_path": "native/keyboard/keyboard-input-host.react.js", "diff": "@@ -103,9 +103,9 @@ class KeyboardInputHost extends React.PureComponent<Props> {\nconst mappedMediaInfos = [];\nfor (let mediaInfo of mediaInfos) {\nif (mediaInfo.type === \"photo\") {\n- mappedMediaInfos.push({ ...mediaInfo });\n+ mappedMediaInfos.push({ type: \"photo\", ...mediaInfo });\n} else {\n- mappedMediaInfos.push({ ...mediaInfo });\n+ mappedMediaInfos.push({ type: \"video\", ...mediaInfo });\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "native/media/camera-modal.react.js", "new_path": "native/media/camera-modal.react.js", "diff": "@@ -953,9 +953,10 @@ class CameraModal extends React.PureComponent<Props, State> {\n);\nconst pendingMediaInfo = {\n+ type: \"photo\",\nuri,\ndimensions: { width, height },\n- type: \"photo\",\n+ filename,\nunlinkURIAfterRemoving: true,\n};\n" }, { "change_type": "MODIFY", "old_path": "native/media/media-gallery-keyboard.react.js", "new_path": "native/media/media-gallery-keyboard.react.js", "diff": "@@ -273,6 +273,7 @@ class MediaGalleryKeyboard extends React.PureComponent<Props, State> {\ntype: \"photo\",\ndimensions: { height, width },\nuri,\n+ filename,\n};\n}\n},\n" }, { "change_type": "MODIFY", "old_path": "native/utils/media-utils.js", "new_path": "native/utils/media-utils.js", "diff": "// @flow\nimport type { Dimensions, MediaType } from 'lib/types/media-types';\n-import type { ClientMediaInfo } from '../chat/chat-input-state';\n+import type {\n+ ClientPhotoInfo,\n+ ClientVideoInfo,\n+ ClientMediaInfo,\n+} from '../chat/chat-input-state';\nimport { Platform, Image } from 'react-native';\nimport base64 from 'base-64';\n@@ -37,24 +41,16 @@ type ReactNativeBlob =\n& { data: { type: string, name: string, size: number } };\nexport type MediaValidationResult =\n| {|\n- mediaType: \"photo\",\n- uri: string,\n- dimensions: Dimensions,\n+ ...ClientPhotoInfo,\nblob: ReactNativeBlob,\n|}\n- | {|\n- mediaType: \"video\",\n- uri: string,\n- dimensions: Dimensions,\n- filename: string,\n- |};\n+ | ClientVideoInfo;\nasync function validateMedia(\nmediaInfo: ClientMediaInfo,\n): Promise<?MediaValidationResult> {\n- const { dimensions, uri, type } = mediaInfo;\n+ const { dimensions, uri, type, filename } = mediaInfo;\nif (mediaInfo.type === \"video\") {\n- const { filename } = mediaInfo;\n- return { mediaType: \"video\", uri, dimensions, filename };\n+ return { type: \"video\", uri, dimensions, filename };\n}\nconst blob = await getBlobFromURI(uri, type);\n@@ -67,7 +63,7 @@ async function validateMedia(\nif (mediaType !== \"photo\") {\nreturn null;\n}\n- return { mediaType: \"photo\", uri, dimensions, blob };\n+ return { type: \"photo\", uri, dimensions, filename, blob };\n}\nfunction blobToDataURI(blob: Blob): Promise<string> {\n@@ -133,7 +129,7 @@ async function convertMedia(\nvalidationResult: MediaValidationResult,\n): Promise<?MediaConversionResult> {\nconst { uri, dimensions } = validationResult;\n- if (validationResult.mediaType === \"video\") {\n+ if (validationResult.type === \"video\") {\nconst result = await transcodeVideo(validationResult);\nif (!result) {\nreturn null;\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Pass filename through stack for photo too For upcoming improved logging
129,187
28.01.2020 17:15:49
28,800
757f04667f4d418b51755f156d6d10f138c10b10
Store unlinkDepartingURI in Redux state
[ { "change_type": "MODIFY", "old_path": "lib/types/media-types.js", "new_path": "lib/types/media-types.js", "diff": "@@ -21,6 +21,7 @@ export type Image = {|\ndimensions: Dimensions,\n// stored on native only during creation in case retry needed after state lost\nfilename?: string,\n+ unlinkURIAfterRemoving?: bool,\n|};\nexport type Video = {|\n@@ -30,6 +31,7 @@ export type Video = {|\ndimensions: Dimensions,\n// stored on native only during creation in case retry needed after state lost\nfilename?: string,\n+ unlinkURIAfterRemoving?: bool,\n|};\nexport type Media =\n" }, { "change_type": "MODIFY", "old_path": "native/chat/chat-input-state-container.react.js", "new_path": "native/chat/chat-input-state-container.react.js", "diff": "@@ -37,7 +37,6 @@ import {\nsendMultimediaMessageActionTypes,\nsendMultimediaMessage,\n} from 'lib/actions/message-actions';\n-import { pathFromURI } from 'lib/utils/file-utils';\nimport { createMediaMessageInfo } from 'lib/shared/message-utils';\nimport { ChatInputStateContext } from './chat-input-state';\n@@ -90,7 +89,6 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\nstate = {\npendingUploads: {},\n};\n- pendingUnlinkURIs = new Set();\nstatic getCompletedUploads(props: Props, state: State): CompletedUploads {\nconst completedUploads = {};\n@@ -260,7 +258,6 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\nsendMultimediaMessage: this.sendMultimediaMessage,\nmessageHasUploadFailure: this.messageHasUploadFailure,\nretryMultimediaMessage: this.retryMultimediaMessage,\n- clearURI: this.clearURI,\n}),\n);\n@@ -268,12 +265,6 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\nthreadID: string,\ninputMediaInfos: $ReadOnlyArray<ClientMediaInfo>,\n) => {\n- const urisToUnlink = new Set(\n- inputMediaInfos.filter(\n- inputImageInfo => !!inputImageInfo.unlinkURIAfterRemoving,\n- ).map(inputImageInfo => inputImageInfo.uri),\n- );\n-\nconst validationResults = await Promise.all(\ninputMediaInfos.map(validateMedia),\n);\n@@ -299,9 +290,6 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\nfailed: null,\nprogressPercent: 0,\n};\n- if (urisToUnlink.has(uri)) {\n- this.pendingUnlinkURIs.add(uri);\n- }\n}\nthis.setState(\n@@ -318,24 +306,30 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\ninvariant(creatorID, \"need viewer ID in order to send a message\");\nconst media = mediaInfos.map(\n({ localID, validationResult }) => {\n+ const {\n+ uri,\n+ dimensions,\n+ filename,\n+ unlinkURIAfterRemoving,\n+ } = validationResult;\n// This conditional is for Flow\nif (validationResult.type === \"photo\") {\n- const { uri, dimensions, filename } = validationResult;\nreturn {\nid: localID,\nuri,\ntype: \"photo\",\ndimensions,\nfilename,\n+ unlinkURIAfterRemoving,\n};\n} else {\n- const { uri, dimensions, filename } = validationResult;\nreturn {\nid: localID,\nuri,\ntype: \"video\",\ndimensions,\nfilename,\n+ unlinkURIAfterRemoving,\n};\n}\n},\n@@ -409,6 +403,7 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\ntype: mediaType,\ndimensions: conversionResult.dimensions,\nfilename: undefined,\n+ unlinkURIAfterRemoving: undefined,\n},\n},\n);\n@@ -578,26 +573,38 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\n},\n}));\n- const galleryMediaInfos: ClientMediaInfo[] =\n+ const clientMediaInfos: ClientMediaInfo[] =\nretryMedia.map(singleMedia => {\n- if (singleMedia.type === \"photo\") {\n- const { dimensions, uri, filename } = singleMedia;\n+ const {\n+ dimensions,\n+ uri,\n+ filename,\n+ unlinkURIAfterRemoving,\n+ } = singleMedia;\ninvariant(\nfilename,\n- \"filename should be set on locally created Video\",\n+ \"filename should be set on locally created Media\",\n);\n- return { type: \"photo\", dimensions, uri, filename };\n+ if (singleMedia.type === \"photo\") {\n+ return {\n+ type: \"photo\",\n+ dimensions,\n+ uri,\n+ filename,\n+ unlinkURIAfterRemoving,\n+ };\n} else {\n- const { dimensions, uri, filename } = singleMedia;\n- invariant(\n+ return {\n+ type: \"video\",\n+ dimensions,\n+ uri,\nfilename,\n- \"filename should be set on locally created Video\",\n- );\n- return { type: \"video\", dimensions, uri, filename };\n+ unlinkURIAfterRemoving,\n+ };\n}\n});\nconst validationResults = await Promise.all(\n- galleryMediaInfos.map(validateMedia),\n+ clientMediaInfos.map(validateMedia),\n);\nconst mediaInfos = [];\n@@ -639,20 +646,6 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\n}\n}\n- clearURI = async (uri: string) => {\n- if (!this.pendingUnlinkURIs.has(uri)) {\n- return;\n- }\n- this.pendingUnlinkURIs.delete(uri);\n- const path = pathFromURI(uri);\n- if (!path) {\n- return;\n- }\n- try {\n- await filesystem.unlink(path);\n- } catch (e) { }\n- }\n-\nrender() {\nconst chatInputState = this.chatInputStateSelector(this.state);\nreturn (\n" }, { "change_type": "MODIFY", "old_path": "native/chat/chat-input-state.js", "new_path": "native/chat/chat-input-state.js", "diff": "@@ -76,7 +76,6 @@ export type ChatInputState = {|\n) => Promise<void>,\nmessageHasUploadFailure: (localMessageID: string) => bool,\nretryMultimediaMessage: (localMessageID: string) => Promise<void>,\n- clearURI: (uri: string) => Promise<void>,\n|};\nconst chatInputStatePropType = PropTypes.shape({\n@@ -84,7 +83,6 @@ const chatInputStatePropType = PropTypes.shape({\nsendMultimediaMessage: PropTypes.func.isRequired,\nmessageHasUploadFailure: PropTypes.func.isRequired,\nretryMultimediaMessage: PropTypes.func.isRequired,\n- clearURI: PropTypes.func.isRequired,\n});\nconst ChatInputStateContext = React.createContext<?ChatInputState>(null);\n" }, { "change_type": "MODIFY", "old_path": "native/media/multimedia.react.js", "new_path": "native/media/multimedia.react.js", "diff": "// @flow\nimport { type MediaInfo, mediaInfoPropType } from 'lib/types/media-types';\n-import {\n- type ChatInputState,\n- chatInputStatePropType,\n- withChatInputState,\n-} from '../chat/chat-input-state';\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport { View, Image, StyleSheet } from 'react-native';\n+import filesystem from 'react-native-fs';\n+\n+import { pathFromURI } from 'lib/utils/file-utils';\nimport RemoteImage from './remote-image.react';\ntype Props = {|\nmediaInfo: MediaInfo,\nspinnerColor: string,\n- // withChatInputState\n- chatInputState: ?ChatInputState,\n|};\ntype State = {|\ncurrentURI: string,\ndepartingURI: ?string,\n+ unlinkDepartingURI: bool,\n|};\nclass Multimedia extends React.PureComponent<Props, State> {\nstatic propTypes = {\nmediaInfo: mediaInfoPropType.isRequired,\nspinnerColor: PropTypes.string.isRequired,\n- chatInputState: chatInputStatePropType,\n};\nstatic defaultProps = {\nspinnerColor: \"black\",\n@@ -39,6 +35,7 @@ class Multimedia extends React.PureComponent<Props, State> {\nthis.state = {\ncurrentURI: props.mediaInfo.uri,\ndepartingURI: null,\n+ unlinkDepartingURI: false,\n};\n}\n@@ -46,7 +43,12 @@ class Multimedia extends React.PureComponent<Props, State> {\nconst newURI = this.props.mediaInfo.uri;\nconst oldURI = prevProps.mediaInfo.uri;\nif (newURI !== oldURI && !this.state.departingURI) {\n- this.setState({ currentURI: newURI, departingURI: oldURI });\n+ const unlinkDepartingURI = !!prevProps.mediaInfo.unlinkURIAfterRemoving;\n+ this.setState({\n+ currentURI: newURI,\n+ departingURI: oldURI,\n+ unlinkDepartingURI,\n+ });\n} else if (newURI !== oldURI) {\nthis.setState({ currentURI: newURI });\n}\n@@ -93,15 +95,25 @@ class Multimedia extends React.PureComponent<Props, State> {\n}\n}\n- onLoad = () => {\n- const { departingURI } = this.state;\n- if (!departingURI) {\n+ onLoad = async () => {\n+ const { departingURI, unlinkDepartingURI } = this.state;\n+ if (!departingURI && !unlinkDepartingURI) {\n+ return;\n+ }\n+ this.setState({ departingURI: null, unlinkDepartingURI: false });\n+\n+ if (!departingURI || !unlinkDepartingURI) {\nreturn;\n}\n- this.setState({ departingURI: null });\n- if (this.props.chatInputState) {\n- this.props.chatInputState.clearURI(departingURI);\n+\n+ const path = pathFromURI(departingURI);\n+ if (!path) {\n+ return;\n}\n+\n+ try {\n+ await filesystem.unlink(path);\n+ } catch (e) { }\n}\n}\n@@ -119,4 +131,4 @@ const styles = StyleSheet.create({\n},\n});\n-export default withChatInputState(Multimedia);\n+export default Multimedia;\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Store unlinkDepartingURI in Redux state
129,187
28.01.2020 19:02:44
28,800
8fa1db9c20e8da65fc62c38d6f897cfd8d49e391
[native] Call validateMedia after creating MultimediaMessage
[ { "change_type": "MODIFY", "old_path": "native/chat/chat-input-state-container.react.js", "new_path": "native/chat/chat-input-state-container.react.js", "diff": "@@ -19,7 +19,6 @@ import {\ntype RawImagesMessageInfo,\ntype RawMediaMessageInfo,\n} from 'lib/types/message-types';\n-import type { MediaValidationResult } from '../utils/media-utils';\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\n@@ -41,11 +40,10 @@ import { createMediaMessageInfo } from 'lib/shared/message-utils';\nimport { ChatInputStateContext } from './chat-input-state';\nimport { validateMedia, convertMedia } from '../utils/media-utils';\n-import { displayActionResultModal } from '../navigation/action-result-modal';\nlet nextLocalUploadID = 0;\n-type MediaInfo = {|\n- validationResult: MediaValidationResult,\n+type MediaInfoWithID = {|\n+ mediaInfo: ClientMediaInfo,\nlocalID: string,\n|};\ntype CompletedUploads = { [localMessageID: string]: ?Set<string> };\n@@ -263,29 +261,16 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\nsendMultimediaMessage = async (\nthreadID: string,\n- inputMediaInfos: $ReadOnlyArray<ClientMediaInfo>,\n+ mediaInfos: $ReadOnlyArray<ClientMediaInfo>,\n) => {\n- const validationResults = await Promise.all(\n- inputMediaInfos.map(validateMedia),\n- );\n- const mediaInfos = validationResults.filter(Boolean).map(\n- validationResult => ({\n- validationResult,\n- localID: `localUpload${nextLocalUploadID++}`,\n- }),\n- );\nconst localMessageID = `local${this.props.nextLocalID}`;\n-\n- if (mediaInfos.length < validationResults.length) {\n- // Since we filter our MIME types in our calls to CameraRoll,\n- // this should never be triggered\n- console.log('unexpected MIME type found');\n- displayActionResultModal(\"unsupported media type :(\");\n- return;\n- }\n+ const mediaInfosWithIDs = mediaInfos.map(mediaInfo => ({\n+ mediaInfo,\n+ localID: `localUpload${nextLocalUploadID++}`,\n+ }));\nconst pendingUploads = {};\n- for (let { localID, validationResult: { uri } } of mediaInfos) {\n+ for (let { localID, mediaInfo: { uri } } of mediaInfosWithIDs) {\npendingUploads[localID] = {\nfailed: null,\nprogressPercent: 0,\n@@ -304,16 +289,16 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\n() => {\nconst creatorID = this.props.viewerID;\ninvariant(creatorID, \"need viewer ID in order to send a message\");\n- const media = mediaInfos.map(\n- ({ localID, validationResult }) => {\n+ const media = mediaInfosWithIDs.map(\n+ ({ localID, mediaInfo }) => {\nconst {\nuri,\ndimensions,\nfilename,\nunlinkURIAfterRemoving,\n- } = validationResult;\n+ } = mediaInfo;\n// This conditional is for Flow\n- if (validationResult.type === \"photo\") {\n+ if (mediaInfo.type === \"photo\") {\nreturn {\nid: localID,\nuri,\n@@ -347,20 +332,32 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\n},\n);\n- await this.uploadFiles(localMessageID, mediaInfos);\n+ await this.uploadFiles(localMessageID, mediaInfosWithIDs);\n}\nuploadFiles(\nlocalMessageID: string,\n- mediaInfos: $ReadOnlyArray<MediaInfo>,\n+ mediaInfosWithIDs: $ReadOnlyArray<MediaInfoWithID>,\n) {\nreturn Promise.all(\n- mediaInfos.map(mediaInfo => this.uploadFile(localMessageID, mediaInfo)),\n+ mediaInfosWithIDs.map(mediaInfo => this.uploadFile(\n+ localMessageID,\n+ mediaInfo,\n+ )),\n);\n}\n- async uploadFile(localMessageID: string, mediaInfo: MediaInfo) {\n- const { localID, validationResult } = mediaInfo;\n+ async uploadFile(localMessageID: string, mediaInfoWithID: MediaInfoWithID) {\n+ const { localID, mediaInfo } = mediaInfoWithID;\n+ const validationResult = await validateMedia(mediaInfo);\n+ if (!validationResult) {\n+ this.handleUploadFailure(\n+ localMessageID,\n+ localID,\n+ new Error(\"validation\"),\n+ );\n+ return;\n+ }\nconst conversionResult = await convertMedia(validationResult);\nif (!conversionResult) {\nthis.handleUploadFailure(\n@@ -573,9 +570,10 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\n},\n}));\n- const clientMediaInfos: ClientMediaInfo[] =\n+ const mediaInfos: MediaInfoWithID[] =\nretryMedia.map(singleMedia => {\nconst {\n+ id,\ndimensions,\nuri,\nfilename,\n@@ -587,64 +585,30 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\n);\nif (singleMedia.type === \"photo\") {\nreturn {\n+ localID: id,\n+ mediaInfo: {\ntype: \"photo\",\ndimensions,\nuri,\nfilename,\nunlinkURIAfterRemoving,\n+ },\n};\n} else {\nreturn {\n+ localID: id,\n+ mediaInfo: {\ntype: \"video\",\ndimensions,\nuri,\nfilename,\nunlinkURIAfterRemoving,\n+ },\n};\n}\n});\n- const validationResults = await Promise.all(\n- clientMediaInfos.map(validateMedia),\n- );\n-\n- const mediaInfos = [];\n- const newPendingUploads = {};\n- for (let i = 0; i < validationResults.length; i++) {\n- const result = validationResults[i];\n- const { id } = retryMedia[i];\n- if (!result) {\n- newPendingUploads[id] = {\n- failed: \"validation\",\n- progressPercent: 0,\n- };\n- continue;\n- }\n- mediaInfos.push({\n- validationResult: result,\n- localID: id,\n- });\n- }\n- if (mediaInfos.length < validationResults.length) {\n- // Since we filter our MIME types in our calls to CameraRoll,\n- // this should never be triggered\n- console.log('unexpected MIME type found');\n- }\n- if (Object.keys(newPendingUploads).length > 0) {\n- this.setState(prevState => ({\n- pendingUploads: {\n- ...prevState.pendingUploads,\n- [localMessageID]: {\n- ...prevState.pendingUploads[localMessageID],\n- ...newPendingUploads,\n- },\n- },\n- }));\n- }\n-\n- if (mediaInfos.length > 0) {\nawait this.uploadFiles(localMessageID, mediaInfos);\n}\n- }\nrender() {\nconst chatInputState = this.chatInputStateSelector(this.state);\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Call validateMedia after creating MultimediaMessage
129,187
28.01.2020 19:19:37
28,800
924e6f47ad6a826864c435456d748b2368fd0edc
[native] displayActionResultModal on any issues with sendMultimediaMessage
[ { "change_type": "MODIFY", "old_path": "native/chat/chat-input-state-container.react.js", "new_path": "native/chat/chat-input-state-container.react.js", "diff": "@@ -40,6 +40,7 @@ import { createMediaMessageInfo } from 'lib/shared/message-utils';\nimport { ChatInputStateContext } from './chat-input-state';\nimport { validateMedia, convertMedia } from '../utils/media-utils';\n+import { displayActionResultModal } from '../navigation/action-result-modal';\nlet nextLocalUploadID = 0;\ntype MediaInfoWithID = {|\n@@ -335,37 +336,38 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\nawait this.uploadFiles(localMessageID, mediaInfosWithIDs);\n}\n- uploadFiles(\n+ async uploadFiles(\nlocalMessageID: string,\nmediaInfosWithIDs: $ReadOnlyArray<MediaInfoWithID>,\n) {\n- return Promise.all(\n+ const results = await Promise.all(\nmediaInfosWithIDs.map(mediaInfo => this.uploadFile(\nlocalMessageID,\nmediaInfo,\n)),\n);\n+ const errors = [ ...new Set(results.filter(Boolean)) ];\n+ if (errors.length > 0) {\n+ displayActionResultModal(errors.join(\", \") + \" :(\");\n+ }\n}\n- async uploadFile(localMessageID: string, mediaInfoWithID: MediaInfoWithID) {\n+ async uploadFile(\n+ localMessageID: string,\n+ mediaInfoWithID: MediaInfoWithID,\n+ ): Promise<?string> {\nconst { localID, mediaInfo } = mediaInfoWithID;\nconst validationResult = await validateMedia(mediaInfo);\nif (!validationResult) {\n- this.handleUploadFailure(\n- localMessageID,\n- localID,\n- new Error(\"validation\"),\n- );\n- return;\n+ const message = \"validation failed\";\n+ this.handleUploadFailure(localMessageID, localID, message);\n+ return message;\n}\nconst conversionResult = await convertMedia(validationResult);\nif (!conversionResult) {\n- this.handleUploadFailure(\n- localMessageID,\n- localID,\n- new Error(\"conversion failed\"),\n- );\n- return;\n+ const message = \"conversion failed\";\n+ this.handleUploadFailure(localMessageID, localID, message);\n+ return message;\n}\nconst {\nuploadURI,\n@@ -375,7 +377,7 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\nmediaType,\n} = conversionResult;\n- let result;\n+ let result, message;\ntry {\nresult = await this.props.uploadMultimedia(\n{ uri: uploadURI, name, type: mime },\n@@ -386,7 +388,8 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\n),\n);\n} catch (e) {\n- this.handleUploadFailure(localMessageID, localID, e);\n+ message = \"upload failed\";\n+ this.handleUploadFailure(localMessageID, localID, message);\n}\nif (result) {\nthis.props.dispatchActionPayload(\n@@ -406,11 +409,12 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\n);\n}\nif (!shouldDisposePath) {\n- return;\n+ return message;\n}\ntry {\nawait filesystem.unlink(shouldDisposePath);\n} catch (e) { }\n+ return message;\n}\nsetProgress(\n@@ -451,7 +455,7 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\nhandleUploadFailure(\nlocalMessageID: string,\nlocalUploadID: string,\n- e: any,\n+ message: string,\n) {\nthis.setState(prevState => {\nconst uploads = prevState.pendingUploads[localMessageID];\n@@ -460,9 +464,6 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\n// The upload has been completed before it failed\nreturn {};\n}\n- const failed = (e instanceof Error && e.message)\n- ? e.message\n- : \"failed\";\nreturn {\npendingUploads: {\n...prevState.pendingUploads,\n@@ -470,7 +471,7 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\n...uploads,\n[localUploadID]: {\n...upload,\n- failed,\n+ failed: message,\nprogressPercent: 0,\n},\n},\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] displayActionResultModal on any issues with sendMultimediaMessage
129,187
03.02.2020 12:15:23
18,000
b252b64b9336d9e650fea28aca0534dd9e66ae6d
Update react-router Flow libdefs
[ { "change_type": "ADD", "old_path": null, "new_path": "server/flow-typed/npm/history_v4.x.x.js", "diff": "+// flow-typed signature: e461b9fe923a5f62ed607392b0742c02\n+// flow-typed version: c6154227d1/history_v4.x.x/flow_>=v0.25.x <=v0.103.x\n+\n+declare module \"history/createBrowserHistory\" {\n+ declare function Unblock(): void;\n+\n+ declare export type Action = \"PUSH\" | \"REPLACE\" | \"POP\";\n+\n+ declare export type BrowserLocation = {\n+ pathname: string,\n+ search: string,\n+ hash: string,\n+ // Browser and Memory specific\n+ state: {},\n+ key: string,\n+ };\n+\n+ declare interface IBrowserHistory {\n+ length: number,\n+ location: BrowserLocation,\n+ action: Action,\n+ push(path: string, state?: {}): void,\n+ push(location: $Shape<BrowserLocation>): void,\n+ replace(path: string, state?: {}): void,\n+ replace(location: $Shape<BrowserLocation>): void,\n+ go(n: number): void,\n+ goBack(): void,\n+ goForward(): void,\n+ listen: Function,\n+ block(message: string): typeof Unblock,\n+ block((location: BrowserLocation, action: Action) => string): typeof Unblock,\n+ }\n+\n+ declare export type BrowserHistory = IBrowserHistory;\n+\n+ declare type HistoryOpts = {\n+ basename?: string,\n+ forceRefresh?: boolean,\n+ getUserConfirmation?: (\n+ message: string,\n+ callback: (willContinue: boolean) => void,\n+ ) => void,\n+ };\n+\n+ declare export default (opts?: HistoryOpts) => BrowserHistory;\n+}\n+\n+declare module \"history/createMemoryHistory\" {\n+ declare function Unblock(): void;\n+\n+ declare export type Action = \"PUSH\" | \"REPLACE\" | \"POP\";\n+\n+ declare export type MemoryLocation = {\n+ pathname: string,\n+ search: string,\n+ hash: string,\n+ // Browser and Memory specific\n+ state: {},\n+ key: string,\n+ };\n+\n+ declare interface IMemoryHistory {\n+ length: number,\n+ location: MemoryLocation,\n+ action: Action,\n+ index: number,\n+ entries: Array<string>,\n+ push(path: string, state?: {}): void,\n+ push(location: $Shape<MemoryLocation>): void,\n+ replace(path: string, state?: {}): void,\n+ replace(location: $Shape<MemoryLocation>): void,\n+ go(n: number): void,\n+ goBack(): void,\n+ goForward(): void,\n+ // Memory only\n+ canGo(n: number): boolean,\n+ listen: Function,\n+ block(message: string): typeof Unblock,\n+ block((location: MemoryLocation, action: Action) => string): typeof Unblock,\n+ }\n+\n+ declare export type MemoryHistory = IMemoryHistory;\n+\n+ declare type HistoryOpts = {\n+ initialEntries?: Array<string>,\n+ initialIndex?: number,\n+ keyLength?: number,\n+ getUserConfirmation?: (\n+ message: string,\n+ callback: (willContinue: boolean) => void,\n+ ) => void,\n+ };\n+\n+ declare export default (opts?: HistoryOpts) => MemoryHistory;\n+}\n+\n+declare module \"history/createHashHistory\" {\n+ declare function Unblock(): void;\n+\n+ declare export type Action = \"PUSH\" | \"REPLACE\" | \"POP\";\n+\n+ declare export type HashLocation = {\n+ pathname: string,\n+ search: string,\n+ hash: string,\n+ };\n+\n+ declare interface IHashHistory {\n+ length: number,\n+ location: HashLocation,\n+ action: Action,\n+ push(path: string, state?: {}): void,\n+ push(location: $Shape<HashLocation>): void,\n+ replace(path: string, state?: {}): void,\n+ replace(location: $Shape<HashLocation>): void,\n+ go(n: number): void,\n+ goBack(): void,\n+ goForward(): void,\n+ listen: Function,\n+ block(message: string): typeof Unblock,\n+ block((location: HashLocation, action: Action) => string): typeof Unblock,\n+ push(path: string): void,\n+ }\n+\n+ declare export type HashHistory = IHashHistory;\n+\n+ declare type HistoryOpts = {\n+ basename?: string,\n+ hashType: \"slash\" | \"noslash\" | \"hashbang\",\n+ getUserConfirmation?: (\n+ message: string,\n+ callback: (willContinue: boolean) => void,\n+ ) => void,\n+ };\n+\n+ declare export default (opts?: HistoryOpts) => HashHistory;\n+}\n" }, { "change_type": "RENAME", "old_path": "web/flow-typed/npm/react-router-dom_v4.x.x.js", "new_path": "server/flow-typed/npm/react-router-dom_v5.x.x.js", "diff": "-// flow-typed signature: 47eb60de49014dd5bfdd9b1acb98383a\n-// flow-typed version: c6154227d1/react-router-dom_v4.x.x/flow_>=v0.98.x <=v0.103.x\n+// flow-typed signature: 5c3ecc173e04f53b410aa08d80e28aa2\n+// flow-typed version: cb4e8f3aa2/react-router-dom_v5.x.x/flow_>=v0.98.x <=v0.103.x\ndeclare module \"react-router-dom\" {\ndeclare export var BrowserRouter: React$ComponentType<{|\n@@ -28,8 +28,8 @@ declare module \"react-router-dom\" {\nto: string | LocationShape,\nactiveClassName?: string,\nclassName?: string,\n- activeStyle?: Object,\n- style?: Object,\n+ activeStyle?: { +[string]: mixed },\n+ style?: { +[string]: mixed },\nisActive?: (match: Match, location: Location) => boolean,\nchildren?: React$Node,\nexact?: boolean,\n@@ -160,7 +160,7 @@ declare module \"react-router-dom\" {\n): React$ComponentType<$Diff<React$ElementConfig<Component>, ContextRouterVoid>>;\ndeclare type MatchPathOptions = {\n- path?: string,\n+ path?: string | string[],\nexact?: boolean,\nsensitive?: boolean,\nstrict?: boolean\n@@ -168,9 +168,9 @@ declare module \"react-router-dom\" {\ndeclare export function matchPath(\npathname: string,\n- options?: MatchPathOptions | string,\n+ options?: MatchPathOptions | string | string[],\nparent?: Match\n): null | Match;\n- declare export function generatePath(pattern?: string, params?: Object): string;\n+ declare export function generatePath(pattern?: string, params?: { +[string]: mixed }): string;\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "web/flow-typed/npm/react-router-dom_v5.x.x.js", "diff": "+// flow-typed signature: 5c3ecc173e04f53b410aa08d80e28aa2\n+// flow-typed version: cb4e8f3aa2/react-router-dom_v5.x.x/flow_>=v0.98.x <=v0.103.x\n+\n+declare module \"react-router-dom\" {\n+ declare export var BrowserRouter: React$ComponentType<{|\n+ basename?: string,\n+ forceRefresh?: boolean,\n+ getUserConfirmation?: GetUserConfirmation,\n+ keyLength?: number,\n+ children?: React$Node\n+ |}>\n+\n+ declare export var HashRouter: React$ComponentType<{|\n+ basename?: string,\n+ getUserConfirmation?: GetUserConfirmation,\n+ hashType?: \"slash\" | \"noslash\" | \"hashbang\",\n+ children?: React$Node\n+ |}>\n+\n+ declare export var Link: React$ComponentType<{\n+ className?: string,\n+ to: string | LocationShape,\n+ replace?: boolean,\n+ children?: React$Node\n+ }>\n+\n+ declare export var NavLink: React$ComponentType<{\n+ to: string | LocationShape,\n+ activeClassName?: string,\n+ className?: string,\n+ activeStyle?: { +[string]: mixed },\n+ style?: { +[string]: mixed },\n+ isActive?: (match: Match, location: Location) => boolean,\n+ children?: React$Node,\n+ exact?: boolean,\n+ strict?: boolean\n+ }>\n+\n+ // NOTE: Below are duplicated from react-router. If updating these, please\n+ // update the react-router and react-router-native types as well.\n+ declare export type Location = {\n+ pathname: string,\n+ search: string,\n+ hash: string,\n+ state?: any,\n+ key?: string\n+ };\n+\n+ declare export type LocationShape = {\n+ pathname?: string,\n+ search?: string,\n+ hash?: string,\n+ state?: any\n+ };\n+\n+ declare export type HistoryAction = \"PUSH\" | \"REPLACE\" | \"POP\";\n+\n+ declare export type RouterHistory = {\n+ length: number,\n+ location: Location,\n+ action: HistoryAction,\n+ listen(\n+ callback: (location: Location, action: HistoryAction) => void\n+ ): () => void,\n+ push(path: string | LocationShape, state?: any): void,\n+ replace(path: string | LocationShape, state?: any): void,\n+ go(n: number): void,\n+ goBack(): void,\n+ goForward(): void,\n+ canGo?: (n: number) => boolean,\n+ block(\n+ callback: string | (location: Location, action: HistoryAction) => ?string\n+ ): () => void,\n+ // createMemoryHistory\n+ index?: number,\n+ entries?: Array<Location>\n+ };\n+\n+ declare export type Match = {\n+ params: { [key: string]: ?string },\n+ isExact: boolean,\n+ path: string,\n+ url: string\n+ };\n+\n+ declare export type ContextRouter = {|\n+ history: RouterHistory,\n+ location: Location,\n+ match: Match,\n+ staticContext?: StaticRouterContext\n+ |};\n+\n+ declare type ContextRouterVoid = {\n+ history: RouterHistory | void,\n+ location: Location | void,\n+ match: Match | void,\n+ staticContext?: StaticRouterContext | void\n+ };\n+\n+ declare export type GetUserConfirmation = (\n+ message: string,\n+ callback: (confirmed: boolean) => void\n+ ) => void;\n+\n+ declare export type StaticRouterContext = {\n+ url?: string\n+ };\n+\n+ declare export var StaticRouter: React$ComponentType<{|\n+ basename?: string,\n+ location?: string | Location,\n+ context: StaticRouterContext,\n+ children?: React$Node\n+ |}>\n+\n+ declare export var MemoryRouter: React$ComponentType<{|\n+ initialEntries?: Array<LocationShape | string>,\n+ initialIndex?: number,\n+ getUserConfirmation?: GetUserConfirmation,\n+ keyLength?: number,\n+ children?: React$Node\n+ |}>\n+\n+ declare export var Router: React$ComponentType<{|\n+ history: RouterHistory,\n+ children?: React$Node\n+ |}>\n+\n+ declare export var Prompt: React$ComponentType<{|\n+ message: string | ((location: Location) => string | boolean),\n+ when?: boolean\n+ |}>\n+\n+ declare export var Redirect: React$ComponentType<{|\n+ to: string | LocationShape,\n+ push?: boolean,\n+ from?: string,\n+ exact?: boolean,\n+ strict?: boolean\n+ |}>\n+\n+ declare export var Route: React$ComponentType<{|\n+ component?: React$ComponentType<*>,\n+ render?: (router: ContextRouter) => React$Node,\n+ children?: React$ComponentType<ContextRouter> | React$Node,\n+ path?: string | Array<string>,\n+ exact?: boolean,\n+ strict?: boolean,\n+ location?: LocationShape,\n+ sensitive?: boolean\n+ |}>\n+\n+ declare export var Switch: React$ComponentType<{|\n+ children?: React$Node,\n+ location?: Location\n+ |}>\n+\n+ declare export function withRouter<Props: {}, Component: React$ComponentType<Props>>(\n+ WrappedComponent: Component\n+ ): React$ComponentType<$Diff<React$ElementConfig<Component>, ContextRouterVoid>>;\n+\n+ declare type MatchPathOptions = {\n+ path?: string | string[],\n+ exact?: boolean,\n+ sensitive?: boolean,\n+ strict?: boolean\n+ };\n+\n+ declare export function matchPath(\n+ pathname: string,\n+ options?: MatchPathOptions | string | string[],\n+ parent?: Match\n+ ): null | Match;\n+\n+ declare export function generatePath(pattern?: string, params?: { +[string]: mixed }): string;\n+}\n" }, { "change_type": "RENAME", "old_path": "web/flow-typed/npm/react-router_v4.x.x.js", "new_path": "web/flow-typed/npm/react-router_v5.x.x.js", "diff": "-// flow-typed signature: fd05ff7ee75da2ba5d12a620675d5923\n-// flow-typed version: c6154227d1/react-router_v4.x.x/flow_>=v0.63.x <=v0.103.x\n+// flow-typed signature: 80f03b85756c359f80a69bddbefbf16d\n+// flow-typed version: 0fc30f59a5/react-router_v5.x.x/flow_>=v0.63.x <=v0.103.x\ndeclare module \"react-router\" {\n// NOTE: many of these are re-exported by react-router-dom and\n@@ -104,7 +104,7 @@ declare module \"react-router\" {\ncomponent?: React$ComponentType<*>,\nrender?: (router: ContextRouter) => React$Node,\nchildren?: React$ComponentType<ContextRouter> | React$Node,\n- path?: string,\n+ path?: string | Array<string>,\nexact?: boolean,\nstrict?: boolean,\nlocation?: LocationShape,\n@@ -121,7 +121,7 @@ declare module \"react-router\" {\n): React$ComponentType<P>;\ndeclare type MatchPathOptions = {\n- path?: string,\n+ path?: string | string[],\nexact?: boolean,\nstrict?: boolean,\nsensitive?: boolean\n@@ -129,6 +129,21 @@ declare module \"react-router\" {\ndeclare export function matchPath(\npathname: string,\n- options?: MatchPathOptions | string\n+ options?: MatchPathOptions | string | string[]\n): null | Match;\n+\n+ declare export function generatePath(pattern?: string, params?: {}): string;\n+\n+ declare export default {\n+ StaticRouter: typeof StaticRouter,\n+ MemoryRouter: typeof MemoryRouter,\n+ Router: typeof Router,\n+ Prompt: typeof Prompt,\n+ Redirect: typeof Redirect,\n+ Route: typeof Route,\n+ Switch: typeof Switch,\n+ withRouter: typeof withRouter,\n+ matchPath: typeof matchPath,\n+ generatePath: typeof generatePath,\n+ };\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Update react-router Flow libdefs
129,187
03.02.2020 13:57:41
18,000
ed31c33dde0e781065f1db1c2066812e9304be85
[native] Use
[ { "change_type": "MODIFY", "old_path": "native/ios/Podfile", "new_path": "native/ios/Podfile", "diff": "@@ -32,5 +32,8 @@ target 'SquadCal' do\npod 'react-native-ffmpeg/min-lts', :podspec => '../../node_modules/react-native-ffmpeg/ios/react-native-ffmpeg.podspec'\npod 'react-native-video/VideoCaching', :podspec => '../../node_modules/react-native-video/react-native-video.podspec'\n+ pod '1PasswordExtension', :git => 'https://github.com/agilebits/onepassword-app-extension.git',\n+ :commit => 'ba96cf1203f6ea749b7c3f4e921b15d577536253'\n+\nuse_native_modules!(\"..\")\nend\n" }, { "change_type": "MODIFY", "old_path": "native/ios/Podfile.lock", "new_path": "native/ios/Podfile.lock", "diff": "PODS:\n- - 1PasswordExtension (1.8.5)\n+ - 1PasswordExtension (1.8.6)\n- boost-for-react-native (1.63.0)\n- DoubleConversion (1.1.6)\n- DVAssetLoaderDelegate (0.3.3)\n@@ -15,15 +15,15 @@ PODS:\n- glog (0.3.5)\n- KeyboardTrackingView (5.5.0):\n- React\n- - libwebp (1.0.3):\n- - libwebp/demux (= 1.0.3)\n- - libwebp/mux (= 1.0.3)\n- - libwebp/webp (= 1.0.3)\n- - libwebp/demux (1.0.3):\n+ - libwebp (1.1.0):\n+ - libwebp/demux (= 1.1.0)\n+ - libwebp/mux (= 1.1.0)\n+ - libwebp/webp (= 1.1.0)\n+ - libwebp/demux (1.1.0):\n- libwebp/webp\n- - libwebp/mux (1.0.3):\n+ - libwebp/mux (1.1.0):\n- libwebp/demux\n- - libwebp/webp (1.0.3)\n+ - libwebp/webp (1.1.0)\n- lottie-ios (3.1.3)\n- lottie-react-native (3.2.1):\n- lottie-ios (~> 3.1.3)\n@@ -160,16 +160,17 @@ PODS:\n- React\n- RNVectorIcons (6.6.0):\n- React\n- - SDWebImage (5.1.1):\n- - SDWebImage/Core (= 5.1.1)\n- - SDWebImage/Core (5.1.1)\n- - SDWebImageWebPCoder (0.2.4):\n+ - SDWebImage (5.5.2):\n+ - SDWebImage/Core (= 5.5.2)\n+ - SDWebImage/Core (5.5.2)\n+ - SDWebImageWebPCoder (0.2.5):\n- libwebp (~> 1.0)\n- SDWebImage/Core (~> 5.0)\n- SPTPersistentCache (1.1.0)\n- yoga (0.60.6.React)\nDEPENDENCIES:\n+ - 1PasswordExtension (from `https://github.com/agilebits/onepassword-app-extension.git`, commit `ba96cf1203f6ea749b7c3f4e921b15d577536253`)\n- DoubleConversion (from `../../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec`)\n- Folly (from `../../node_modules/react-native/third-party-podspecs/Folly.podspec`)\n- glog (from `../../node_modules/react-native/third-party-podspecs/glog.podspec`)\n@@ -220,8 +221,7 @@ DEPENDENCIES:\n- yoga (from `../../node_modules/react-native/ReactCommon/yoga`)\nSPEC REPOS:\n- https://github.com/CocoaPods/Specs.git:\n- - 1PasswordExtension\n+ trunk:\n- boost-for-react-native\n- DVAssetLoaderDelegate\n- libwebp\n@@ -231,6 +231,9 @@ SPEC REPOS:\n- SPTPersistentCache\nEXTERNAL SOURCES:\n+ 1PasswordExtension:\n+ :commit: ba96cf1203f6ea749b7c3f4e921b15d577536253\n+ :git: https://github.com/agilebits/onepassword-app-extension.git\nDoubleConversion:\n:podspec: \"../../node_modules/react-native/third-party-podspecs/DoubleConversion.podspec\"\nFolly:\n@@ -328,15 +331,20 @@ EXTERNAL SOURCES:\nyoga:\n:path: \"../../node_modules/react-native/ReactCommon/yoga\"\n+CHECKOUT OPTIONS:\n+ 1PasswordExtension:\n+ :commit: ba96cf1203f6ea749b7c3f4e921b15d577536253\n+ :git: https://github.com/agilebits/onepassword-app-extension.git\n+\nSPEC CHECKSUMS:\n- 1PasswordExtension: 0e95bdea64ec8ff2f4f693be5467a09fac42a83d\n+ 1PasswordExtension: f97cc80ae58053c331b2b6dc8843ba7103b33794\nboost-for-react-native: 39c7adb57c4e60d6c5479dd8623128eb5b3f0f2c\nDoubleConversion: 5805e889d232975c086db112ece9ed034df7a0b2\nDVAssetLoaderDelegate: 0caec20e4e08b8560b691131539e9180024d4bce\nFolly: 30e7936e1c45c08d884aa59369ed951a8e68cf51\nglog: 1f3da668190260b06b429bb211bfbee5cd790c28\nKeyboardTrackingView: fd40d2a0acc26bcc923f39b8ad65d834ac5af217\n- libwebp: 057912d6d0abfb6357d8bb05c0ea470301f5d61e\n+ libwebp: 946cb3063cea9236285f7e9a8505d806d30e07f3\nlottie-ios: 496ac5cea1bbf1a7bd1f1f472f3232eb1b8d744b\nlottie-react-native: b123a79529cc732201091f585c62c89bb4747252\nmobile-ffmpeg-min: 05ebe3998721155274ae50466b5223d3637a92ab\n@@ -381,11 +389,11 @@ SPEC CHECKSUMS:\nRNReanimated: 6abbbae2e5e72609d85aabd92a982a94566885f1\nRNScreens: 000c9e6e31c9a483688943155107e4ca9394d37a\nRNVectorIcons: 0bb4def82230be1333ddaeee9fcba45f0b288ed4\n- SDWebImage: 96d7f03415ccb28d299d765f93557ff8a617abd8\n- SDWebImageWebPCoder: cc72085bb20368b2f8dbb21b7e355c667e1309b7\n+ SDWebImage: 4d5c027c935438f341ed33dbac53ff9f479922ca\n+ SDWebImageWebPCoder: 947093edd1349d820c40afbd9f42acb6cdecd987\nSPTPersistentCache: df36ea46762d7cf026502bbb86a8b79d0080dff4\nyoga: 5079887aa3e4c62142d6bcee493022643ee4d730\n-PODFILE CHECKSUM: edddd963d5b3cf05676bab073f5e73501d9b163f\n+PODFILE CHECKSUM: 854ab89ac3b1d39a6889a2a6c47a64f84df459b4\nCOCOAPODS: 1.8.4\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Use 1PasswordExtension@1.8.6
129,187
06.02.2020 18:28:09
18,000
259b08e42c3eaad72ba1fbec14e7f5c7e959244e
[native] TagInput hack to make backspace work correctly on Android
[ { "change_type": "MODIFY", "old_path": "native/components/tag-input.react.js", "new_path": "native/components/tag-input.react.js", "diff": "@@ -130,6 +130,7 @@ class TagInput<T> extends React.PureComponent<Props<T>, State> {\n// refs\ntagInput: ?React.ElementRef<typeof TextInput> = null;\nscrollView: ?React.ElementRef<typeof ScrollView> = null;\n+ lastChange: ?{| time: number, prevText: string |};\nstatic defaultProps = {\nminHeight: 30,\n@@ -187,13 +188,28 @@ class TagInput<T> extends React.PureComponent<Props<T>, State> {\n}\n}\n+ onChangeText = (text: string) => {\n+ this.lastChange = { time: Date.now(), prevText: this.props.text };\n+ this.props.onChangeText(text);\n+ }\n+\nonBlur = (event: { nativeEvent: { text: string } }) => {\ninvariant(Platform.OS === \"ios\", \"only iOS gets text on TextInput.onBlur\");\n- this.props.onChangeText(event.nativeEvent.text);\n+ this.onChangeText(event.nativeEvent.text);\n}\nonKeyPress = (event: { nativeEvent: { key: string } }) => {\n- if (this.props.text !== '' || event.nativeEvent.key !== 'Backspace') {\n+ const { lastChange } = this;\n+ let { text } = this.props;\n+ if (\n+ Platform.OS === \"android\" &&\n+ lastChange !== null &&\n+ lastChange !== undefined &&\n+ Date.now() - lastChange.time < 150\n+ ) {\n+ text = lastChange.prevText;\n+ }\n+ if (text !== '' || event.nativeEvent.key !== 'Backspace') {\nreturn;\n}\nconst tags = [...this.props.value];\n@@ -282,7 +298,7 @@ class TagInput<T> extends React.PureComponent<Props<T>, State> {\ncolor: inputColor,\n}]}\nonBlur={Platform.OS === \"ios\" ? this.onBlur : undefined}\n- onChangeText={this.props.onChangeText}\n+ onChangeText={this.onChangeText}\nautoCapitalize=\"none\"\nautoCorrect={false}\nplaceholder=\"Start typing\"\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] TagInput hack to make backspace work correctly on Android
129,187
06.02.2020 23:19:24
18,000
79ff4b682c3db903cda43a2471d98be9d2f65236
[native] Android TextInput transparent editTextBackground
[ { "change_type": "MODIFY", "old_path": "native/android/app/src/main/res/values/styles.xml", "new_path": "native/android/app/src/main/res/values/styles.xml", "diff": "<resources>\n<style name=\"AppTheme\" parent=\"Theme.AppCompat.Light.NoActionBar\">\n+ <item name=\"android:editTextBackground\">@android:color/transparent</item>\n</style>\n<style name=\"SplashTheme\" parent=\"Theme.AppCompat.Light.NoActionBar\">\n<item name=\"android:textColor\">#000000</item>\n" }, { "change_type": "MODIFY", "old_path": "native/calendar/entry.react.js", "new_path": "native/calendar/entry.react.js", "diff": "@@ -689,8 +689,8 @@ const styles = {\n},\ntextInput: {\nposition: 'absolute',\n- top: Platform.OS === \"android\" ? 2 : 0,\n- left: 10,\n+ top: Platform.OS === \"android\" ? 4.8 : 0,\n+ left: Platform.OS === \"android\" ? 9.8 : 10,\nright: 10,\npadding: 0,\nmargin: 0,\n" }, { "change_type": "MODIFY", "old_path": "native/chat/settings/delete-thread.react.js", "new_path": "native/chat/settings/delete-thread.react.js", "diff": "@@ -21,7 +21,6 @@ import {\nView,\nTextInput,\nScrollView,\n- Platform,\nAlert,\nActivityIndicator,\n} from 'react-native';\n@@ -278,10 +277,7 @@ const styles = {\nborderTopWidth: 1,\nborderBottomWidth: 1,\nborderColor: 'panelForegroundBorder',\n- paddingVertical: Platform.select({\n- ios: 12,\n- default: 8,\n- }),\n+ paddingVertical: 12,\npaddingHorizontal: 24,\nmarginBottom: 24,\n},\n" }, { "change_type": "MODIFY", "old_path": "native/components/search.react.js", "new_path": "native/components/search.react.js", "diff": "@@ -6,13 +6,7 @@ import type { ViewStyle, Styles } from '../types/styles';\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\n-import {\n- View,\n- ViewPropTypes,\n- TouchableOpacity,\n- TextInput,\n- Platform,\n-} from 'react-native';\n+import { View, ViewPropTypes, TouchableOpacity, TextInput } from 'react-native';\nimport Icon from 'react-native-vector-icons/FontAwesome';\nimport { connect } from 'lib/utils/redux-utils';\n@@ -74,7 +68,6 @@ class Search extends React.PureComponent<Props> {\nname=\"search\"\nsize={18}\ncolor={iconColor}\n- style={this.props.styles.searchIcon}\n/>\n<TextInput\nstyle={this.props.styles.searchInput}\n@@ -98,17 +91,13 @@ class Search extends React.PureComponent<Props> {\n}\nconst styles = {\n- searchIcon: {\n- paddingBottom: Platform.OS === \"android\" ? 0 : 2,\n- },\nsearch: {\nbackgroundColor: 'listSearchBackground',\nflexDirection: 'row',\nalignItems: 'center',\npaddingLeft: 14,\npaddingRight: 12,\n- paddingTop: Platform.OS === \"android\" ? 1 : 6,\n- paddingBottom: Platform.OS === \"android\" ? 2 : 6,\n+ paddingVertical: 6,\nborderRadius: 6,\n},\nsearchInput: {\n" }, { "change_type": "MODIFY", "old_path": "native/more/delete-account.react.js", "new_path": "native/more/delete-account.react.js", "diff": "@@ -20,7 +20,6 @@ import {\nView,\nTextInput,\nScrollView,\n- Platform,\nAlert,\nActivityIndicator,\n} from 'react-native';\n@@ -255,10 +254,7 @@ const styles = {\njustifyContent: 'space-between',\nborderTopWidth: 1,\nborderBottomWidth: 1,\n- paddingVertical: Platform.select({\n- ios: 12,\n- default: 8,\n- }),\n+ paddingVertical: 12,\npaddingHorizontal: 24,\nmarginBottom: 24,\nbackgroundColor: 'panelForeground',\n@@ -267,7 +263,7 @@ const styles = {\ninput: {\nflex: 1,\nfontSize: 16,\n- color: 'panelModalBackgroundLabel',\n+ color: 'panelBackgroundLabel',\nfontFamily: 'Arial',\npaddingVertical: 0,\n},\n" }, { "change_type": "MODIFY", "old_path": "native/more/edit-email.react.js", "new_path": "native/more/edit-email.react.js", "diff": "@@ -17,7 +17,6 @@ import {\nView,\nTextInput,\nScrollView,\n- Platform,\nAlert,\nActivityIndicator,\n} from 'react-native';\n@@ -316,10 +315,7 @@ const styles = {\njustifyContent: 'space-between',\nborderTopWidth: 1,\nborderBottomWidth: 1,\n- paddingVertical: Platform.select({\n- ios: 12,\n- default: 8,\n- }),\n+ paddingVertical: 12,\npaddingHorizontal: 24,\nmarginBottom: 24,\nbackgroundColor: 'panelForeground',\n" }, { "change_type": "MODIFY", "old_path": "native/more/edit-password.react.js", "new_path": "native/more/edit-password.react.js", "diff": "@@ -17,7 +17,6 @@ import {\nView,\nTextInput,\nScrollView,\n- Platform,\nAlert,\nActivityIndicator,\n} from 'react-native';\n@@ -371,10 +370,7 @@ const styles = {\nsection: {\nborderTopWidth: 1,\nborderBottomWidth: 1,\n- paddingVertical: Platform.select({\n- ios: 3,\n- default: 2,\n- }),\n+ paddingVertical: 3,\nmarginBottom: 24,\nbackgroundColor: 'panelForeground',\nborderColor: 'panelForegroundBorder',\n@@ -382,10 +378,7 @@ const styles = {\nrow: {\nflexDirection: 'row',\njustifyContent: 'space-between',\n- paddingVertical: Platform.select({\n- ios: 9,\n- default: 6,\n- }),\n+ paddingVertical: 9,\npaddingHorizontal: 24,\n},\nhr: {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Android TextInput transparent editTextBackground
129,187
07.02.2020 13:22:18
18,000
f2d322e95629e2106d1e585ffda2d9050ff2203a
[native] Fix up some color scheme issues Primarily placeholder color on `TextInput`s
[ { "change_type": "MODIFY", "old_path": "native/components/tag-input.react.js", "new_path": "native/components/tag-input.react.js", "diff": "@@ -239,11 +239,13 @@ class TagInput<T> extends React.PureComponent<Props<T>, State> {\n}\nrender() {\n- const tagColor = this.props.tagColor || this.props.colors.modalSubtext;\n+ const tagColor = this.props.tagColor ||\n+ this.props.colors.modalSubtext;\nconst tagTextColor = this.props.tagTextColor ||\n- this.props.colors.modalSubtextLabel;\n+ this.props.colors.modalForegroundLabel;\nconst inputColor = this.props.inputColor ||\n- this.props.colors.modalSubtextLabel;\n+ this.props.colors.modalForegroundLabel;\n+ const placeholderColor = this.props.colors.modalForegroundTertiaryLabel;\nconst tags = this.props.value.map((tag, index) => (\n<Tag\nindex={index}\n@@ -302,7 +304,7 @@ class TagInput<T> extends React.PureComponent<Props<T>, State> {\nautoCapitalize=\"none\"\nautoCorrect={false}\nplaceholder=\"Start typing\"\n- placeholderTextColor={tagColor}\n+ placeholderTextColor={placeholderColor}\nreturnKeyType=\"done\"\nkeyboardType=\"default\"\nunderlineColorAndroid=\"rgba(0,0,0,0)\"\n@@ -455,7 +457,7 @@ const styles = StyleSheet.create({\nflexWrap: 'wrap',\n},\ntextInput: {\n- fontSize: 18,\n+ fontSize: 16,\nheight: 24,\nflex: .6,\npadding: 0,\n@@ -467,7 +469,7 @@ const styles = StyleSheet.create({\n},\ntag: {\njustifyContent: 'center',\n- marginTop: 3,\n+ marginBottom: 3,\nmarginRight: 3,\npaddingVertical: 2,\npaddingHorizontal: 6,\n" }, { "change_type": "MODIFY", "old_path": "native/more/delete-account.react.js", "new_path": "native/more/delete-account.react.js", "diff": "@@ -8,6 +8,7 @@ import { loadingStatusPropType } from 'lib/types/loading-types';\nimport type { LogOutResult } from 'lib/types/account-types';\nimport { type GlobalTheme, globalThemePropType } from '../types/themes';\nimport type { Styles } from '../types/styles';\n+import { type Colors, colorsPropType } from '../themes/colors';\nimport {\ntype PreRequestUserState,\npreRequestUserStatePropType,\n@@ -37,7 +38,7 @@ import { preRequestUserStateSelector } from 'lib/selectors/account-selectors';\nimport Button from '../components/button.react';\nimport OnePasswordButton from '../components/one-password-button.react';\nimport { deleteNativeCredentialsFor } from '../account/native-credentials';\n-import { styleSelector } from '../themes/colors';\n+import { colorsSelector, styleSelector } from '../themes/colors';\ntype Props = {|\nnavigation: NavigationScreenProp<*>,\n@@ -46,6 +47,7 @@ type Props = {|\nusername: ?string,\npreRequestUserState: PreRequestUserState,\nactiveTheme: ?GlobalTheme,\n+ colors: Colors,\nstyles: Styles,\n// Redux dispatch functions\ndispatchActionPromise: DispatchActionPromise,\n@@ -69,6 +71,7 @@ class DeleteAccount extends React.PureComponent<Props, State> {\nusername: PropTypes.string,\npreRequestUserState: preRequestUserStatePropType.isRequired,\nactiveTheme: globalThemePropType,\n+ colors: colorsPropType.isRequired,\nstyles: PropTypes.objectOf(PropTypes.object).isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\ndeleteAccount: PropTypes.func.isRequired,\n@@ -123,6 +126,7 @@ class DeleteAccount extends React.PureComponent<Props, State> {\nconst buttonContent = this.props.loadingStatus === \"loading\"\n? <ActivityIndicator size=\"small\" color=\"white\" />\n: <Text style={this.props.styles.saveText}>Delete account</Text>;\n+ const { panelForegroundTertiaryLabel } = this.props.colors;\nreturn (\n<ScrollView\ncontentContainerStyle={this.props.styles.scrollViewContentContainer}\n@@ -149,6 +153,7 @@ class DeleteAccount extends React.PureComponent<Props, State> {\nvalue={this.state.password}\nonChangeText={this.onChangePasswordText}\nplaceholder=\"Password\"\n+ placeholderTextColor={panelForegroundTertiaryLabel}\nsecureTextEntry={true}\nreturnKeyType=\"go\"\nonSubmitEditing={this.submitDeletion}\n@@ -263,7 +268,7 @@ const styles = {\ninput: {\nflex: 1,\nfontSize: 16,\n- color: 'panelBackgroundLabel',\n+ color: 'panelForegroundLabel',\nfontFamily: 'Arial',\npaddingVertical: 0,\n},\n@@ -278,7 +283,7 @@ const styles = {\nsaveText: {\nfontSize: 18,\ntextAlign: 'center',\n- color: 'panelForegroundLabel',\n+ color: 'white',\n},\nonePasswordButton: {\nmarginLeft: 6,\n@@ -286,7 +291,7 @@ const styles = {\nwarningText: {\nmarginHorizontal: 24,\ntextAlign: 'center',\n- color: 'modalBackgroundLabel',\n+ color: 'panelForegroundLabel',\nfontSize: 16,\n},\nlastWarningText: {\n@@ -307,6 +312,7 @@ export default connect(\n: undefined,\npreRequestUserState: preRequestUserStateSelector(state),\nactiveTheme: state.globalThemeInfo.activeTheme,\n+ colors: colorsSelector(state),\nstyles: stylesSelector(state),\n}),\n{ deleteAccount },\n" }, { "change_type": "MODIFY", "old_path": "native/more/edit-email.react.js", "new_path": "native/more/edit-email.react.js", "diff": "@@ -9,6 +9,7 @@ import type { AccountUpdate } from 'lib/types/user-types';\nimport type { ChangeUserSettingsResult } from 'lib/types/account-types';\nimport { type GlobalTheme, globalThemePropType } from '../types/themes';\nimport type { Styles } from '../types/styles';\n+import { type Colors, colorsPropType } from '../themes/colors';\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\n@@ -33,7 +34,7 @@ import { createLoadingStatusSelector } from 'lib/selectors/loading-selectors';\nimport Button from '../components/button.react';\nimport OnePasswordButton from '../components/one-password-button.react';\n-import { styleSelector } from '../themes/colors';\n+import { colorsSelector, styleSelector } from '../themes/colors';\ntype Props = {|\nnavigation: NavigationScreenProp<*>,\n@@ -41,6 +42,7 @@ type Props = {|\nemail: ?string,\nloadingStatus: LoadingStatus,\nactiveTheme: ?GlobalTheme,\n+ colors: Colors,\nstyles: Styles,\n// Redux dispatch functions\ndispatchActionPromise: DispatchActionPromise,\n@@ -63,6 +65,7 @@ class EditEmail extends React.PureComponent<Props, State> {\nemail: PropTypes.string,\nloadingStatus: loadingStatusPropType.isRequired,\nactiveTheme: globalThemePropType,\n+ colors: colorsPropType.isRequired,\nstyles: PropTypes.objectOf(PropTypes.object).isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\nchangeUserSettings: PropTypes.func.isRequired,\n@@ -119,6 +122,7 @@ class EditEmail extends React.PureComponent<Props, State> {\nconst buttonContent = this.props.loadingStatus === \"loading\"\n? <ActivityIndicator size=\"small\" color=\"white\" />\n: <Text style={this.props.styles.saveText}>Save</Text>;\n+ const { panelForegroundTertiaryLabel } = this.props.colors;\nreturn (\n<ScrollView\ncontentContainerStyle={this.props.styles.scrollViewContentContainer}\n@@ -132,6 +136,7 @@ class EditEmail extends React.PureComponent<Props, State> {\nvalue={this.state.email}\nonChangeText={this.onChangeEmailText}\nplaceholder=\"Email\"\n+ placeholderTextColor={panelForegroundTertiaryLabel}\nautoFocus={true}\nselectTextOnFocus={true}\nreturnKeyType=\"next\"\n@@ -147,6 +152,7 @@ class EditEmail extends React.PureComponent<Props, State> {\nvalue={this.state.password}\nonChangeText={this.onChangePasswordText}\nplaceholder=\"Password\"\n+ placeholderTextColor={panelForegroundTertiaryLabel}\nsecureTextEntry={true}\nreturnKeyType=\"go\"\nonSubmitEditing={this.submitEmail}\n@@ -324,7 +330,7 @@ const styles = {\ninput: {\nflex: 1,\nfontSize: 16,\n- color: 'modalBackgroundLabel',\n+ color: 'panelForegroundLabel',\nfontFamily: 'Arial',\npaddingVertical: 0,\n},\n@@ -339,7 +345,7 @@ const styles = {\nsaveText: {\nfontSize: 18,\ntextAlign: 'center',\n- color: 'panelForegroundLabel',\n+ color: 'white',\n},\nonePasswordButton: {\nmarginLeft: 6,\n@@ -358,6 +364,7 @@ export default connect(\n: undefined,\nloadingStatus: loadingStatusSelector(state),\nactiveTheme: state.globalThemeInfo.activeTheme,\n+ colors: colorsSelector(state),\nstyles: stylesSelector(state),\n}),\n{ changeUserSettings },\n" }, { "change_type": "MODIFY", "old_path": "native/more/edit-password.react.js", "new_path": "native/more/edit-password.react.js", "diff": "@@ -9,6 +9,7 @@ import type { AccountUpdate } from 'lib/types/user-types';\nimport type { ChangeUserSettingsResult } from 'lib/types/account-types';\nimport { type GlobalTheme, globalThemePropType } from '../types/themes';\nimport type { Styles } from '../types/styles';\n+import { type Colors, colorsPropType } from '../themes/colors';\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\n@@ -33,13 +34,14 @@ import { createLoadingStatusSelector } from 'lib/selectors/loading-selectors';\nimport Button from '../components/button.react';\nimport OnePasswordButton from '../components/one-password-button.react';\nimport { setNativeCredentials } from '../account/native-credentials';\n-import { styleSelector } from '../themes/colors';\n+import { colorsSelector, styleSelector } from '../themes/colors';\ntype Props = {\nnavigation: NavigationScreenProp<*>,\n// Redux state\nloadingStatus: LoadingStatus,\nactiveTheme: ?GlobalTheme,\n+ colors: Colors,\nstyles: Styles,\n// Redux dispatch functions\ndispatchActionPromise: DispatchActionPromise,\n@@ -62,6 +64,7 @@ class EditPassword extends React.PureComponent<Props, State> {\n}).isRequired,\nloadingStatus: loadingStatusPropType.isRequired,\nactiveTheme: globalThemePropType,\n+ colors: colorsPropType.isRequired,\nstyles: PropTypes.objectOf(PropTypes.object).isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\nchangeUserSettings: PropTypes.func.isRequired,\n@@ -128,6 +131,7 @@ class EditPassword extends React.PureComponent<Props, State> {\nconst buttonContent = this.props.loadingStatus === \"loading\"\n? <ActivityIndicator size=\"small\" color=\"white\" />\n: <Text style={this.props.styles.saveText}>Save</Text>;\n+ const { panelForegroundTertiaryLabel } = this.props.colors;\nreturn (\n<ScrollView\ncontentContainerStyle={this.props.styles.scrollViewContentContainer}\n@@ -142,6 +146,7 @@ class EditPassword extends React.PureComponent<Props, State> {\nvalue={this.state.currentPassword}\nonChangeText={this.onChangeCurrentPassword}\nplaceholder=\"Current password\"\n+ placeholderTextColor={panelForegroundTertiaryLabel}\nsecureTextEntry={true}\nautoFocus={true}\nreturnKeyType=\"next\"\n@@ -160,6 +165,7 @@ class EditPassword extends React.PureComponent<Props, State> {\nvalue={this.state.newPassword}\nonChangeText={this.onChangeNewPassword}\nplaceholder=\"New password\"\n+ placeholderTextColor={panelForegroundTertiaryLabel}\nsecureTextEntry={true}\nreturnKeyType=\"next\"\nonSubmitEditing={this.focusConfirmPassword}\n@@ -175,6 +181,7 @@ class EditPassword extends React.PureComponent<Props, State> {\nvalue={this.state.confirmPassword}\nonChangeText={this.onChangeConfirmPassword}\nplaceholder=\"Confirm password\"\n+ placeholderTextColor={panelForegroundTertiaryLabel}\nsecureTextEntry={true}\nreturnKeyType=\"go\"\nonSubmitEditing={this.submitPassword}\n@@ -389,7 +396,7 @@ const styles = {\ninput: {\nflex: 1,\nfontSize: 16,\n- color: 'modalBackgroundLabel',\n+ color: 'panelForegroundLabel',\nfontFamily: 'Arial',\npaddingVertical: 0,\n},\n@@ -404,7 +411,7 @@ const styles = {\nsaveText: {\nfontSize: 18,\ntextAlign: 'center',\n- color: 'panelForegroundLabel',\n+ color: 'white',\n},\nonePasswordButton: {\nmarginLeft: 6,\n@@ -420,6 +427,7 @@ export default connect(\n(state: AppState) => ({\nloadingStatus: loadingStatusSelector(state),\nactiveTheme: state.globalThemeInfo.activeTheme,\n+ colors: colorsSelector(state),\nstyles: stylesSelector(state),\n}),\n{ changeUserSettings },\n" }, { "change_type": "MODIFY", "old_path": "native/themes/colors.js", "new_path": "native/themes/colors.js", "diff": "@@ -31,6 +31,7 @@ const light = Object.freeze({\nmodalForegroundBorder: '#CCCCCC',\nmodalForegroundLabel: 'black',\nmodalForegroundSecondaryLabel: '#888888',\n+ modalForegroundTertiaryLabel: '#AAAAAA',\nmodalBackground: '#EEEEEE',\nmodalBackgroundLabel: '#333333',\nmodalBackgroundSecondaryLabel: '#AAAAAA',\n@@ -88,6 +89,7 @@ const dark: Colors = Object.freeze({\nmodalForegroundBorder: '#1C1C1E',\nmodalForegroundLabel: 'white',\nmodalForegroundSecondaryLabel: '#AAAAAA',\n+ modalForegroundTertiaryLabel: '#666666',\nmodalBackground: '#2C2C2E',\nmodalBackgroundLabel: '#CCCCCC',\nmodalBackgroundSecondaryLabel: '#555555',\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Fix up some color scheme issues Primarily placeholder color on `TextInput`s
129,187
10.02.2020 10:55:23
18,000
e5f27cbc21f8fe2a28656fd71e0bc1880fda9664
[native] Fix ThreadSettings behavior when editing name/description
[ { "change_type": "MODIFY", "old_path": "native/chat/settings/thread-settings-description.react.js", "new_path": "native/chat/settings/thread-settings-description.react.js", "diff": "@@ -209,23 +209,25 @@ class ThreadSettingsDescription extends React.PureComponent<Props> {\nreturn;\n}\n+ const editDescriptionPromise = this.editDescription(description);\nthis.props.dispatchActionPromise(\nchangeThreadSettingsActionTypes,\n- this.editDescription(description),\n+ editDescriptionPromise,\n{\ncustomKeyName: `${changeThreadSettingsActionTypes.started}:description`,\n},\n);\n+ editDescriptionPromise.then(() => {\n+ this.props.setDescriptionEditValue(null);\n+ });\n}\nasync editDescription(newDescription: string) {\ntry {\n- const result = await this.props.changeThreadSettings({\n+ return await this.props.changeThreadSettings({\nthreadID: this.props.threadInfo.id,\nchanges: { description: newDescription },\n});\n- this.props.setDescriptionEditValue(null);\n- return result;\n} catch (e) {\nAlert.alert(\n\"Unknown error\",\n" }, { "change_type": "MODIFY", "old_path": "native/chat/settings/thread-settings-name.react.js", "new_path": "native/chat/settings/thread-settings-name.react.js", "diff": "@@ -175,21 +175,23 @@ class ThreadSettingsName extends React.PureComponent<Props> {\nreturn;\n}\n+ const editNamePromise = this.editName(name);\nthis.props.dispatchActionPromise(\nchangeThreadSettingsActionTypes,\n- this.editName(name),\n+ editNamePromise,\n{ customKeyName: `${changeThreadSettingsActionTypes.started}:name` },\n);\n+ editNamePromise.then(() => {\n+ this.props.setNameEditValue(null);\n+ });\n}\nasync editName(newName: string) {\ntry {\n- const result = await this.props.changeThreadSettings({\n+ return await this.props.changeThreadSettings({\nthreadID: this.props.threadInfo.id,\nchanges: { name: newName },\n});\n- this.props.setNameEditValue(null);\n- return result;\n} catch (e) {\nAlert.alert(\n\"Unknown error\",\n" }, { "change_type": "MODIFY", "old_path": "native/chat/settings/thread-settings.react.js", "new_path": "native/chat/settings/thread-settings.react.js", "diff": "@@ -315,10 +315,7 @@ class ThreadSettings extends React.PureComponent<Props, State> {\n}\nget canReset() {\n- return this.props.tabActive &&\n- (this.state.nameEditValue === null ||\n- this.state.nameEditValue === undefined) &&\n- !this.props.somethingIsSaving;\n+ return this.props.tabActive && !this.props.somethingIsSaving;\n}\nrender() {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Fix ThreadSettings behavior when editing name/description
129,187
10.02.2020 14:00:33
18,000
d524fb06edf81f602f538505057bdc42e9d1faac
[native] Fix up display of emojis in Entry Use `System` `fontFamily`, adjust spacing, and hide `Text` while `TextInput` is active
[ { "change_type": "MODIFY", "old_path": "native/calendar/entry.react.js", "new_path": "native/calendar/entry.react.js", "diff": "@@ -375,7 +375,11 @@ class InternalEntry extends React.Component<Props, State> {\nif (rawText === \"\" || rawText.slice(-1) === \"\\n\") {\nrawText += \" \";\n}\n- const textStyle = { color: textColor };\n+ const textStyle = {};\n+ textStyle.color = textColor;\n+ if (textInput) {\n+ textStyle.opacity = 0;\n+ }\nconst linkStyle = darkColor ? styles.lightLinkText : styles.darkLinkText;\n// We use an empty View to set the height of the entry, and then position\n// the Text and TextInput absolutely. This allows to measure height changes\n@@ -679,7 +683,7 @@ const styles = {\npaddingBottom: 6,\npaddingLeft: 10,\npaddingRight: 10,\n- fontFamily: 'Arial',\n+ fontFamily: 'System',\n},\ntextContainer: {\nposition: 'absolute',\n@@ -689,13 +693,13 @@ const styles = {\n},\ntextInput: {\nposition: 'absolute',\n- top: Platform.OS === \"android\" ? 4.8 : 0,\n+ top: Platform.OS === \"android\" ? 4.8 : 0.5,\nleft: Platform.OS === \"android\" ? 9.8 : 10,\nright: 10,\npadding: 0,\nmargin: 0,\nfontSize: 16,\n- fontFamily: 'Arial',\n+ fontFamily: 'System',\n},\nactionLinks: {\nflex: 1,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Fix up display of emojis in Entry Use `System` `fontFamily`, adjust spacing, and hide `Text` while `TextInput` is active
129,187
10.02.2020 14:07:39
18,000
e1144a7d6cca1253847cdc7be3e3637f7772bedb
[native] codeVersion -> 42
[ { "change_type": "MODIFY", "old_path": "native/android/app/build.gradle", "new_path": "native/android/app/build.gradle", "diff": "@@ -131,8 +131,8 @@ android {\napplicationId \"org.squadcal\"\nminSdkVersion rootProject.ext.minSdkVersion\ntargetSdkVersion rootProject.ext.targetSdkVersion\n- versionCode 41\n- versionName \"0.0.41\"\n+ versionCode 42\n+ versionName \"0.0.42\"\nmissingDimensionStrategy 'react-native-camera', 'general'\nmultiDexEnabled true\n}\n" }, { "change_type": "MODIFY", "old_path": "native/ios/SquadCal/Info.debug.plist", "new_path": "native/ios/SquadCal/Info.debug.plist", "diff": "<key>CFBundlePackageType</key>\n<string>APPL</string>\n<key>CFBundleShortVersionString</key>\n- <string>0.0.41</string>\n+ <string>0.0.42</string>\n<key>CFBundleSignature</key>\n<string>????</string>\n<key>CFBundleVersion</key>\n- <string>41</string>\n+ <string>42</string>\n<key>LSApplicationQueriesSchemes</key>\n<array>\n<string>org-appextension-feature-password-management</string>\n" }, { "change_type": "MODIFY", "old_path": "native/ios/SquadCal/Info.release.plist", "new_path": "native/ios/SquadCal/Info.release.plist", "diff": "<key>CFBundlePackageType</key>\n<string>APPL</string>\n<key>CFBundleShortVersionString</key>\n- <string>0.0.41</string>\n+ <string>0.0.42</string>\n<key>CFBundleSignature</key>\n<string>????</string>\n<key>CFBundleVersion</key>\n- <string>41</string>\n+ <string>42</string>\n<key>LSApplicationQueriesSchemes</key>\n<array>\n<string>org-appextension-feature-password-management</string>\n" }, { "change_type": "MODIFY", "old_path": "native/redux/persist.js", "new_path": "native/redux/persist.js", "diff": "@@ -164,7 +164,7 @@ const persistConfig = {\ntimeout: __DEV__ ? 0 : undefined,\n};\n-const codeVersion = 41;\n+const codeVersion = 42;\n// This local exists to avoid a circular dependency where redux-setup needs to\n// import all the navigation and screen stuff, but some of those screens want to\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] codeVersion -> 42
129,187
10.02.2020 14:35:55
18,000
90a0ce023e068a349747588b59e45f0ff926a20d
[server] Use license key for GeoIP update
[ { "change_type": "MODIFY", "old_path": "server/package.json", "new_path": "server/package.json", "diff": "\"babel-build\": \"yarn --silent babel src/ --out-dir dist/ --config-file ./.babelrc --verbose --ignore 'src/lib/flow-typed','src/lib/node_modules','src/lib/package.json','src/web/flow-typed','src/web/node_modules','src/web/package.json','src/web/dist','src/web/webpack.config.js','src/web/account-bar.react.js','src/web/app.react.js','src/web/calendar','src/web/chat','src/web/flow','src/web/loading-indicator.react.js','src/web/modals','src/web/root.js','src/web/router-history.js','src/web/script.js','src/web/selectors/chat-selectors.js','src/web/selectors/entry-selectors.js','src/web/splash','src/web/vector-utils.js','src/web/vectors.react.js'\",\n\"rsync\": \"rsync -rLpmuv --exclude '*/package.json' --exclude '*/node_modules/*' --include '*.json' --include '*.cjs' --exclude '*.*' src/ dist/\",\n\"prod-build\": \"yarn babel-build && yarn rsync && yarn update-geoip\",\n- \"update-geoip\": \"cd ../node_modules/geoip-lite && yarn updatedb\",\n+ \"update-geoip\": \"yarn script dist/scripts/update-geoip.js\",\n\"prod\": \"node --experimental-modules --experimental-json-modules --loader ./loader.mjs --es-module-specifier-resolution node dist/server\",\n\"dev-rsync\": \"yarn --silent chokidar --initial --silent -s 'src/**/*.json' 'src/**/*.cjs' -c 'yarn rsync > /dev/null 2>&1'\",\n\"dev\": \"NODE_ENV=dev yarn concurrently --names=\\\"BABEL,RSYNC,NODEM\\\" -c \\\"bgBlue.bold,bgMagenta.bold,bgGreen.bold\\\" \\\"yarn babel-build -- --watch\\\" \\\"yarn dev-rsync\\\" \\\"nodemon -e js,json,cjs --watch dist --experimental-modules --experimental-json-modules --loader ./loader.mjs --es-module-specifier-resolution node dist/server\\\"\",\n\"express\": \"^4.17.1\",\n\"express-ws\": \"^4.0.0\",\n\"firebase-admin\": \"^8.6.0\",\n- \"geoip-lite\": \"^1.3.8\",\n+ \"geoip-lite\": \"^1.4.0\",\n\"invariant\": \"^2.2.4\",\n\"lib\": \"0.0.1\",\n\"lodash\": \"^4.17.5\",\n" }, { "change_type": "MODIFY", "old_path": "server/src/cron/update-geoip-db.js", "new_path": "server/src/cron/update-geoip-db.js", "diff": "@@ -5,11 +5,15 @@ import geoip from 'geoip-lite';\nimport cluster from 'cluster';\nimport { handleAsyncPromise } from '../responders/handlers';\n+import geoipLicense from '../../secrets/geoip_license';\nfunction updateGeoipDB(): Promise<void> {\nconst spawned = childProcess.spawn(\nprocess.execPath,\n- [ '../node_modules/geoip-lite/scripts/updatedb.js' ],\n+ [\n+ '../node_modules/geoip-lite/scripts/updatedb.js',\n+ `license_key=${geoipLicense.key}`,\n+ ],\n);\nreturn new Promise((resolve, reject) => {\nspawned.on('error', reject);\n@@ -47,5 +51,6 @@ if (!cluster.isMaster) {\n}\nexport {\n+ updateGeoipDB,\nupdateAndReloadGeoipDB,\n};\n" }, { "change_type": "ADD", "old_path": null, "new_path": "server/src/scripts/update-geoip.js", "diff": "+// @flow\n+\n+import { endScript } from './utils';\n+import { updateGeoipDB } from '../cron/update-geoip-db';\n+\n+async function main() {\n+ try {\n+ await updateGeoipDB();\n+ endScript();\n+ } catch (e) {\n+ endScript();\n+ console.warn(e);\n+ }\n+}\n+\n+main();\n" }, { "change_type": "MODIFY", "old_path": "yarn.lock", "new_path": "yarn.lock", "diff": "@@ -5315,10 +5315,10 @@ generate-function@^2.3.1:\ndependencies:\nis-property \"^1.0.2\"\n-geoip-lite@^1.3.8:\n- version \"1.3.8\"\n- resolved \"https://registry.yarnpkg.com/geoip-lite/-/geoip-lite-1.3.8.tgz#f065424f338faaf85e0016ec93c25fd1bb97f611\"\n- integrity sha512-K0YNaQlHRjdLymVfDr47UEy+NTw40WLVmaAKy8lCzIrwWvuS764ZeIDlDofdApFWVbwU3HgJoU4oSIJvsA09bg==\n+geoip-lite@^1.4.0:\n+ version \"1.4.0\"\n+ resolved \"https://registry.yarnpkg.com/geoip-lite/-/geoip-lite-1.4.0.tgz#7fd823491484e2f2290b9f3c55900f328dc78249\"\n+ integrity sha512-pQmZqkOAs6yRAEruVvX9Vbj1rdGHSc8QpbOA/FSZIhIsTsySOrufc3DPxjHimWo4zxIZMbdHwOiWvA6FB3bZhQ==\ndependencies:\nasync \"^2.1.1\"\ncolors \"^1.1.2\"\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Use license key for GeoIP update
129,187
12.02.2020 18:03:22
18,000
445e99e5e5c786fe61e2cbce0b15ca7128efaa23
Return partial details from fileInfoFromData on failure
[ { "change_type": "MODIFY", "old_path": "lib/utils/file-utils.js", "new_path": "lib/utils/file-utils.js", "diff": "@@ -4,19 +4,23 @@ import type { MediaType } from '../types/media-types';\nimport fileType from 'file-type';\n-type FileInfo = {| name: string, mime: string, mediaType: MediaType |};\n+type FileInfo = {|\n+ mime: ?string,\n+ mediaType: ?MediaType,\n+ name: ?string,\n+|};\nfunction fileInfoFromData(\ndata: Uint8Array | Buffer,\nfileName: string,\n-): ?FileInfo {\n+): FileInfo {\nconst fileTypeResult = fileType(data);\nif (!fileTypeResult) {\n- return null;\n+ return { mime: null, mediaType: null, name: null };\n}\nconst { ext, mime } = fileTypeResult;\nconst mediaType = mimeTypesToMediaTypes[mime];\nif (!mediaType) {\n- return null;\n+ return { mime, mediaType, name: null };\n}\nlet [ readableFileName ] = fileName.split('.');\nif (!readableFileName) {\n" }, { "change_type": "MODIFY", "old_path": "native/media/save-image.js", "new_path": "native/media/save-image.js", "diff": "@@ -111,9 +111,8 @@ async function saveToDisk(uri: string, directory: string) {\nconst intArray = dataURIToIntArray(dataURI);\nconst fileName = blob.data.name ? blob.data.name : \"\";\n- const fileInfo = fileInfoFromData(intArray, fileName);\n- invariant(fileInfo, 'unsupported media type');\n- const { name, mime } = fileInfo;\n+ const { name } = fileInfoFromData(intArray, fileName);\n+ invariant(name, 'unsupported media type');\nconst filePath = `${directory}/${name}`;\nawait filesystem.writeFile(filePath, base64, 'base64');\n" }, { "change_type": "MODIFY", "old_path": "native/utils/media-utils.js", "new_path": "native/utils/media-utils.js", "diff": "@@ -181,15 +181,11 @@ async function convertMedia(\nconst intArray = dataURIToIntArray(dataURI);\nconst blobName = blob.data.name;\n- const fileInfo = fileInfoFromData(intArray, blobName);\n- if (!fileInfo) {\n+ const { name, mime, mediaType } = fileInfoFromData(intArray, blobName);\n+ if (!name || !mime || mediaType !== \"photo\") {\nreturn null;\n}\n- const { name, mime, mediaType } = fileInfo;\n- if (mediaType !== \"photo\") {\n- return null;\n- }\nreturn {\nuploadURI: Platform.OS === \"ios\" ? dataURI : uri,\nshouldDisposePath: null,\n" }, { "change_type": "MODIFY", "old_path": "server/src/uploads/media-utils.js", "new_path": "server/src/uploads/media-utils.js", "diff": "@@ -19,18 +19,26 @@ async function validateAndConvert(\ninitialName: string,\nsize: number, // in bytes\n): Promise<?UploadInput> {\n- const fileInfo = fileInfoFromData(initialBuffer, initialName);\n- if (!fileInfo) {\n+ const {\n+ mime,\n+ mediaType,\n+ name,\n+ } = fileInfoFromData(initialBuffer, initialName);\n+ if (!mime || !mediaType || !name) {\nreturn null;\n}\n- const { mime } = fileInfo;\nif (!allowedMimeTypes.has(mime)) {\n// This should've gotten converted on the client\nreturn null;\n}\nif (size < fiveMegabytes && (mime === \"image/png\" || mime === \"image/jpeg\")) {\n- return { ...fileInfo, buffer: initialBuffer };\n+ return {\n+ mime,\n+ mediaType,\n+ name,\n+ buffer: initialBuffer,\n+ };\n}\nlet sharpImage;\n@@ -52,11 +60,20 @@ async function validateAndConvert(\n}\nconst convertedBuffer = await sharpImage.toBuffer();\n- const convertedFileInfo = fileInfoFromData(convertedBuffer, initialName);\n- if (!convertedFileInfo) {\n+ const {\n+ mime: convertedMIME,\n+ mediaType: convertedMediaType,\n+ name: convertedName,\n+ } = fileInfoFromData(convertedBuffer, initialName);\n+ if (!convertedMIME || !convertedMediaType || !convertedName) {\nreturn null;\n}\n- return { ...convertedFileInfo, buffer: convertedBuffer };\n+ return {\n+ mime: convertedMIME,\n+ mediaType: convertedMediaType,\n+ name: convertedName,\n+ buffer: convertedBuffer,\n+ };\n}\nexport {\n" }, { "change_type": "MODIFY", "old_path": "web/utils/media-utils.js", "new_path": "web/utils/media-utils.js", "diff": "@@ -40,12 +40,11 @@ type FileValidationResult = {|\n|};\nasync function validateFile(file: File): Promise<?FileValidationResult> {\nconst arrayBuffer = await blobToArrayBuffer(file);\n- const fileInfo = fileInfoFromData(new Uint8Array(arrayBuffer), file.name);\n- if (!fileInfo) {\n- return null;\n- }\n- const { name, mime, mediaType } = fileInfo;\n- if (!allowedMimeTypes.has(mime)) {\n+ const { name, mime, mediaType } = fileInfoFromData(\n+ new Uint8Array(arrayBuffer),\n+ file.name,\n+ );\n+ if (!name || !mime || !mediaType || !allowedMimeTypes.has(mime)) {\nreturn null;\n}\nlet dimensions = null;\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Return partial details from fileInfoFromData on failure
129,187
12.02.2020 21:22:49
18,000
644acd9118d9d695761214cdb6b1869988ddac9b
MediaMission for validateMedia on native
[ { "change_type": "MODIFY", "old_path": "lib/types/media-types.js", "new_path": "lib/types/media-types.js", "diff": "@@ -96,3 +96,136 @@ export type UpdateMultimediaMessageMediaPayload = {|\nexport type UploadDeletionRequest = {|\nid: string,\n|};\n+\n+export type MediaMissionStep =\n+ | {|\n+ step: \"photo_capture\",\n+ time: number, // ms\n+ dimensions: Dimensions,\n+ filename: string,\n+ uri: string,\n+ |}\n+ | {|\n+ step: \"photo_library\",\n+ dimensions: Dimensions,\n+ filename: string,\n+ uri: string,\n+ |}\n+ | {|\n+ step: \"video_library\",\n+ dimensions: Dimensions,\n+ filename: string,\n+ uri: string,\n+ playableDuration: number,\n+ |}\n+ | {|\n+ step: \"validation\",\n+ type: MediaType,\n+ success: bool,\n+ time: number, // ms\n+ blobFetched: bool,\n+ blobMIME: ?string,\n+ reportedMIME: ?string,\n+ blobName: ?string,\n+ size: ?number,\n+ |}\n+ | {|\n+ step: \"photo_resize_transcode\",\n+ success: bool,\n+ time: number, // ms\n+ newMIME: ?string,\n+ newDimensions: ?Dimensions,\n+ newURI: ?string,\n+ newPath: ?string,\n+ newName: ?string,\n+ |}\n+ | {|\n+ step: \"video_copy\",\n+ success: bool,\n+ time: number, // ms\n+ newPath: ?string,\n+ |}\n+ | {|\n+ step: \"video_probe\",\n+ success: bool,\n+ time: number, // ms\n+ path: string,\n+ ext: string,\n+ codec: ?string,\n+ |}\n+ | {|\n+ step: \"video_ios_native_transcode\",\n+ success: bool,\n+ time: number, // ms\n+ newURI: ?string,\n+ newPath: ?string,\n+ |}\n+ | {|\n+ step: \"video_ffmpeg_transcode\",\n+ success: bool,\n+ time: number, // ms\n+ newPath: ?string,\n+ |}\n+ | {|\n+ step: \"final_file_data_analysis\",\n+ success: bool,\n+ time: number, // ms\n+ uri: string,\n+ detectedMIME: ?string,\n+ detectedMediaType: ?string,\n+ newName: ?string,\n+ |}\n+ | {|\n+ step: \"dispose_uploaded_local_file\",\n+ success: bool,\n+ time: number, // ms\n+ path: string,\n+ |};\n+\n+export type MediaMissionFailure =\n+ | {|\n+ success: false,\n+ reason: \"too_large_cant_downscale\",\n+ size: number, // in bytes\n+ |}\n+ | {|\n+ success: false,\n+ reason: \"blob_reported_mime_issue\",\n+ mime: ?string,\n+ |}\n+ | {|\n+ success: false,\n+ reason: \"file_data_detected_mime_issue\",\n+ reportedMIME: string,\n+ reportedMediaType: MediaType,\n+ detectedMIME: ?string,\n+ detectedMediaType: ?MediaType,\n+ |}\n+ | {|\n+ success: false,\n+ reason: \"http_upload_failed\",\n+ |}\n+ | {|\n+ success: false,\n+ reason: \"video_path_extraction_failed\",\n+ uri: string,\n+ |}\n+ | {|\n+ success: false,\n+ reason: \"video_ios_asset_copy_failed\",\n+ inputURI: string,\n+ destinationPath: string,\n+ |}\n+ | {|\n+ success: false,\n+ reason: \"video_transcode_failed\",\n+ |};\n+\n+type MediaMissionResult =\n+ | MediaMissionFailure\n+ | {| success: true |};\n+\n+export type MediaMission = {|\n+ steps: MediaMissionStep[],\n+ result: MediaMissionResult,\n+|};\n" }, { "change_type": "MODIFY", "old_path": "native/chat/chat-input-state-container.react.js", "new_path": "native/chat/chat-input-state-container.react.js", "diff": "@@ -357,8 +357,8 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\nmediaInfoWithID: MediaInfoWithID,\n): Promise<?string> {\nconst { localID, mediaInfo } = mediaInfoWithID;\n- const validationResult = await validateMedia(mediaInfo);\n- if (!validationResult) {\n+ const { result: validationResult } = await validateMedia(mediaInfo);\n+ if (!validationResult.success) {\nconst message = \"validation failed\";\nthis.handleUploadFailure(localMessageID, localID, message);\nreturn message;\n" }, { "change_type": "MODIFY", "old_path": "native/utils/media-utils.js", "new_path": "native/utils/media-utils.js", "diff": "// @flow\n-import type { Dimensions, MediaType } from 'lib/types/media-types';\n+import type {\n+ Dimensions,\n+ MediaType,\n+ MediaMissionStep,\n+ MediaMissionFailure,\n+} from 'lib/types/media-types';\nimport type {\nClientPhotoInfo,\nClientVideoInfo,\n@@ -41,29 +46,76 @@ type ReactNativeBlob =\n& { data: { type: string, name: string, size: number } };\nexport type MediaValidationResult =\n| {|\n+ success: true,\n...ClientPhotoInfo,\nblob: ReactNativeBlob,\n|}\n- | ClientVideoInfo;\n+ | {|\n+ success: true,\n+ ...ClientVideoInfo,\n+ blob: ?ReactNativeBlob,\n+ |};\nasync function validateMedia(\nmediaInfo: ClientMediaInfo,\n-): Promise<?MediaValidationResult> {\n+): Promise<{|\n+ steps: $ReadOnlyArray<MediaMissionStep>,\n+ result: MediaMissionFailure | MediaValidationResult,\n+|}> {\nconst { dimensions, uri, type, filename } = mediaInfo;\n- if (mediaInfo.type === \"video\") {\n- return { type: \"video\", uri, dimensions, filename };\n- }\n+ const blobFetchStart = Date.now();\n- const blob = await getBlobFromURI(uri, type);\n- const reportedMIME =\n+ let blob, reportedMIME, reportedMediaType;\n+ try {\n+ blob = await getBlobFromURI(uri, type);\n+ reportedMIME =\n(uri.startsWith('ph://') && blob.type === \"application/octet-stream\")\n? \"video/quicktime\"\n: blob.type;\n+ reportedMediaType = mimeTypesToMediaTypes[reportedMIME];\n+ } catch { }\n- const mediaType = mimeTypesToMediaTypes[reportedMIME];\n- if (mediaType !== \"photo\") {\n- return null;\n+ const validationStep = {\n+ step: \"validation\",\n+ type,\n+ success: type === reportedMediaType,\n+ time: Date.now() - blobFetchStart,\n+ blobFetched: !!blob,\n+ blobMIME: blob ? blob.type : null,\n+ reportedMIME,\n+ blobName: (blob && blob.data) ? blob.data.name : null,\n+ size: blob ? blob.size : null,\n+ };\n+\n+ let result;\n+ if (type === \"photo\") {\n+ if (blob && reportedMediaType === \"photo\") {\n+ result = {\n+ success: true,\n+ type: \"photo\",\n+ uri,\n+ dimensions,\n+ filename,\n+ blob,\n+ };\n+ } else {\n+ result = {\n+ success: false,\n+ reason: \"blob_reported_mime_issue\",\n+ mime: reportedMIME,\n+ };\n+ }\n+ } else {\n+ result = {\n+ success: true,\n+ type: \"video\",\n+ uri,\n+ dimensions,\n+ filename,\n+ blob,\n+ };\n}\n- return { type: \"photo\", uri, dimensions, filename, blob };\n+\n+ return { steps: [ validationStep ], result };\n}\nfunction blobToDataURI(blob: Blob): Promise<string> {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
MediaMission for validateMedia on native
129,187
17.02.2020 21:16:07
28,800
226ebadf27531a6d84fd9c1b3a3ae9cb564fac7f
MediaMission for transcodeVideo on native
[ { "change_type": "MODIFY", "old_path": "lib/types/media-types.js", "new_path": "lib/types/media-types.js", "diff": "@@ -97,6 +97,15 @@ export type UploadDeletionRequest = {|\nid: string,\n|};\n+export type VideoProbeMediaMissionStep = {|\n+ step: \"video_probe\",\n+ success: bool,\n+ time: number, // ms\n+ path: string,\n+ ext: ?string,\n+ codec: ?string,\n+|};\n+\nexport type MediaMissionStep =\n| {|\nstep: \"photo_capture\",\n@@ -145,25 +154,18 @@ export type MediaMissionStep =\ntime: number, // ms\nnewPath: ?string,\n|}\n- | {|\n- step: \"video_probe\",\n- success: bool,\n- time: number, // ms\n- path: string,\n- ext: string,\n- codec: ?string,\n- |}\n+ | VideoProbeMediaMissionStep\n| {|\nstep: \"video_ios_native_transcode\",\nsuccess: bool,\ntime: number, // ms\n- newURI: ?string,\nnewPath: ?string,\n|}\n| {|\nstep: \"video_ffmpeg_transcode\",\nsuccess: bool,\ntime: number, // ms\n+ returnCode: ?number,\nnewPath: ?string,\n|}\n| {|\n" }, { "change_type": "MODIFY", "old_path": "native/utils/media-utils.js", "new_path": "native/utils/media-utils.js", "diff": "@@ -182,11 +182,11 @@ async function convertMedia(\n): Promise<?MediaConversionResult> {\nconst { uri, dimensions } = validationResult;\nif (validationResult.type === \"video\") {\n- const result = await transcodeVideo(validationResult);\n- if (!result) {\n+ const { result } = await transcodeVideo(validationResult);\n+ if (!result.success) {\nreturn null;\n}\n- const { uri: uploadURI, filename } = result.videoInfo;\n+ const { uri: uploadURI, filename } = result;\nconst shouldDisposePath = uri !== uploadURI ? uploadURI : null;\nreturn {\nuploadURI,\n" }, { "change_type": "MODIFY", "old_path": "native/utils/video-utils.js", "new_path": "native/utils/video-utils.js", "diff": "// @flow\n+import type {\n+ MediaMissionStep,\n+ MediaMissionFailure,\n+ VideoProbeMediaMissionStep,\n+} from 'lib/types/media-types';\n+\nimport filesystem from 'react-native-fs';\nimport { RNFFmpeg } from 'react-native-ffmpeg';\nimport { NativeModules, Platform } from 'react-native';\n@@ -23,29 +29,35 @@ type TranscodeVideoInfo = {\nfilename: string,\n...\n};\n-type TranscodeResult = $Shape<{|\n- iosCopy: {| time: number |},\n- initialProbe: {| time: number |},\n- iosNativeTranscode: {| time: number, success: bool |},\n- ffmpegTranscode: {| time: number, success: bool |},\n-|}>;\nasync function transcodeVideo<InputInfo: TranscodeVideoInfo>(\ninput: InputInfo,\n-): Promise<?{| videoInfo: InputInfo, transcodeResult: TranscodeResult |}> {\n- const transcodeResult: TranscodeResult = {}, createdPaths = [];\n+): Promise<{|\n+ steps: $ReadOnlyArray<MediaMissionStep>,\n+ result: MediaMissionFailure | (InputInfo & { success: true, ... }),\n+|}> {\n+ const steps = [], createdPaths = [];\nlet path = pathFromURI(input.uri), filename = input.filename;\n- const finish = () => {\n+ const finish = (failure?: MediaMissionFailure) => {\nfor (let createdPath of createdPaths) {\n- if (createdPath !== path) {\n+ if (failure || createdPath !== path) {\nfilesystem.unlink(createdPath);\n}\n}\n- if (!path) {\n- return null;\n+ if (failure) {\n+ return { steps, result: failure };\n}\n+ invariant(\n+ path,\n+ \"if we're finishing successfully we should have a final path\",\n+ );\nreturn {\n- videoInfo: { ...input, uri: `file://${path}`, filename },\n- transcodeResult,\n+ steps,\n+ result: {\n+ ...input,\n+ uri: `file://${path}`,\n+ filename,\n+ success: true,\n+ },\n};\n};\n@@ -65,20 +77,32 @@ async function transcodeVideo<InputInfo: TranscodeVideoInfo>(\ncreatedPaths.push(iosCopyPath);\npath = iosCopyPath;\n} catch (e) { }\n- transcodeResult.iosCopy = { time: Date.now() - copyStart };\n- }\n+ steps.push({\n+ step: \"video_copy\",\n+ success: !!path,\n+ time: Date.now() - copyStart,\n+ newPath: path,\n+ });\nif (!path) {\n- console.log(`could not extract path from ${input.uri}`);\n- return finish();\n+ return finish({\n+ success: false,\n+ reason: \"video_ios_asset_copy_failed\",\n+ inputURI: input.uri,\n+ destinationPath: iosCopyPath,\n+ });\n+ }\n+ } else if (!path) {\n+ return finish({\n+ success: false,\n+ reason: \"video_path_extraction_failed\",\n+ uri: input.uri,\n+ });\n}\n// Let's decide if we even need to do a transcoding step\n- const {\n- success: initialCheck,\n- timing: initialCheckTiming,\n- } = await checkVideoCodec(path);\n- transcodeResult.initialProbe = { time: initialCheckTiming };\n- if (initialCheck) {\n+ const initialCheckStep = await checkVideoCodec(path);\n+ steps.push(initialCheckStep);\n+ if (initialCheckStep.success) {\nreturn finish();\n}\n@@ -87,7 +111,6 @@ async function transcodeVideo<InputInfo: TranscodeVideoInfo>(\n// iOS defaults to HEVC since iOS 11\nif (Platform.OS === \"ios\") {\nconst iosNativeTranscodeStart = Date.now();\n- let iosNativeTranscodeSuccess = false;\ntry {\nconst [ iosNativeTranscodedURI ] = await MovToMp4.convertMovToMp4(\npath,\n@@ -100,20 +123,35 @@ async function transcodeVideo<InputInfo: TranscodeVideoInfo>(\niosNativeTranscodedURI,\n);\ncreatedPaths.push(iosNativeTranscodedPath);\n- const { success: iosCheck } = await checkVideoCodec(\n+ const iosTranscodeProbeStep = await checkVideoCodec(\niosNativeTranscodedPath,\n);\n- if (iosCheck) {\n+ if (iosTranscodeProbeStep.success) {\npath = iosNativeTranscodedPath;\n- iosNativeTranscodeSuccess = true;\n- }\n- } catch (e) { }\n- transcodeResult.iosNativeTranscode = {\n+ steps.push({\n+ step: \"video_ios_native_transcode\",\n+ success: true,\ntime: Date.now() - iosNativeTranscodeStart,\n- success: iosNativeTranscodeSuccess,\n- };\n- if (iosNativeTranscodeSuccess) {\n+ newPath: path,\n+ });\n+ steps.push(iosTranscodeProbeStep);\nreturn finish();\n+ } else {\n+ steps.push({\n+ step: \"video_ios_native_transcode\",\n+ success: false,\n+ time: Date.now() - iosNativeTranscodeStart,\n+ newPath: iosNativeTranscodedPath,\n+ });\n+ steps.push(iosTranscodeProbeStep);\n+ }\n+ } catch (e) {\n+ steps.push({\n+ step: \"video_ios_native_transcode\",\n+ success: false,\n+ time: Date.now() - iosNativeTranscodeStart,\n+ newPath: null,\n+ });\n}\n}\n@@ -127,7 +165,6 @@ async function transcodeVideo<InputInfo: TranscodeVideoInfo>(\ndefault: 'h264',\n});\nconst ffmpegTranscodeStart = Date.now();\n- let ffmpegTranscodeSuccess = false;\nconst ffmpegTranscodedPath =\n`${filesystem.TemporaryDirectoryPath}transcode.${Date.now()}.${filename}`;\ntry {\n@@ -136,44 +173,75 @@ async function transcodeVideo<InputInfo: TranscodeVideoInfo>(\n);\nif (rc === 0) {\ncreatedPaths.push(ffmpegTranscodedPath);\n- const { success: transcodeCheck } = await checkVideoCodec(\n+ const transcodeProbeStep = await checkVideoCodec(\nffmpegTranscodedPath,\n);\n- if (transcodeCheck) {\n+ steps.push({\n+ step: \"video_ffmpeg_transcode\",\n+ success: transcodeProbeStep.success,\n+ time: Date.now() - ffmpegTranscodeStart,\n+ returnCode: rc,\n+ newPath: ffmpegTranscodedPath,\n+ });\n+ steps.push(transcodeProbeStep);\n+ if (transcodeProbeStep.success) {\npath = ffmpegTranscodedPath;\n- ffmpegTranscodeSuccess = true;\n+ } else {\n+ return finish({\n+ success: false,\n+ reason: \"video_transcode_failed\",\n+ });\n}\n+ } else {\n+ steps.push({\n+ step: \"video_ffmpeg_transcode\",\n+ success: false,\n+ time: Date.now() - ffmpegTranscodeStart,\n+ returnCode: rc,\n+ newPath: null,\n+ });\n+ return finish({\n+ success: false,\n+ reason: \"video_transcode_failed\",\n+ });\n}\n- } catch (e) { }\n- transcodeResult.ffmpegTranscode = {\n+ } catch (e) {\n+ steps.push({\n+ step: \"video_ffmpeg_transcode\",\n+ success: false,\ntime: Date.now() - ffmpegTranscodeStart,\n- success: ffmpegTranscodeSuccess,\n- };\n-\n- if (!ffmpegTranscodeSuccess) {\n- console.log(\n- `failed to transcode ${input.uri}, ` +\n- `result: ${JSON.stringify(transcodeResult)}`,\n- );\n- path = null;\n+ returnCode: null,\n+ newPath: null,\n+ });\n+ return finish({\n+ success: false,\n+ reason: \"video_transcode_failed\",\n+ });\n}\nreturn finish();\n}\n-type CheckCodecResult = {|\n- success: bool,\n- timing: number,\n-|};\n-async function checkVideoCodec(path: string) {\n+async function checkVideoCodec(\n+ path: string,\n+): Promise<VideoProbeMediaMissionStep> {\nconst probeStart = Date.now();\nconst ext = extensionFromFilename(path);\nlet success = ext === \"mp4\" || ext === \"mov\";\n+ let codec;\nif (success) {\nconst videoInfo = await RNFFmpeg.getMediaInformation(path);\n- success = getVideoCodec(videoInfo) === \"h264\";\n+ codec = getVideoCodec(videoInfo);\n+ success = codec === \"h264\";\n}\n- return { success, timing: Date.now() - probeStart };\n+ return {\n+ step: \"video_probe\",\n+ success,\n+ time: Date.now() - probeStart,\n+ path,\n+ ext,\n+ codec,\n+ };\n}\nfunction getVideoCodec(info): ?string {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
MediaMission for transcodeVideo on native
129,187
02.03.2020 18:28:46
18,000
382b7f68750614845ccae440647f4c453d18c276
MediaMission for convertMedia on native
[ { "change_type": "MODIFY", "old_path": "lib/types/media-types.js", "new_path": "lib/types/media-types.js", "diff": "@@ -21,7 +21,7 @@ export type Image = {|\ndimensions: Dimensions,\n// stored on native only during creation in case retry needed after state lost\nfilename?: string,\n- unlinkURIAfterRemoving?: bool,\n+ unlinkURIAfterRemoving?: ?bool,\n|};\nexport type Video = {|\n@@ -31,7 +31,7 @@ export type Video = {|\ndimensions: Dimensions,\n// stored on native only during creation in case retry needed after state lost\nfilename?: string,\n- unlinkURIAfterRemoving?: bool,\n+ unlinkURIAfterRemoving?: ?bool,\n|};\nexport type Media =\n" }, { "change_type": "MODIFY", "old_path": "native/chat/chat-input-state-container.react.js", "new_path": "native/chat/chat-input-state-container.react.js", "diff": "@@ -363,8 +363,8 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\nthis.handleUploadFailure(localMessageID, localID, message);\nreturn message;\n}\n- const conversionResult = await convertMedia(validationResult);\n- if (!conversionResult) {\n+ const { result: conversionResult } = await convertMedia(validationResult);\n+ if (!conversionResult.success) {\nconst message = \"conversion failed\";\nthis.handleUploadFailure(localMessageID, localID, message);\nreturn message;\n" }, { "change_type": "MODIFY", "old_path": "native/chat/chat-input-state.js", "new_path": "native/chat/chat-input-state.js", "diff": "@@ -15,7 +15,7 @@ export type ClientPhotoInfo = {|\nuri: string,\ndimensions: Dimensions,\nfilename: string,\n- unlinkURIAfterRemoving?: bool,\n+ unlinkURIAfterRemoving?: ?bool,\n|};\nexport type ClientVideoInfo = {|\n@@ -23,14 +23,14 @@ export type ClientVideoInfo = {|\nuri: string,\ndimensions: Dimensions,\nfilename: string,\n- unlinkURIAfterRemoving?: bool,\n+ unlinkURIAfterRemoving?: ?bool,\n|};\nexport type ClientMediaInfo =\n| ClientPhotoInfo\n| ClientVideoInfo;\n-export const clientMediaInfoPropType = PropTypes.oneOf([\n+export const clientMediaInfoPropType = PropTypes.oneOfType([\nPropTypes.shape({\ntype: PropTypes.oneOf([ \"photo\" ]).isRequired,\nuri: PropTypes.string.isRequired,\n" }, { "change_type": "MODIFY", "old_path": "native/utils/media-utils.js", "new_path": "native/utils/media-utils.js", "diff": "@@ -170,6 +170,7 @@ function getDimensions(uri: string): Promise<Dimensions> {\n}\nexport type MediaConversionResult = {|\n+ success: true,\nuploadURI: string,\nshouldDisposePath: ?string,\nname: string,\n@@ -179,73 +180,179 @@ export type MediaConversionResult = {|\n|};\nasync function convertMedia(\nvalidationResult: MediaValidationResult,\n-): Promise<?MediaConversionResult> {\n- const { uri, dimensions } = validationResult;\n- if (validationResult.type === \"video\") {\n- const { result } = await transcodeVideo(validationResult);\n- if (!result.success) {\n- return null;\n+): Promise<{|\n+ steps: $ReadOnlyArray<MediaMissionStep>,\n+ result: MediaMissionFailure | MediaConversionResult,\n+|}> {\n+ let steps = [];\n+ let uploadURI = validationResult.uri,\n+ dimensions = validationResult.dimensions,\n+ shouldDisposePath = null,\n+ name = validationResult.filename,\n+ mime = null,\n+ mediaType = validationResult.type;\n+ const finish = (failure?: MediaMissionFailure) => {\n+ if (failure) {\n+ return { steps, result: failure };\n}\n- const { uri: uploadURI, filename } = result;\n- const shouldDisposePath = uri !== uploadURI ? uploadURI : null;\n+ invariant(\n+ mime,\n+ \"if we're finishing successfully we should have a MIME type\",\n+ );\nreturn {\n+ steps,\n+ result: {\n+ success: true,\nuploadURI,\nshouldDisposePath,\n- name: filename,\n- mime: \"video/mp4\",\n- mediaType: \"video\",\n+ name,\n+ mime,\n+ mediaType,\ndimensions,\n+ },\n+ };\n};\n- }\n-\n- let { blob } = validationResult;\n- const { type: reportedMIME, size } = blob;\n+ if (validationResult.type === \"video\") {\n+ const {\n+ steps: transcodeSteps,\n+ result: transcodeResult,\n+ } = await transcodeVideo(validationResult);\n+ steps = [ ...steps, ...transcodeSteps ];\n+ if (!transcodeResult.success) {\n+ return finish(transcodeResult);\n+ }\n+ uploadURI = transcodeResult.uri;\n+ name = transcodeResult.filename;\n+ shouldDisposePath = validationResult.uri !== uploadURI ? uploadURI : null;\n+ mime = \"video/mp4\";\n+ } else if (validationResult.type === \"photo\") {\n+ const { type: reportedMIME, size } = validationResult.blob;\nif (\nreportedMIME === \"image/heic\" ||\nsize > 5e6 ||\n(size > 5e5 && (dimensions.width > 3000 || dimensions.height > 2000))\n) {\n+ const photoResizeStart = Date.now();\ntry {\nconst compressFormat = reportedMIME === \"image/png\" ? \"PNG\" : \"JPEG\";\nconst compressQuality = size > 5e6 ? 92 : 100;\n- const { uri: resizedURI, path, name } =\n+ const { uri: resizedURI, path, name: resizedName } =\nawait ImageResizer.createResizedImage(\n- uri,\n+ uploadURI,\n3000,\n2000,\ncompressFormat,\ncompressQuality,\n);\n- const resizedDimensions = await getDimensions(resizedURI);\n- return {\n- uploadURI: resizedURI,\n- shouldDisposePath: path,\n- name,\n- mime: reportedMIME === \"image/png\" ? \"image/png\" : \"image/jpeg\",\n- mediaType: \"photo\",\n- dimensions: resizedDimensions,\n- };\n+ uploadURI = resizedURI;\n+ name = resizedName;\n+ shouldDisposePath = path;\n+ mime = reportedMIME === \"image/png\" ? \"image/png\" : \"image/jpeg\";\n+ dimensions = await getDimensions(resizedURI);\n} catch (e) { }\n+ const success = uploadURI !== validationResult.uri;\n+ steps.push({\n+ step: \"photo_resize_transcode\",\n+ success,\n+ time: Date.now() - photoResizeStart,\n+ newMIME: success ? mime : null,\n+ newDimensions: success ? dimensions : null,\n+ newURI: success ? uploadURI : null,\n+ newPath: success ? shouldDisposePath : null,\n+ newName: success ? name : null,\n+ });\n+ if (!success) {\n+ return finish({\n+ success: false,\n+ reason: \"too_large_cant_downscale\",\n+ size,\n+ });\n+ }\n+ }\n}\n- const dataURI = await blobToDataURI(blob);\n+ let { blob } = validationResult;\n+ if (uploadURI !== validationResult.uri) {\n+ const newMediaInfo = validationResult.type === \"video\"\n+ ? {\n+ type: \"video\",\n+ uri: uploadURI,\n+ dimensions,\n+ filename: name,\n+ unlinkURIAfterRemoving: validationResult.unlinkURIAfterRemoving,\n+ }\n+ : {\n+ type: \"photo\",\n+ uri: uploadURI,\n+ dimensions,\n+ filename: name,\n+ unlinkURIAfterRemoving: validationResult.unlinkURIAfterRemoving,\n+ };\n+ const {\n+ steps: newValidationSteps,\n+ result: newValidationResult,\n+ } = await validateMedia(newMediaInfo);\n+ steps = [ ...steps, ...newValidationSteps ];\n+ if (!newValidationResult.success) {\n+ return finish(newValidationResult);\n+ }\n+ blob = newValidationResult.blob;\n+ }\n+\n+ let fileDataDetectionStep, dataURI;\n+ if (blob) {\n+ const fileDataDetectionStart = Date.now();\n+ dataURI = await blobToDataURI(blob);\nconst intArray = dataURIToIntArray(dataURI);\nconst blobName = blob.data.name;\n- const { name, mime, mediaType } = fileInfoFromData(intArray, blobName);\n- if (!name || !mime || mediaType !== \"photo\") {\n- return null;\n+ const fileDetectionResult = fileInfoFromData(intArray, blobName);\n+ fileDataDetectionStep = {\n+ step: \"final_file_data_analysis\",\n+ success: !!fileDetectionResult.name &&\n+ !!fileDetectionResult.mime &&\n+ fileDetectionResult.mediaType === validationResult.type,\n+ time: Date.now() - fileDataDetectionStart,\n+ uri: uploadURI,\n+ detectedMIME: fileDetectionResult.mime,\n+ detectedMediaType: fileDetectionResult.mediaType,\n+ newName: fileDetectionResult.name,\n+ };\n+ steps.push(fileDataDetectionStep);\n+ if (fileDetectionResult.name) {\n+ name = fileDetectionResult.name;\n+ }\n+ if (fileDetectionResult.mime) {\n+ mime = fileDetectionResult.mime;\n+ }\n}\n- return {\n- uploadURI: Platform.OS === \"ios\" ? dataURI : uri,\n- shouldDisposePath: null,\n- name,\n- mime,\n- mediaType: \"photo\",\n- dimensions,\n- };\n+ if (\n+ validationResult.type === \"photo\" &&\n+ uploadURI === validationResult.uri &&\n+ (!fileDataDetectionStep || !fileDataDetectionStep.success)\n+ ) {\n+ const reportedMIME = validationResult.blob.type;\n+ return finish({\n+ success: false,\n+ reason: \"file_data_detected_mime_issue\",\n+ reportedMIME,\n+ reportedMediaType: validationResult.type,\n+ detectedMIME: mime,\n+ detectedMediaType: mediaType,\n+ });\n+ }\n+\n+ if (Platform.OS === \"ios\" && mediaType === \"photo\" && dataURI) {\n+ // TODO do we even need this? compare how long upload takes once that step\n+ // is recorded\n+ // TODO should this depend on uploadURI protocol instead of dataURI\n+ // existing?\n+ //console.log(`iOS ${uploadURI} -> ${dataURI}`);\n+ uploadURI = dataURI;\n+ }\n+ return finish();\n}\nfunction getCompatibleMediaURI(uri: string, ext: string): string {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
MediaMission for convertMedia on native
129,187
02.03.2020 18:46:47
18,000
ee017152974a93bf29a015c4a452f293208a25ec
[native] Combine validateMedia and convertMedia into processMedia
[ { "change_type": "MODIFY", "old_path": "native/chat/chat-input-state-container.react.js", "new_path": "native/chat/chat-input-state-container.react.js", "diff": "@@ -39,7 +39,7 @@ import {\nimport { createMediaMessageInfo } from 'lib/shared/message-utils';\nimport { ChatInputStateContext } from './chat-input-state';\n-import { validateMedia, convertMedia } from '../utils/media-utils';\n+import { processMedia } from '../utils/media-utils';\nimport { displayActionResultModal } from '../navigation/action-result-modal';\nlet nextLocalUploadID = 0;\n@@ -357,15 +357,9 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\nmediaInfoWithID: MediaInfoWithID,\n): Promise<?string> {\nconst { localID, mediaInfo } = mediaInfoWithID;\n- const { result: validationResult } = await validateMedia(mediaInfo);\n- if (!validationResult.success) {\n- const message = \"validation failed\";\n- this.handleUploadFailure(localMessageID, localID, message);\n- return message;\n- }\n- const { result: conversionResult } = await convertMedia(validationResult);\n- if (!conversionResult.success) {\n- const message = \"conversion failed\";\n+ const { result: processResult, steps } = await processMedia(mediaInfo);\n+ if (!processResult.success) {\n+ const message = \"processing failed\";\nthis.handleUploadFailure(localMessageID, localID, message);\nreturn message;\n}\n@@ -375,7 +369,7 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\nname,\nmime,\nmediaType,\n- } = conversionResult;\n+ } = processResult;\nlet result, message;\ntry {\n@@ -401,7 +395,7 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\nid: result.id,\nuri: result.uri,\ntype: mediaType,\n- dimensions: conversionResult.dimensions,\n+ dimensions: processResult.dimensions,\nfilename: undefined,\nunlinkURIAfterRemoving: undefined,\n},\n" }, { "change_type": "MODIFY", "old_path": "native/utils/media-utils.js", "new_path": "native/utils/media-utils.js", "diff": "@@ -371,10 +371,30 @@ function getCompatibleMediaURI(uri: string, ext: string): string {\n`?id=${photoKitLocalIdentifier}&ext=${ext}`;\n}\n+async function processMedia(\n+ mediaInfo: ClientMediaInfo,\n+): Promise<{|\n+ steps: $ReadOnlyArray<MediaMissionStep>,\n+ result: MediaMissionFailure | MediaConversionResult,\n+|}> {\n+ const {\n+ result: validationResult,\n+ steps: validationSteps,\n+ } = await validateMedia(mediaInfo);\n+ if (!validationResult.success) {\n+ return { result: validationResult, steps: validationSteps };\n+ }\n+ const {\n+ result: conversionResult,\n+ steps: conversionSteps,\n+ } = await convertMedia(validationResult);\n+ const steps = [ ...validationSteps, ...conversionSteps ];\n+ return { steps, result: conversionResult };\n+}\n+\nexport {\n- validateMedia,\nblobToDataURI,\ndataURIToIntArray,\n- convertMedia,\n+ processMedia,\ngetCompatibleMediaURI,\n};\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Combine validateMedia and convertMedia into processMedia
129,187
02.03.2020 19:00:28
18,000
9be892adfe0368090a94ccb97a9c6df411eef86c
[native] Keep Redux info needed for media retry in localMediaCreationInfo
[ { "change_type": "MODIFY", "old_path": "lib/types/media-types.js", "new_path": "lib/types/media-types.js", "diff": "@@ -14,14 +14,18 @@ export const dimensionsPropType = PropTypes.shape({\nexport type MediaType = \"photo\" | \"video\";\n+// stored on native only during creation in case retry needed after state lost\n+type LocalMediaCreationInfo = {|\n+ filename: string,\n+ unlinkURIAfterRemoving: ?bool,\n+|};\n+\nexport type Image = {|\nid: string,\nuri: string,\ntype: \"photo\",\ndimensions: Dimensions,\n- // stored on native only during creation in case retry needed after state lost\n- filename?: string,\n- unlinkURIAfterRemoving?: ?bool,\n+ localMediaCreationInfo?: LocalMediaCreationInfo,\n|};\nexport type Video = {|\n@@ -29,9 +33,7 @@ export type Video = {|\nuri: string,\ntype: \"video\",\ndimensions: Dimensions,\n- // stored on native only during creation in case retry needed after state lost\n- filename?: string,\n- unlinkURIAfterRemoving?: ?bool,\n+ localMediaCreationInfo?: LocalMediaCreationInfo,\n|};\nexport type Media =\n" }, { "change_type": "MODIFY", "old_path": "native/chat/chat-input-state-container.react.js", "new_path": "native/chat/chat-input-state-container.react.js", "diff": "@@ -305,8 +305,10 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\nuri,\ntype: \"photo\",\ndimensions,\n+ localMediaCreationInfo: {\nfilename,\nunlinkURIAfterRemoving,\n+ },\n};\n} else {\nreturn {\n@@ -314,8 +316,10 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\nuri,\ntype: \"video\",\ndimensions,\n+ localMediaCreationInfo: {\nfilename,\nunlinkURIAfterRemoving,\n+ },\n};\n}\n},\n@@ -396,8 +400,7 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\nuri: result.uri,\ntype: mediaType,\ndimensions: processResult.dimensions,\n- filename: undefined,\n- unlinkURIAfterRemoving: undefined,\n+ localMediaCreationInfo: undefined,\n},\n},\n);\n@@ -571,13 +574,13 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\nid,\ndimensions,\nuri,\n- filename,\n- unlinkURIAfterRemoving,\n+ localMediaCreationInfo,\n} = singleMedia;\ninvariant(\n- filename,\n- \"filename should be set on locally created Media\",\n+ localMediaCreationInfo,\n+ \"localMediaCreationInfo should be set on locally created Media\",\n);\n+ const { filename, unlinkURIAfterRemoving } = localMediaCreationInfo;\nif (singleMedia.type === \"photo\") {\nreturn {\nlocalID: id,\n" }, { "change_type": "MODIFY", "old_path": "native/media/multimedia.react.js", "new_path": "native/media/multimedia.react.js", "diff": "@@ -43,7 +43,10 @@ class Multimedia extends React.PureComponent<Props, State> {\nconst newURI = this.props.mediaInfo.uri;\nconst oldURI = prevProps.mediaInfo.uri;\nif (newURI !== oldURI && !this.state.departingURI) {\n- const unlinkDepartingURI = !!prevProps.mediaInfo.unlinkURIAfterRemoving;\n+ const unlinkDepartingURI = !!(\n+ prevProps.mediaInfo.localMediaCreationInfo &&\n+ prevProps.mediaInfo.localMediaCreationInfo.unlinkURIAfterRemoving\n+ );\nthis.setState({\ncurrentURI: newURI,\ndepartingURI: oldURI,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Keep Redux info needed for media retry in localMediaCreationInfo
129,187
02.03.2020 20:02:13
18,000
8bd56af83c3b667d06aa097161336e1b992f80d5
New type MediaSelection for native
[ { "change_type": "MODIFY", "old_path": "lib/types/media-types.js", "new_path": "lib/types/media-types.js", "diff": "@@ -14,18 +14,13 @@ export const dimensionsPropType = PropTypes.shape({\nexport type MediaType = \"photo\" | \"video\";\n-// stored on native only during creation in case retry needed after state lost\n-type LocalMediaCreationInfo = {|\n- filename: string,\n- unlinkURIAfterRemoving: ?bool,\n-|};\n-\nexport type Image = {|\nid: string,\nuri: string,\ntype: \"photo\",\ndimensions: Dimensions,\n- localMediaCreationInfo?: LocalMediaCreationInfo,\n+ // stored on native only during creation in case retry needed after state lost\n+ localMediaSelection?: MediaSelection,\n|};\nexport type Video = {|\n@@ -33,7 +28,8 @@ export type Video = {|\nuri: string,\ntype: \"video\",\ndimensions: Dimensions,\n- localMediaCreationInfo?: LocalMediaCreationInfo,\n+ // stored on native only during creation in case retry needed after state lost\n+ localMediaSelection?: MediaSelection,\n|};\nexport type Media =\n@@ -108,14 +104,7 @@ export type VideoProbeMediaMissionStep = {|\ncodec: ?string,\n|};\n-export type MediaMissionStep =\n- | {|\n- step: \"photo_capture\",\n- time: number, // ms\n- dimensions: Dimensions,\n- filename: string,\n- uri: string,\n- |}\n+export type MediaLibrarySelection =\n| {|\nstep: \"photo_library\",\ndimensions: Dimensions,\n@@ -128,7 +117,38 @@ export type MediaMissionStep =\nfilename: string,\nuri: string,\nplayableDuration: number,\n- |}\n+ |};\n+\n+export const mediaLibrarySelectionPropType = PropTypes.oneOfType([\n+ PropTypes.shape({\n+ step: PropTypes.oneOf([ \"photo_library\" ]).isRequired,\n+ dimensions: dimensionsPropType.isRequired,\n+ filename: PropTypes.string.isRequired,\n+ uri: PropTypes.string.isRequired,\n+ }),\n+ PropTypes.shape({\n+ step: PropTypes.oneOf([ \"video_library\" ]).isRequired,\n+ dimensions: dimensionsPropType.isRequired,\n+ filename: PropTypes.string.isRequired,\n+ uri: PropTypes.string.isRequired,\n+ playableDuration: PropTypes.number.isRequired,\n+ }),\n+]);\n+\n+export type PhotoCapture = {|\n+ step: \"photo_capture\",\n+ time: number, // ms\n+ dimensions: Dimensions,\n+ filename: string,\n+ uri: string,\n+|};\n+\n+export type MediaSelection =\n+ | MediaLibrarySelection\n+ | PhotoCapture;\n+\n+export type MediaMissionStep =\n+ | MediaSelection\n| {|\nstep: \"validation\",\ntype: MediaType,\n" }, { "change_type": "MODIFY", "old_path": "native/chat/chat-input-state-container.react.js", "new_path": "native/chat/chat-input-state-container.react.js", "diff": "// @flow\n-import type {\n- PendingMultimediaUploads,\n- ClientMediaInfo,\n-} from './chat-input-state';\n+import type { PendingMultimediaUploads } from './chat-input-state';\nimport type { AppState } from '../redux/redux-setup';\nimport type {\nDispatchActionPayload,\nDispatchActionPromise,\n} from 'lib/utils/action-utils';\n-import type { UploadMultimediaResult, Media } from 'lib/types/media-types';\n+import type {\n+ UploadMultimediaResult,\n+ Media,\n+ MediaSelection,\n+} from 'lib/types/media-types';\nimport {\nmessageTypes,\ntype RawMessageInfo,\n@@ -43,8 +44,8 @@ import { processMedia } from '../utils/media-utils';\nimport { displayActionResultModal } from '../navigation/action-result-modal';\nlet nextLocalUploadID = 0;\n-type MediaInfoWithID = {|\n- mediaInfo: ClientMediaInfo,\n+type SelectionWithID = {|\n+ selection: MediaSelection,\nlocalID: string,\n|};\ntype CompletedUploads = { [localMessageID: string]: ?Set<string> };\n@@ -262,16 +263,16 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\nsendMultimediaMessage = async (\nthreadID: string,\n- mediaInfos: $ReadOnlyArray<ClientMediaInfo>,\n+ selections: $ReadOnlyArray<MediaSelection>,\n) => {\nconst localMessageID = `local${this.props.nextLocalID}`;\n- const mediaInfosWithIDs = mediaInfos.map(mediaInfo => ({\n- mediaInfo,\n+ const selectionsWithIDs = selections.map(selection => ({\n+ selection,\nlocalID: `localUpload${nextLocalUploadID++}`,\n}));\nconst pendingUploads = {};\n- for (let { localID, mediaInfo: { uri } } of mediaInfosWithIDs) {\n+ for (let { localID } of selectionsWithIDs) {\npendingUploads[localID] = {\nfailed: null,\nprogressPercent: 0,\n@@ -290,38 +291,37 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\n() => {\nconst creatorID = this.props.viewerID;\ninvariant(creatorID, \"need viewer ID in order to send a message\");\n- const media = mediaInfosWithIDs.map(\n- ({ localID, mediaInfo }) => {\n- const {\n- uri,\n- dimensions,\n- filename,\n- unlinkURIAfterRemoving,\n- } = mediaInfo;\n- // This conditional is for Flow\n- if (mediaInfo.type === \"photo\") {\n+ const media = selectionsWithIDs.map(\n+ ({ localID, selection }) => {\n+ if (selection.step === \"photo_library\") {\nreturn {\nid: localID,\n- uri,\n+ uri: selection.uri,\ntype: \"photo\",\n- dimensions,\n- localMediaCreationInfo: {\n- filename,\n- unlinkURIAfterRemoving,\n- },\n+ dimensions: selection.dimensions,\n+ localMediaSelection: selection,\n};\n- } else {\n+ } else if (selection.step === \"photo_capture\") {\n+ return {\n+ id: localID,\n+ uri: selection.uri,\n+ type: \"photo\",\n+ dimensions: selection.dimensions,\n+ localMediaSelection: selection,\n+ };\n+ } else if (selection.step === \"video_library\") {\nreturn {\nid: localID,\n- uri,\n+ uri: selection.uri,\ntype: \"video\",\n- dimensions,\n- localMediaCreationInfo: {\n- filename,\n- unlinkURIAfterRemoving,\n- },\n+ dimensions: selection.dimensions,\n+ localMediaSelection: selection,\n};\n}\n+ invariant(\n+ false,\n+ `invalid selection ${JSON.stringify(selection)}`,\n+ );\n},\n);\nconst messageInfo = createMediaMessageInfo({\n@@ -337,17 +337,17 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\n},\n);\n- await this.uploadFiles(localMessageID, mediaInfosWithIDs);\n+ await this.uploadFiles(localMessageID, selectionsWithIDs);\n}\nasync uploadFiles(\nlocalMessageID: string,\n- mediaInfosWithIDs: $ReadOnlyArray<MediaInfoWithID>,\n+ selectionsWithIDs: $ReadOnlyArray<SelectionWithID>,\n) {\nconst results = await Promise.all(\n- mediaInfosWithIDs.map(mediaInfo => this.uploadFile(\n+ selectionsWithIDs.map(selectionWithID => this.uploadFile(\nlocalMessageID,\n- mediaInfo,\n+ selectionWithID,\n)),\n);\nconst errors = [ ...new Set(results.filter(Boolean)) ];\n@@ -358,9 +358,38 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\nasync uploadFile(\nlocalMessageID: string,\n- mediaInfoWithID: MediaInfoWithID,\n+ selectionWithID: SelectionWithID,\n): Promise<?string> {\n- const { localID, mediaInfo } = mediaInfoWithID;\n+ const { localID, selection } = selectionWithID;\n+ let mediaInfo;\n+ if (selection.step === \"photo_library\") {\n+ mediaInfo = {\n+ type: \"photo\",\n+ uri: selection.uri,\n+ dimensions: selection.dimensions,\n+ filename: selection.filename,\n+ };\n+ } else if (selection.step === \"photo_capture\") {\n+ mediaInfo = {\n+ type: \"photo\",\n+ uri: selection.uri,\n+ dimensions: selection.dimensions,\n+ filename: selection.filename,\n+ };\n+ } else if (selection.step === \"video_library\") {\n+ mediaInfo = {\n+ type: \"video\",\n+ uri: selection.uri,\n+ dimensions: selection.dimensions,\n+ filename: selection.filename,\n+ };\n+ } else {\n+ invariant(\n+ false,\n+ `invalid selection ${JSON.stringify(selection)}`,\n+ );\n+ }\n+\nconst { result: processResult, steps } = await processMedia(mediaInfo);\nif (!processResult.success) {\nconst message = \"processing failed\";\n@@ -568,44 +597,16 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\n},\n}));\n- const mediaInfos: MediaInfoWithID[] =\n- retryMedia.map(singleMedia => {\n- const {\n- id,\n- dimensions,\n- uri,\n- localMediaCreationInfo,\n- } = singleMedia;\n+ const selectionsWithIDs = retryMedia.map(singleMedia => {\n+ const { id, localMediaSelection } = singleMedia;\ninvariant(\n- localMediaCreationInfo,\n- \"localMediaCreationInfo should be set on locally created Media\",\n+ localMediaSelection,\n+ \"localMediaSelection should be set on locally created Media\",\n);\n- const { filename, unlinkURIAfterRemoving } = localMediaCreationInfo;\n- if (singleMedia.type === \"photo\") {\n- return {\n- localID: id,\n- mediaInfo: {\n- type: \"photo\",\n- dimensions,\n- uri,\n- filename,\n- unlinkURIAfterRemoving,\n- },\n- };\n- } else {\n- return {\n- localID: id,\n- mediaInfo: {\n- type: \"video\",\n- dimensions,\n- uri,\n- filename,\n- unlinkURIAfterRemoving,\n- },\n- };\n- }\n+ return { selection: localMediaSelection, localID: id };\n});\n- await this.uploadFiles(localMessageID, mediaInfos);\n+\n+ await this.uploadFiles(localMessageID, selectionsWithIDs);\n}\nrender() {\n" }, { "change_type": "MODIFY", "old_path": "native/chat/chat-input-state.js", "new_path": "native/chat/chat-input-state.js", "diff": "// @flow\n-import { type Dimensions, dimensionsPropType } from 'lib/types/media-types';\n+import type { Dimensions, MediaSelection } from 'lib/types/media-types';\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\n@@ -10,43 +10,6 @@ export type PendingMultimediaUpload = {|\nprogressPercent: number,\n|};\n-export type ClientPhotoInfo = {|\n- type: \"photo\",\n- uri: string,\n- dimensions: Dimensions,\n- filename: string,\n- unlinkURIAfterRemoving?: ?bool,\n-|};\n-\n-export type ClientVideoInfo = {|\n- type: \"video\",\n- uri: string,\n- dimensions: Dimensions,\n- filename: string,\n- unlinkURIAfterRemoving?: ?bool,\n-|};\n-\n-export type ClientMediaInfo =\n- | ClientPhotoInfo\n- | ClientVideoInfo;\n-\n-export const clientMediaInfoPropType = PropTypes.oneOfType([\n- PropTypes.shape({\n- type: PropTypes.oneOf([ \"photo\" ]).isRequired,\n- uri: PropTypes.string.isRequired,\n- dimensions: dimensionsPropType.isRequired,\n- filename: PropTypes.string.isRequired,\n- unlinkURIAfterRemoving: PropTypes.bool,\n- }),\n- PropTypes.shape({\n- type: PropTypes.oneOf([ \"video\" ]).isRequired,\n- uri: PropTypes.string.isRequired,\n- dimensions: dimensionsPropType.isRequired,\n- filename: PropTypes.string.isRequired,\n- unlinkURIAfterRemoving: PropTypes.bool,\n- }),\n-]);\n-\nconst pendingMultimediaUploadPropType = PropTypes.shape({\nfailed: PropTypes.string,\nprogressPercent: PropTypes.number.isRequired,\n@@ -72,7 +35,7 @@ export type ChatInputState = {|\npendingUploads: PendingMultimediaUploads,\nsendMultimediaMessage: (\nthreadID: string,\n- mediaInfos: $ReadOnlyArray<ClientMediaInfo>,\n+ selections: $ReadOnlyArray<MediaSelection>,\n) => Promise<void>,\nmessageHasUploadFailure: (localMessageID: string) => bool,\nretryMultimediaMessage: (localMessageID: string) => Promise<void>,\n" }, { "change_type": "MODIFY", "old_path": "native/keyboard/keyboard-input-host.react.js", "new_path": "native/keyboard/keyboard-input-host.react.js", "diff": "@@ -6,13 +6,13 @@ import {\ntype ChatInputState,\nchatInputStatePropType,\nwithChatInputState,\n- type ClientMediaInfo,\n} from '../chat/chat-input-state';\nimport {\ntype KeyboardState,\nkeyboardStatePropType,\nwithKeyboardState,\n} from '../keyboard/keyboard-state';\n+import type { MediaLibrarySelection } from 'lib/types/media-types';\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\n@@ -80,7 +80,7 @@ class KeyboardInputHost extends React.PureComponent<Props> {\nonMediaGalleryItemSelected = (\nkeyboardName: string,\n- mediaInfos: $ReadOnlyArray<ClientMediaInfo>,\n+ selections: $ReadOnlyArray<MediaLibrarySelection>,\n) => {\nconst { keyboardState } = this.props;\ninvariant(\n@@ -98,20 +98,9 @@ class KeyboardInputHost extends React.PureComponent<Props> {\nchatInputState,\n\"chatInputState should be set in onMediaGalleryItemSelected\",\n);\n-\n- // We do this for Flow\n- const mappedMediaInfos = [];\n- for (let mediaInfo of mediaInfos) {\n- if (mediaInfo.type === \"photo\") {\n- mappedMediaInfos.push({ type: \"photo\", ...mediaInfo });\n- } else {\n- mappedMediaInfos.push({ type: \"video\", ...mediaInfo });\n- }\n- }\n-\nchatInputState.sendMultimediaMessage(\nmediaGalleryThreadID,\n- mappedMediaInfos,\n+ selections,\n);\n}\n" }, { "change_type": "MODIFY", "old_path": "native/media/camera-modal.react.js", "new_path": "native/media/camera-modal.react.js", "diff": "@@ -7,7 +7,11 @@ import type {\nNavigationStackTransitionProps,\n} from 'react-navigation-stack';\nimport type { AppState } from '../redux/redux-setup';\n-import { type Dimensions, dimensionsPropType } from 'lib/types/media-types';\n+import {\n+ type Dimensions,\n+ dimensionsPropType,\n+ type PhotoCapture,\n+} from 'lib/types/media-types';\nimport type { DispatchActionPayload } from 'lib/utils/action-utils';\nimport { updateDeviceCameraInfoActionType } from '../redux/action-types';\nimport {\n@@ -19,7 +23,6 @@ import {\ntype ChatInputState,\nchatInputStatePropType,\nwithChatInputState,\n- type ClientMediaInfo,\n} from '../chat/chat-input-state';\nimport type { ViewStyle } from '../types/styles';\n@@ -265,7 +268,7 @@ type State = {|\nflashMode: number,\nautoFocusPointOfInterest: ?{| x: number, y: number, autoExposure?: bool |},\nstagingMode: bool,\n- pendingMediaInfo: ?ClientMediaInfo,\n+ pendingPhotoCapture: ?PhotoCapture,\n|};\nclass CameraModal extends React.PureComponent<Props, State> {\n@@ -346,7 +349,7 @@ class CameraModal extends React.PureComponent<Props, State> {\nflashMode: RNCamera.Constants.FlashMode.off,\nautoFocusPointOfInterest: undefined,\nstagingMode: false,\n- pendingMediaInfo: undefined,\n+ pendingPhotoCapture: undefined,\n};\nconst { position } = props;\n@@ -623,22 +626,19 @@ class CameraModal extends React.PureComponent<Props, State> {\nthis.stagingModeProgress.setValue(0);\n}\n- if (this.state.pendingMediaInfo && !prevState.pendingMediaInfo) {\n+ if (this.state.pendingPhotoCapture && !prevState.pendingPhotoCapture) {\ntiming(\nthis.sendButtonProgress,\n{ ...stagingModeAnimationConfig, toValue: 1 },\n).start();\n- } else if (!this.state.pendingMediaInfo && prevState.pendingMediaInfo) {\n- CameraModal.cleanUpPendingImageInfo(prevState.pendingMediaInfo);\n+ } else if (!this.state.pendingPhotoCapture && prevState.pendingPhotoCapture) {\n+ CameraModal.cleanUpPendingPhotoCapture(prevState.pendingPhotoCapture);\nthis.sendButtonProgress.setValue(0);\n}\n}\n- static async cleanUpPendingImageInfo(pendingMediaInfo: ClientMediaInfo) {\n- if (!pendingMediaInfo.unlinkURIAfterRemoving) {\n- return;\n- }\n- const path = pathFromURI(pendingMediaInfo.uri);\n+ static async cleanUpPendingPhotoCapture(pendingPhotoCapture: PhotoCapture) {\n+ const path = pathFromURI(pendingPhotoCapture.uri);\nif (!path) {\nreturn;\n}\n@@ -693,9 +693,9 @@ class CameraModal extends React.PureComponent<Props, State> {\nrenderStagingView() {\nlet image = null;\n- const { pendingMediaInfo } = this.state;\n- if (pendingMediaInfo) {\n- const imageSource = { uri: pendingMediaInfo.uri };\n+ const { pendingPhotoCapture } = this.state;\n+ if (pendingPhotoCapture) {\n+ const imageSource = { uri: pendingPhotoCapture.uri };\nimage = <Image source={imageSource} style={styles.stagingImage} />;\n} else {\nimage = <ContentLoading fillType=\"flex\" colors={colors.dark} />;\n@@ -715,7 +715,7 @@ class CameraModal extends React.PureComponent<Props, State> {\n</TouchableOpacity>\n<SendMediaButton\nonPress={this.sendPhoto}\n- pointerEvents={pendingMediaInfo ? 'auto' : 'none'}\n+ pointerEvents={pendingPhotoCapture ? 'auto' : 'none'}\ncontainerStyle={styles.sendButtonContainer}\nstyle={this.sendButtonStyle}\n/>\n@@ -936,6 +936,7 @@ class CameraModal extends React.PureComponent<Props, State> {\nconst usingFrontCamera = this.state.useFrontCamera ||\n(!hasCamerasOnBothSides && defaultUseFrontCamera);\n+ const startTime = Date.now();\nconst photoPromise = camera.takePictureAsync({\npauseAfterCapture: Platform.OS === \"android\",\nmirrorImage: usingFrontCamera,\n@@ -952,24 +953,24 @@ class CameraModal extends React.PureComponent<Props, State> {\n`unable to parse filename out of react-native-camera URI ${uri}`,\n);\n- const pendingMediaInfo = {\n- type: \"photo\",\n+ const pendingPhotoCapture = {\n+ step: \"photo_capture\",\nuri,\ndimensions: { width, height },\nfilename,\n- unlinkURIAfterRemoving: true,\n+ time: Date.now() - startTime,\n};\nthis.setState({\n- pendingMediaInfo,\n+ pendingPhotoCapture,\nzoom: 0,\nautoFocusPointOfInterest: undefined,\n});\n}\nsendPhoto = async () => {\n- const { pendingMediaInfo } = this.state;\n- if (!pendingMediaInfo) {\n+ const { pendingPhotoCapture } = this.state;\n+ if (!pendingPhotoCapture) {\nreturn;\n}\nconst { chatInputState } = this.props;\n@@ -977,9 +978,9 @@ class CameraModal extends React.PureComponent<Props, State> {\nthis.close();\nchatInputState.sendMultimediaMessage(\nthis.props.navigation.state.params.threadID,\n- [ pendingMediaInfo ],\n+ [ pendingPhotoCapture ],\n);\n- saveImage({ uri: pendingMediaInfo.uri, type: \"photo\" });\n+ saveImage({ uri: pendingPhotoCapture.uri, type: \"photo\" });\n}\nclearPendingImage = () => {\n@@ -987,7 +988,7 @@ class CameraModal extends React.PureComponent<Props, State> {\nthis.camera.resumePreview();\nthis.setState({\nstagingMode: false,\n- pendingMediaInfo: undefined,\n+ pendingPhotoCapture: undefined,\n});\n}\n" }, { "change_type": "MODIFY", "old_path": "native/media/media-gallery-keyboard.react.js", "new_path": "native/media/media-gallery-keyboard.react.js", "diff": "// @flow\nimport type { AppState } from '../redux/redux-setup';\n-import { type Dimensions, dimensionsPropType } from 'lib/types/media-types';\n+import {\n+ type Dimensions,\n+ dimensionsPropType,\n+ type MediaLibrarySelection,\n+} from 'lib/types/media-types';\nimport type { ViewToken } from 'react-native/Libraries/Lists/ViewabilityHelper';\nimport type { ViewStyle, Styles } from '../types/styles';\nimport { type Colors, colorsPropType } from '../themes/colors';\n-import type { ClientMediaInfo } from '../chat/chat-input-state';\nimport * as React from 'react';\nimport {\n@@ -53,7 +56,7 @@ type Props = {|\nstyles: Styles,\n|};\ntype State = {|\n- mediaInfos: ?$ReadOnlyArray<ClientMediaInfo>,\n+ selections: ?$ReadOnlyArray<MediaLibrarySelection>,\nerror: ?string,\ncontainerHeight: ?number,\n// null means end reached; undefined means no fetch yet\n@@ -94,7 +97,7 @@ class MediaGalleryKeyboard extends React.PureComponent<Props, State> {\n],\n};\nthis.state = {\n- mediaInfos: null,\n+ selections: null,\nerror: null,\ncontainerHeight: null,\ncursor: undefined,\n@@ -136,9 +139,9 @@ class MediaGalleryKeyboard extends React.PureComponent<Props, State> {\n}\nconst { flatList, viewableIndices } = this;\n- const { mediaInfos, focusedMediaURI } = this.state;\n+ const { selections, focusedMediaURI } = this.state;\nlet scrollingSomewhere = false;\n- if (flatList && mediaInfos) {\n+ if (flatList && selections) {\nlet newURI;\nif (focusedMediaURI && focusedMediaURI !== prevState.focusedMediaURI) {\nnewURI = focusedMediaURI;\n@@ -157,7 +160,7 @@ class MediaGalleryKeyboard extends React.PureComponent<Props, State> {\n}\nlet index;\nif (newURI !== null && newURI !== undefined) {\n- index = mediaInfos.findIndex(({ uri }) => uri === newURI);\n+ index = selections.findIndex(({ uri }) => uri === newURI);\n}\nif (index !== null && index !== undefined) {\nif (index === viewableIndices[0]) {\n@@ -177,11 +180,11 @@ class MediaGalleryKeyboard extends React.PureComponent<Props, State> {\nif (\n!scrollingSomewhere &&\nthis.flatList &&\n- this.state.mediaInfos &&\n- prevState.mediaInfos &&\n- this.state.mediaInfos.length > 0 &&\n- prevState.mediaInfos.length > 0 &&\n- this.state.mediaInfos[0].uri !== prevState.mediaInfos[0].uri\n+ this.state.selections &&\n+ prevState.selections &&\n+ this.state.selections.length > 0 &&\n+ prevState.selections.length > 0 &&\n+ this.state.selections[0].uri !== prevState.selections[0].uri\n) {\nthis.flatList.scrollToIndex({ index: 0 });\n}\n@@ -233,12 +236,12 @@ class MediaGalleryKeyboard extends React.PureComponent<Props, State> {\nlet firstRemoved = false, lastRemoved = false;\n- const mediaURIs = this.state.mediaInfos\n- ? this.state.mediaInfos.map(({ uri }) => uri)\n+ const mediaURIs = this.state.selections\n+ ? this.state.selections.map(({ uri }) => uri)\n: [];\nconst existingURIs = new Set(mediaURIs);\nlet first = true;\n- const mediaInfos = edges.map(\n+ const selections = edges.map(\n({ node }) => {\nconst { height, width, filename, playableDuration } = node.image;\nconst isVideo =\n@@ -263,14 +266,15 @@ class MediaGalleryKeyboard extends React.PureComponent<Props, State> {\nif (isVideo) {\nreturn {\n- type: \"video\",\n+ step: \"video_library\",\ndimensions: { height, width },\nuri,\nfilename,\n+ playableDuration,\n};\n} else {\nreturn {\n- type: \"photo\",\n+ step: \"photo_library\",\ndimensions: { height, width },\nuri,\nfilename,\n@@ -286,17 +290,17 @@ class MediaGalleryKeyboard extends React.PureComponent<Props, State> {\nappendOrPrepend = \"prepend\";\n}\n- let newMediaInfos = mediaInfos;\n- if (this.state.mediaInfos) {\n+ let newSelections = selections;\n+ if (this.state.selections) {\nif (appendOrPrepend === \"prepend\") {\n- newMediaInfos = [ ...newMediaInfos, ...this.state.mediaInfos ];\n+ newSelections = [ ...newSelections, ...this.state.selections ];\n} else {\n- newMediaInfos = [ ...this.state.mediaInfos, ...newMediaInfos ];\n+ newSelections = [ ...this.state.selections, ...newSelections ];\n}\n}\nthis.guardedSetState({\n- mediaInfos: newMediaInfos,\n+ selections: newSelections,\nerror: null,\ncursor: page_info.has_next_page\n? page_info.end_cursor\n@@ -304,7 +308,7 @@ class MediaGalleryKeyboard extends React.PureComponent<Props, State> {\n});\n} catch (e) {\nthis.guardedSetState({\n- mediaInfos: null,\n+ selections: null,\nerror: \"something went wrong :(\",\n});\n}\n@@ -329,7 +333,7 @@ class MediaGalleryKeyboard extends React.PureComponent<Props, State> {\nreturn !!this.state.queuedMediaURIs;\n}\n- renderItem = (row: { item: ClientMediaInfo }) => {\n+ renderItem = (row: { item: MediaLibrarySelection }) => {\nconst { containerHeight, queuedMediaURIs } = this.state;\ninvariant(containerHeight, \"should be set\");\nconst { uri } = row.item;\n@@ -337,7 +341,7 @@ class MediaGalleryKeyboard extends React.PureComponent<Props, State> {\nconst { queueModeActive } = this;\nreturn (\n<MediaGalleryMedia\n- mediaInfo={row.item}\n+ selection={row.item}\ncontainerHeight={containerHeight}\nqueueModeActive={queueModeActive}\nisQueued={isQueued}\n@@ -355,18 +359,18 @@ class MediaGalleryKeyboard extends React.PureComponent<Props, State> {\nreturn <View style={this.props.styles.separator} />;\n}\n- static keyExtractor(item: ClientMediaInfo) {\n+ static keyExtractor(item: MediaLibrarySelection) {\nreturn item.uri;\n}\nrender() {\nlet content;\n- const { mediaInfos, error, containerHeight } = this.state;\n- if (mediaInfos && mediaInfos.length > 0 && containerHeight) {\n+ const { selections, error, containerHeight } = this.state;\n+ if (selections && selections.length > 0 && containerHeight) {\ncontent = (\n<FlatList\nhorizontal={true}\n- data={mediaInfos}\n+ data={selections}\nrenderItem={this.renderItem}\nItemSeparatorComponent={this.ItemSeparator}\nkeyExtractor={MediaGalleryKeyboard.keyExtractor}\n@@ -379,7 +383,7 @@ class MediaGalleryKeyboard extends React.PureComponent<Props, State> {\nref={this.flatListRef}\n/>\n);\n- } else if (mediaInfos && containerHeight) {\n+ } else if (selections && containerHeight) {\ncontent = (\n<Text style={this.props.styles.error}>\nno media was found!\n@@ -446,7 +450,7 @@ class MediaGalleryKeyboard extends React.PureComponent<Props, State> {\nthis.viewableIndices = viewableIndices;\n}\n- setMediaQueued = (mediaInfo: ClientMediaInfo, isQueued: bool) => {\n+ setMediaQueued = (selection: MediaLibrarySelection, isQueued: bool) => {\nthis.setState((prevState: State) => {\nconst prevQueuedMediaURIs = prevState.queuedMediaURIs\n? [ ...prevState.queuedMediaURIs ]\n@@ -455,13 +459,13 @@ class MediaGalleryKeyboard extends React.PureComponent<Props, State> {\nreturn {\nqueuedMediaURIs: new Set([\n...prevQueuedMediaURIs,\n- mediaInfo.uri,\n+ selection.uri,\n]),\nfocusedMediaURI: null,\n};\n}\nconst queuedMediaURIs = prevQueuedMediaURIs.filter(\n- uri => uri !== mediaInfo.uri,\n+ uri => uri !== selection.uri,\n);\nif (queuedMediaURIs.length < prevQueuedMediaURIs.length) {\nreturn {\n@@ -473,8 +477,8 @@ class MediaGalleryKeyboard extends React.PureComponent<Props, State> {\n});\n}\n- setFocus = (mediaInfo: ClientMediaInfo, isFocused: bool) => {\n- const { uri } = mediaInfo;\n+ setFocus = (selection: MediaLibrarySelection, isFocused: bool) => {\n+ const { uri } = selection;\nif (isFocused) {\nthis.setState({ focusedMediaURI: uri });\n} else if (this.state.focusedMediaURI === uri) {\n@@ -482,33 +486,33 @@ class MediaGalleryKeyboard extends React.PureComponent<Props, State> {\n}\n}\n- sendSingleMedia = (mediaInfo: ClientMediaInfo) => {\n- this.sendMedia([ mediaInfo ]);\n+ sendSingleMedia = (selection: MediaLibrarySelection) => {\n+ this.sendMedia([ selection ]);\n}\nsendQueuedMedia = () => {\n- const { mediaInfos, queuedMediaURIs } = this.state;\n- if (!mediaInfos || !queuedMediaURIs) {\n+ const { selections, queuedMediaURIs } = this.state;\n+ if (!selections || !queuedMediaURIs) {\nreturn;\n}\n- const queuedMediaInfos = [];\n+ const queuedSelections = [];\nfor (let uri of queuedMediaURIs) {\n- for (let mediaInfo of mediaInfos) {\n- if (mediaInfo.uri === uri) {\n- queuedMediaInfos.push(mediaInfo);\n+ for (let selection of selections) {\n+ if (selection.uri === uri) {\n+ queuedSelections.push(selection);\nbreak;\n}\n}\n}\n- this.sendMedia(queuedMediaInfos);\n+ this.sendMedia(queuedSelections);\n}\n- sendMedia(mediaInfos: $ReadOnlyArray<ClientMediaInfo>) {\n+ sendMedia(selections: $ReadOnlyArray<MediaLibrarySelection>) {\nif (this.mediaSelected) {\nreturn;\n}\nthis.mediaSelected = true;\n- KeyboardRegistry.onItemSelected(mediaGalleryKeyboardName, mediaInfos);\n+ KeyboardRegistry.onItemSelected(mediaGalleryKeyboardName, selections);\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "native/media/media-gallery-media.react.js", "new_path": "native/media/media-gallery-media.react.js", "diff": "import type { ViewStyle, ImageStyle } from '../types/styles';\nimport { type Colors, colorsPropType } from '../themes/colors';\nimport {\n- type ClientMediaInfo,\n- clientMediaInfoPropType,\n-} from '../chat/chat-input-state';\n+ type MediaLibrarySelection,\n+ mediaLibrarySelectionPropType,\n+} from 'lib/types/media-types';\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\n@@ -43,21 +43,21 @@ const reanimatedSpec = {\n};\ntype Props = {|\n- mediaInfo: ClientMediaInfo,\n+ selection: MediaLibrarySelection,\ncontainerHeight: number,\nqueueModeActive: bool,\nisQueued: bool,\n- setMediaQueued: (media: ClientMediaInfo, isQueued: bool) => void,\n- sendMedia: (media: ClientMediaInfo) => void,\n+ setMediaQueued: (media: MediaLibrarySelection, isQueued: bool) => void,\n+ sendMedia: (media: MediaLibrarySelection) => void,\nisFocused: bool,\n- setFocus: (media: ClientMediaInfo, isFocused: bool) => void,\n+ setFocus: (media: MediaLibrarySelection, isFocused: bool) => void,\nscreenWidth: number,\ncolors: Colors,\n|};\nclass MediaGalleryMedia extends React.PureComponent<Props> {\nstatic propTypes = {\n- mediaInfo: clientMediaInfoPropType.isRequired,\n+ selection: mediaLibrarySelectionPropType.isRequired,\ncontainerHeight: PropTypes.number.isRequired,\nqueueModeActive: PropTypes.bool.isRequired,\nisQueued: PropTypes.bool.isRequired,\n@@ -189,8 +189,8 @@ class MediaGalleryMedia extends React.PureComponent<Props> {\n}\nrender() {\n- const { mediaInfo, containerHeight } = this.props;\n- const { uri, dimensions: { width, height }, type } = mediaInfo;\n+ const { selection, containerHeight } = this.props;\n+ const { uri, dimensions: { width, height }, step } = selection;\nconst active = MediaGalleryMedia.isActive(this.props);\nconst dimensionsStyle = {\nheight: containerHeight,\n@@ -236,7 +236,7 @@ class MediaGalleryMedia extends React.PureComponent<Props> {\nlet media;\nconst source = { uri };\n- if (type === \"video\") {\n+ if (step === \"video_library\") {\nmedia = (\n<Reanimated.View style={this.videoContainerStyle}>\n<Video\n@@ -287,11 +287,11 @@ class MediaGalleryMedia extends React.PureComponent<Props> {\nonPressBackdrop = () => {\nif (this.props.isQueued) {\n- this.props.setMediaQueued(this.props.mediaInfo, false);\n+ this.props.setMediaQueued(this.props.selection, false);\n} else if (this.props.queueModeActive) {\n- this.props.setMediaQueued(this.props.mediaInfo, true);\n+ this.props.setMediaQueued(this.props.selection, true);\n} else {\n- this.props.setFocus(this.props.mediaInfo, !this.props.isFocused);\n+ this.props.setFocus(this.props.selection, !this.props.isFocused);\n}\n}\n@@ -317,11 +317,11 @@ class MediaGalleryMedia extends React.PureComponent<Props> {\n}\nonPressSend = () => {\n- this.props.sendMedia(this.props.mediaInfo);\n+ this.props.sendMedia(this.props.selection);\n}\nonPressEnqueue = () => {\n- this.props.setMediaQueued(this.props.mediaInfo, true);\n+ this.props.setMediaQueued(this.props.selection, true);\n}\nonAnimatingBackdropToZeroCompletion = ({ finished }: { finished: bool }) => {\n" }, { "change_type": "MODIFY", "old_path": "native/media/multimedia.react.js", "new_path": "native/media/multimedia.react.js", "diff": "@@ -6,6 +6,7 @@ import * as React from 'react';\nimport PropTypes from 'prop-types';\nimport { View, Image, StyleSheet } from 'react-native';\nimport filesystem from 'react-native-fs';\n+import invariant from 'invariant';\nimport { pathFromURI } from 'lib/utils/file-utils';\n@@ -39,14 +40,29 @@ class Multimedia extends React.PureComponent<Props, State> {\n};\n}\n+ static shouldUnlinkDepartingURI(props: Props): bool {\n+ const { localMediaSelection } = props.mediaInfo;\n+ if (!localMediaSelection) {\n+ return false;\n+ }\n+ if (\n+ localMediaSelection.step === \"photo_library\" ||\n+ localMediaSelection.step === \"video_library\"\n+ ) {\n+ return false;\n+ }\n+ invariant(\n+ localMediaSelection.step === \"photo_capture\",\n+ \"selection should be photo_capture if not from library\",\n+ );\n+ return true;\n+ }\n+\ncomponentDidUpdate(prevProps: Props) {\nconst newURI = this.props.mediaInfo.uri;\nconst oldURI = prevProps.mediaInfo.uri;\nif (newURI !== oldURI && !this.state.departingURI) {\n- const unlinkDepartingURI = !!(\n- prevProps.mediaInfo.localMediaCreationInfo &&\n- prevProps.mediaInfo.localMediaCreationInfo.unlinkURIAfterRemoving\n- );\n+ const unlinkDepartingURI = Multimedia.shouldUnlinkDepartingURI(prevProps);\nthis.setState({\ncurrentURI: newURI,\ndepartingURI: oldURI,\n" }, { "change_type": "MODIFY", "old_path": "native/utils/media-utils.js", "new_path": "native/utils/media-utils.js", "diff": "@@ -6,11 +6,6 @@ import type {\nMediaMissionStep,\nMediaMissionFailure,\n} from 'lib/types/media-types';\n-import type {\n- ClientPhotoInfo,\n- ClientVideoInfo,\n- ClientMediaInfo,\n-} from '../chat/chat-input-state';\nimport { Platform, Image } from 'react-native';\nimport base64 from 'base-64';\n@@ -41,6 +36,22 @@ async function getBlobFromURI(\nreturn await response.blob();\n}\n+type ClientPhotoInfo = {|\n+ type: \"photo\",\n+ uri: string,\n+ dimensions: Dimensions,\n+ filename: string,\n+|};\n+type ClientVideoInfo = {|\n+ type: \"video\",\n+ uri: string,\n+ dimensions: Dimensions,\n+ filename: string,\n+|};\n+type ClientMediaInfo =\n+ | ClientPhotoInfo\n+ | ClientVideoInfo;\n+\ntype ReactNativeBlob =\n& Blob\n& { data: { type: string, name: string, size: number } };\n@@ -280,14 +291,12 @@ async function convertMedia(\nuri: uploadURI,\ndimensions,\nfilename: name,\n- unlinkURIAfterRemoving: validationResult.unlinkURIAfterRemoving,\n}\n: {\ntype: \"photo\",\nuri: uploadURI,\ndimensions,\nfilename: name,\n- unlinkURIAfterRemoving: validationResult.unlinkURIAfterRemoving,\n};\nconst {\nsteps: newValidationSteps,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
New type MediaSelection for native
129,187
02.03.2020 22:59:11
18,000
e7c44b094796f5c067d107135fe0214071ed6a8d
Construct full MediaMission in native ChatInputStateContainer uploadFile
[ { "change_type": "MODIFY", "old_path": "lib/types/media-types.js", "new_path": "lib/types/media-types.js", "diff": "@@ -204,6 +204,16 @@ export type MediaMissionStep =\nsuccess: bool,\ntime: number, // ms\npath: string,\n+ |}\n+ | {|\n+ step: \"upload\",\n+ success: bool,\n+ time: number,\n+ |}\n+ | {|\n+ step: \"processing_exception\",\n+ time: number,\n+ message: ?string,\n|};\nexport type MediaMissionFailure =\n@@ -243,11 +253,17 @@ export type MediaMissionFailure =\n| {|\nsuccess: false,\nreason: \"video_transcode_failed\",\n+ |}\n+ | {|\n+ success: false,\n+ reason: \"processing_exception\",\n+ time: number,\n+ message: ?string,\n|};\n-type MediaMissionResult =\n+export type MediaMissionResult =\n| MediaMissionFailure\n- | {| success: true |};\n+ | {| success: true, totalTime: number |};\nexport type MediaMission = {|\nsteps: MediaMissionStep[],\n" }, { "change_type": "MODIFY", "old_path": "native/chat/chat-input-state-container.react.js", "new_path": "native/chat/chat-input-state-container.react.js", "diff": "@@ -10,6 +10,8 @@ import type {\nUploadMultimediaResult,\nMedia,\nMediaSelection,\n+ MediaMissionResult,\n+ MediaMission,\n} from 'lib/types/media-types';\nimport {\nmessageTypes,\n@@ -360,7 +362,21 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\nlocalMessageID: string,\nselectionWithID: SelectionWithID,\n): Promise<?string> {\n+ const start = Date.now();\n+\nconst { localID, selection } = selectionWithID;\n+ let steps = [ selection ], serverID;\n+ const finish = (result: MediaMissionResult, errorMessage: ?string) => {\n+ if (errorMessage) {\n+ this.handleUploadFailure(localMessageID, localID, errorMessage);\n+ }\n+ this.queueMediaMissionReport(\n+ { localID, localMessageID, serverID },\n+ { steps, result },\n+ );\n+ return errorMessage;\n+ };\n+\nlet mediaInfo;\nif (selection.step === \"photo_library\") {\nmediaInfo = {\n@@ -390,23 +406,40 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\n);\n}\n- const { result: processResult, steps } = await processMedia(mediaInfo);\n+ let processedMedia;\n+ const processingStart = Date.now();\n+ try {\n+ const {\n+ result: processResult,\n+ steps: processSteps,\n+ } = await processMedia(mediaInfo);\n+ steps = [ ...steps, ...processSteps ];\nif (!processResult.success) {\n- const message = \"processing failed\";\n- this.handleUploadFailure(localMessageID, localID, message);\n- return message;\n+ return finish(processResult, \"processing failed\");\n+ }\n+ processedMedia = processResult;\n+ } catch (e) {\n+ const message = (e && e.message) ? e.message : \"processing threw\";\n+ const time = Date.now() - processingStart;\n+ steps.push({ step: \"processing_exception\", time, message });\n+ return finish(\n+ { success: false, reason: \"processing_exception\", time, message },\n+ message,\n+ );\n}\n+\nconst {\nuploadURI,\nshouldDisposePath,\nname,\nmime,\nmediaType,\n- } = processResult;\n+ } = processedMedia;\n- let result, message;\n+ const uploadStart = Date.now();\n+ let uploadResult, message;\ntry {\n- result = await this.props.uploadMultimedia(\n+ uploadResult = await this.props.uploadMultimedia(\n{ uri: uploadURI, name, type: mime },\n(percent: number) => this.setProgress(\nlocalMessageID,\n@@ -416,31 +449,49 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\n);\n} catch (e) {\nmessage = \"upload failed\";\n- this.handleUploadFailure(localMessageID, localID, message);\n}\n- if (result) {\n+ if (uploadResult) {\n+ serverID = uploadResult.id;\nthis.props.dispatchActionPayload(\nupdateMultimediaMessageMediaActionType,\n{\nmessageID: localMessageID,\ncurrentMediaID: localID,\nmediaUpdate: {\n- id: result.id,\n- uri: result.uri,\n+ id: serverID,\n+ uri: uploadResult.uri,\ntype: mediaType,\n- dimensions: processResult.dimensions,\n+ dimensions: processedMedia.dimensions,\nlocalMediaCreationInfo: undefined,\n},\n},\n);\n}\n+ steps.push({\n+ step: \"upload\",\n+ success: !!uploadResult,\n+ time: Date.now() - uploadStart,\n+ });\n+ const mediaMissionResult = uploadResult\n+ ? { success: true, totalTime: Date.now() - start }\n+ : { success: false, reason: \"http_upload_failed\" };\n+\nif (!shouldDisposePath) {\n- return message;\n+ return finish(mediaMissionResult, message);\n}\n+ let disposeSuccess = false;\n+ const disposeStart = Date.now();\ntry {\nawait filesystem.unlink(shouldDisposePath);\n+ disposeSuccess = true;\n} catch (e) { }\n- return message;\n+ steps.push({\n+ step: \"dispose_uploaded_local_file\",\n+ success: disposeSuccess,\n+ time: disposeStart - Date.now(),\n+ path: shouldDisposePath,\n+ });\n+ return finish(mediaMissionResult, message);\n}\nsetProgress(\n@@ -506,6 +557,12 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\n});\n}\n+ queueMediaMissionReport(\n+ ids: {| localID: string, localMessageID: string, serverID: ?string |},\n+ mediaMission: MediaMission,\n+ ) {\n+ }\n+\nmessageHasUploadFailure = (localMessageID: string) => {\nconst pendingUploads = this.state.pendingUploads[localMessageID];\nif (!pendingUploads) {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Construct full MediaMission in native ChatInputStateContainer uploadFile
129,187
03.03.2020 00:45:10
18,000
7687adcfb7c4319b0cdccd32f79f333d23dff3b6
[native] Stop using data URI for upload on iOS We've been doing this since where we first started uploading images. It's not clear why we started, maybe the old version of React Native couldn't handle uploading `ph://` protocol?
[ { "change_type": "MODIFY", "old_path": "native/utils/media-utils.js", "new_path": "native/utils/media-utils.js", "diff": "@@ -309,10 +309,10 @@ async function convertMedia(\nblob = newValidationResult.blob;\n}\n- let fileDataDetectionStep, dataURI;\n+ let fileDataDetectionStep;\nif (blob) {\nconst fileDataDetectionStart = Date.now();\n- dataURI = await blobToDataURI(blob);\n+ const dataURI = await blobToDataURI(blob);\nconst intArray = dataURIToIntArray(dataURI);\nconst blobName = blob.data.name;\n@@ -353,14 +353,6 @@ async function convertMedia(\n});\n}\n- if (Platform.OS === \"ios\" && mediaType === \"photo\" && dataURI) {\n- // TODO do we even need this? compare how long upload takes once that step\n- // is recorded\n- // TODO should this depend on uploadURI protocol instead of dataURI\n- // existing?\n- //console.log(`iOS ${uploadURI} -> ${dataURI}`);\n- uploadURI = dataURI;\n- }\nreturn finish();\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Stop using data URI for upload on iOS We've been doing this since 5b1fee81c8029488ae1086900316d3869d0eb014 where we first started uploading images. It's not clear why we started, maybe the old version of React Native couldn't handle uploading `ph://` protocol?
129,187
03.03.2020 17:03:14
18,000
040010e03b1682c715ede70cdc226d0f5bba3652
[lib] InconsistencyReportHandler -> ReportHandler
[ { "change_type": "MODIFY", "old_path": "lib/selectors/socket-selectors.js", "new_path": "lib/selectors/socket-selectors.js", "diff": "@@ -26,7 +26,7 @@ import { values, hash } from '../utils/objects';\nimport { currentCalendarQuery } from './nav-selectors';\nimport threadWatcher from '../shared/thread-watcher';\n-const queuedInconsistencyReports: (\n+const queuedReports: (\nstate: AppState,\n) => $ReadOnlyArray<ClientInconsistencyResponse> = createSelector(\n(state: AppState) => state.threadStore.inconsistencyResponses,\n@@ -157,7 +157,7 @@ const sessionStateFuncSelector: (\n);\nexport {\n- queuedInconsistencyReports,\n+ queuedReports,\ngetClientResponsesSelector,\nsessionStateFuncSelector,\n};\n" }, { "change_type": "RENAME", "old_path": "lib/socket/inconsistency-report-handler.react.js", "new_path": "lib/socket/report-handler.react.js", "diff": "@@ -19,14 +19,14 @@ import invariant from 'invariant';\nimport { connect } from '../utils/redux-utils';\nimport { sendReportActionTypes, sendReport } from '../actions/report-actions';\n-import { queuedInconsistencyReports } from '../selectors/socket-selectors';\n+import { queuedReports } from '../selectors/socket-selectors';\nimport { ServerError } from '../utils/errors';\ntype Props = {|\nhasWiFi: bool,\nfrozen: bool,\n// Redux state\n- queuedInconsistencyReports: $ReadOnlyArray<ClientInconsistencyResponse>,\n+ queuedReports: $ReadOnlyArray<ClientInconsistencyResponse>,\n// Redux dispatch functions\ndispatchActionPromise: DispatchActionPromise,\n// async functions that hit server APIs\n@@ -34,12 +34,12 @@ type Props = {|\nrequest: ClientReportCreationRequest,\n) => Promise<ReportCreationResponse>,\n|};\n-class InconsistencyReportHandler extends React.PureComponent<Props> {\n+class ReportHandler extends React.PureComponent<Props> {\nstatic propTypes = {\nhasWiFi: PropTypes.bool.isRequired,\nfrozen: PropTypes.bool.isRequired,\n- queuedInconsistencyReports: PropTypes.arrayOf(\n+ queuedReports: PropTypes.arrayOf(\nclientResponsePropType,\n).isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\n@@ -52,28 +52,28 @@ class InconsistencyReportHandler extends React.PureComponent<Props> {\n}\ncomponentDidMount() {\n- if (InconsistencyReportHandler.canSend(this.props)) {\n- this.sendResponses(this.props.queuedInconsistencyReports);\n+ if (ReportHandler.canSend(this.props)) {\n+ this.sendResponses(this.props.queuedReports);\n}\n}\ncomponentDidUpdate(prevProps: Props) {\n- const canSend = InconsistencyReportHandler.canSend(this.props);\n+ const canSend = ReportHandler.canSend(this.props);\nif (!canSend) {\nreturn;\n}\n- const couldSend = InconsistencyReportHandler.canSend(prevProps);\n- const { queuedInconsistencyReports } = this.props;\n+ const couldSend = ReportHandler.canSend(prevProps);\n+ const { queuedReports } = this.props;\nif (!couldSend) {\n- this.sendResponses(queuedInconsistencyReports);\n+ this.sendResponses(queuedReports);\nreturn;\n}\n- const prevInconsistencyReports = prevProps.queuedInconsistencyReports;\n- if (queuedInconsistencyReports !== prevInconsistencyReports) {\n- const prevResponses = new Set(prevInconsistencyReports);\n- const newResponses = queuedInconsistencyReports.filter(\n+ const prevReports = prevProps.queuedReports;\n+ if (queuedReports !== prevReports) {\n+ const prevResponses = new Set(prevReports);\n+ const newResponses = queuedReports.filter(\nresponse => !prevResponses.has(response),\n);\nthis.sendResponses(newResponses);\n@@ -121,7 +121,7 @@ class InconsistencyReportHandler extends React.PureComponent<Props> {\nexport default connect(\n(state: AppState) => ({\n- queuedInconsistencyReports: queuedInconsistencyReports(state),\n+ queuedReports: queuedReports(state),\n}),\n{ sendReport },\n-)(InconsistencyReportHandler);\n+)(ReportHandler);\n" }, { "change_type": "MODIFY", "old_path": "lib/socket/socket.react.js", "new_path": "lib/socket/socket.react.js", "diff": "@@ -66,7 +66,7 @@ import RequestResponseHandler from './request-response-handler.react';\nimport UpdateHandler from './update-handler.react';\nimport MessageHandler from './message-handler.react';\nimport CalendarQueryHandler from './calendar-query-handler.react';\n-import InconsistencyReportHandler from './inconsistency-report-handler.react';\n+import ReportHandler from './report-handler.react';\nimport { logOutActionTypes } from '../actions/user-actions';\nimport { updateActivityActionTypes } from '../actions/activity-actions';\nimport { unsupervisedBackgroundActionType } from '../reducers/foreground-reducer';\n@@ -349,7 +349,7 @@ class Socket extends React.PureComponent<Props, State> {\ncurrentCalendarQuery={this.props.currentCalendarQuery}\nfrozen={this.props.frozen}\n/>\n- <InconsistencyReportHandler\n+ <ReportHandler\nhasWiFi={this.props.hasWiFi}\nfrozen={this.props.frozen}\n/>\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[lib] InconsistencyReportHandler -> ReportHandler
129,187
03.03.2020 18:08:18
18,000
565c11034a383a612627c57d9c9e5d76846ebfd9
Store ClientReportCreationRequests instead of ClientInconsistencyResponses in Redux
[ { "change_type": "MODIFY", "old_path": "lib/reducers/entry-reducer.js", "new_path": "lib/reducers/entry-reducer.js", "diff": "@@ -14,8 +14,6 @@ import {\nprocessUpdatesActionType,\n} from '../types/update-types';\nimport {\n- type ClientEntryInconsistencyClientResponse,\n- type ServerRequest,\nserverRequestTypes,\nprocessServerRequestsActionType,\n} from '../types/request-types';\n@@ -24,6 +22,10 @@ import {\nincrementalStateSyncActionType,\n} from '../types/socket-types';\nimport { sendReportActionTypes } from '../actions/report-actions';\n+import {\n+ type ClientEntryInconsistencyReportCreationRequest,\n+ reportTypes,\n+} from '../types/report-types';\nimport _flow from 'lodash/fp/flow';\nimport _map from 'lodash/fp/map';\n@@ -178,7 +180,7 @@ function reduceEntryInfos(\nentryInfos,\ndaysToEntries,\nlastUserInteractionCalendar,\n- inconsistencyResponses,\n+ inconsistencyReports,\n} = entryStore;\nif (\naction.type === logOutActionTypes.success ||\n@@ -200,7 +202,7 @@ function reduceEntryInfos(\nentryInfos,\ndaysToEntries,\nlastUserInteractionCalendar: newLastUserInteractionCalendar,\n- inconsistencyResponses,\n+ inconsistencyReports,\n};\n}\nconst newDaysToEntries = filterExistingDaysToEntriesWithNewEntryInfos(\n@@ -211,7 +213,7 @@ function reduceEntryInfos(\nentryInfos: newEntryInfos,\ndaysToEntries: newDaysToEntries,\nlastUserInteractionCalendar: newLastUserInteractionCalendar,\n- inconsistencyResponses,\n+ inconsistencyReports,\n};\n} else if (action.type === setNewSessionActionType) {\nconst authorizedThreadInfos = _pickBy(threadInFilterList)(newThreadInfos);\n@@ -231,14 +233,14 @@ function reduceEntryInfos(\nentryInfos,\ndaysToEntries,\nlastUserInteractionCalendar: newLastUserInteractionCalendar,\n- inconsistencyResponses,\n+ inconsistencyReports,\n};\n}\nreturn {\nentryInfos: newEntryInfos,\ndaysToEntries: newDaysToEntries,\nlastUserInteractionCalendar: newLastUserInteractionCalendar,\n- inconsistencyResponses,\n+ inconsistencyReports,\n};\n} else if (action.type === fetchEntriesActionTypes.success) {\nconst [updatedEntryInfos, updatedDaysToEntries] = mergeNewEntryInfos(\n@@ -250,7 +252,7 @@ function reduceEntryInfos(\nentryInfos: updatedEntryInfos,\ndaysToEntries: updatedDaysToEntries,\nlastUserInteractionCalendar,\n- inconsistencyResponses,\n+ inconsistencyReports,\n};\n} else if (\naction.type === updateCalendarQueryActionTypes.started &&\n@@ -261,7 +263,7 @@ function reduceEntryInfos(\nentryInfos,\ndaysToEntries,\nlastUserInteractionCalendar: Date.now(),\n- inconsistencyResponses,\n+ inconsistencyReports,\n};\n} else if (action.type === updateCalendarQueryActionTypes.success) {\nconst newLastUserInteractionCalendar = action.payload.calendarQuery\n@@ -280,7 +282,7 @@ function reduceEntryInfos(\nentryInfos: deletionMarkedEntryInfos,\ndaysToEntries: updatedDaysToEntries,\nlastUserInteractionCalendar: newLastUserInteractionCalendar,\n- inconsistencyResponses,\n+ inconsistencyReports,\n};\n} else if (action.type === createLocalEntryActionType) {\nconst entryInfo = action.payload;\n@@ -300,7 +302,7 @@ function reduceEntryInfos(\nentryInfos: newEntryInfos,\ndaysToEntries: newDaysToEntries,\nlastUserInteractionCalendar: Date.now(),\n- inconsistencyResponses,\n+ inconsistencyReports,\n};\n} else if (action.type === createEntryActionTypes.success) {\nconst localID = action.payload.localID;\n@@ -360,8 +362,8 @@ function reduceEntryInfos(\nentryInfos: updatedEntryInfos,\ndaysToEntries: newDaysToEntries,\nlastUserInteractionCalendar: Date.now(),\n- inconsistencyResponses: [\n- ...inconsistencyResponses,\n+ inconsistencyReports: [\n+ ...inconsistencyReports,\n...newInconsistencies,\n],\n};\n@@ -403,8 +405,8 @@ function reduceEntryInfos(\nentryInfos: updatedEntryInfos,\ndaysToEntries,\nlastUserInteractionCalendar: Date.now(),\n- inconsistencyResponses: [\n- ...inconsistencyResponses,\n+ inconsistencyReports: [\n+ ...inconsistencyReports,\n...newInconsistencies,\n],\n};\n@@ -428,7 +430,7 @@ function reduceEntryInfos(\nentryInfos: newEntryInfos,\ndaysToEntries,\nlastUserInteractionCalendar,\n- inconsistencyResponses,\n+ inconsistencyReports,\n};\n} else if (action.type === deleteEntryActionTypes.started) {\nconst payload = action.payload;\n@@ -447,7 +449,7 @@ function reduceEntryInfos(\nentryInfos: newEntryInfos,\ndaysToEntries,\nlastUserInteractionCalendar: Date.now(),\n- inconsistencyResponses,\n+ inconsistencyReports,\n};\n} else if (action.type === deleteEntryActionTypes.success && action.payload) {\nconst { payload } = action;\n@@ -471,8 +473,8 @@ function reduceEntryInfos(\nentryInfos,\ndaysToEntries,\nlastUserInteractionCalendar,\n- inconsistencyResponses: [\n- ...inconsistencyResponses,\n+ inconsistencyReports: [\n+ ...inconsistencyReports,\n...newInconsistencies,\n],\n};\n@@ -498,7 +500,7 @@ function reduceEntryInfos(\nentryInfos: newEntryInfos,\ndaysToEntries,\nlastUserInteractionCalendar,\n- inconsistencyResponses,\n+ inconsistencyReports,\n};\n} else if (action.type === restoreEntryActionTypes.success) {\nconst entryInfo = action.payload.entryInfo;\n@@ -529,8 +531,8 @@ function reduceEntryInfos(\nentryInfos: updatedEntryInfos,\ndaysToEntries,\nlastUserInteractionCalendar: Date.now(),\n- inconsistencyResponses: [\n- ...inconsistencyResponses,\n+ inconsistencyReports: [\n+ ...inconsistencyReports,\n...newInconsistencies,\n],\n};\n@@ -550,7 +552,7 @@ function reduceEntryInfos(\nentryInfos: updatedEntryInfos,\ndaysToEntries: updatedDaysToEntries,\nlastUserInteractionCalendar,\n- inconsistencyResponses,\n+ inconsistencyReports,\n};\n}\n} else if (action.type === incrementalStateSyncActionType) {\n@@ -571,7 +573,7 @@ function reduceEntryInfos(\nentryInfos: deletionMarkedEntryInfos,\ndaysToEntries: updatedDaysToEntries,\nlastUserInteractionCalendar,\n- inconsistencyResponses,\n+ inconsistencyReports,\n};\n} else if (action.type === processUpdatesActionType) {\nconst updateEntryInfos = mergeUpdateEntryInfos(\n@@ -587,7 +589,7 @@ function reduceEntryInfos(\nentryInfos: updatedEntryInfos,\ndaysToEntries: updatedDaysToEntries,\nlastUserInteractionCalendar,\n- inconsistencyResponses,\n+ inconsistencyReports,\n};\n} else if (action.type === fullStateSyncActionType) {\nconst [ updatedEntryInfos, updatedDaysToEntries ] = mergeNewEntryInfos(\n@@ -599,7 +601,7 @@ function reduceEntryInfos(\nentryInfos: updatedEntryInfos,\ndaysToEntries: updatedDaysToEntries,\nlastUserInteractionCalendar,\n- inconsistencyResponses,\n+ inconsistencyReports,\n};\n} else if (\naction.type === changeThreadSettingsActionTypes.success ||\n@@ -621,21 +623,21 @@ function reduceEntryInfos(\nentryInfos: newEntryInfos,\ndaysToEntries: newDaysToEntries,\nlastUserInteractionCalendar,\n- inconsistencyResponses,\n+ inconsistencyReports,\n};\n} else if (action.type === sendReportActionTypes.success && action.payload) {\nconst { payload } = action;\n- const updatedResponses = inconsistencyResponses.filter(\n+ const updatedReports = inconsistencyReports.filter(\nresponse => !payload.reports.includes(response),\n);\n- if (updatedResponses.length === inconsistencyResponses.length) {\n+ if (updatedReports.length === inconsistencyReports.length) {\nreturn entryStore;\n}\nreturn {\nentryInfos,\ndaysToEntries,\nlastUserInteractionCalendar,\n- inconsistencyResponses: updatedResponses,\n+ inconsistencyReports: updatedReports,\n};\n} else if (action.type === processServerRequestsActionType) {\nconst checkStateRequest = action.payload.serverRequests.find(\n@@ -680,8 +682,8 @@ function reduceEntryInfos(\nentryInfos: updatedEntryInfos,\ndaysToEntries: updatedDaysToEntries,\nlastUserInteractionCalendar,\n- inconsistencyResponses: [\n- ...inconsistencyResponses,\n+ inconsistencyReports: [\n+ ...inconsistencyReports,\n...newInconsistencies,\n],\n};\n@@ -723,7 +725,7 @@ function findInconsistencies(\noldResult: {[id: string]: RawEntryInfo},\nnewResult: {[id: string]: RawEntryInfo},\ncalendarQuery: CalendarQuery,\n-): ClientEntryInconsistencyClientResponse[] {\n+): ClientEntryInconsistencyReportCreationRequest[] {\n// We don't want to bother reporting an inconsistency if it's just because of\n// extraneous EntryInfos (not within the current calendarQuery) on either side\nconst filteredPollResult = filterRawEntryInfosByCalendarQuery(\n@@ -739,14 +741,14 @@ function findInconsistencies(\n}\nif (action.type === \"SEND_REPORT_SUCCESS\") {\n// We can get a memory leak if we include a previous\n- // ClientEntryInconsistencyClientResponse in this one\n+ // ClientEntryInconsistencyReportCreationRequest in this one\naction = {\ntype: \"SEND_REPORT_SUCCESS\",\nloadingInfo: action.loadingInfo,\n};\n}\nreturn [{\n- type: serverRequestTypes.ENTRY_INCONSISTENCY,\n+ type: reportTypes.ENTRY_INCONSISTENCY,\nplatformDetails: getConfig().platformDetails,\nbeforeAction,\naction: sanitizeAction(action),\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/thread-reducer.js", "new_path": "lib/reducers/thread-reducer.js", "diff": "@@ -8,7 +8,6 @@ import {\nprocessUpdatesActionType,\n} from '../types/update-types';\nimport {\n- type ClientThreadInconsistencyClientResponse,\nserverRequestTypes,\nprocessServerRequestsActionType,\n} from '../types/request-types';\n@@ -18,6 +17,10 @@ import {\n} from '../types/socket-types';\nimport { updateActivityActionTypes } from '../actions/activity-actions';\nimport { sendReportActionTypes } from '../actions/report-actions';\n+import {\n+ type ClientThreadInconsistencyReportCreationRequest,\n+ reportTypes,\n+} from '../types/report-types';\nimport invariant from 'invariant';\nimport _isEqual from 'lodash/fp/isEqual';\n@@ -106,20 +109,20 @@ function findInconsistencies(\naction: BaseAction,\noldResult: {[id: string]: RawThreadInfo},\nnewResult: {[id: string]: RawThreadInfo},\n-): ClientThreadInconsistencyClientResponse[] {\n+): ClientThreadInconsistencyReportCreationRequest[] {\nif (_isEqual(oldResult)(newResult)) {\nreturn emptyArray;\n}\nif (action.type === \"SEND_REPORT_SUCCESS\") {\n// We can get a memory leak if we include a previous\n- // ClientThreadInconsistencyClientResponse in this one\n+ // ClientThreadInconsistencyReportCreationRequest in this one\naction = {\ntype: \"SEND_REPORT_SUCCESS\",\nloadingInfo: action.loadingInfo,\n};\n}\nreturn [{\n- type: serverRequestTypes.THREAD_INCONSISTENCY,\n+ type: reportTypes.THREAD_INCONSISTENCY,\nplatformDetails: getConfig().platformDetails,\nbeforeAction,\naction: sanitizeAction(action),\n@@ -145,7 +148,7 @@ export default function reduceThreadInfos(\n}\nreturn {\nthreadInfos: action.payload.threadInfos,\n- inconsistencyResponses: state.inconsistencyResponses,\n+ inconsistencyReports: state.inconsistencyReports,\n};\n} else if (\naction.type === logOutActionTypes.success ||\n@@ -158,7 +161,7 @@ export default function reduceThreadInfos(\n}\nreturn {\nthreadInfos: {},\n- inconsistencyResponses: state.inconsistencyResponses,\n+ inconsistencyReports: state.inconsistencyReports,\n};\n} else if (\naction.type === joinThreadActionTypes.success ||\n@@ -178,8 +181,8 @@ export default function reduceThreadInfos(\nconst newResult = reduceThreadUpdates(state.threadInfos, action.payload);\nreturn {\nthreadInfos: oldResult,\n- inconsistencyResponses: [\n- ...state.inconsistencyResponses,\n+ inconsistencyReports: [\n+ ...state.inconsistencyReports,\n...findInconsistencies(\nstate.threadInfos,\naction,\n@@ -195,7 +198,7 @@ export default function reduceThreadInfos(\nconst updateResult = reduceThreadUpdates(state.threadInfos, action.payload);\nreturn {\nthreadInfos: updateResult,\n- inconsistencyResponses: state.inconsistencyResponses,\n+ inconsistencyReports: state.inconsistencyReports,\n};\n} else if (action.type === newThreadActionTypes.success) {\nconst newThreadInfo = action.payload.newThreadInfo;\n@@ -212,8 +215,8 @@ export default function reduceThreadInfos(\nconst newResult = reduceThreadUpdates(state.threadInfos, action.payload);\nreturn {\nthreadInfos: oldResult,\n- inconsistencyResponses: [\n- ...state.inconsistencyResponses,\n+ inconsistencyReports: [\n+ ...state.inconsistencyReports,\n...findInconsistencies(\nstate.threadInfos,\naction,\n@@ -235,7 +238,7 @@ export default function reduceThreadInfos(\n};\nreturn {\nthreadInfos: newThreadInfos,\n- inconsistencyResponses: state.inconsistencyResponses,\n+ inconsistencyReports: state.inconsistencyReports,\n};\n} else if (action.type === saveMessagesActionType) {\nconst threadIDToMostRecentTime = new Map();\n@@ -269,20 +272,20 @@ export default function reduceThreadInfos(\n...state.threadInfos,\n...changedThreadInfos,\n},\n- inconsistencyResponses: state.inconsistencyResponses,\n+ inconsistencyReports: state.inconsistencyReports,\n};\n}\n} else if (action.type === sendReportActionTypes.success && action.payload) {\nconst { payload } = action;\n- const updatedResponses = state.inconsistencyResponses.filter(\n+ const updatedReports = state.inconsistencyReports.filter(\nresponse => !payload.reports.includes(response),\n);\n- if (updatedResponses.length === state.inconsistencyResponses.length) {\n+ if (updatedReports.length === state.inconsistencyReports.length) {\nreturn state;\n}\nreturn {\nthreadInfos: state.threadInfos,\n- inconsistencyResponses: updatedResponses,\n+ inconsistencyReports: updatedReports,\n};\n} else if (action.type === processServerRequestsActionType) {\nconst checkStateRequest = action.payload.serverRequests.find(\n@@ -316,8 +319,8 @@ export default function reduceThreadInfos(\n);\nreturn {\nthreadInfos: newThreadInfos,\n- inconsistencyResponses: [\n- ...state.inconsistencyResponses,\n+ inconsistencyReports: [\n+ ...state.inconsistencyReports,\n...newInconsistencies,\n],\n};\n@@ -340,7 +343,7 @@ export default function reduceThreadInfos(\n}\nreturn {\nthreadInfos: { ...state.threadInfos, ...updatedThreadInfos },\n- inconsistencyResponses: state.inconsistencyResponses,\n+ inconsistencyReports: state.inconsistencyReports,\n};\n}\nreturn state;\n" }, { "change_type": "MODIFY", "old_path": "lib/selectors/socket-selectors.js", "new_path": "lib/selectors/socket-selectors.js", "diff": "@@ -5,14 +5,16 @@ import {\nserverRequestTypes,\ntype ServerRequest,\ntype ClientClientResponse,\n- type ClientInconsistencyResponse,\n- type ClientThreadInconsistencyClientResponse,\n- type ClientEntryInconsistencyClientResponse,\n} from '../types/request-types';\nimport type { RawEntryInfo, CalendarQuery } from '../types/entry-types';\nimport type { CurrentUserInfo } from '../types/user-types';\nimport type { RawThreadInfo } from '../types/thread-types';\nimport type { SessionState } from '../types/session-types';\n+import type {\n+ ClientThreadInconsistencyReportCreationRequest,\n+ ClientEntryInconsistencyReportCreationRequest,\n+ ClientReportCreationRequest,\n+} from '../types/report-types';\nimport { createSelector } from 'reselect';\n@@ -28,17 +30,17 @@ import threadWatcher from '../shared/thread-watcher';\nconst queuedReports: (\nstate: AppState,\n-) => $ReadOnlyArray<ClientInconsistencyResponse> = createSelector(\n- (state: AppState) => state.threadStore.inconsistencyResponses,\n- (state: AppState) => state.entryStore.inconsistencyResponses,\n+) => $ReadOnlyArray<ClientReportCreationRequest> = createSelector(\n+ (state: AppState) => state.threadStore.inconsistencyReports,\n+ (state: AppState) => state.entryStore.inconsistencyReports,\n(\n- threadInconsistencyResponses:\n- $ReadOnlyArray<ClientThreadInconsistencyClientResponse>,\n- entryInconsistencyResponses:\n- $ReadOnlyArray<ClientEntryInconsistencyClientResponse>,\n- ): $ReadOnlyArray<ClientInconsistencyResponse> => [\n- ...threadInconsistencyResponses,\n- ...entryInconsistencyResponses,\n+ threadInconsistencyReports:\n+ $ReadOnlyArray<ClientThreadInconsistencyReportCreationRequest>,\n+ entryInconsistencyReports:\n+ $ReadOnlyArray<ClientEntryInconsistencyReportCreationRequest>,\n+ ): $ReadOnlyArray<ClientReportCreationRequest> => [\n+ ...threadInconsistencyReports,\n+ ...entryInconsistencyReports,\n],\n);\n" }, { "change_type": "ADD", "old_path": null, "new_path": "lib/shared/report-utils.js", "diff": "+// @flow\n+\n+import {\n+ type ClientInconsistencyResponse,\n+ serverRequestTypes,\n+} from '../types/request-types';\n+import {\n+ type ClientReportCreationRequest,\n+ reportTypes,\n+} from '../types/report-types';\n+\n+import invariant from 'invariant';\n+\n+function inconsistencyResponsesToReports(\n+ responses: $ReadOnlyArray<ClientInconsistencyResponse>,\n+): ClientReportCreationRequest[] {\n+ return responses.map(response => {\n+ if (response.type === serverRequestTypes.THREAD_INCONSISTENCY) {\n+ const { type, ...rest } = response;\n+ return { ...rest, type: reportTypes.THREAD_INCONSISTENCY };\n+ } else if (response.type === serverRequestTypes.ENTRY_INCONSISTENCY) {\n+ const { type, ...rest } = response;\n+ return { ...rest, type: reportTypes.ENTRY_INCONSISTENCY };\n+ } else {\n+ invariant(false, `unexpected serverRequestType ${response.type}`);\n+ }\n+ });\n+}\n+\n+export {\n+ inconsistencyResponsesToReports,\n+};\n" }, { "change_type": "MODIFY", "old_path": "lib/socket/report-handler.react.js", "new_path": "lib/socket/report-handler.react.js", "diff": "@@ -4,12 +4,8 @@ import {\ntype ClientReportCreationRequest,\ntype ReportCreationResponse,\nreportTypes,\n+ queuedClientReportCreationRequestPropType,\n} from '../types/report-types';\n-import {\n- type ClientInconsistencyResponse,\n- serverRequestTypes,\n- clientResponsePropType,\n-} from '../types/request-types';\nimport type { DispatchActionPromise } from '../utils/action-utils';\nimport type { AppState } from '../types/redux-types';\n@@ -26,7 +22,7 @@ type Props = {|\nhasWiFi: bool,\nfrozen: bool,\n// Redux state\n- queuedReports: $ReadOnlyArray<ClientInconsistencyResponse>,\n+ queuedReports: $ReadOnlyArray<ClientReportCreationRequest>,\n// Redux dispatch functions\ndispatchActionPromise: DispatchActionPromise,\n// async functions that hit server APIs\n@@ -40,7 +36,7 @@ class ReportHandler extends React.PureComponent<Props> {\nhasWiFi: PropTypes.bool.isRequired,\nfrozen: PropTypes.bool.isRequired,\nqueuedReports: PropTypes.arrayOf(\n- clientResponsePropType,\n+ queuedClientReportCreationRequestPropType,\n).isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\nsendReport: PropTypes.func.isRequired,\n@@ -84,7 +80,7 @@ class ReportHandler extends React.PureComponent<Props> {\nreturn null;\n}\n- sendResponses(responses: $ReadOnlyArray<ClientInconsistencyResponse>) {\n+ sendResponses(responses: $ReadOnlyArray<ClientReportCreationRequest>) {\nfor (let response of responses) {\nthis.props.dispatchActionPromise(\nsendReportActionTypes,\n@@ -93,17 +89,9 @@ class ReportHandler extends React.PureComponent<Props> {\n}\n}\n- async sendResponse(response: ClientInconsistencyResponse) {\n- if (response.type === serverRequestTypes.THREAD_INCONSISTENCY) {\n- const { type, ...rest } = response;\n- const report = { ...rest, type: reportTypes.THREAD_INCONSISTENCY };\n- await this.sendReport(report);\n- } else if (response.type === serverRequestTypes.ENTRY_INCONSISTENCY) {\n- const { type, ...rest } = response;\n- const report = { ...rest, type: reportTypes.ENTRY_INCONSISTENCY };\n+ async sendResponse(report: ClientReportCreationRequest) {\nawait this.sendReport(report);\n- }\n- return { reports: [ response ] };\n+ return { reports: [ report ] };\n}\nasync sendReport(report: ClientReportCreationRequest) {\n" }, { "change_type": "MODIFY", "old_path": "lib/types/entry-types.js", "new_path": "lib/types/entry-types.js", "diff": "@@ -8,8 +8,10 @@ import {\ndefaultCalendarFilters,\n} from './filter-types';\nimport type { CreateUpdatesResponse } from './update-types';\n-import type { ClientEntryInconsistencyClientResponse } from './request-types';\nimport type { Platform } from './device-types';\n+import type {\n+ ClientEntryInconsistencyReportCreationRequest,\n+} from './report-types';\nimport PropTypes from 'prop-types';\n@@ -75,8 +77,8 @@ export type EntryStore = {|\nentryInfos: {[id: string]: RawEntryInfo},\ndaysToEntries: {[day: string]: string[]},\nlastUserInteractionCalendar: number,\n- inconsistencyResponses:\n- $ReadOnlyArray<ClientEntryInconsistencyClientResponse>,\n+ inconsistencyReports:\n+ $ReadOnlyArray<ClientEntryInconsistencyReportCreationRequest>,\n|};\nexport type CalendarQuery = {|\n" }, { "change_type": "MODIFY", "old_path": "lib/types/redux-types.js", "new_path": "lib/types/redux-types.js", "diff": "@@ -46,10 +46,8 @@ import type {\nLocallyComposedMessageInfo,\n} from './message-types';\nimport type { SetSessionPayload } from './session-types';\n-import type {\n- ClearDeliveredReportsPayload,\n- ProcessServerRequestsPayload,\n-} from './request-types';\n+import type { ProcessServerRequestsPayload } from './request-types';\n+import type { ClearDeliveredReportsPayload } from './report-types';\nimport type {\nCalendarFilter,\nCalendarThreadFilter,\n" }, { "change_type": "MODIFY", "old_path": "lib/types/report-types.js", "new_path": "lib/types/report-types.js", "diff": "// @flow\nimport type { AppState, BaseAction } from './redux-types';\n-import type { UserInfo } from './user-types';\n-import type { PlatformDetails } from './device-types';\n-import type { RawThreadInfo } from './thread-types';\n-import type { RawEntryInfo, CalendarQuery } from './entry-types';\n+import {\n+ type UserInfo,\n+ accountUserInfoPropType,\n+ currentUserPropType,\n+} from './user-types';\n+import {\n+ type PlatformDetails,\n+ platformDetailsPropType,\n+} from './device-types';\n+import { type RawThreadInfo, rawThreadInfoPropType } from './thread-types';\n+import {\n+ type RawEntryInfo,\n+ type CalendarQuery,\n+ rawEntryInfoPropType,\n+ calendarQueryPropType,\n+} from './entry-types';\nimport invariant from 'invariant';\n+import PropTypes from 'prop-types';\nexport const reportTypes = Object.freeze({\nERROR: 0,\n@@ -99,10 +112,57 @@ export type ClientEntryInconsistencyReportShape = {|\nlastActions: $ReadOnlyArray<ActionSummary>,\ntime: number,\n|};\n+\n+export type ClientThreadInconsistencyReportCreationRequest = {|\n+ ...ClientThreadInconsistencyReportShape,\n+ type: 1,\n+|};\n+export type ClientEntryInconsistencyReportCreationRequest = {|\n+ ...ClientEntryInconsistencyReportShape,\n+ type: 2,\n+|};\n+\nexport type ClientReportCreationRequest =\n| ErrorReportCreationRequest\n- | {| ...ClientThreadInconsistencyReportShape, type: 1 |}\n- | {| ...EntryInconsistencyReportShape, type: 2 |};\n+ | ClientThreadInconsistencyReportCreationRequest\n+ | ClientEntryInconsistencyReportCreationRequest;\n+\n+export type ClearDeliveredReportsPayload = {|\n+ reports: $ReadOnlyArray<ClientReportCreationRequest>,\n+|};\n+\n+const actionSummaryPropType = PropTypes.shape({\n+ type: PropTypes.string.isRequired,\n+ time: PropTypes.number.isRequired,\n+ summary: PropTypes.string.isRequired,\n+});\n+export const queuedClientReportCreationRequestPropType = PropTypes.oneOfType([\n+ PropTypes.shape({\n+ type: PropTypes.oneOf([\n+ reportTypes.THREAD_INCONSISTENCY,\n+ ]).isRequired,\n+ platformDetails: platformDetailsPropType.isRequired,\n+ beforeAction: PropTypes.objectOf(rawThreadInfoPropType).isRequired,\n+ action: PropTypes.object.isRequired,\n+ pollResult: PropTypes.objectOf(rawThreadInfoPropType).isRequired,\n+ pushResult: PropTypes.objectOf(rawThreadInfoPropType).isRequired,\n+ lastActions: PropTypes.arrayOf(actionSummaryPropType).isRequired,\n+ time: PropTypes.number.isRequired,\n+ }),\n+ PropTypes.shape({\n+ type: PropTypes.oneOf([\n+ reportTypes.ENTRY_INCONSISTENCY,\n+ ]).isRequired,\n+ platformDetails: platformDetailsPropType.isRequired,\n+ beforeAction: PropTypes.objectOf(rawEntryInfoPropType).isRequired,\n+ action: PropTypes.object.isRequired,\n+ calendarQuery: calendarQueryPropType.isRequired,\n+ pollResult: PropTypes.objectOf(rawEntryInfoPropType).isRequired,\n+ pushResult: PropTypes.objectOf(rawEntryInfoPropType).isRequired,\n+ lastActions: PropTypes.arrayOf(actionSummaryPropType).isRequired,\n+ time: PropTypes.number.isRequired,\n+ }),\n+]);\nexport type ReportCreationResponse = {|\nid: string,\n" }, { "change_type": "MODIFY", "old_path": "lib/types/request-types.js", "new_path": "lib/types/request-types.js", "diff": "// @flow\n-import {\n- type Platform,\n- type PlatformDetails,\n- platformPropType,\n- platformDetailsPropType,\n-} from './device-types';\n-import { type RawThreadInfo, rawThreadInfoPropType } from './thread-types';\n-import {\n- type RawEntryInfo,\n- type CalendarQuery,\n- rawEntryInfoPropType,\n- calendarQueryPropType,\n-} from './entry-types';\n+import type { Platform, PlatformDetails } from './device-types';\n+import type { RawThreadInfo } from './thread-types';\n+import type { RawEntryInfo, CalendarQuery } from './entry-types';\nimport type { BaseAction } from './redux-types';\n-import { type ActivityUpdate, activityUpdatePropType } from './activity-types';\n+import { type ActivityUpdate } from './activity-types';\nimport {\ntype CurrentUserInfo,\ntype AccountUserInfo,\n@@ -29,7 +19,6 @@ import type {\n} from './report-types';\nimport invariant from 'invariant';\n-import PropTypes from 'prop-types';\n// \"Server requests\" are requests for information that the server delivers to\n// clients. Clients then respond to those requests with a \"client response\".\n@@ -144,11 +133,11 @@ export type ClientResponse =\n// This is just the client variant of ClientResponse. The server needs to handle\n// multiple client versions so the type supports old versions of certain client\n// responses, but the client variant only need to support the latest version.\n-export type ClientThreadInconsistencyClientResponse = {|\n+type ClientThreadInconsistencyClientResponse = {|\n...ClientThreadInconsistencyReportShape,\ntype: 2,\n|};\n-export type ClientEntryInconsistencyClientResponse = {|\n+type ClientEntryInconsistencyClientResponse = {|\ntype: 5,\n...ClientEntryInconsistencyReportShape,\n|};\n@@ -162,71 +151,9 @@ export type ClientClientResponse =\n| CheckStateClientResponse\n| InitialActivityUpdatesClientResponse;\n-const actionSummaryPropType = PropTypes.shape({\n- type: PropTypes.string.isRequired,\n- time: PropTypes.number.isRequired,\n- summary: PropTypes.string.isRequired,\n-});\n-export const clientResponsePropType = PropTypes.oneOfType([\n- PropTypes.shape({\n- type: PropTypes.oneOf([ serverRequestTypes.PLATFORM ]).isRequired,\n- platform: platformPropType.isRequired,\n- }),\n- PropTypes.shape({\n- type: PropTypes.oneOf([ serverRequestTypes.DEVICE_TOKEN ]).isRequired,\n- deviceToken: PropTypes.string.isRequired,\n- }),\n- PropTypes.shape({\n- type: PropTypes.oneOf([\n- serverRequestTypes.THREAD_INCONSISTENCY,\n- ]).isRequired,\n- platformDetails: platformDetailsPropType.isRequired,\n- beforeAction: PropTypes.objectOf(rawThreadInfoPropType).isRequired,\n- action: PropTypes.object.isRequired,\n- pollResult: PropTypes.objectOf(rawThreadInfoPropType).isRequired,\n- pushResult: PropTypes.objectOf(rawThreadInfoPropType).isRequired,\n- lastActions: PropTypes.arrayOf(actionSummaryPropType).isRequired,\n- time: PropTypes.number.isRequired,\n- }),\n- PropTypes.shape({\n- type: PropTypes.oneOf([ serverRequestTypes.PLATFORM_DETAILS ]).isRequired,\n- platformDetails: platformDetailsPropType.isRequired,\n- }),\n- PropTypes.shape({\n- type: PropTypes.oneOf([ serverRequestTypes.INITIAL_ACTIVITY_UPDATE ]).isRequired,\n- threadID: PropTypes.string.isRequired,\n- }),\n- PropTypes.shape({\n- type: PropTypes.oneOf([\n- serverRequestTypes.ENTRY_INCONSISTENCY,\n- ]).isRequired,\n- platformDetails: platformDetailsPropType.isRequired,\n- beforeAction: PropTypes.objectOf(rawEntryInfoPropType).isRequired,\n- action: PropTypes.object.isRequired,\n- calendarQuery: calendarQueryPropType.isRequired,\n- pollResult: PropTypes.objectOf(rawEntryInfoPropType).isRequired,\n- pushResult: PropTypes.objectOf(rawEntryInfoPropType).isRequired,\n- lastActions: PropTypes.arrayOf(actionSummaryPropType).isRequired,\n- time: PropTypes.number.isRequired,\n- }),\n- PropTypes.shape({\n- type: PropTypes.oneOf([ serverRequestTypes.CHECK_STATE ]).isRequired,\n- hashResults: PropTypes.objectOf(PropTypes.bool).isRequired,\n- }),\n- PropTypes.shape({\n- type: PropTypes.oneOf([\n- serverRequestTypes.INITIAL_ACTIVITY_UPDATES,\n- ]).isRequired,\n- activityUpdates: PropTypes.arrayOf(activityUpdatePropType).isRequired,\n- }),\n-]);\n-\nexport type ClientInconsistencyResponse =\n| ClientThreadInconsistencyClientResponse\n| ClientEntryInconsistencyClientResponse;\n-export type ClearDeliveredReportsPayload = {|\n- reports: $ReadOnlyArray<ClientInconsistencyResponse>,\n-|};\nexport const processServerRequestsActionType = \"PROCESS_SERVER_REQUESTS\";\nexport type ProcessServerRequestsPayload = {|\n" }, { "change_type": "MODIFY", "old_path": "lib/types/thread-types.js", "new_path": "lib/types/thread-types.js", "diff": "@@ -12,7 +12,9 @@ import type {\nRawEntryInfo,\n} from './entry-types';\nimport type { UpdateInfo } from './update-types';\n-import type { ClientThreadInconsistencyClientResponse } from './request-types';\n+import type {\n+ ClientThreadInconsistencyReportCreationRequest,\n+} from './report-types';\nimport PropTypes from 'prop-types';\nimport invariant from 'invariant';\n@@ -240,8 +242,8 @@ export type ServerThreadInfo = {|\nexport type ThreadStore = {|\nthreadInfos: {[id: string]: RawThreadInfo},\n- inconsistencyResponses:\n- $ReadOnlyArray<ClientThreadInconsistencyClientResponse>,\n+ inconsistencyReports:\n+ $ReadOnlyArray<ClientThreadInconsistencyReportCreationRequest>,\n|};\nexport type ThreadDeletionRequest = {|\n" }, { "change_type": "MODIFY", "old_path": "native/chat/chat-input-state-container.react.js", "new_path": "native/chat/chat-input-state-container.react.js", "diff": "@@ -561,6 +561,7 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\nids: {| localID: string, localMessageID: string, serverID: ?string |},\nmediaMission: MediaMission,\n) {\n+ console.log(mediaMission);\n}\nmessageHasUploadFailure = (localMessageID: string) => {\n" }, { "change_type": "MODIFY", "old_path": "native/redux/persist.js", "new_path": "native/redux/persist.js", "diff": "@@ -15,6 +15,7 @@ import Orientation from 'react-native-orientation-locker';\nimport { highestLocalIDSelector } from 'lib/selectors/local-id-selectors';\nimport { unshimMessageStore } from 'lib/shared/unshim-utils';\n+import { inconsistencyResponsesToReports } from 'lib/shared/report-utils';\nimport { nativeCalendarQuery } from '../selectors/nav-selectors';\nimport { defaultNotifPermissionAlertInfo } from '../push/alerts';\n@@ -152,6 +153,24 @@ const migrations = {\n[ messageTypes.MULTIMEDIA ],\n),\n}),\n+ [15]: (state) => ({\n+ ...state,\n+ threadStore: {\n+ ...state.threadStore,\n+ inconsistencyReports: inconsistencyResponsesToReports(\n+ state.threadStore.inconsistencyResponses,\n+ ),\n+ inconsistencyResponses: undefined,\n+ },\n+ entryStore: {\n+ ...state.entryStore,\n+ inconsistencyReports: inconsistencyResponsesToReports(\n+ state.entryStore.inconsistencyResponses,\n+ ),\n+ inconsistencyResponses: undefined,\n+ },\n+\n+ }),\n};\nconst persistConfig = {\n@@ -159,7 +178,7 @@ const persistConfig = {\nstorage: AsyncStorage,\nblacklist,\ndebug: __DEV__,\n- version: 14,\n+ version: 15,\nmigrate: createMigrate(migrations, { debug: __DEV__ }),\ntimeout: __DEV__ ? 0 : undefined,\n};\n" }, { "change_type": "MODIFY", "old_path": "native/redux/redux-setup.js", "new_path": "native/redux/redux-setup.js", "diff": "@@ -148,11 +148,11 @@ const defaultState = ({\nentryInfos: {},\ndaysToEntries: {},\nlastUserInteractionCalendar: 0,\n- inconsistencyResponses: [],\n+ inconsistencyReports: [],\n},\nthreadStore: {\nthreadInfos: {},\n- inconsistencyResponses: [],\n+ inconsistencyReports: [],\n},\nuserInfos: {},\nmessageStore: {\n" }, { "change_type": "MODIFY", "old_path": "server/src/responders/website-responders.js", "new_path": "server/src/responders/website-responders.js", "diff": "@@ -131,7 +131,7 @@ async function websiteResponder(\nconst threadStorePromise = (async () => {\nconst { threadInfos } = await threadInfoPromise;\n- return { threadInfos, inconsistencyResponses: [] };\n+ return { threadInfos, inconsistencyReports: [] };\n})();\nconst messageStorePromise = (async () => {\nconst [\n@@ -151,7 +151,7 @@ async function websiteResponder(\nentryInfos: _keyBy('id')(rawEntryInfos),\ndaysToEntries: daysToEntriesFromEntryInfos(rawEntryInfos),\nlastUserInteractionCalendar: initialTime,\n- inconsistencyResponses: [],\n+ inconsistencyReports: [],\n};\n})();\nconst userInfoPromise = (async () => {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Store ClientReportCreationRequests instead of ClientInconsistencyResponses in Redux
129,187
04.03.2020 11:28:35
18,000
514500358aa54765392b54b872e603856b0e5449
Actually upload and handle MediaMission reports
[ { "change_type": "MODIFY", "old_path": "lib/actions/report-actions.js", "new_path": "lib/actions/report-actions.js", "diff": "@@ -24,7 +24,10 @@ async function sendReport(\nreturn { id: response.id };\n}\n+const queueReportsActionType = \"QUEUE_REPORTS\";\n+\nexport {\nsendReportActionTypes,\nsendReport,\n+ queueReportsActionType,\n};\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/master-reducer.js", "new_path": "lib/reducers/master-reducer.js", "diff": "@@ -19,6 +19,7 @@ import reduceCalendarFilters from './calendar-filters-reducer';\nimport reduceConnectionInfo from './connection-reducer';\nimport reduceForeground from './foreground-reducer';\nimport reduceNextLocalID from './local-id-reducer';\n+import reduceQueuedReports from './report-reducer';\nexport default function baseReducer<N: BaseNavInfo, T: BaseAppState<N>>(\nstate: T,\n@@ -84,5 +85,6 @@ export default function baseReducer<N: BaseNavInfo, T: BaseAppState<N>>(\nconnection,\nforeground: reduceForeground(state.foreground, action),\nnextLocalID: reduceNextLocalID(state.nextLocalID, action),\n+ queuedReports: reduceQueuedReports(state.queuedReports, action),\n};\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "lib/reducers/report-reducer.js", "diff": "+// @flow\n+\n+import type { BaseAction } from '../types/redux-types';\n+import type { ClientReportCreationRequest } from '../types/report-types';\n+\n+import {\n+ sendReportActionTypes,\n+ queueReportsActionType,\n+} from '../actions/report-actions';\n+\n+export default function reduceQueuedReports(\n+ state: $ReadOnlyArray<ClientReportCreationRequest>,\n+ action: BaseAction,\n+): $ReadOnlyArray<ClientReportCreationRequest> {\n+ if (action.type === sendReportActionTypes.success && action.payload) {\n+ const { payload } = action;\n+ const updatedReports = state.filter(\n+ response => !payload.reports.includes(response),\n+ );\n+ if (updatedReports.length === state.length) {\n+ return state;\n+ }\n+ return updatedReports;\n+ } else if (action.type === queueReportsActionType) {\n+ const { reports } = action.payload;\n+ return [ ...state, ...reports ];\n+ }\n+ return state;\n+}\n" }, { "change_type": "MODIFY", "old_path": "lib/selectors/socket-selectors.js", "new_path": "lib/selectors/socket-selectors.js", "diff": "@@ -33,14 +33,17 @@ const queuedReports: (\n) => $ReadOnlyArray<ClientReportCreationRequest> = createSelector(\n(state: AppState) => state.threadStore.inconsistencyReports,\n(state: AppState) => state.entryStore.inconsistencyReports,\n+ (state: AppState) => state.queuedReports,\n(\nthreadInconsistencyReports:\n$ReadOnlyArray<ClientThreadInconsistencyReportCreationRequest>,\nentryInconsistencyReports:\n$ReadOnlyArray<ClientEntryInconsistencyReportCreationRequest>,\n+ queuedReports: $ReadOnlyArray<ClientReportCreationRequest>,\n): $ReadOnlyArray<ClientReportCreationRequest> => [\n...threadInconsistencyReports,\n...entryInconsistencyReports,\n+ ...queuedReports,\n],\n);\n" }, { "change_type": "MODIFY", "old_path": "lib/socket/report-handler.react.js", "new_path": "lib/socket/report-handler.react.js", "diff": "import {\ntype ClientReportCreationRequest,\ntype ReportCreationResponse,\n+ type ClearDeliveredReportsPayload,\nreportTypes,\nqueuedClientReportCreationRequestPropType,\n} from '../types/report-types';\n@@ -91,7 +92,7 @@ class ReportHandler extends React.PureComponent<Props> {\nasync sendResponse(report: ClientReportCreationRequest) {\nawait this.sendReport(report);\n- return { reports: [ report ] };\n+ return ({ reports: [ report ] }: ClearDeliveredReportsPayload);\n}\nasync sendReport(report: ClientReportCreationRequest) {\n" }, { "change_type": "MODIFY", "old_path": "lib/types/media-types.js", "new_path": "lib/types/media-types.js", "diff": "@@ -119,20 +119,24 @@ export type MediaLibrarySelection =\nplayableDuration: number,\n|};\n-export const mediaLibrarySelectionPropType = PropTypes.oneOfType([\n- PropTypes.shape({\n+const photoLibrarySelectionPropType = PropTypes.shape({\nstep: PropTypes.oneOf([ \"photo_library\" ]).isRequired,\ndimensions: dimensionsPropType.isRequired,\nfilename: PropTypes.string.isRequired,\nuri: PropTypes.string.isRequired,\n- }),\n- PropTypes.shape({\n+});\n+\n+const videoLibrarySelectionPropType = PropTypes.shape({\nstep: PropTypes.oneOf([ \"video_library\" ]).isRequired,\ndimensions: dimensionsPropType.isRequired,\nfilename: PropTypes.string.isRequired,\nuri: PropTypes.string.isRequired,\nplayableDuration: PropTypes.number.isRequired,\n- }),\n+});\n+\n+export const mediaLibrarySelectionPropType = PropTypes.oneOfType([\n+ photoLibrarySelectionPropType,\n+ videoLibrarySelectionPropType,\n]);\nexport type PhotoCapture = {|\n@@ -238,6 +242,7 @@ export type MediaMissionFailure =\n| {|\nsuccess: false,\nreason: \"http_upload_failed\",\n+ message: ?string,\n|}\n| {|\nsuccess: false,\n@@ -269,3 +274,140 @@ export type MediaMission = {|\nsteps: MediaMissionStep[],\nresult: MediaMissionResult,\n|};\n+\n+export const mediaMissionPropType = PropTypes.shape({\n+ steps: PropTypes.arrayOf(PropTypes.oneOfType([\n+ photoLibrarySelectionPropType,\n+ videoLibrarySelectionPropType,\n+ PropTypes.shape({\n+ step: PropTypes.oneOf([ \"photo_capture\" ]).isRequired,\n+ time: PropTypes.number.isRequired,\n+ dimensions: dimensionsPropType.isRequired,\n+ filename: PropTypes.string.isRequired,\n+ uri: PropTypes.string.isRequired,\n+ }),\n+ PropTypes.shape({\n+ step: PropTypes.oneOf([ \"validation\" ]).isRequired,\n+ type: mediaTypePropType.isRequired,\n+ success: PropTypes.bool.isRequired,\n+ time: PropTypes.number.isRequired,\n+ blobFetched: PropTypes.bool.isRequired,\n+ blobMIME: PropTypes.string,\n+ reportedMIME: PropTypes.string,\n+ blobName: PropTypes.string,\n+ size: PropTypes.number,\n+ }),\n+ PropTypes.shape({\n+ step: PropTypes.oneOf([ \"photo_resize_transcode\" ]).isRequired,\n+ success: PropTypes.bool.isRequired,\n+ time: PropTypes.number.isRequired,\n+ newMIME: PropTypes.string,\n+ newDimensions: dimensionsPropType,\n+ newURI: PropTypes.string,\n+ newPath: PropTypes.string,\n+ newName: PropTypes.string,\n+ }),\n+ PropTypes.shape({\n+ step: PropTypes.oneOf([ \"video_copy\" ]).isRequired,\n+ success: PropTypes.bool.isRequired,\n+ time: PropTypes.number.isRequired,\n+ newPath: PropTypes.string,\n+ }),\n+ PropTypes.shape({\n+ step: PropTypes.oneOf([ \"video_probe\" ]).isRequired,\n+ success: PropTypes.bool.isRequired,\n+ time: PropTypes.number.isRequired,\n+ path: PropTypes.string.isRequired,\n+ ext: PropTypes.string,\n+ codec: PropTypes.string,\n+ }),\n+ PropTypes.shape({\n+ step: PropTypes.oneOf([ \"video_ios_native_transcode\" ]).isRequired,\n+ success: PropTypes.bool.isRequired,\n+ time: PropTypes.number.isRequired,\n+ newPath: PropTypes.string,\n+ }),\n+ PropTypes.shape({\n+ step: PropTypes.oneOf([ \"video_ffmpeg_transcode\" ]).isRequired,\n+ success: PropTypes.bool.isRequired,\n+ time: PropTypes.number.isRequired,\n+ returnCode: PropTypes.number,\n+ newPath: PropTypes.string,\n+ }),\n+ PropTypes.shape({\n+ step: PropTypes.oneOf([ \"final_file_data_analysis\" ]).isRequired,\n+ success: PropTypes.bool.isRequired,\n+ time: PropTypes.number.isRequired,\n+ uri: PropTypes.string.isRequired,\n+ detectedMIME: PropTypes.string,\n+ detectedMediaType: mediaTypePropType,\n+ newName: PropTypes.string,\n+ }),\n+ PropTypes.shape({\n+ step: PropTypes.oneOf([ \"dispose_uploaded_local_file\" ]).isRequired,\n+ success: PropTypes.bool.isRequired,\n+ time: PropTypes.number.isRequired,\n+ path: PropTypes.string.isRequired,\n+ }),\n+ PropTypes.shape({\n+ step: PropTypes.oneOf([ \"upload\" ]).isRequired,\n+ success: PropTypes.bool.isRequired,\n+ time: PropTypes.number.isRequired,\n+ }),\n+ PropTypes.shape({\n+ step: PropTypes.oneOf([ \"processing_exception\" ]).isRequired,\n+ success: PropTypes.bool.isRequired,\n+ message: PropTypes.string,\n+ }),\n+ ])).isRequired,\n+ result: PropTypes.oneOfType([\n+ PropTypes.shape({\n+ success: PropTypes.oneOf([ true ]).isRequired,\n+ totalTime: PropTypes.number.isRequired,\n+ }),\n+ PropTypes.shape({\n+ success: PropTypes.oneOf([ false ]).isRequired,\n+ reason: PropTypes.oneOf([ \"too_large_cant_downscale\" ]).isRequired,\n+ size: PropTypes.number.isRequired,\n+ }),\n+ PropTypes.shape({\n+ success: PropTypes.oneOf([ false ]).isRequired,\n+ reason: PropTypes.oneOf([ \"blob_reported_mime_issue\" ]).isRequired,\n+ mime: PropTypes.string,\n+ }),\n+ PropTypes.shape({\n+ success: PropTypes.oneOf([ false ]).isRequired,\n+ reason: PropTypes.oneOf([ \"file_data_detected_mime_issue\" ]).isRequired,\n+ reportedMIME: PropTypes.string.isRequired,\n+ reportedMediaType: mediaTypePropType.isRequired,\n+ detectedMIME: PropTypes.string,\n+ detectedMediaType: mediaTypePropType,\n+ }),\n+ PropTypes.shape({\n+ success: PropTypes.oneOf([ false ]).isRequired,\n+ reason: PropTypes.oneOf([ \"http_upload_failed\" ]).isRequired,\n+ message: PropTypes.string,\n+ }),\n+ PropTypes.shape({\n+ success: PropTypes.oneOf([ false ]).isRequired,\n+ reason: PropTypes.oneOf([ \"video_path_extraction_failed\" ]).isRequired,\n+ uri: PropTypes.string.isRequired,\n+ }),\n+ PropTypes.shape({\n+ success: PropTypes.oneOf([ false ]).isRequired,\n+ reason: PropTypes.oneOf([ \"video_ios_asset_copy_failed\" ]).isRequired,\n+ inputURI: PropTypes.string.isRequired,\n+ destinationPath: PropTypes.string.isRequired,\n+ }),\n+ PropTypes.shape({\n+ success: PropTypes.oneOf([ false ]).isRequired,\n+ reason: PropTypes.oneOf([ \"video_transcode_failed\" ]).isRequired,\n+ }),\n+ PropTypes.shape({\n+ success: PropTypes.oneOf([ false ]).isRequired,\n+ reason: PropTypes.oneOf([ \"processing_exception\" ]).isRequired,\n+ time: PropTypes.number.isRequired,\n+ message: PropTypes.string,\n+ }),\n+ ]),\n+});\n" }, { "change_type": "MODIFY", "old_path": "lib/types/redux-types.js", "new_path": "lib/types/redux-types.js", "diff": "@@ -47,7 +47,11 @@ import type {\n} from './message-types';\nimport type { SetSessionPayload } from './session-types';\nimport type { ProcessServerRequestsPayload } from './request-types';\n-import type { ClearDeliveredReportsPayload } from './report-types';\n+import type {\n+ ClearDeliveredReportsPayload,\n+ ClientReportCreationRequest,\n+ QueueReportsPayload,\n+} from './report-types';\nimport type {\nCalendarFilter,\nCalendarThreadFilter,\n@@ -84,6 +88,7 @@ export type BaseAppState<NavInfo: BaseNavInfo> = {\nwatchedThreadIDs: $ReadOnlyArray<string>,\nforeground: bool,\nnextLocalID: number,\n+ queuedReports: $ReadOnlyArray<ClientReportCreationRequest>,\n};\n// Web JS runtime doesn't have access to the cookie for security reasons.\n@@ -540,6 +545,9 @@ export type BaseAction =\ntype: \"SEND_REPORT_SUCCESS\",\npayload?: ClearDeliveredReportsPayload,\nloadingInfo: LoadingInfo,\n+ |} | {|\n+ type: \"QUEUE_REPORTS\",\n+ payload: QueueReportsPayload,\n|} | {|\ntype: \"SET_URL_PREFIX\",\npayload: string,\n" }, { "change_type": "MODIFY", "old_path": "lib/types/report-types.js", "new_path": "lib/types/report-types.js", "diff": "@@ -17,6 +17,7 @@ import {\nrawEntryInfoPropType,\ncalendarQueryPropType,\n} from './entry-types';\n+import { type MediaMission, mediaMissionPropType } from './media-types';\nimport invariant from 'invariant';\nimport PropTypes from 'prop-types';\n@@ -25,13 +26,15 @@ export const reportTypes = Object.freeze({\nERROR: 0,\nTHREAD_INCONSISTENCY: 1,\nENTRY_INCONSISTENCY: 2,\n+ MEDIA_MISSION: 3,\n});\ntype ReportType = $Values<typeof reportTypes>;\nfunction assertReportType(reportType: number): ReportType {\ninvariant(\nreportType === 0 ||\nreportType === 1 ||\n- reportType === 2,\n+ reportType === 2 ||\n+ reportType === 3,\n\"number is not ReportType enum\",\n);\nreturn reportType;\n@@ -88,10 +91,20 @@ export type EntryInconsistencyReportCreationRequest = {|\n...EntryInconsistencyReportShape,\ntype: 2,\n|};\n+export type MediaMissionReportCreationRequest = {|\n+ type: 3,\n+ platformDetails: PlatformDetails,\n+ time: number, // ms\n+ mediaMission: MediaMission,\n+ uploadServerID: ?string,\n+ uploadLocalID: string,\n+ mediaLocalID: string,\n+|};\nexport type ReportCreationRequest =\n| ErrorReportCreationRequest\n| ThreadInconsistencyReportCreationRequest\n- | EntryInconsistencyReportCreationRequest;\n+ | EntryInconsistencyReportCreationRequest\n+ | MediaMissionReportCreationRequest;\nexport type ClientThreadInconsistencyReportShape = {|\nplatformDetails: PlatformDetails,\n@@ -125,7 +138,12 @@ export type ClientEntryInconsistencyReportCreationRequest = {|\nexport type ClientReportCreationRequest =\n| ErrorReportCreationRequest\n| ClientThreadInconsistencyReportCreationRequest\n- | ClientEntryInconsistencyReportCreationRequest;\n+ | ClientEntryInconsistencyReportCreationRequest\n+ | MediaMissionReportCreationRequest;\n+\n+export type QueueReportsPayload = {|\n+ reports: $ReadOnlyArray<ClientReportCreationRequest>,\n+|};\nexport type ClearDeliveredReportsPayload = {|\nreports: $ReadOnlyArray<ClientReportCreationRequest>,\n@@ -138,9 +156,7 @@ const actionSummaryPropType = PropTypes.shape({\n});\nexport const queuedClientReportCreationRequestPropType = PropTypes.oneOfType([\nPropTypes.shape({\n- type: PropTypes.oneOf([\n- reportTypes.THREAD_INCONSISTENCY,\n- ]).isRequired,\n+ type: PropTypes.oneOf([ reportTypes.THREAD_INCONSISTENCY ]).isRequired,\nplatformDetails: platformDetailsPropType.isRequired,\nbeforeAction: PropTypes.objectOf(rawThreadInfoPropType).isRequired,\naction: PropTypes.object.isRequired,\n@@ -150,9 +166,7 @@ export const queuedClientReportCreationRequestPropType = PropTypes.oneOfType([\ntime: PropTypes.number.isRequired,\n}),\nPropTypes.shape({\n- type: PropTypes.oneOf([\n- reportTypes.ENTRY_INCONSISTENCY,\n- ]).isRequired,\n+ type: PropTypes.oneOf([ reportTypes.ENTRY_INCONSISTENCY ]).isRequired,\nplatformDetails: platformDetailsPropType.isRequired,\nbeforeAction: PropTypes.objectOf(rawEntryInfoPropType).isRequired,\naction: PropTypes.object.isRequired,\n@@ -162,6 +176,15 @@ export const queuedClientReportCreationRequestPropType = PropTypes.oneOfType([\nlastActions: PropTypes.arrayOf(actionSummaryPropType).isRequired,\ntime: PropTypes.number.isRequired,\n}),\n+ PropTypes.shape({\n+ type: PropTypes.oneOf([ reportTypes.MEDIA_MISSION ]).isRequired,\n+ platformDetails: platformDetailsPropType.isRequired,\n+ time: PropTypes.number.isRequired,\n+ mediaMission: mediaMissionPropType.isRequired,\n+ uploadServerID: PropTypes.string,\n+ uploadLocalID: PropTypes.string.isRequired,\n+ mediaLocalID: PropTypes.string.isRequired,\n+ }),\n]);\nexport type ReportCreationResponse = {|\n" }, { "change_type": "MODIFY", "old_path": "native/chat/chat-input-state-container.react.js", "new_path": "native/chat/chat-input-state-container.react.js", "diff": "@@ -22,6 +22,10 @@ import {\ntype RawImagesMessageInfo,\ntype RawMediaMessageInfo,\n} from 'lib/types/message-types';\n+import {\n+ type MediaMissionReportCreationRequest,\n+ reportTypes,\n+} from 'lib/types/report-types';\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\n@@ -40,6 +44,8 @@ import {\nsendMultimediaMessage,\n} from 'lib/actions/message-actions';\nimport { createMediaMessageInfo } from 'lib/shared/message-utils';\n+import { queueReportsActionType } from 'lib/actions/report-actions';\n+import { getConfig } from 'lib/utils/config';\nimport { ChatInputStateContext } from './chat-input-state';\nimport { processMedia } from '../utils/media-utils';\n@@ -437,7 +443,7 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\n} = processedMedia;\nconst uploadStart = Date.now();\n- let uploadResult, message;\n+ let uploadResult, message, mediaMissionResult;\ntry {\nuploadResult = await this.props.uploadMultimedia(\n{ uri: uploadURI, name, type: mime },\n@@ -447,8 +453,14 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\npercent,\n),\n);\n+ mediaMissionResult = { success: true, totalTime: Date.now() - start };\n} catch (e) {\nmessage = \"upload failed\";\n+ mediaMissionResult = {\n+ success: false,\n+ reason: \"http_upload_failed\",\n+ message: (e && e.message) ? e.message : undefined,\n+ };\n}\nif (uploadResult) {\nserverID = uploadResult.id;\n@@ -472,9 +484,6 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\nsuccess: !!uploadResult,\ntime: Date.now() - uploadStart,\n});\n- const mediaMissionResult = uploadResult\n- ? { success: true, totalTime: Date.now() - start }\n- : { success: false, reason: \"http_upload_failed\" };\nif (!shouldDisposePath) {\nreturn finish(mediaMissionResult, message);\n@@ -561,7 +570,19 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\nids: {| localID: string, localMessageID: string, serverID: ?string |},\nmediaMission: MediaMission,\n) {\n- console.log(mediaMission);\n+ const report: MediaMissionReportCreationRequest = {\n+ type: reportTypes.MEDIA_MISSION,\n+ time: Date.now(),\n+ platformDetails: getConfig().platformDetails,\n+ mediaMission,\n+ uploadServerID: ids.serverID,\n+ uploadLocalID: ids.localID,\n+ mediaLocalID: ids.localMessageID,\n+ };\n+ this.props.dispatchActionPayload(\n+ queueReportsActionType,\n+ { reports: [ report ] },\n+ );\n}\nmessageHasUploadFailure = (localMessageID: string) => {\n" }, { "change_type": "MODIFY", "old_path": "native/redux/persist.js", "new_path": "native/redux/persist.js", "diff": "@@ -169,7 +169,7 @@ const migrations = {\n),\ninconsistencyResponses: undefined,\n},\n-\n+ queuedReports: [],\n}),\n};\n" }, { "change_type": "MODIFY", "old_path": "native/redux/redux-setup.js", "new_path": "native/redux/redux-setup.js", "diff": "@@ -39,6 +39,7 @@ import {\ndefaultDeviceCameraInfo,\n} from '../types/camera';\nimport type { Orientations } from 'react-native-orientation-locker';\n+import type { ClientReportCreationRequest } from 'lib/types/report-types';\nimport * as React from 'react';\nimport invariant from 'invariant';\n@@ -130,6 +131,7 @@ export type AppState = {|\nwatchedThreadIDs: $ReadOnlyArray<string>,\nforeground: bool,\nnextLocalID: number,\n+ queuedReports: $ReadOnlyArray<ClientReportCreationRequest>,\n_persist: ?PersistState,\nsessionID?: void,\ndimensions: Dimensions,\n@@ -176,6 +178,7 @@ const defaultState = ({\nwatchedThreadIDs: [],\nforeground: true,\nnextLocalID: 0,\n+ queuedReports: [],\n_persist: null,\ndimensions: { height, width },\nconnectivity: defaultConnectivityInfo,\n" }, { "change_type": "MODIFY", "old_path": "server/src/creators/report-creator.js", "new_path": "server/src/creators/report-creator.js", "diff": "@@ -46,6 +46,8 @@ async function createReport(\ntime = time ? time : Date.now();\n} else if (request.type === reportTypes.ENTRY_INCONSISTENCY) {\n({ type, time, ...report } = request);\n+ } else if (request.type === reportTypes.MEDIA_MISSION) {\n+ ({ type, time, ...report } = request);\n} else {\n({ type, ...report } = request);\ntime = Date.now();\n@@ -154,6 +156,12 @@ function getSquadbotMessage(\n`using ${platformString}\\n` +\n`occurred during ${request.action.type}\\n` +\n`entry IDs that are inconsistent: ${nonMatchingString}`;\n+ } else if (request.type === reportTypes.MEDIA_MISSION) {\n+ const mediaMissionJSON = JSON.stringify(request.mediaMission);\n+ const success = request.mediaMission.result.success\n+ ? \"uploaded media successfully\"\n+ : \"failed to upload media :(\";\n+ return `${name} ${success}\\n` + mediaMissionJSON;\n} else {\nreturn null;\n}\n" }, { "change_type": "MODIFY", "old_path": "server/src/responders/report-responders.js", "new_path": "server/src/responders/report-responders.js", "diff": "@@ -87,6 +87,18 @@ const reportCreationRequestInputValidator = t.union([\nx => x === reportTypes.ENTRY_INCONSISTENCY,\n),\n}),\n+ tShape({\n+ type: t.irreducible(\n+ 'reportTypes.MEDIA_MISSION',\n+ x => x === reportTypes.MEDIA_MISSION,\n+ ),\n+ platformDetails: tPlatformDetails,\n+ time: t.Number,\n+ mediaMission: t.Object,\n+ uploadServerID: t.maybe(t.String),\n+ uploadLocalID: t.String,\n+ mediaLocalID: t.String,\n+ }),\n]);\nasync function reportCreationResponder(\n" }, { "change_type": "MODIFY", "old_path": "server/src/responders/website-responders.js", "new_path": "server/src/responders/website-responders.js", "diff": "@@ -273,6 +273,7 @@ async function websiteResponder(\nwatchedThreadIDs: [],\nforeground: true,\nnextLocalID: 0,\n+ queuedReports: [],\ntimeZone: viewer.timeZone,\nuserAgent: viewer.userAgent,\ncookie: undefined,\n" }, { "change_type": "MODIFY", "old_path": "web/redux-setup.js", "new_path": "web/redux-setup.js", "diff": "@@ -11,6 +11,7 @@ import type { MessageStore } from 'lib/types/message-types';\nimport type { CalendarFilter } from 'lib/types/filter-types';\nimport { setNewSessionActionType } from 'lib/utils/action-utils';\nimport type { ConnectionInfo } from 'lib/types/socket-types';\n+import type { ClientReportCreationRequest } from 'lib/types/report-types';\nimport PropTypes from 'prop-types';\nimport invariant from 'invariant';\n@@ -67,6 +68,7 @@ export type AppState = {|\nwatchedThreadIDs: $ReadOnlyArray<string>,\nforeground: bool,\nnextLocalID: number,\n+ queuedReports: $ReadOnlyArray<ClientReportCreationRequest>,\ntimeZone: ?string,\nuserAgent: ?string,\n|};\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Actually upload and handle MediaMission reports
129,187
04.03.2020 15:45:19
18,000
7ad509458428960d1067bd76b836b464fd83a444
[native] Try to keep original media filename
[ { "change_type": "MODIFY", "old_path": "native/utils/media-utils.js", "new_path": "native/utils/media-utils.js", "diff": "@@ -15,6 +15,7 @@ import invariant from 'invariant';\nimport {\nfileInfoFromData,\nmimeTypesToMediaTypes,\n+ stripExtension,\n} from 'lib/utils/file-utils';\nimport { transcodeVideo } from './video-utils';\n@@ -257,7 +258,11 @@ async function convertMedia(\ncompressQuality,\n);\nuploadURI = resizedURI;\n- name = resizedName;\n+ if (reportedMIME === \"image/png\" && !name.endsWith('.png')) {\n+ name = `${stripExtension(name)}.png`;\n+ } else if (reportedMIME !== \"image/png\" && !name.endsWith('.jpg')) {\n+ name = `${stripExtension(name)}.jpg`;\n+ }\nshouldDisposePath = path;\nmime = reportedMIME === \"image/png\" ? \"image/png\" : \"image/jpeg\";\ndimensions = await getDimensions(resizedURI);\n@@ -315,8 +320,7 @@ async function convertMedia(\nconst dataURI = await blobToDataURI(blob);\nconst intArray = dataURIToIntArray(dataURI);\n- const blobName = blob.data.name;\n- const fileDetectionResult = fileInfoFromData(intArray, blobName);\n+ const fileDetectionResult = fileInfoFromData(intArray, name);\nfileDataDetectionStep = {\nstep: \"final_file_data_analysis\",\nsuccess: !!fileDetectionResult.name &&\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Try to keep original media filename
129,187
17.03.2020 18:05:23
14,400
1b108e3fb76cf7b0e2790f976987517a2830244f
[server] run-nvm.sh -> run-prod.sh
[ { "change_type": "MODIFY", "old_path": "server/bash/deploy.sh", "new_path": "server/bash/deploy.sh", "diff": "@@ -31,7 +31,7 @@ su $DAEMON_USER -c \"server/bash/setup.sh\"\n# STEP 2: test if the binary crashes within 60 seconds\nset +e\n-su $DAEMON_USER -c \"cd server && PORT=3001 timeout 60 bash/run-nvm.sh\"\n+su $DAEMON_USER -c \"cd server && PORT=3001 timeout 60 bash/run-prod.sh\"\n[[ $? -eq 124 ]] || exit 1\nset -e\n" }, { "change_type": "RENAME", "old_path": "server/bash/run-nvm.sh", "new_path": "server/bash/run-prod.sh", "diff": "" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] run-nvm.sh -> run-prod.sh
129,187
17.03.2020 18:26:52
14,400
e0261b639fa38b7b57f782b362471316bc21d503
[server] Use nvm on dev environment
[ { "change_type": "ADD", "old_path": null, "new_path": "server/bash/source-nvm.sh", "diff": "+#!/bin/bash\n+\n+# source as: logged in user\n+# source from: package.json (via npm/yarn scripts)\n+\n+unset PREFIX\n+[ -s \"/usr/local/opt/nvm/nvm.sh\" ] && . \"/usr/local/opt/nvm/nvm.sh\"\n+[ -s \"$NVM_DIR/nvm.sh\" ] && . \"$NVM_DIR/nvm.sh\"\n+nvm install --no-progress\n" }, { "change_type": "MODIFY", "old_path": "server/package.json", "new_path": "server/package.json", "diff": "\"update-geoip\": \"yarn script dist/scripts/update-geoip.js\",\n\"prod\": \"node --experimental-modules --experimental-json-modules --loader ./loader.mjs --es-module-specifier-resolution node dist/server\",\n\"dev-rsync\": \"yarn --silent chokidar --initial --silent -s 'src/**/*.json' 'src/**/*.cjs' -c 'yarn rsync > /dev/null 2>&1'\",\n- \"dev\": \"NODE_ENV=dev yarn concurrently --names=\\\"BABEL,RSYNC,NODEM\\\" -c \\\"bgBlue.bold,bgMagenta.bold,bgGreen.bold\\\" \\\"yarn babel-build -- --watch\\\" \\\"yarn dev-rsync\\\" \\\"nodemon -e js,json,cjs --watch dist --experimental-modules --experimental-json-modules --loader ./loader.mjs --es-module-specifier-resolution node dist/server\\\"\",\n- \"script\": \"node --experimental-modules --experimental-json-modules --loader ./loader.mjs --es-module-specifier-resolution node\"\n+ \"dev\": \"yarn concurrently --names=\\\"BABEL,RSYNC,NODEM\\\" -c \\\"bgBlue.bold,bgMagenta.bold,bgGreen.bold\\\" \\\"yarn babel-build --watch\\\" \\\"yarn dev-rsync\\\" \\\". bash/source-nvm.sh && NODE_ENV=dev nodemon -e js,json,cjs --watch dist --experimental-modules --experimental-json-modules --loader ./loader.mjs --es-module-specifier-resolution node dist/server\\\"\",\n+ \"script\": \". bash/source-nvm.sh && node --experimental-modules --experimental-json-modules --loader ./loader.mjs --es-module-specifier-resolution node\"\n},\n\"devDependencies\": {\n\"@babel/cli\": \"^7.6.2\",\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Use nvm on dev environment
129,187
18.03.2020 15:44:43
14,400
77891ceec9217a0b4cd6ef1409d825ba97d9cbd9
[server] Don't require server/facts/backups.json to exist
[ { "change_type": "MODIFY", "old_path": "server/src/cron/backups.js", "new_path": "server/src/cron/backups.js", "diff": "@@ -6,15 +6,34 @@ import zlib from 'zlib';\nimport dateFormat from 'dateformat';\nimport StreamCache from 'stream-cache';\nimport { promisify } from 'util';\n+import invariant from 'invariant';\nimport dbConfig from '../../secrets/db_config';\n-import backupConfig from '../../facts/backups';\nconst readdir = promisify(fs.readdir);\nconst lstat = promisify(fs.lstat);\nconst unlink = promisify(fs.unlink);\n+let importedBackupConfig = undefined;\n+async function importBackupConfig() {\n+ if (importedBackupConfig !== undefined) {\n+ return importedBackupConfig;\n+ }\n+ try {\n+ const backupExports = await import('../../facts/backups');\n+ if (importedBackupConfig === undefined) {\n+ importedBackupConfig = backupExports.default;\n+ }\n+ } catch {\n+ if (importedBackupConfig === undefined) {\n+ importedBackupConfig = null;\n+ }\n+ }\n+ return importedBackupConfig;\n+}\n+\nasync function backupDB() {\n+ const backupConfig = await importBackupConfig();\nif (!backupConfig || !backupConfig.enabled) {\nreturn;\n}\n@@ -73,6 +92,8 @@ function trySaveBackup(filePath: string, cache: StreamCache): Promise<void> {\n}\nasync function deleteOldestBackup() {\n+ const backupConfig = await importBackupConfig();\n+ invariant(backupConfig, \"backupConfig should be non-null\");\nconst files = await readdir(backupConfig.directory);\nlet oldestFile;\nfor (let file of files) {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Don't require server/facts/backups.json to exist
129,187
18.03.2020 17:32:13
14,400
8d98f0d03a597fd4fcf300575dd6e2d664fda8cc
[server] ScriptContext
[ { "change_type": "MODIFY", "old_path": "server/src/database.js", "new_path": "server/src/database.js", "diff": "@@ -5,7 +5,7 @@ import mysql from 'mysql2';\nimport SQL from 'sql-template-strings';\nimport dbConfig from '../secrets/db_config';\n-import { isDryRun } from './scripts/dry-run';\n+import { getScriptContext } from './scripts/script-context';\nconst SQLStatement = SQL.SQLStatement;\n@@ -66,10 +66,12 @@ FakeSQLResult.prototype = Array.prototype;\nconst fakeResult: any = new FakeSQLResult();\nasync function dbQuery(statement: SQLStatement, triesLeft?: number = 2) {\n+ const scriptContext = getScriptContext();\ntry {\nconst sql = statement.sql.trim();\nif (\n- isDryRun() &&\n+ scriptContext &&\n+ scriptContext.dryRun &&\n(sql.startsWith(\"INSERT\") ||\nsql.startsWith(\"DELETE\") ||\nsql.startsWith(\"UPDATE\"))\n" }, { "change_type": "DELETE", "old_path": "server/src/scripts/dry-run.js", "new_path": null, "diff": "-// @flow\n-\n-// I flip this bit when testing things sometimes\n-const dryRun = false;\n-function isDryRun() {\n- return dryRun;\n-}\n-\n-export {\n- isDryRun,\n-};\n" }, { "change_type": "ADD", "old_path": null, "new_path": "server/src/scripts/script-context.js", "diff": "+// @flow\n+\n+type ScriptContext = {|\n+ // Prevents all mutations from occuring,\n+ // eg. MySQL INSERT/DELETE/UPDATE, Redis publish, etc.\n+ dryRun?: bool,\n+|};\n+\n+let scriptContext: ?ScriptContext = null;\n+\n+function getScriptContext(): ?ScriptContext {\n+ return scriptContext;\n+}\n+\n+function setScriptContext(newScriptContext: ?ScriptContext) {\n+ scriptContext = newScriptContext;\n+}\n+\n+export {\n+ getScriptContext,\n+ setScriptContext,\n+};\n" }, { "change_type": "MODIFY", "old_path": "server/src/socket/redis.js", "new_path": "server/src/socket/redis.js", "diff": "@@ -11,7 +11,7 @@ import {\nimport redis from 'redis';\nimport uuidv4 from 'uuid/v4';\n-import { isDryRun } from '../scripts/dry-run';\n+import { getScriptContext } from '../scripts/script-context';\nfunction channelNameForUpdateTarget(updateTarget: UpdateTarget): string {\nif (updateTarget.sessionID) {\n@@ -32,7 +32,8 @@ class RedisPublisher {\nsendMessage(target: UpdateTarget, message: RedisMessage) {\nconst channelName = channelNameForUpdateTarget(target);\nconst stringifiedMessage = JSON.stringify(message);\n- if (isDryRun()) {\n+ const scriptContext = getScriptContext();\n+ if (scriptContext && scriptContext.dryRun) {\nconsole.log(`Redis publish to ${channelName}: ${stringifiedMessage}`);\nreturn;\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] ScriptContext
129,187
18.03.2020 17:39:50
14,400
5ebf68d59b58018af5edf0811c40db6233b71249
[server] ScriptContext.allowMultiStatementSQLQueries
[ { "change_type": "MODIFY", "old_path": "server/src/database.js", "new_path": "server/src/database.js", "diff": "@@ -14,10 +14,21 @@ export type QueryResult = [\nany[],\n];\n-const pool = mysqlPromise.createPool({\n+let pool;\n+function getPool() {\n+ if (pool) {\n+ return pool;\n+ }\n+ const scriptContext = getScriptContext();\n+ pool = mysqlPromise.createPool({\n...dbConfig,\nconnectionLimit: 10,\n+ multipleStatements: !!(\n+ scriptContext && scriptContext.allowMultiStatementSQLQueries\n+ ),\n});\n+ return pool;\n+}\ntype SQLOrString = SQLStatement | string;\nfunction appendSQLArray(\n@@ -79,7 +90,7 @@ async function dbQuery(statement: SQLStatement, triesLeft?: number = 2) {\nconsole.log(rawSQL(statement));\nreturn [ fakeResult ];\n}\n- return await pool.query(statement);\n+ return await getPool().query(statement);\n} catch (e) {\nif (e.errno === 1213 && triesLeft > 0) {\nconsole.log('deadlock occurred, trying again', e);\n@@ -95,7 +106,7 @@ function rawSQL(statement: SQLStatement) {\n}\nexport {\n- pool,\n+ getPool,\nSQL,\nSQLStatement,\nappendSQLArray,\n" }, { "change_type": "MODIFY", "old_path": "server/src/scripts/script-context.js", "new_path": "server/src/scripts/script-context.js", "diff": "@@ -4,6 +4,8 @@ type ScriptContext = {|\n// Prevents all mutations from occuring,\n// eg. MySQL INSERT/DELETE/UPDATE, Redis publish, etc.\ndryRun?: bool,\n+ // Multiple statements in a single SQL query\n+ allowMultiStatementSQLQueries?: bool,\n|};\nlet scriptContext: ?ScriptContext = null;\n" }, { "change_type": "MODIFY", "old_path": "server/src/scripts/utils.js", "new_path": "server/src/scripts/utils.js", "diff": "// @flow\n-import { pool } from '../database';\n+import { getPool } from '../database';\nimport { publisher } from '../socket/redis';\nfunction endScript() {\n- pool.end();\n+ getPool().end();\npublisher.end();\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] ScriptContext.allowMultiStatementSQLQueries
129,187
18.03.2020 17:40:02
14,400
7033157f90b29c87b2995c2e7601761eb95d787b
[server] createTables script
[ { "change_type": "ADD", "old_path": null, "new_path": "server/src/scripts/create-tables.js", "diff": "+// @flow\n+\n+import { setScriptContext } from './script-context';\n+import { endScript } from './utils';\n+import { dbQuery, SQL } from '../database';\n+\n+setScriptContext({\n+ allowMultiStatementSQLQueries: true,\n+});\n+\n+async function main() {\n+ try {\n+ await createTables();\n+ endScript();\n+ } catch (e) {\n+ endScript();\n+ console.warn(e);\n+ }\n+}\n+\n+async function createTables() {\n+ await dbQuery(SQL`\n+ CREATE TABLE cookies (\n+ id bigint(20) NOT NULL,\n+ hash char(60) NOT NULL,\n+ user bigint(20) DEFAULT NULL,\n+ platform varchar(255) DEFAULT NULL,\n+ creation_time bigint(20) NOT NULL,\n+ last_used bigint(20) NOT NULL,\n+ device_token varchar(255) DEFAULT NULL,\n+ versions json DEFAULT NULL\n+ ) ENGINE=InnoDB DEFAULT CHARSET=latin1;\n+\n+ CREATE TABLE days (\n+ id bigint(20) NOT NULL,\n+ date date NOT NULL,\n+ thread bigint(20) NOT NULL\n+ ) ENGINE=InnoDB DEFAULT CHARSET=latin1;\n+\n+ CREATE TABLE entries (\n+ id bigint(20) NOT NULL,\n+ day bigint(20) NOT NULL,\n+ text mediumtext COLLATE utf8mb4_bin NOT NULL,\n+ creator bigint(20) NOT NULL,\n+ creation_time bigint(20) NOT NULL,\n+ last_update bigint(20) NOT NULL,\n+ deleted tinyint(1) UNSIGNED NOT NULL,\n+ creation varchar(255) COLLATE utf8mb4_bin DEFAULT NULL\n+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;\n+\n+ CREATE TABLE focused (\n+ user bigint(20) NOT NULL,\n+ session bigint(20) NOT NULL,\n+ thread bigint(20) NOT NULL,\n+ time bigint(20) NOT NULL\n+ ) ENGINE=InnoDB DEFAULT CHARSET=latin1;\n+\n+ CREATE TABLE ids (\n+ id bigint(20) NOT NULL,\n+ table_name varchar(255) NOT NULL\n+ ) ENGINE=InnoDB DEFAULT CHARSET=latin1;\n+\n+ CREATE TABLE memberships (\n+ thread bigint(20) NOT NULL,\n+ user bigint(20) NOT NULL,\n+ role bigint(20) NOT NULL,\n+ permissions json NOT NULL,\n+ permissions_for_children json DEFAULT NULL,\n+ creation_time bigint(20) NOT NULL,\n+ subscription json NOT NULL,\n+ unread tinyint(1) NOT NULL\n+ ) ENGINE=InnoDB DEFAULT CHARSET=latin1;\n+\n+ CREATE TABLE messages (\n+ id bigint(20) NOT NULL,\n+ thread bigint(20) NOT NULL,\n+ user bigint(20) NOT NULL,\n+ type tinyint(3) UNSIGNED NOT NULL,\n+ content mediumtext COLLATE utf8mb4_bin,\n+ time bigint(20) NOT NULL,\n+ creation varchar(255) COLLATE utf8mb4_bin DEFAULT NULL\n+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;\n+\n+ CREATE TABLE notifications (\n+ id bigint(20) NOT NULL,\n+ user bigint(20) NOT NULL,\n+ thread bigint(20) NOT NULL,\n+ message bigint(20) NOT NULL,\n+ collapse_key varchar(255) DEFAULT NULL,\n+ delivery json NOT NULL,\n+ rescinded tinyint(1) NOT NULL\n+ ) ENGINE=InnoDB DEFAULT CHARSET=latin1;\n+\n+ CREATE TABLE reports (\n+ id bigint(20) NOT NULL,\n+ user bigint(20) NOT NULL,\n+ type tinyint(3) UNSIGNED NOT NULL,\n+ platform varchar(255) NOT NULL,\n+ report json NOT NULL,\n+ creation_time bigint(20) NOT NULL\n+ ) ENGINE=InnoDB DEFAULT CHARSET=latin1;\n+\n+ CREATE TABLE revisions (\n+ id bigint(20) NOT NULL,\n+ entry bigint(20) NOT NULL,\n+ author bigint(20) NOT NULL,\n+ text mediumtext COLLATE utf8mb4_bin NOT NULL,\n+ creation_time bigint(20) NOT NULL,\n+ session bigint(20) NOT NULL,\n+ last_update bigint(20) NOT NULL,\n+ deleted tinyint(1) UNSIGNED NOT NULL\n+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;\n+\n+ CREATE TABLE roles (\n+ id bigint(20) NOT NULL,\n+ thread bigint(20) NOT NULL,\n+ name varchar(191) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NOT NULL,\n+ permissions json NOT NULL,\n+ creation_time bigint(20) NOT NULL\n+ ) ENGINE=InnoDB DEFAULT CHARSET=latin1;\n+\n+ CREATE TABLE sessions (\n+ id bigint(20) NOT NULL,\n+ user bigint(20) NOT NULL,\n+ cookie bigint(20) NOT NULL,\n+ query json NOT NULL,\n+ creation_time bigint(20) NOT NULL,\n+ last_update bigint(20) NOT NULL,\n+ last_validated bigint(20) NOT NULL\n+ ) ENGINE=InnoDB DEFAULT CHARSET=latin1;\n+\n+ CREATE TABLE threads (\n+ id bigint(20) NOT NULL,\n+ type tinyint(3) NOT NULL,\n+ name varchar(191) COLLATE utf8mb4_bin DEFAULT NULL,\n+ description mediumtext COLLATE utf8mb4_bin,\n+ parent_thread_id bigint(20) DEFAULT NULL,\n+ default_role bigint(20) NOT NULL,\n+ creator bigint(20) NOT NULL,\n+ creation_time bigint(20) NOT NULL,\n+ color char(6) COLLATE utf8mb4_bin NOT NULL\n+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;\n+\n+ CREATE TABLE updates (\n+ id bigint(20) NOT NULL,\n+ user bigint(20) NOT NULL,\n+ type tinyint(3) UNSIGNED NOT NULL,\n+ \\`key\\` bigint(20) DEFAULT NULL,\n+ updater bigint(20) DEFAULT NULL,\n+ target bigint(20) DEFAULT NULL,\n+ content mediumtext CHARACTER SET utf8mb4 COLLATE utf8mb4_bin,\n+ time bigint(20) NOT NULL\n+ ) ENGINE=InnoDB DEFAULT CHARSET=latin1;\n+\n+ CREATE TABLE uploads (\n+ id bigint(20) NOT NULL,\n+ uploader bigint(20) NOT NULL,\n+ container bigint(20) DEFAULT NULL,\n+ type varchar(255) NOT NULL,\n+ filename varchar(255) NOT NULL,\n+ mime varchar(255) NOT NULL,\n+ content longblob NOT NULL,\n+ secret varchar(255) NOT NULL,\n+ creation_time bigint(20) NOT NULL,\n+ extra json DEFAULT NULL\n+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8;\n+\n+ CREATE TABLE users (\n+ id bigint(20) NOT NULL,\n+ username varchar(191) COLLATE utf8mb4_bin NOT NULL,\n+ hash char(60) COLLATE utf8mb4_bin NOT NULL,\n+ email varchar(191) COLLATE utf8mb4_bin NOT NULL,\n+ email_verified tinyint(1) UNSIGNED NOT NULL DEFAULT '0',\n+ avatar varchar(191) COLLATE utf8mb4_bin DEFAULT NULL,\n+ creation_time bigint(20) NOT NULL\n+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_bin;\n+\n+ CREATE TABLE verifications (\n+ id bigint(20) NOT NULL,\n+ user bigint(20) NOT NULL,\n+ field tinyint(1) UNSIGNED NOT NULL,\n+ hash char(60) NOT NULL,\n+ creation_time bigint(20) NOT NULL\n+ ) ENGINE=InnoDB DEFAULT CHARSET=latin1;\n+\n+ CREATE TABLE versions (\n+ id bigint(20) NOT NULL,\n+ code_version int(11) NOT NULL,\n+ platform varchar(255) NOT NULL,\n+ creation_time bigint(20) NOT NULL,\n+ deploy_time bigint(20) DEFAULT NULL\n+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8;\n+\n+\n+ ALTER TABLE cookies\n+ ADD PRIMARY KEY (id),\n+ ADD UNIQUE KEY device_token (device_token),\n+ ADD KEY user_device_token (user,device_token);\n+\n+ ALTER TABLE days\n+ ADD PRIMARY KEY (id),\n+ ADD UNIQUE KEY date_thread (date,thread) USING BTREE;\n+\n+ ALTER TABLE entries\n+ ADD PRIMARY KEY (id),\n+ ADD UNIQUE KEY creator_creation (creator,creation),\n+ ADD KEY day (day);\n+\n+ ALTER TABLE focused\n+ ADD UNIQUE KEY user_cookie_thread (user,session,thread),\n+ ADD KEY thread_user (thread,user);\n+\n+ ALTER TABLE ids\n+ ADD PRIMARY KEY (id);\n+\n+ ALTER TABLE memberships\n+ ADD UNIQUE KEY thread_user (thread,user) USING BTREE,\n+ ADD KEY role (role) USING BTREE;\n+\n+ ALTER TABLE messages\n+ ADD PRIMARY KEY (id),\n+ ADD UNIQUE KEY user_creation (user,creation),\n+ ADD KEY thread (thread);\n+\n+ ALTER TABLE notifications\n+ ADD PRIMARY KEY (id),\n+ ADD KEY rescinded_user_collapse_key (rescinded,user,collapse_key)\n+ USING BTREE,\n+ ADD KEY thread (thread),\n+ ADD KEY rescinded_user_thread_message (rescinded,user,thread,message)\n+ USING BTREE;\n+\n+ ALTER TABLE reports\n+ ADD PRIMARY KEY (id);\n+\n+ ALTER TABLE revisions\n+ ADD PRIMARY KEY (id),\n+ ADD KEY entry (entry);\n+\n+ ALTER TABLE roles\n+ ADD PRIMARY KEY (id),\n+ ADD KEY thread (thread);\n+\n+ ALTER TABLE sessions\n+ ADD PRIMARY KEY (id),\n+ ADD KEY user (user);\n+\n+ ALTER TABLE threads\n+ ADD PRIMARY KEY (id);\n+\n+ ALTER TABLE updates\n+ ADD PRIMARY KEY (id),\n+ ADD KEY user_time (user,time),\n+ ADD KEY user_key_type (user,\\`key\\`,type);\n+\n+ ALTER TABLE uploads\n+ ADD PRIMARY KEY (id);\n+\n+ ALTER TABLE users\n+ ADD PRIMARY KEY (id),\n+ ADD UNIQUE KEY username (username),\n+ ADD UNIQUE KEY email (email);\n+\n+ ALTER TABLE verifications\n+ ADD PRIMARY KEY (id),\n+ ADD KEY user_field (user,field);\n+\n+ ALTER TABLE versions\n+ ADD PRIMARY KEY (id),\n+ ADD UNIQUE KEY code_version_platform (code_version,platform);\n+\n+\n+ ALTER TABLE ids\n+ MODIFY id bigint(20) NOT NULL AUTO_INCREMENT;\n+ `);\n+}\n+\n+main();\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] createTables script
129,187
18.03.2020 23:04:54
14,400
36a2dbff9dc234dd59ec3891c519430066607d94
[server] Don't require push secrets to exist
[ { "change_type": "MODIFY", "old_path": "server/src/push/utils.js", "new_path": "server/src/push/utils.js", "diff": "@@ -4,15 +4,48 @@ import { threadPermissions } from 'lib/types/thread-types';\nimport apn from 'apn';\nimport fcmAdmin from 'firebase-admin';\n+import invariant from 'invariant';\nimport { dbQuery, SQL } from '../database';\n-import apnConfig from '../../secrets/apn_config';\n-import fcmConfig from '../../secrets/fcm_config';\n-const apnProvider = new apn.Provider(apnConfig);\n+let cachedAPNProvider = undefined;\n+async function getAPNProvider() {\n+ if (cachedAPNProvider !== undefined) {\n+ return cachedAPNProvider;\n+ }\n+ try {\n+ const apnConfig = await import('../../secrets/apn_config');\n+ if (cachedAPNProvider === undefined) {\n+ cachedAPNProvider = new apn.Provider(apnConfig.default);\n+ }\n+ } catch {\n+ if (cachedAPNProvider === undefined) {\n+ cachedAPNProvider = null;\n+ }\n+ }\n+ return cachedAPNProvider;\n+}\n+\n+let fcmAppInitialized = undefined;\n+async function initializeFCMApp() {\n+ if (fcmAppInitialized !== undefined) {\n+ return fcmAppInitialized;\n+ }\n+ try {\n+ const fcmConfig = await import('../../secrets/fcm_config');\n+ if (fcmAppInitialized === undefined) {\n+ fcmAppInitialized = true;\nfcmAdmin.initializeApp({\n- credential: fcmAdmin.credential.cert(fcmConfig),\n+ credential: fcmAdmin.credential.cert(fcmConfig.default),\n});\n+ }\n+ } catch {\n+ if (cachedAPNProvider === undefined) {\n+ fcmAppInitialized = false;\n+ }\n+ }\n+ return fcmAppInitialized;\n+}\nconst fcmTokenInvalidationErrors = new Set([\n\"messaging/registration-token-not-registered\",\n@@ -26,6 +59,12 @@ async function apnPush(\nnotification: apn.Notification,\ndeviceTokens: $ReadOnlyArray<string>,\n) {\n+ const apnProvider = await getAPNProvider();\n+ if (!apnProvider && process.env.NODE_ENV === \"dev\") {\n+ console.log('no server/secrets/apn_config.json so ignoring notifs');\n+ return { success: true };\n+ }\n+ invariant(apnProvider, 'server/secrets/apn_config.json should exist');\nconst result = await apnProvider.send(notification, deviceTokens);\nconst errors = [];\nconst invalidTokens = [];\n@@ -53,6 +92,12 @@ async function fcmPush(\ndeviceTokens: $ReadOnlyArray<string>,\ncollapseKey: ?string,\n) {\n+ const initialized = await initializeFCMApp();\n+ if (!initialized && process.env.NODE_ENV === \"dev\") {\n+ console.log('no server/secrets/fcm_config.json so ignoring notifs');\n+ return { success: true };\n+ }\n+ invariant(initialized, 'server/secrets/fcm_config.json should exist');\nconst options: Object = {\npriority: 'high',\n};\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Don't require push secrets to exist
129,187
18.03.2020 23:16:51
14,400
4478cac4bdfda012a2c9607980b82f4dbb893a27
[server] Don't require server/secrets/geoip_license.json to exist
[ { "change_type": "MODIFY", "old_path": "server/src/cron/update-geoip-db.js", "new_path": "server/src/cron/update-geoip-db.js", "diff": "@@ -5,9 +5,35 @@ import geoip from 'geoip-lite';\nimport cluster from 'cluster';\nimport { handleAsyncPromise } from '../responders/handlers';\n-import geoipLicense from '../../secrets/geoip_license';\n-function updateGeoipDB(): Promise<void> {\n+let cachedGeoipLicense = undefined;\n+async function getGeoipLicense() {\n+ if (cachedGeoipLicense !== undefined) {\n+ return cachedGeoipLicense;\n+ }\n+ try {\n+ const geoipLicenseImport = await import('../../secrets/geoip_license');\n+ if (cachedGeoipLicense !== undefined) {\n+ cachedGeoipLicense = geoipLicenseImport.default;\n+ }\n+ } catch {\n+ if (cachedGeoipLicense !== undefined) {\n+ cachedGeoipLicense = null;\n+ }\n+ }\n+ return cachedGeoipLicense;\n+}\n+\n+async function updateGeoipDB(): Promise<void> {\n+ const geoipLicense = await getGeoipLicense();\n+ if (!geoipLicense) {\n+ console.log('no server/secrets/geoip_license.json so skipping update');\n+ return;\n+ }\n+ await spawnUpdater(geoipLicense);\n+}\n+\n+function spawnUpdater(geoipLicense: { key: string }): Promise<void> {\nconst spawned = childProcess.spawn(\nprocess.execPath,\n[\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Don't require server/secrets/geoip_license.json to exist
129,187
19.03.2020 13:23:09
14,400
977d497f6b7cef5a1a9ff222d80087846a567b7e
[docs] Minor docs fix
[ { "change_type": "MODIFY", "old_path": "docs/dev_environment.md", "new_path": "docs/dev_environment.md", "diff": "@@ -369,8 +369,7 @@ yarn cleaninstall\nThe server side needs to see some config files before things can work. The first is a config file with MySQL details.\n```\n-cd squadcal\n-cd secrets\n+cd squadcal/server\nmkdir secrets\nvim secrets/db_config.json\n```\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[docs] Minor docs fix
129,187
19.03.2020 15:44:30
14,400
6a467123b192751f2410fb6a4a334eb1bd56868b
[native] codeVersion -> 43
[ { "change_type": "MODIFY", "old_path": "native/android/app/build.gradle", "new_path": "native/android/app/build.gradle", "diff": "@@ -131,8 +131,8 @@ android {\napplicationId \"org.squadcal\"\nminSdkVersion rootProject.ext.minSdkVersion\ntargetSdkVersion rootProject.ext.targetSdkVersion\n- versionCode 42\n- versionName \"0.0.42\"\n+ versionCode 43\n+ versionName \"0.0.43\"\nmissingDimensionStrategy 'react-native-camera', 'general'\nmultiDexEnabled true\n}\n" }, { "change_type": "MODIFY", "old_path": "native/ios/SquadCal/Info.debug.plist", "new_path": "native/ios/SquadCal/Info.debug.plist", "diff": "<key>CFBundlePackageType</key>\n<string>APPL</string>\n<key>CFBundleShortVersionString</key>\n- <string>0.0.42</string>\n+ <string>0.0.43</string>\n<key>CFBundleSignature</key>\n<string>????</string>\n<key>CFBundleVersion</key>\n- <string>42</string>\n+ <string>43</string>\n<key>LSApplicationQueriesSchemes</key>\n<array>\n<string>org-appextension-feature-password-management</string>\n" }, { "change_type": "MODIFY", "old_path": "native/ios/SquadCal/Info.release.plist", "new_path": "native/ios/SquadCal/Info.release.plist", "diff": "<key>CFBundlePackageType</key>\n<string>APPL</string>\n<key>CFBundleShortVersionString</key>\n- <string>0.0.42</string>\n+ <string>0.0.43</string>\n<key>CFBundleSignature</key>\n<string>????</string>\n<key>CFBundleVersion</key>\n- <string>42</string>\n+ <string>43</string>\n<key>LSApplicationQueriesSchemes</key>\n<array>\n<string>org-appextension-feature-password-management</string>\n" }, { "change_type": "MODIFY", "old_path": "native/redux/persist.js", "new_path": "native/redux/persist.js", "diff": "@@ -177,7 +177,7 @@ const persistConfig = {\ntimeout: __DEV__ ? 0 : undefined,\n};\n-const codeVersion = 42;\n+const codeVersion = 43;\n// This local exists to avoid a circular dependency where redux-setup needs to\n// import all the navigation and screen stuff, but some of those screens want to\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] codeVersion -> 43
129,187
19.03.2020 20:44:15
14,400
1ee5fbeeb03ccfefefa101100cb34d3af97a676b
[native] Update app vs. index and tests
[ { "change_type": "DELETE", "old_path": "native/__tests__/index.ios.js", "new_path": null, "diff": "-import 'react-native';\n-import React from 'react';\n-import Index from '../index.js';\n-\n-// Note: test renderer must be required after react-native.\n-import renderer from 'react-test-renderer';\n-\n-it('renders correctly', () => {\n- const tree = renderer.create(<Index />);\n-});\n" }, { "change_type": "RENAME", "old_path": "native/__tests__/index.android.js", "new_path": "native/__tests__/test.js", "diff": "+// @flow\n+\nimport 'react-native';\n-import React from 'react';\n-import Index from '../index.js';\n+import * as React from 'react';\n+import App from '../app.react';\n// Note: test renderer must be required after react-native.\nimport renderer from 'react-test-renderer';\nit('renders correctly', () => {\n- const tree = renderer.create(<Index />);\n+ renderer.create(<App />);\n});\n" }, { "change_type": "MODIFY", "old_path": "native/app.react.js", "new_path": "native/app.react.js", "diff": "@@ -9,7 +9,6 @@ import type { DispatchActionPayload } from 'lib/utils/action-utils';\nimport * as React from 'react';\nimport { Provider } from 'react-redux';\nimport {\n- AppRegistry,\nPlatform,\nUIManager,\nAppState as NativeAppState,\n@@ -180,11 +179,12 @@ const ConnectedAppWithNavigationState = connect(\ntrue,\n)(AppWithNavigationState);\n-const App = (props: {}) => (\n+const App = () => (\n<Provider store={store}>\n<ErrorBoundary>\n<ConnectedAppWithNavigationState />\n</ErrorBoundary>\n</Provider>\n);\n-AppRegistry.registerComponent('SquadCal', () => App);\n+\n+export default App;\n" }, { "change_type": "MODIFY", "old_path": "native/index.js", "new_path": "native/index.js", "diff": "import './reactotron';\nimport './config';\n-import './app.react';\n+\n+import { AppRegistry } from 'react-native';\n+\n+import App from './app.react';\n+import { name as appName } from './app.json';\n+\n+AppRegistry.registerComponent(appName, () => App);\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Update app vs. index and tests
129,187
21.03.2020 12:14:10
14,400
12bc22a62a41e5a1d53110122cf84c682fa028eb
[native] Avoid using same route key for MesssageList
[ { "change_type": "MODIFY", "old_path": "native/navigation/navigation-setup.js", "new_path": "native/navigation/navigation-setup.js", "diff": "@@ -119,10 +119,10 @@ export type NavInfo = {|\nnavigationState: NavigationState,\n|};\n-const uniqueBaseId = `id-${Date.now()}`;\n-let uuidCount = 0;\n-function _getUuid() {\n- return `${uniqueBaseId}-${uuidCount++}`;\n+const messageListRouteBase = Date.now();\n+let messageListRouteIndex = 0;\n+function getUniqueMessageListRouteKey() {\n+ return `${messageListRouteBase}-${messageListRouteIndex++}`;\n}\nexport type Action =\n@@ -715,12 +715,15 @@ function handleNewThread(\n(route: NavigationRoute) =>\nroute.routeName === ComposeThreadRouteName ? 'remove' : 'break',\n);\n+ const key =\n+ `${MessageListRouteName}${threadInfo.id}:` +\n+ getUniqueMessageListRouteKey();\nreturn {\n...newChatRoute,\nroutes: [\n...newChatRoute.routes,\n{\n- key: `${MessageListRouteName}${threadInfo.id}`,\n+ key,\nrouteName: MessageListRouteName,\nparams: { threadInfo },\n},\n@@ -748,12 +751,15 @@ function replaceChatStackWithThread(\n(route: NavigationRoute) =>\nroute.routeName === ChatThreadListRouteName ? 'break' : 'remove',\n);\n+ const key =\n+ `${MessageListRouteName}${threadInfo.id}:` +\n+ getUniqueMessageListRouteKey();\nreturn {\n...newChatRoute,\nroutes: [\n...newChatRoute.routes,\n{\n- key: `${MessageListRouteName}${threadInfo.id}`,\n+ key,\nrouteName: MessageListRouteName,\nparams: { threadInfo },\n},\n@@ -819,12 +825,14 @@ function handleNotificationPress(\nviewerID,\nuserInfos,\n);\n+ const key =\n+ `${MessageListRouteName}${threadInfo.id}:` + getUniqueMessageListRouteKey();\nconst newChatRoute = {\n...chatRoute,\nroutes: [\n...chatRoute.routes,\n{\n- key: `${MessageListRouteName}${threadInfo.id}`,\n+ key,\nrouteName: MessageListRouteName,\nparams: { threadInfo },\n},\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Avoid using same route key for MesssageList
129,187
21.03.2020 15:37:07
14,400
72318133701fd12e3897a50c84f2a6aa4f38920e
[native] Avoid double-pruning MessageStore
[ { "change_type": "MODIFY", "old_path": "native/chat/message-store-pruner.react.js", "new_path": "native/chat/message-store-pruner.react.js", "diff": "@@ -31,9 +31,16 @@ class MessageStorePruner extends React.PureComponent<Props> {\nfrozen: PropTypes.bool.isRequired,\ndispatchActionPayload: PropTypes.func.isRequired,\n};\n+ pruned = false;\ncomponentDidUpdate(prevProps: Props) {\n- if (this.props.frozen) {\n+ if (\n+ this.pruned &&\n+ this.props.nextMessagePruneTime !== prevProps.nextMessagePruneTime\n+ ) {\n+ this.pruned = false;\n+ }\n+ if (this.props.frozen || this.pruned) {\nreturn;\n}\nconst { nextMessagePruneTime } = this.props;\n@@ -48,6 +55,7 @@ class MessageStorePruner extends React.PureComponent<Props> {\nif (threadIDs.length === 0) {\nreturn;\n}\n+ this.pruned = true;\nthis.props.dispatchActionPayload(messageStorePruneActionType, {\nthreadIDs,\n});\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Avoid double-pruning MessageStore
129,187
22.03.2020 09:37:55
14,400
352b1e0d3bfde5ce7d5a594a5a6d2e3d2d4abef0
Standardize on babel.config.cjs
[ { "change_type": "RENAME", "old_path": "native/babel.config.js", "new_path": "native/babel.config.cjs", "diff": "" }, { "change_type": "RENAME", "old_path": "server/.babelrc", "new_path": "server/babel.config.cjs", "diff": "-{\n+module.exports = {\npresets: ['@babel/preset-react', '@babel/preset-flow'],\nplugins: [\n'@babel/plugin-proposal-class-properties',\n'@babel/plugin-proposal-object-rest-spread',\n- '@babel/plugin-syntax-dynamic-import'\n+ '@babel/plugin-syntax-dynamic-import',\n],\n-}\n+};\n" }, { "change_type": "MODIFY", "old_path": "server/package.json", "new_path": "server/package.json", "diff": "\"main\": \"dist/server\",\n\"scripts\": {\n\"clean\": \"rm -rf dist/ && rm -rf node_modules/ && mkdir dist\",\n- \"babel-build\": \"yarn --silent babel src/ --out-dir dist/ --config-file ./.babelrc --verbose --ignore 'src/lib/flow-typed','src/lib/node_modules','src/lib/package.json','src/web/flow-typed','src/web/node_modules','src/web/package.json','src/web/dist','src/web/webpack.config.js','src/web/account-bar.react.js','src/web/app.react.js','src/web/calendar','src/web/chat','src/web/flow','src/web/loading-indicator.react.js','src/web/modals','src/web/root.js','src/web/router-history.js','src/web/script.js','src/web/selectors/chat-selectors.js','src/web/selectors/entry-selectors.js','src/web/splash','src/web/vector-utils.js','src/web/vectors.react.js'\",\n+ \"babel-build\": \"yarn --silent babel src/ --out-dir dist/ --config-file ./babel.config.cjs --verbose --ignore 'src/lib/flow-typed','src/lib/node_modules','src/lib/package.json','src/web/flow-typed','src/web/node_modules','src/web/package.json','src/web/dist','src/web/webpack.config.js','src/web/account-bar.react.js','src/web/app.react.js','src/web/calendar','src/web/chat','src/web/flow','src/web/loading-indicator.react.js','src/web/modals','src/web/root.js','src/web/router-history.js','src/web/script.js','src/web/selectors/chat-selectors.js','src/web/selectors/entry-selectors.js','src/web/splash','src/web/vector-utils.js','src/web/vectors.react.js'\",\n\"rsync\": \"rsync -rLpmuv --exclude '*/package.json' --exclude '*/node_modules/*' --include '*.json' --include '*.cjs' --exclude '*.*' src/ dist/\",\n\"prod-build\": \"yarn babel-build && yarn rsync && yarn update-geoip\",\n\"update-geoip\": \"yarn script dist/scripts/update-geoip.js\",\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Standardize on babel.config.cjs
129,187
22.03.2020 10:59:13
14,400
30ab0f6cc8f0141347b63e2769f2f338a1f2cbfe
[web] babel.config.cjs
[ { "change_type": "ADD", "old_path": null, "new_path": "web/babel.config.cjs", "diff": "+module.exports = {\n+ presets: ['@babel/preset-react', '@babel/preset-flow'],\n+ plugins: [\n+ '@babel/plugin-proposal-class-properties',\n+ '@babel/plugin-proposal-object-rest-spread',\n+ ],\n+};\n" }, { "change_type": "MODIFY", "old_path": "web/webpack.config.cjs", "new_path": "web/webpack.config.cjs", "diff": "@@ -6,6 +6,8 @@ const TerserPlugin = require('terser-webpack-plugin');\nconst OptimizeCssAssetsPlugin = require('optimize-css-assets-webpack-plugin');\nconst { CleanWebpackPlugin } = require('clean-webpack-plugin');\n+const babelConfig = require('./babel.config.cjs');\n+\nconst cssLoader = {\nloader: 'css-loader',\noptions: {\n@@ -20,13 +22,7 @@ const babelRule = {\ntest: /\\.js$/,\nexclude: /node_modules\\/(?!lib)/,\nloader: 'babel-loader',\n- options: {\n- presets: [ '@babel/preset-react', '@babel/preset-flow' ],\n- plugins: [\n- '@babel/plugin-proposal-class-properties',\n- '@babel/plugin-proposal-object-rest-spread',\n- ],\n- },\n+ options: babelConfig,\n};\nconst browserBabelRule = {\n...babelRule,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[web] babel.config.cjs
129,187
22.03.2020 23:32:39
14,400
20fea866ecce601d803f28e44b176580b17d0a86
[server] Only use local fonts if they are available
[ { "change_type": "MODIFY", "old_path": "server/src/responders/website-responders.js", "new_path": "server/src/responders/website-responders.js", "diff": "@@ -14,6 +14,8 @@ import ReactRedux from 'react-redux';\nimport ReactRouter from 'react-router';\nimport React from 'react';\nimport _keyBy from 'lodash/fp/keyBy';\n+import fs from 'fs';\n+import { promisify } from 'util';\nimport { ServerError } from 'lib/utils/errors';\nimport { currentDateInTimeZone } from 'lib/utils/date-utils';\n@@ -52,6 +54,19 @@ const { Route, StaticRouter } = ReactRouter;\nconst baseURL = basePath.replace(/\\/$/, '');\nconst baseHref = baseDomain + baseURL;\n+const access = promisify(fs.access);\n+const googleFontsURL =\n+ 'https://fonts.googleapis.com/css?family=Open+Sans:300,600%7CAnaheim';\n+const localFontsURL = 'fonts/local-fonts.css';\n+async function getFontsURL() {\n+ try {\n+ await access(localFontsURL);\n+ return localFontsURL;\n+ } catch {\n+ return googleFontsURL;\n+ }\n+}\n+\ntype AssetInfo = {| jsURL: string, fontsURL: string, cssInclude: string |};\nlet assetInfo: ?AssetInfo = null;\nasync function getAssetInfo() {\n@@ -59,9 +74,10 @@ async function getAssetInfo() {\nreturn assetInfo;\n}\nif (process.env.NODE_ENV === 'dev') {\n+ const fontsURL = await getFontsURL();\nassetInfo = {\njsURL: 'http://localhost:8080/dev.build.js',\n- fontsURL: 'fonts/local-fonts.css',\n+ fontsURL,\ncssInclude: '',\n};\nreturn assetInfo;\n@@ -70,8 +86,7 @@ async function getAssetInfo() {\nconst { default: assets } = await import('../../compiled/assets');\nassetInfo = {\njsURL: `compiled/${assets.browser.js}`,\n- fontsURL:\n- 'https://fonts.googleapis.com/css?family=Open+Sans:300,600%7CAnaheim',\n+ fontsURL: googleFontsURL,\ncssInclude: html`\n<link\nrel=\"stylesheet\"\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Only use local fonts if they are available
129,187
22.03.2020 23:42:16
14,400
a9559a26cb0f717e85b7c9f4e3b872acd9a0baf5
[native] codeVersion -> 44 This is an iOS-only build to test if introduced a regression in media library order on iOS
[ { "change_type": "MODIFY", "old_path": "native/android/app/build.gradle", "new_path": "native/android/app/build.gradle", "diff": "@@ -131,8 +131,8 @@ android {\napplicationId \"org.squadcal\"\nminSdkVersion rootProject.ext.minSdkVersion\ntargetSdkVersion rootProject.ext.targetSdkVersion\n- versionCode 43\n- versionName \"0.0.43\"\n+ versionCode 44\n+ versionName \"0.0.44\"\nmissingDimensionStrategy 'react-native-camera', 'general'\nmultiDexEnabled true\n}\n" }, { "change_type": "MODIFY", "old_path": "native/ios/SquadCal/Info.debug.plist", "new_path": "native/ios/SquadCal/Info.debug.plist", "diff": "<key>CFBundlePackageType</key>\n<string>APPL</string>\n<key>CFBundleShortVersionString</key>\n- <string>0.0.43</string>\n+ <string>0.0.44</string>\n<key>CFBundleSignature</key>\n<string>????</string>\n<key>CFBundleVersion</key>\n- <string>43</string>\n+ <string>44</string>\n<key>LSApplicationQueriesSchemes</key>\n<array>\n<string>org-appextension-feature-password-management</string>\n" }, { "change_type": "MODIFY", "old_path": "native/ios/SquadCal/Info.release.plist", "new_path": "native/ios/SquadCal/Info.release.plist", "diff": "<key>CFBundlePackageType</key>\n<string>APPL</string>\n<key>CFBundleShortVersionString</key>\n- <string>0.0.43</string>\n+ <string>0.0.44</string>\n<key>CFBundleSignature</key>\n<string>????</string>\n<key>CFBundleVersion</key>\n- <string>43</string>\n+ <string>44</string>\n<key>LSApplicationQueriesSchemes</key>\n<array>\n<string>org-appextension-feature-password-management</string>\n" }, { "change_type": "MODIFY", "old_path": "native/redux/persist.js", "new_path": "native/redux/persist.js", "diff": "@@ -167,7 +167,7 @@ const persistConfig = {\ntimeout: __DEV__ ? 0 : undefined,\n};\n-const codeVersion = 43;\n+const codeVersion = 44;\n// This local exists to avoid a circular dependency where redux-setup needs to\n// import all the navigation and screen stuff, but some of those screens want to\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] codeVersion -> 44 This is an iOS-only build to test if 6a467123b192751f2410fb6a4a334eb1bd56868b introduced a regression in media library order on iOS
129,187
24.03.2020 00:42:45
14,400
5769a3c13ad831937a63e9df6cc4936693c05b51
[server] Allow createUpdates while logged out
[ { "change_type": "MODIFY", "old_path": "server/src/creators/update-creator.js", "new_path": "server/src/creators/update-creator.js", "diff": "@@ -42,7 +42,6 @@ import {\nconditionKeyForUpdateDataFromKey,\nrawUpdateInfoFromUpdateData,\n} from 'lib/shared/update-utils';\n-import { ServerError } from 'lib/utils/errors';\nimport { dbQuery, SQL, SQLStatement, mergeAndConditions } from '../database';\nimport createIDs from './id-creator';\n@@ -108,12 +107,13 @@ async function createUpdates(\nif (updateDatas.length === 0) {\nreturn defaultUpdateCreationResult;\n}\n- if (passedViewerInfo && !passedViewerInfo.viewer.loggedIn) {\n- throw new ServerError('not_logged_in');\n- }\n- let viewerInfo = passedViewerInfo;\n- if (viewerInfo && viewerInfo.viewer.isScriptViewer) {\n+\n// viewer.session will throw for a script Viewer\n+ let viewerInfo = passedViewerInfo;\n+ if (\n+ viewerInfo &&\n+ (viewerInfo.viewer.isScriptViewer || !viewerInfo.viewer.loggedIn)\n+ ) {\nviewerInfo = null;\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Allow createUpdates while logged out
129,187
24.03.2020 02:34:46
14,400
cb7aad567e296fdae9d5c49ce0073d64f2341a60
[native] Fix Android bug where notif press leads to log-in screen
[ { "change_type": "MODIFY", "old_path": "native/account/logged-out-modal.react.js", "new_path": "native/account/logged-out-modal.react.js", "diff": "@@ -209,6 +209,15 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\ncomponentDidMount() {\nthis.mounted = true;\n+ if (this.props.rehydrateConcluded && !__DEV__) {\n+ // If rehydrate concludes before the first time LoggedOutModal is mounted\n+ // on dev mode, it's probably because the dev started with logged-in nav\n+ // state and then logged out. In this case we don't want to call\n+ // onInitialAppLoad. However, if the same thing happens in release mode,\n+ // it's probably because Android rehydrated as a result of a notification.\n+ // In this case, we still want to call onInitialAppLoad.\n+ this.onInitialAppLoad();\n+ }\nif (this.props.isForeground) {\nthis.onForeground();\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Fix Android bug where notif press leads to log-in screen
129,187
24.03.2020 03:11:21
14,400
6ea3f455872a1bc8b7b160c0aefda157bdaefa91
Don't pass list of staged files to Flow from lint-staged
[ { "change_type": "ADD", "old_path": null, "new_path": ".lintstagedrc.js", "diff": "+const { CLIEngine } = require('eslint');\n+\n+const cli = new CLIEngine({ });\n+\n+module.exports = {\n+ \"*.js\": \"eslint --cache --fix\",\n+ \"lib/**/*.js\": function libFlow(files) { return \"yarn workspace lib flow --quiet\" },\n+ \"web/**/*.js\": function webFlow(files) { return \"yarn workspace web flow --quiet\" },\n+ \"native/**/*.js\": function nativeFlow(files) { return \"yarn workspace native flow --quiet\" },\n+ \"server/**/*.js\": function serverFlow(files) { return \"yarn workspace server flow --quiet\" }\n+};\n" }, { "change_type": "MODIFY", "old_path": "package.json", "new_path": "package.json", "diff": "\"hooks\": {\n\"pre-commit\": \"lint-staged\"\n}\n- },\n- \"lint-staged\": {\n- \"*.js\": \"eslint --cache --fix\",\n- \"lib/**/*.js\": \"yarn workspace lib flow --quiet\",\n- \"web/**/*.js\": \"yarn workspace web flow --quiet\",\n- \"native/**/*.js\": \"yarn workspace native flow --quiet\",\n- \"server/**/*.js\": \"yarn workspace server flow --quiet\"\n}\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Don't pass list of staged files to Flow from lint-staged
129,187
24.03.2020 03:28:14
14,400
4f9c337e64a68af71173c8ef67d65b7e5069ba90
[server] Fix getGeoipLicense to actually find license file
[ { "change_type": "MODIFY", "old_path": "server/src/cron/update-geoip-db.js", "new_path": "server/src/cron/update-geoip-db.js", "diff": "@@ -13,11 +13,11 @@ async function getGeoipLicense() {\n}\ntry {\nconst geoipLicenseImport = await import('../../secrets/geoip_license');\n- if (cachedGeoipLicense !== undefined) {\n+ if (cachedGeoipLicense === undefined) {\ncachedGeoipLicense = geoipLicenseImport.default;\n}\n} catch {\n- if (cachedGeoipLicense !== undefined) {\n+ if (cachedGeoipLicense === undefined) {\ncachedGeoipLicense = null;\n}\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Fix getGeoipLicense to actually find license file
129,187
25.03.2020 23:42:13
14,400
524e4f6612d32beb90ef1da3cb1f70b850555e5c
[web] Autofocus ChatInputBar when loading thread
[ { "change_type": "MODIFY", "old_path": "web/chat/chat-input-bar.react.js", "new_path": "web/chat/chat-input-bar.react.js", "diff": "@@ -115,6 +115,11 @@ class ChatInputBar extends React.PureComponent<Props> {\n) {\n// Whenever a pending upload is added, we focus the textarea\nthis.textarea.focus();\n+ return;\n+ }\n+\n+ if (this.props.threadInfo.id !== prevProps.threadInfo.id && this.textarea) {\n+ this.textarea.focus();\n}\n}\n@@ -188,6 +193,7 @@ class ChatInputBar extends React.PureComponent<Props> {\nonChange={this.onChangeMessageText}\nonKeyDown={this.onKeyDown}\nref={this.textareaRef}\n+ autoFocus\n/>\n<a className={css.multimediaUpload} onClick={this.onMultimediaClick}>\n<input\n@@ -249,6 +255,9 @@ class ChatInputBar extends React.PureComponent<Props> {\ntextareaRef = (textarea: ?HTMLTextAreaElement) => {\nthis.textarea = textarea;\n+ if (textarea) {\n+ textarea.focus();\n+ }\n};\nonChangeMessageText = (event: SyntheticEvent<HTMLTextAreaElement>) => {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[web] Autofocus ChatInputBar when loading thread
129,207
30.03.2020 23:53:57
-7,200
cfaa86d13b59b025044152013df3e0b9ed99b707
[server] Update sharp version
[ { "change_type": "MODIFY", "old_path": "server/package.json", "new_path": "server/package.json", "diff": "\"redis\": \"^2.8.0\",\n\"redux\": \"^4.0.4\",\n\"replacestream\": \"^4.0.3\",\n- \"sharp\": \"^0.23.1\",\n+ \"sharp\": \"^0.25.2\",\n\"sql-template-strings\": \"^2.2.2\",\n\"stream-cache\": \"^0.0.2\",\n\"stream-combiner\": \"^0.2.2\",\n" }, { "change_type": "MODIFY", "old_path": "yarn.lock", "new_path": "yarn.lock", "diff": "@@ -3801,6 +3801,11 @@ chownr@^1.1.1, chownr@^1.1.2:\nresolved \"https://registry.yarnpkg.com/chownr/-/chownr-1.1.3.tgz#42d837d5239688d55f303003a508230fa6727142\"\nintegrity sha512-i70fVHhmV3DtTl6nqvZOnIjbY0Pe4kAUjwHj8z0zAdgBtYrJyYwLKCCuRBQ5ppkyL0AkN7HKRnETdmdp1zqNXw==\n+chownr@^1.1.3:\n+ version \"1.1.4\"\n+ resolved \"https://registry.yarnpkg.com/chownr/-/chownr-1.1.4.tgz#6fc9d7b42d32a583596337666e7d08084da2cc6b\"\n+ integrity sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg==\n+\nchrome-trace-event@^1.0.2:\nversion \"1.0.2\"\nresolved \"https://registry.yarnpkg.com/chrome-trace-event/-/chrome-trace-event-1.0.2.tgz#234090ee97c7d4ad1a2c4beae27505deffc608a4\"\n@@ -9436,6 +9441,14 @@ minizlib@^1.2.1:\ndependencies:\nminipass \"^2.9.0\"\n+minizlib@^2.1.0:\n+ version \"2.1.0\"\n+ resolved \"https://registry.yarnpkg.com/minizlib/-/minizlib-2.1.0.tgz#fd52c645301ef09a63a2c209697c294c6ce02cf3\"\n+ integrity sha512-EzTZN/fjSvifSX0SlqUERCN39o6T40AMarPbv0MrarSFtIITCBh7bi+dU8nxGFHuqs9jdIAeoYoKuQAAASsPPA==\n+ dependencies:\n+ minipass \"^3.0.0\"\n+ yallist \"^4.0.0\"\n+\nmississippi@^3.0.0:\nversion \"3.0.0\"\nresolved \"https://registry.yarnpkg.com/mississippi/-/mississippi-3.0.0.tgz#ea0a3291f97e0b5e8776b363d5f0a12d94c67022\"\n@@ -9479,6 +9492,11 @@ mkdirp@^0.5.3:\ndependencies:\nminimist \"^1.2.5\"\n+mkdirp@^1.0.3:\n+ version \"1.0.3\"\n+ resolved \"https://registry.yarnpkg.com/mkdirp/-/mkdirp-1.0.3.tgz#4cf2e30ad45959dddea53ad97d518b6c8205e1ea\"\n+ integrity sha512-6uCP4Qc0sWsgMLy1EOqqS/3rjDHOEnsStVr/4vtAIK2Y5i2kA7lFFejYrpIyiN9w0pYf4ckeCYT9f1r1P9KX5g==\n+\nmoment-timezone@^0.5.25:\nversion \"0.5.26\"\nresolved \"https://registry.yarnpkg.com/moment-timezone/-/moment-timezone-0.5.26.tgz#c0267ca09ae84631aa3dc33f65bedbe6e8e0d772\"\n@@ -9587,7 +9605,7 @@ named-placeholders@^1.1.2:\ndependencies:\nlru-cache \"^4.1.3\"\n-nan@^2.12.1, nan@^2.14.0:\n+nan@^2.12.1:\nversion \"2.14.0\"\nresolved \"https://registry.yarnpkg.com/nan/-/nan-2.14.0.tgz#7818f722027b2459a86f0295d434d1fc2336c52c\"\nintegrity sha512-INOFj37C7k3AfaNTtX8RhsTw7qRy7eLET14cROi9+5HAVbbHuIWUHEauBv5qT4Av2tWasiTY1Jw6puUNqRJXQg==\n@@ -9650,6 +9668,11 @@ node-abi@^2.7.0:\ndependencies:\nsemver \"^5.4.1\"\n+node-addon-api@^2.0.0:\n+ version \"2.0.0\"\n+ resolved \"https://registry.yarnpkg.com/node-addon-api/-/node-addon-api-2.0.0.tgz#f9afb8d777a91525244b01775ea0ddbe1125483b\"\n+ integrity sha512-ASCL5U13as7HhOExbT6OlWJJUV/lLzL2voOSP1UVehpRD8FbSrSDjfScK/KwAvVTI5AS6r4VwbOMlIqtvRidnA==\n+\nnode-environment-flags@^1.0.5:\nversion \"1.0.6\"\nresolved \"https://registry.yarnpkg.com/node-environment-flags/-/node-environment-flags-1.0.6.tgz#a30ac13621f6f7d674260a54dede048c3982c088\"\n@@ -11004,10 +11027,10 @@ postinstall-postinstall@^2.0.0:\nresolved \"https://registry.yarnpkg.com/postinstall-postinstall/-/postinstall-postinstall-2.0.0.tgz#7ba6711b4420575c4f561638836a81faad47f43f\"\nintegrity sha512-3f6qWexsHiT4WKtZc5DRb0FPLilHtARi5KpY4fqban/DJNn8/YhZH8U7dVKVz51WbOxEnR31gV+qYQhvEdHtdQ==\n-prebuild-install@^5.3.2:\n- version \"5.3.2\"\n- resolved \"https://registry.yarnpkg.com/prebuild-install/-/prebuild-install-5.3.2.tgz#6392e9541ac0b879ef0f22b3d65037417eb2035e\"\n- integrity sha512-INDfXzTPnhT+WYQemqnAXlP7SvfiFMopMozSgXCZ+RDLb279gKfIuLk4o7PgEawLp3WrMgIYGBpkxpraROHsSA==\n+prebuild-install@^5.3.3:\n+ version \"5.3.3\"\n+ resolved \"https://registry.yarnpkg.com/prebuild-install/-/prebuild-install-5.3.3.tgz#ef4052baac60d465f5ba6bf003c9c1de79b9da8e\"\n+ integrity sha512-GV+nsUXuPW2p8Zy7SarF/2W/oiK8bFQgJcncoJ0d7kRpekEA0ftChjfEaF9/Y+QJEc/wFR7RAEa8lYByuUIe2g==\ndependencies:\ndetect-libc \"^1.0.3\"\nexpand-template \"^2.0.3\"\n@@ -12519,6 +12542,11 @@ semver@^6.0.0, semver@^6.1.2, semver@^6.2.0, semver@^6.3.0:\nresolved \"https://registry.yarnpkg.com/semver/-/semver-6.3.0.tgz#ee0a64c8af5e8ceea67687b133761e1becbd1d3d\"\nintegrity sha512-b39TBaTSfV6yBrapU89p5fKekE2m/NwnDocOVruQFS1/veMgdzuPcnOM34M6CwxW8jH/lxEa5rBoDeUwu5HHTw==\n+semver@^7.1.3:\n+ version \"7.1.3\"\n+ resolved \"https://registry.yarnpkg.com/semver/-/semver-7.1.3.tgz#e4345ce73071c53f336445cfc19efb1c311df2a6\"\n+ integrity sha512-ekM0zfiA9SCBlsKa2X1hxyxiI4L3B6EbVJkkdgQXnSEEaHlGdvyodMruTiulSRWMMB4NeIuYNMC9rTKTz97GxA==\n+\nsend@0.17.1:\nversion \"0.17.1\"\nresolved \"https://registry.yarnpkg.com/send/-/send-0.17.1.tgz#c1d8b059f7900f7466dd4938bdc44e11ddb376c8\"\n@@ -12624,19 +12652,19 @@ shallowequal@^1.0.2, shallowequal@^1.1.0:\nresolved \"https://registry.yarnpkg.com/shallowequal/-/shallowequal-1.1.0.tgz#188d521de95b9087404fd4dcb68b13df0ae4e7f8\"\nintegrity sha512-y0m1JoUZSlPAjXVtPPW70aZWfIL/dSP7AFkRnniLCrK/8MDKog3TySTBmckD+RObVxH0v4Tox67+F14PdED2oQ==\n-sharp@^0.23.1:\n- version \"0.23.1\"\n- resolved \"https://registry.yarnpkg.com/sharp/-/sharp-0.23.1.tgz#28f930c1677f219b448dee4d28d04a69dc0966aa\"\n- integrity sha512-xt1SOwC5ewuqApBzKMFQ5VaRsC3GjOl1xklsnPNAAG7KWEAi50STFrVwjxFRe4puZ/59JU0QQqoFe7TZNnXd/g==\n+sharp@^0.25.2:\n+ version \"0.25.2\"\n+ resolved \"https://registry.yarnpkg.com/sharp/-/sharp-0.25.2.tgz#f9003d73be50e9265e98f79f04fe53d8c66a3967\"\n+ integrity sha512-l1GN0kFNtJr3U9i9pt7a+vo2Ij0xv4tTKDIPx8W6G9WELhPwrMyZZJKAAQNBSI785XB4uZfS5Wpz8C9jWV4AFQ==\ndependencies:\ncolor \"^3.1.2\"\ndetect-libc \"^1.0.3\"\n- nan \"^2.14.0\"\n+ node-addon-api \"^2.0.0\"\nnpmlog \"^4.1.2\"\n- prebuild-install \"^5.3.2\"\n- semver \"^6.3.0\"\n+ prebuild-install \"^5.3.3\"\n+ semver \"^7.1.3\"\nsimple-get \"^3.1.0\"\n- tar \"^4.4.13\"\n+ tar \"^6.0.1\"\ntunnel-agent \"^0.6.0\"\nshebang-command@^1.2.0:\n@@ -13426,7 +13454,7 @@ tar-stream@^2.0.0:\ninherits \"^2.0.3\"\nreadable-stream \"^3.1.1\"\n-tar@^4, tar@^4.4.13:\n+tar@^4:\nversion \"4.4.13\"\nresolved \"https://registry.yarnpkg.com/tar/-/tar-4.4.13.tgz#43b364bc52888d555298637b10d60790254ab525\"\nintegrity sha512-w2VwSrBoHa5BsSyH+KxEqeQBAllHhccyMFVHtGtdMpF4W7IRWfZjFiQceJPChOeTsSDVUpER2T8FA93pr0L+QA==\n@@ -13439,6 +13467,18 @@ tar@^4, tar@^4.4.13:\nsafe-buffer \"^5.1.2\"\nyallist \"^3.0.3\"\n+tar@^6.0.1:\n+ version \"6.0.1\"\n+ resolved \"https://registry.yarnpkg.com/tar/-/tar-6.0.1.tgz#7b3bd6c313cb6e0153770108f8d70ac298607efa\"\n+ integrity sha512-bKhKrrz2FJJj5s7wynxy/fyxpE0CmCjmOQ1KV4KkgXFWOgoIT/NbTMnB1n+LFNrNk0SSBVGGxcK5AGsyC+pW5Q==\n+ dependencies:\n+ chownr \"^1.1.3\"\n+ fs-minipass \"^2.0.0\"\n+ minipass \"^3.0.0\"\n+ minizlib \"^2.1.0\"\n+ mkdirp \"^1.0.3\"\n+ yallist \"^4.0.0\"\n+\ntcomb@^3.2.24:\nversion \"3.2.29\"\nresolved \"https://registry.yarnpkg.com/tcomb/-/tcomb-3.2.29.tgz#32404fe9456d90c2cf4798682d37439f1ccc386c\"\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Update sharp version
129,187
05.04.2020 23:48:37
14,400
37709afb0286356784cb08a0fb7f6c35b1492a96
[native] apns JSON test file for XCode 11.4
[ { "change_type": "ADD", "old_path": null, "new_path": "native/ios/apns/test.apns", "diff": "+{\n+ \"Simulator Target Bundle\": \"org.squadcal.app\",\n+ \"body\": \"asdasd\",\n+ \"title\": \"test\",\n+ \"threadID\": \"82251\",\n+ \"messageInfos\": \"[{\\\"type\\\":0,\\\"threadID\\\":\\\"82251\\\",\\\"creatorID\\\":\\\"1402\\\",\\\"time\\\":1586135605476,\\\"text\\\":\\\"asdasd\\\",\\\"id\\\":\\\"166127\\\"}]\",\n+ \"aps\": {\n+ \"alert\": \"test: asdasd\",\n+ \"sound\": \"default\",\n+ \"badge\": 12,\n+ \"thread-id\": \"82251\"\n+ }\n+}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] apns JSON test file for XCode 11.4
129,187
26.03.2020 14:47:15
14,400
8511cbe519881f889209c78964529ed4562dd8f3
[native] App -> Root
[ { "change_type": "MODIFY", "old_path": "native/__tests__/test.js", "new_path": "native/__tests__/test.js", "diff": "import 'react-native';\nimport * as React from 'react';\n-import App from '../app.react';\n+import Root from '../root.react';\n// Note: test renderer must be required after react-native.\nimport renderer from 'react-test-renderer';\nit('renders correctly', () => {\n- renderer.create(<App />);\n+ renderer.create(<Root />);\n});\n" }, { "change_type": "MODIFY", "old_path": "native/index.js", "new_path": "native/index.js", "diff": "@@ -5,7 +5,7 @@ import './config';\nimport { AppRegistry } from 'react-native';\n-import App from './app.react';\n+import Root from './root.react';\nimport { name as appName } from './app.json';\n-AppRegistry.registerComponent(appName, () => App);\n+AppRegistry.registerComponent(appName, () => Root);\n" }, { "change_type": "RENAME", "old_path": "native/app.react.js", "new_path": "native/root.react.js", "diff": "@@ -62,7 +62,7 @@ type Props = {\ntype State = {|\ndetectUnsupervisedBackground: ?(alreadyClosed: boolean) => boolean,\n|};\n-class AppWithNavigationState extends React.PureComponent<Props, State> {\n+class Root extends React.PureComponent<Props, State> {\nstatic propTypes = {\nnavigationState: PropTypes.object.isRequired,\nactiveTheme: globalThemePropType,\n@@ -170,21 +170,20 @@ const styles = StyleSheet.create({\n},\n});\n-const ConnectedAppWithNavigationState = connect(\n+const ConnectedRoot = connect(\n(state: AppState) => ({\nnavigationState: state.navInfo.navigationState,\nactiveTheme: state.globalThemeInfo.activeTheme,\n}),\nnull,\ntrue,\n-)(AppWithNavigationState);\n+)(Root);\n-const App = () => (\n+const AppRoot = () => (\n<Provider store={store}>\n<ErrorBoundary>\n- <ConnectedAppWithNavigationState />\n+ <ConnectedRoot />\n</ErrorBoundary>\n</Provider>\n);\n-\n-export default App;\n+export default AppRoot;\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] App -> Root
129,187
26.03.2020 18:35:31
14,400
c2938afb629bf81c89d36a94b144fc797adcd6e2
[native] Separate nav state and Redux state in backgroundIsDarkSelector
[ { "change_type": "MODIFY", "old_path": "native/navigation/action-result-modal.react.js", "new_path": "native/navigation/action-result-modal.react.js", "diff": "@@ -119,5 +119,5 @@ const styles = {\nconst stylesSelector = overlayStyleSelector(styles);\nexport default connect((state: AppState) => ({\n- styles: stylesSelector(state),\n+ styles: stylesSelector({ redux: state, nav: state.navInfo.navigationState }),\n}))(ActionResultModal);\n" }, { "change_type": "MODIFY", "old_path": "native/selectors/nav-selectors.js", "new_path": "native/selectors/nav-selectors.js", "diff": "@@ -5,6 +5,7 @@ import type { NavigationState } from 'react-navigation';\nimport type { CalendarFilter } from 'lib/types/filter-types';\nimport type { CalendarQuery } from 'lib/types/entry-types';\nimport type { GlobalTheme } from '../types/themes';\n+import type { NavPlusRedux } from '../types/selector-types';\nimport { createSelector } from 'reselect';\nimport _memoize from 'lodash/memoize';\n@@ -90,9 +91,11 @@ const scrollBlockingChatModalsClosedSelector: (\n},\n);\n-const backgroundIsDarkSelector: (state: AppState) => boolean = createSelector(\n- (state: AppState) => state.navInfo.navigationState,\n- (state: AppState) => state.globalThemeInfo.activeTheme,\n+const backgroundIsDarkSelector: (\n+ input: NavPlusRedux,\n+) => boolean = createSelector(\n+ (input: NavPlusRedux) => input.nav,\n+ (input: NavPlusRedux) => input.redux.globalThemeInfo.activeTheme,\n(navigationState: NavigationState, theme: ?GlobalTheme) => {\nconst currentRootSubroute = navigationState.routes[navigationState.index];\nif (currentRootSubroute.routeName !== AppRouteName) {\n" }, { "change_type": "MODIFY", "old_path": "native/themes/colors.js", "new_path": "native/themes/colors.js", "diff": "import type { GlobalTheme } from '../types/themes';\nimport type { Styles } from '../types/styles';\nimport type { AppState } from '../redux/redux-setup';\n+import type { NavPlusRedux } from '../types/selector-types';\nimport { StyleSheet } from 'react-native';\nimport { createSelector } from 'reselect';\n@@ -130,7 +131,7 @@ const colorsSelector: (state: AppState) => Colors = createSelector(\n},\n);\n-const overlayColorsSelector: (state: AppState) => Colors = createSelector(\n+const overlayColorsSelector: (input: NavPlusRedux) => Colors = createSelector(\nbackgroundIsDarkSelector,\n(backgroundIsDark: boolean) => {\nconst syntheticTheme = backgroundIsDark ? 'dark' : 'light';\n@@ -180,7 +181,7 @@ function styleSelector<IS: InStyles, +OS: Styles>(\nfunction overlayStyleSelector<IS: InStyles, +OS: Styles>(\nobj: IS,\n-): (state: AppState) => OS {\n+): (input: NavPlusRedux) => OS {\nreturn createSelector(overlayColorsSelector, (themeColors: Colors) =>\nstylesFromColors(obj, themeColors),\n);\n" }, { "change_type": "ADD", "old_path": null, "new_path": "native/types/selector-types.js", "diff": "+// @flow\n+\n+import type { AppState } from '../redux/redux-setup';\n+import type { NavigationState } from 'react-navigation';\n+\n+export type NavPlusRedux = {|\n+ redux: AppState,\n+ nav: NavigationState,\n+|};\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Separate nav state and Redux state in backgroundIsDarkSelector
129,187
27.03.2020 14:49:18
14,400
b227067d278a083341b2c17ef7554381973dd74a
[native] Separate nav state and Redux state in calendarQuery nav selectors
[ { "change_type": "MODIFY", "old_path": "native/calendar/entry.react.js", "new_path": "native/calendar/entry.react.js", "diff": "@@ -744,7 +744,10 @@ const activeThreadPickerSelector = createIsForegroundSelector(\nconst Entry = connect(\n(state: AppState) => ({\n- calendarQuery: nonThreadCalendarQuery(state),\n+ calendarQuery: nonThreadCalendarQuery({\n+ redux: state,\n+ nav: state.navInfo.navigationState,\n+ }),\nthreadPickerActive: activeThreadPickerSelector(state),\nforegroundKey: foregroundKeySelector(state),\nonline: state.connection.status === 'connected',\n" }, { "change_type": "MODIFY", "old_path": "native/chat/chat-input-bar.react.js", "new_path": "native/chat/chat-input-bar.react.js", "diff": "@@ -641,7 +641,10 @@ export default connect(\nviewerID: state.currentUserInfo && state.currentUserInfo.id,\ndraft: draft ? draft : '',\njoinThreadLoadingStatus: joinThreadLoadingStatusSelector(state),\n- calendarQuery: nonThreadCalendarQuery(state),\n+ calendarQuery: nonThreadCalendarQuery({\n+ redux: state,\n+ nav: state.navInfo.navigationState,\n+ }),\nnextLocalID: state.nextLocalID,\ncolors: colorsSelector(state),\nstyles: stylesSelector(state),\n" }, { "change_type": "MODIFY", "old_path": "native/navigation/nav-selectors.js", "new_path": "native/navigation/nav-selectors.js", "diff": "@@ -214,10 +214,10 @@ const calendarActiveSelector: (state: AppState) => boolean = createSelector(\n);\nconst nativeCalendarQuery: (\n- state: AppState,\n+ input: NavPlusRedux,\n) => () => CalendarQuery = createSelector(\n- currentCalendarQuery,\n- calendarActiveSelector,\n+ (input: NavPlusRedux) => currentCalendarQuery(input.redux),\n+ (input: NavPlusRedux) => calendarActiveSelector(input.redux),\n(\ncalendarQuery: (calendarActive: boolean) => CalendarQuery,\ncalendarActive: boolean,\n@@ -225,10 +225,10 @@ const nativeCalendarQuery: (\n);\nconst nonThreadCalendarQuery: (\n- state: AppState,\n+ input: NavPlusRedux,\n) => () => CalendarQuery = createSelector(\nnativeCalendarQuery,\n- nonThreadCalendarFiltersSelector,\n+ (input: NavPlusRedux) => nonThreadCalendarFiltersSelector(input.redux),\n(\ncalendarQuery: () => CalendarQuery,\nfilters: $ReadOnlyArray<CalendarFilter>,\n" }, { "change_type": "MODIFY", "old_path": "native/redux/persist.js", "new_path": "native/redux/persist.js", "diff": "@@ -17,7 +17,6 @@ import { highestLocalIDSelector } from 'lib/selectors/local-id-selectors';\nimport { unshimMessageStore } from 'lib/shared/unshim-utils';\nimport { inconsistencyResponsesToReports } from 'lib/shared/report-utils';\n-import { nativeCalendarQuery } from '../navigation/nav-selectors';\nimport { defaultNotifPermissionAlertInfo } from '../push/alerts';\nconst baseBlacklist = [\n@@ -84,7 +83,6 @@ const migrations = {\nentryStore: {\n...state.entryStore,\ninconsistencyResponses: [],\n- actualizedCalendarQuery: nativeCalendarQuery(state)(),\n},\n}),\n[8]: (state: AppState) => ({\n" }, { "change_type": "MODIFY", "old_path": "native/socket.react.js", "new_path": "native/socket.react.js", "diff": "@@ -36,7 +36,10 @@ export default connect(\ncookie: state.cookie,\nurlPrefix: state.urlPrefix,\nconnection: state.connection,\n- currentCalendarQuery: nativeCalendarQuery(state),\n+ currentCalendarQuery: nativeCalendarQuery({\n+ redux: state,\n+ nav: state.navInfo.navigationState,\n+ }),\nhasWiFi: state.connectivity.hasWiFi,\nfrozen: state.frozen,\npreRequestUserState: preRequestUserStateSelector(state),\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Separate nav state and Redux state in calendarQuery nav selectors
129,187
27.03.2020 19:57:48
14,400
6225d09e9081d1e22ab2609bc563883779b35f8b
[native] Move sendTextMessage to ChatInputStateContainer
[ { "change_type": "MODIFY", "old_path": "native/chat/chat-input-bar.react.js", "new_path": "native/chat/chat-input-bar.react.js", "diff": "@@ -5,12 +5,7 @@ import type {\nDispatchActionPayload,\nDispatchActionPromise,\n} from 'lib/utils/action-utils';\n-import {\n- type RawTextMessageInfo,\n- type SendMessageResult,\n- type SendMessagePayload,\n- messageTypes,\n-} from 'lib/types/message-types';\n+import { messageTypes } from 'lib/types/message-types';\nimport {\ntype ThreadInfo,\nthreadInfoPropType,\n@@ -31,6 +26,11 @@ import {\ntype MessageListNavProp,\nmessageListNavPropType,\n} from './message-list-types';\n+import {\n+ type ChatInputState,\n+ chatInputStatePropType,\n+ withChatInputState,\n+} from './chat-input-state';\nimport * as React from 'react';\nimport {\n@@ -52,10 +52,6 @@ import { TextInputKeyboardMangerIOS } from 'react-native-keyboard-input';\nimport _throttle from 'lodash/throttle';\nimport { connect } from 'lib/utils/redux-utils';\n-import {\n- sendTextMessageActionTypes,\n- sendTextMessage,\n-} from 'lib/actions/message-actions';\nimport { saveDraftActionType } from 'lib/actions/miscellaneous-action-types';\nimport { threadHasPermission, viewerIsMember } from 'lib/shared/thread-utils';\nimport { joinThreadActionTypes, joinThread } from 'lib/actions/thread-actions';\n@@ -97,12 +93,9 @@ type Props = {|\ndispatchActionPayload: DispatchActionPayload,\ndispatchActionPromise: DispatchActionPromise,\n// async functions that hit server APIs\n- sendTextMessage: (\n- threadID: string,\n- localID: string,\n- text: string,\n- ) => Promise<SendMessageResult>,\njoinThread: (request: ClientThreadJoinRequest) => Promise<ThreadJoinPayload>,\n+ // withChatInputState\n+ chatInputState: ?ChatInputState,\n|};\ntype State = {|\ntext: string,\n@@ -123,8 +116,8 @@ class ChatInputBar extends React.PureComponent<Props, State> {\nkeyboardState: keyboardStatePropType,\ndispatchActionPayload: PropTypes.func.isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\n- sendTextMessage: PropTypes.func.isRequired,\njoinThread: PropTypes.func.isRequired,\n+ chatInputState: chatInputStatePropType,\n};\ntextInput: ?TextInput;\nexpandOpacity: Animated.Value;\n@@ -441,48 +434,19 @@ class ChatInputBar extends React.PureComponent<Props, State> {\nconst localID = `local${this.props.nextLocalID}`;\nconst creatorID = this.props.viewerID;\ninvariant(creatorID, 'should have viewer ID in order to send a message');\n- const messageInfo = ({\n+ invariant(\n+ this.props.chatInputState,\n+ 'chatInputState should be set in ChatInputBar.onSend',\n+ );\n+ this.props.chatInputState.sendTextMessage({\ntype: messageTypes.TEXT,\nlocalID,\nthreadID: this.props.threadInfo.id,\ntext,\ncreatorID,\ntime: Date.now(),\n- }: RawTextMessageInfo);\n- this.props.dispatchActionPromise(\n- sendTextMessageActionTypes,\n- this.sendTextMessageAction(messageInfo),\n- undefined,\n- messageInfo,\n- );\n- };\n-\n- async sendTextMessageAction(\n- messageInfo: RawTextMessageInfo,\n- ): Promise<SendMessagePayload> {\n- try {\n- const { localID } = messageInfo;\n- invariant(\n- localID !== null && localID !== undefined,\n- 'localID should be set',\n- );\n- const result = await this.props.sendTextMessage(\n- messageInfo.threadID,\n- localID,\n- messageInfo.text,\n- );\n- return {\n- localID,\n- serverID: result.id,\n- threadID: messageInfo.threadID,\n- time: result.time,\n+ });\n};\n- } catch (e) {\n- e.localID = messageInfo.localID;\n- e.threadID = messageInfo.threadID;\n- throw e;\n- }\n- }\nonPressJoin = () => {\nthis.props.dispatchActionPromise(joinThreadActionTypes, this.joinAction());\n@@ -660,6 +624,6 @@ export default connectNav((context: ?NavContextType) => ({\nstyles: stylesSelector(state),\n};\n},\n- { sendTextMessage, joinThread },\n- )(withKeyboardState(ChatInputBar)),\n+ { joinThread },\n+ )(withKeyboardState(withChatInputState(ChatInputBar))),\n);\n" }, { "change_type": "MODIFY", "old_path": "native/chat/chat-input-state-container.react.js", "new_path": "native/chat/chat-input-state-container.react.js", "diff": "@@ -21,6 +21,7 @@ import {\ntype SendMessagePayload,\ntype RawImagesMessageInfo,\ntype RawMediaMessageInfo,\n+ type RawTextMessageInfo,\n} from 'lib/types/message-types';\nimport {\ntype MediaMissionReportCreationRequest,\n@@ -42,6 +43,8 @@ import {\ncreateLocalMessageActionType,\nsendMultimediaMessageActionTypes,\nsendMultimediaMessage,\n+ sendTextMessageActionTypes,\n+ sendTextMessage,\n} from 'lib/actions/message-actions';\nimport { createMediaMessageInfo } from 'lib/shared/message-utils';\nimport { queueReportsActionType } from 'lib/actions/report-actions';\n@@ -78,6 +81,11 @@ type Props = {|\nlocalID: string,\nmediaIDs: $ReadOnlyArray<string>,\n) => Promise<SendMessageResult>,\n+ sendTextMessage: (\n+ threadID: string,\n+ localID: string,\n+ text: string,\n+ ) => Promise<SendMessageResult>,\n|};\ntype State = {|\npendingUploads: PendingMultimediaUploads,\n@@ -92,6 +100,7 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\ndispatchActionPromise: PropTypes.func.isRequired,\nuploadMultimedia: PropTypes.func.isRequired,\nsendMultimediaMessage: PropTypes.func.isRequired,\n+ sendTextMessage: PropTypes.func.isRequired,\n};\nstate = {\npendingUploads: {},\n@@ -261,12 +270,49 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\n(state: State) => state.pendingUploads,\n(pendingUploads: PendingMultimediaUploads) => ({\npendingUploads,\n+ sendTextMessage: this.sendTextMessage,\nsendMultimediaMessage: this.sendMultimediaMessage,\nmessageHasUploadFailure: this.messageHasUploadFailure,\nretryMultimediaMessage: this.retryMultimediaMessage,\n}),\n);\n+ sendTextMessage = (messageInfo: RawTextMessageInfo) => {\n+ this.props.dispatchActionPromise(\n+ sendTextMessageActionTypes,\n+ this.sendTextMessageAction(messageInfo),\n+ undefined,\n+ messageInfo,\n+ );\n+ };\n+\n+ async sendTextMessageAction(\n+ messageInfo: RawTextMessageInfo,\n+ ): Promise<SendMessagePayload> {\n+ try {\n+ const { localID } = messageInfo;\n+ invariant(\n+ localID !== null && localID !== undefined,\n+ 'localID should be set',\n+ );\n+ const result = await this.props.sendTextMessage(\n+ messageInfo.threadID,\n+ localID,\n+ messageInfo.text,\n+ );\n+ return {\n+ localID,\n+ serverID: result.id,\n+ threadID: messageInfo.threadID,\n+ time: result.time,\n+ };\n+ } catch (e) {\n+ e.localID = messageInfo.localID;\n+ e.threadID = messageInfo.threadID;\n+ throw e;\n+ }\n+ }\n+\nsendMultimediaMessage = async (\nthreadID: string,\nselections: $ReadOnlyArray<MediaSelection>,\n@@ -679,5 +725,5 @@ export default connect(\nnextLocalID: state.nextLocalID,\nmessageStoreMessages: state.messageStore.messages,\n}),\n- { uploadMultimedia, sendMultimediaMessage },\n+ { uploadMultimedia, sendMultimediaMessage, sendTextMessage },\n)(ChatInputStateContainer);\n" }, { "change_type": "MODIFY", "old_path": "native/chat/chat-input-state.js", "new_path": "native/chat/chat-input-state.js", "diff": "// @flow\nimport type { MediaSelection } from 'lib/types/media-types';\n+import type { RawTextMessageInfo } from 'lib/types/message-types';\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\n@@ -33,6 +34,7 @@ const pendingMultimediaUploadsPropType = PropTypes.objectOf(\nexport type ChatInputState = {|\npendingUploads: PendingMultimediaUploads,\n+ sendTextMessage: (messageInfo: RawTextMessageInfo) => void,\nsendMultimediaMessage: (\nthreadID: string,\nselections: $ReadOnlyArray<MediaSelection>,\n@@ -43,6 +45,7 @@ export type ChatInputState = {|\nconst chatInputStatePropType = PropTypes.shape({\npendingUploads: pendingMultimediaUploadsPropType.isRequired,\n+ sendTextMessage: PropTypes.func.isRequired,\nsendMultimediaMessage: PropTypes.func.isRequired,\nmessageHasUploadFailure: PropTypes.func.isRequired,\nretryMultimediaMessage: PropTypes.func.isRequired,\n" }, { "change_type": "MODIFY", "old_path": "native/keyboard/keyboard-input-host.react.js", "new_path": "native/keyboard/keyboard-input-host.react.js", "diff": "@@ -37,7 +37,7 @@ type Props = {|\nactiveMessageList: ?string,\n// withKeyboardState\nkeyboardState: ?KeyboardState,\n- // withChatInput\n+ // withChatInputState\nchatInputState: ?ChatInputState,\n|};\nclass KeyboardInputHost extends React.PureComponent<Props> {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Move sendTextMessage to ChatInputStateContainer
129,187
27.03.2020 20:12:05
14,400
5049e7a562a0aa4038c1211f2ab71d34eab89c15
[native] Move retrying sendTextMessage to ChatInputStateContainer
[ { "change_type": "MODIFY", "old_path": "native/chat/failed-send.react.js", "new_path": "native/chat/failed-send.react.js", "diff": "import type { ChatMessageInfoItemWithHeight } from './message.react';\nimport { chatMessageItemPropType } from 'lib/selectors/chat-selectors';\n-import {\n- messageTypes,\n- type SendMessageResult,\n- type SendMessagePayload,\n- type RawTextMessageInfo,\n- type RawMessageInfo,\n-} from 'lib/types/message-types';\n+import { messageTypes, type RawMessageInfo } from 'lib/types/message-types';\nimport type { AppState } from '../redux/redux-setup';\n-import type { DispatchActionPromise } from 'lib/utils/action-utils';\nimport type { Styles } from '../types/styles';\nimport {\ntype ChatInputState,\n@@ -25,14 +18,11 @@ import PropTypes from 'prop-types';\nimport { messageID } from 'lib/shared/message-utils';\nimport { connect } from 'lib/utils/redux-utils';\n-import {\n- sendTextMessageActionTypes,\n- sendTextMessage,\n-} from 'lib/actions/message-actions';\nimport Button from '../components/button.react';\nimport { styleSelector } from '../themes/colors';\nimport multimediaMessageSendFailed from './multimedia-message-send-failed';\n+import textMessageSendFailed from './text-message-send-failed';\nconst failedSendHeight = 22;\n@@ -41,14 +31,6 @@ type Props = {|\n// Redux state\nrawMessageInfo: ?RawMessageInfo,\nstyles: Styles,\n- // Redux dispatch functions\n- dispatchActionPromise: DispatchActionPromise,\n- // async functions that hit server APIs\n- sendTextMessage: (\n- threadID: string,\n- localID: string,\n- text: string,\n- ) => Promise<SendMessageResult>,\n// withChatInputState\nchatInputState: ?ChatInputState,\n|};\n@@ -57,8 +39,6 @@ class FailedSend extends React.PureComponent<Props> {\nitem: chatMessageItemPropType.isRequired,\nrawMessageInfo: PropTypes.object,\nstyles: PropTypes.objectOf(PropTypes.object).isRequired,\n- dispatchActionPromise: PropTypes.func.isRequired,\n- sendTextMessage: PropTypes.func.isRequired,\nchatInputState: chatInputStatePropType,\n};\nretryingText = false;\n@@ -66,22 +46,36 @@ class FailedSend extends React.PureComponent<Props> {\ncomponentDidUpdate(prevProps: Props) {\nconst newItem = this.props.item;\n- if (newItem.messageShapeType !== 'multimedia') {\n- return;\n- }\nconst prevItem = prevProps.item;\n- if (prevItem.messageShapeType !== 'multimedia') {\n- return;\n- }\n+ if (\n+ newItem.messageShapeType === 'multimedia' &&\n+ prevItem.messageShapeType === 'multimedia'\n+ ) {\nconst isFailed = multimediaMessageSendFailed(newItem);\nconst wasFailed = multimediaMessageSendFailed(prevItem);\nconst isDone =\nnewItem.messageInfo.id !== null && newItem.messageInfo.id !== undefined;\nconst wasDone =\n- prevItem.messageInfo.id !== null && prevItem.messageInfo.id !== undefined;\n+ prevItem.messageInfo.id !== null &&\n+ prevItem.messageInfo.id !== undefined;\nif ((isFailed && !wasFailed) || (isDone && !wasDone)) {\nthis.retryingMedia = false;\n}\n+ } else if (\n+ newItem.messageShapeType === 'text' &&\n+ prevItem.messageShapeType === 'text'\n+ ) {\n+ const isFailed = textMessageSendFailed(newItem);\n+ const wasFailed = textMessageSendFailed(prevItem);\n+ const isDone =\n+ newItem.messageInfo.id !== null && newItem.messageInfo.id !== undefined;\n+ const wasDone =\n+ prevItem.messageInfo.id !== null &&\n+ prevItem.messageInfo.id !== undefined;\n+ if ((isFailed && !wasFailed) || (isDone && !wasDone)) {\n+ this.retryingText = false;\n+ }\n+ }\n}\nrender() {\n@@ -107,31 +101,26 @@ class FailedSend extends React.PureComponent<Props> {\nif (!rawMessageInfo) {\nreturn;\n}\n+ const { chatInputState } = this.props;\n+ invariant(\n+ chatInputState,\n+ 'chatInputState should be initialized before user can hit retry',\n+ );\nif (rawMessageInfo.type === messageTypes.TEXT) {\nif (this.retryingText) {\nreturn;\n}\n- const newRawMessageInfo = {\n+ this.retryingText = true;\n+ chatInputState.sendTextMessage({\n...rawMessageInfo,\ntime: Date.now(),\n- };\n- this.props.dispatchActionPromise(\n- sendTextMessageActionTypes,\n- this.sendTextMessageAction(newRawMessageInfo),\n- undefined,\n- newRawMessageInfo,\n- );\n+ });\n} else if (\nrawMessageInfo.type === messageTypes.IMAGES ||\nrawMessageInfo.type === messageTypes.MULTIMEDIA\n) {\nconst { localID } = rawMessageInfo;\ninvariant(localID, 'failed RawMessageInfo should have localID');\n- const { chatInputState } = this.props;\n- invariant(\n- chatInputState,\n- 'chatInputState should be initialized before user can hit retry',\n- );\nif (this.retryingMedia) {\nreturn;\n}\n@@ -139,36 +128,6 @@ class FailedSend extends React.PureComponent<Props> {\nchatInputState.retryMultimediaMessage(localID);\n}\n};\n-\n- async sendTextMessageAction(\n- messageInfo: RawTextMessageInfo,\n- ): Promise<SendMessagePayload> {\n- this.retryingText = true;\n- try {\n- const { localID } = messageInfo;\n- invariant(\n- localID !== null && localID !== undefined,\n- 'localID should be set',\n- );\n- const result = await this.props.sendTextMessage(\n- messageInfo.threadID,\n- localID,\n- messageInfo.text,\n- );\n- return {\n- localID,\n- serverID: result.id,\n- threadID: messageInfo.threadID,\n- time: result.time,\n- };\n- } catch (e) {\n- e.localID = messageInfo.localID;\n- e.threadID = messageInfo.threadID;\n- throw e;\n- } finally {\n- this.retryingText = false;\n- }\n- }\n}\nconst styles = {\n@@ -198,7 +157,6 @@ const ConnectedFailedSend = connect(\nstyles: stylesSelector(state),\n};\n},\n- { sendTextMessage },\n)(withChatInputState(FailedSend));\nexport { ConnectedFailedSend as FailedSend, failedSendHeight };\n" }, { "change_type": "MODIFY", "old_path": "native/chat/multimedia-message-send-failed.js", "new_path": "native/chat/multimedia-message-send-failed.js", "diff": "@@ -4,7 +4,7 @@ import type { ChatMultimediaMessageInfoItem } from './multimedia-message.react';\nexport default function multimediaMessageSendFailed(\nitem: ChatMultimediaMessageInfoItem,\n-) {\n+): boolean {\nconst { messageInfo, localMessageInfo, pendingUploads } = item;\nconst { id: serverID } = messageInfo;\nif (serverID !== null && serverID !== undefined) {\n" }, { "change_type": "ADD", "old_path": null, "new_path": "native/chat/text-message-send-failed.js", "diff": "+// @flow\n+\n+import type { ChatTextMessageInfoItemWithHeight } from './text-message.react';\n+\n+export default function textMessageSendFailed(\n+ item: ChatTextMessageInfoItemWithHeight,\n+): boolean {\n+ const {\n+ id,\n+ creator: { isViewer },\n+ } = item.messageInfo;\n+ return !!(\n+ isViewer &&\n+ (id === null || id === undefined) &&\n+ item.localMessageInfo &&\n+ item.localMessageInfo.sendFailed\n+ );\n+}\n" }, { "change_type": "MODIFY", "old_path": "native/chat/text-message.react.js", "new_path": "native/chat/text-message.react.js", "diff": "@@ -37,6 +37,7 @@ import { TextMessageTooltipModalRouteName } from '../navigation/route-names';\nimport { ComposedMessage, clusterEndHeight } from './composed-message.react';\nimport { authorNameHeight } from './message-header.react';\nimport { failedSendHeight } from './failed-send.react';\n+import textMessageSendFailed from './text-message-send-failed';\nexport type ChatTextMessageInfoItemWithHeight = {|\nitemType: 'message',\n@@ -52,8 +53,7 @@ export type ChatTextMessageInfoItemWithHeight = {|\nfunction textMessageItemHeight(item: ChatTextMessageInfoItemWithHeight) {\nconst { messageInfo, contentHeight, startsCluster, endsCluster } = item;\n- const { id, creator } = messageInfo;\n- const { isViewer } = creator;\n+ const { isViewer } = messageInfo.creator;\nlet height = 17 + contentHeight; // for padding, margin, and text\nif (!isViewer && startsCluster) {\nheight += authorNameHeight;\n@@ -61,13 +61,7 @@ function textMessageItemHeight(item: ChatTextMessageInfoItemWithHeight) {\nif (endsCluster) {\nheight += clusterEndHeight;\n}\n- if (\n- isViewer &&\n- id !== null &&\n- id !== undefined &&\n- item.localMessageInfo &&\n- item.localMessageInfo.sendFailed\n- ) {\n+ if (textMessageSendFailed(item)) {\nheight += failedSendHeight;\n}\nreturn height;\n@@ -108,18 +102,10 @@ class TextMessage extends React.PureComponent<Props> {\nkeyboardState,\n...viewProps\n} = this.props;\n- const { id, creator } = item.messageInfo;\n- const { isViewer } = creator;\n- const sendFailed =\n- isViewer &&\n- (id === null || id === undefined) &&\n- item.localMessageInfo &&\n- item.localMessageInfo.sendFailed;\n-\nreturn (\n<ComposedMessage\nitem={item}\n- sendFailed={!!sendFailed}\n+ sendFailed={textMessageSendFailed(item)}\nfocused={focused}\n{...viewProps}\n>\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Move retrying sendTextMessage to ChatInputStateContainer
129,187
27.03.2020 22:43:38
14,400
a8c345e806038d29ce3ad1207d47c5eefb9557bd
[web] Move sendTextMessage to ChatInputStateContainer
[ { "change_type": "MODIFY", "old_path": "web/chat/chat-input-bar.react.js", "new_path": "web/chat/chat-input-bar.react.js", "diff": "@@ -15,12 +15,7 @@ import {\ntype ClientThreadJoinRequest,\ntype ThreadJoinPayload,\n} from 'lib/types/thread-types';\n-import {\n- type RawTextMessageInfo,\n- type SendMessageResult,\n- type SendMessagePayload,\n- messageTypes,\n-} from 'lib/types/message-types';\n+import { messageTypes } from 'lib/types/message-types';\nimport {\nchatInputStatePropType,\ntype ChatInputState,\n@@ -36,10 +31,6 @@ import PropTypes from 'prop-types';\nimport _difference from 'lodash/fp/difference';\nimport { connect } from 'lib/utils/redux-utils';\n-import {\n- sendTextMessageActionTypes,\n- sendTextMessage,\n-} from 'lib/actions/message-actions';\nimport { joinThreadActionTypes, joinThread } from 'lib/actions/thread-actions';\nimport { createLoadingStatusSelector } from 'lib/selectors/loading-selectors';\nimport { threadHasPermission, viewerIsMember } from 'lib/shared/thread-utils';\n@@ -62,11 +53,6 @@ type Props = {|\ndispatchActionPromise: DispatchActionPromise,\ndispatchActionPayload: DispatchActionPayload,\n// async functions that hit server APIs\n- sendTextMessage: (\n- threadID: string,\n- localID: string,\n- text: string,\n- ) => Promise<SendMessageResult>,\njoinThread: (request: ClientThreadJoinRequest) => Promise<ThreadJoinPayload>,\n|};\nclass ChatInputBar extends React.PureComponent<Props> {\n@@ -79,7 +65,6 @@ class ChatInputBar extends React.PureComponent<Props> {\nnextLocalID: PropTypes.number.isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\ndispatchActionPayload: PropTypes.func.isRequired,\n- sendTextMessage: PropTypes.func.isRequired,\njoinThread: PropTypes.func.isRequired,\n};\ntextarea: ?HTMLTextAreaElement;\n@@ -296,47 +281,14 @@ class ChatInputBar extends React.PureComponent<Props> {\nconst localID = `local${nextLocalID}`;\nconst creatorID = this.props.viewerID;\ninvariant(creatorID, 'should have viewer ID in order to send a message');\n- const messageInfo = ({\n+ this.props.chatInputState.sendTextMessage({\ntype: messageTypes.TEXT,\nlocalID,\nthreadID: this.props.threadInfo.id,\ntext,\ncreatorID,\ntime: Date.now(),\n- }: RawTextMessageInfo);\n- this.props.dispatchActionPromise(\n- sendTextMessageActionTypes,\n- this.sendTextMessageAction(messageInfo),\n- undefined,\n- messageInfo,\n- );\n- }\n-\n- async sendTextMessageAction(\n- messageInfo: RawTextMessageInfo,\n- ): Promise<SendMessagePayload> {\n- try {\n- const { localID } = messageInfo;\n- invariant(\n- localID !== null && localID !== undefined,\n- 'localID should be set',\n- );\n- const result = await this.props.sendTextMessage(\n- messageInfo.threadID,\n- localID,\n- messageInfo.text,\n- );\n- return {\n- localID,\n- serverID: result.id,\n- threadID: messageInfo.threadID,\n- time: result.time,\n- };\n- } catch (e) {\n- e.localID = messageInfo.localID;\n- e.threadID = messageInfo.threadID;\n- throw e;\n- }\n+ });\n}\nmultimediaInputRef = (multimediaInput: ?HTMLInputElement) => {\n@@ -385,5 +337,5 @@ export default connect(\ncalendarQuery: nonThreadCalendarQuery(state),\nnextLocalID: state.nextLocalID,\n}),\n- { sendTextMessage, joinThread },\n+ { joinThread },\n)(ChatInputBar);\n" }, { "change_type": "MODIFY", "old_path": "web/chat/chat-input-state-container.react.js", "new_path": "web/chat/chat-input-state-container.react.js", "diff": "@@ -15,6 +15,7 @@ import {\ntype RawMultimediaMessageInfo,\ntype SendMessageResult,\ntype SendMessagePayload,\n+ type RawTextMessageInfo,\n} from 'lib/types/message-types';\nimport * as React from 'react';\n@@ -37,6 +38,8 @@ import {\ncreateLocalMessageActionType,\nsendMultimediaMessageActionTypes,\nsendMultimediaMessage,\n+ sendTextMessageActionTypes,\n+ sendTextMessage,\n} from 'lib/actions/message-actions';\nimport { createMediaMessageInfo } from 'lib/shared/message-utils';\n@@ -68,6 +71,11 @@ type Props = {|\nlocalID: string,\nmediaIDs: $ReadOnlyArray<string>,\n) => Promise<SendMessageResult>,\n+ sendTextMessage: (\n+ threadID: string,\n+ localID: string,\n+ text: string,\n+ ) => Promise<SendMessageResult>,\n|};\ntype State = {|\npendingUploads: {\n@@ -87,6 +95,7 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\nuploadMultimedia: PropTypes.func.isRequired,\ndeleteUpload: PropTypes.func.isRequired,\nsendMultimediaMessage: PropTypes.func.isRequired,\n+ sendTextMessage: PropTypes.func.isRequired,\n};\nstate = {\npendingUploads: {},\n@@ -322,6 +331,8 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\nthis.appendFiles(threadID, files),\ncancelPendingUpload: (localUploadID: string) =>\nthis.cancelPendingUpload(threadID, localUploadID),\n+ sendTextMessage: (messageInfo: RawTextMessageInfo) =>\n+ this.sendTextMessage(messageInfo),\ncreateMultimediaMessage: (localID?: number) =>\nthis.createMultimediaMessage(threadID, localID),\nsetDraft: (newDraft: string) => this.setDraft(threadID, newDraft),\n@@ -604,6 +615,42 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\n);\n}\n+ sendTextMessage(messageInfo: RawTextMessageInfo) {\n+ this.props.dispatchActionPromise(\n+ sendTextMessageActionTypes,\n+ this.sendTextMessageAction(messageInfo),\n+ undefined,\n+ messageInfo,\n+ );\n+ }\n+\n+ async sendTextMessageAction(\n+ messageInfo: RawTextMessageInfo,\n+ ): Promise<SendMessagePayload> {\n+ try {\n+ const { localID } = messageInfo;\n+ invariant(\n+ localID !== null && localID !== undefined,\n+ 'localID should be set',\n+ );\n+ const result = await this.props.sendTextMessage(\n+ messageInfo.threadID,\n+ localID,\n+ messageInfo.text,\n+ );\n+ return {\n+ localID,\n+ serverID: result.id,\n+ threadID: messageInfo.threadID,\n+ time: result.time,\n+ };\n+ } catch (e) {\n+ e.localID = messageInfo.localID;\n+ e.threadID = messageInfo.threadID;\n+ throw e;\n+ }\n+ }\n+\n// Creates a MultimediaMessage from the unassigned pending uploads,\n// if there are any\ncreateMultimediaMessage(threadID: string, localID: ?number) {\n@@ -800,5 +847,5 @@ export default connect(\nnextLocalID: state.nextLocalID,\nmessageStoreMessages: state.messageStore.messages,\n}),\n- { uploadMultimedia, deleteUpload, sendMultimediaMessage },\n+ { uploadMultimedia, deleteUpload, sendMultimediaMessage, sendTextMessage },\n)(ChatInputStateContainer);\n" }, { "change_type": "MODIFY", "old_path": "web/chat/chat-input-state.js", "new_path": "web/chat/chat-input-state.js", "diff": "@@ -6,6 +6,7 @@ import {\ntype Dimensions,\ndimensionsPropType,\n} from 'lib/types/media-types';\n+import type { RawTextMessageInfo } from 'lib/types/message-types';\nimport PropTypes from 'prop-types';\n@@ -52,6 +53,7 @@ export type ChatInputState = {|\ndraft: string,\nappendFiles: (files: $ReadOnlyArray<File>) => Promise<void>,\ncancelPendingUpload: (localUploadID: string) => void,\n+ sendTextMessage: (messageInfo: RawTextMessageInfo) => void,\ncreateMultimediaMessage: (localID?: number) => void,\nsetDraft: (draft: string) => void,\nmessageHasUploadFailure: (localMessageID: string) => boolean,\n@@ -66,6 +68,7 @@ export const chatInputStatePropType = PropTypes.shape({\ndraft: PropTypes.string.isRequired,\nappendFiles: PropTypes.func.isRequired,\ncancelPendingUpload: PropTypes.func.isRequired,\n+ sendTextMessage: PropTypes.func.isRequired,\ncreateMultimediaMessage: PropTypes.func.isRequired,\nsetDraft: PropTypes.func.isRequired,\nmessageHasUploadFailure: PropTypes.func.isRequired,\n" }, { "change_type": "MODIFY", "old_path": "web/chat/failed-send.react.js", "new_path": "web/chat/failed-send.react.js", "diff": "@@ -6,15 +6,11 @@ import {\n} from 'lib/selectors/chat-selectors';\nimport {\nmessageTypes,\n- type SendMessageResult,\n- type SendMessagePayload,\ntype RawComposableMessageInfo,\n- type RawTextMessageInfo,\nassertComposableMessageType,\n} from 'lib/types/message-types';\nimport { type ThreadInfo, threadInfoPropType } from 'lib/types/thread-types';\nimport type { AppState } from '../redux-setup';\n-import type { DispatchActionPromise } from 'lib/utils/action-utils';\nimport {\nchatInputStatePropType,\ntype ChatInputState,\n@@ -26,13 +22,10 @@ import PropTypes from 'prop-types';\nimport { messageID } from 'lib/shared/message-utils';\nimport { connect } from 'lib/utils/redux-utils';\n-import {\n- sendTextMessageActionTypes,\n- sendTextMessage,\n-} from 'lib/actions/message-actions';\nimport css from './chat-message-list.css';\nimport multimediaMessageSendFailed from './multimedia-message-send-failed';\n+import textMessageSendFailed from './text-message-send-failed';\ntype Props = {|\nitem: ChatMessageInfoItem,\n@@ -40,14 +33,6 @@ type Props = {|\nchatInputState: ChatInputState,\n// Redux state\nrawMessageInfo: RawComposableMessageInfo,\n- // Redux dispatch functions\n- dispatchActionPromise: DispatchActionPromise,\n- // async functions that hit server APIs\n- sendTextMessage: (\n- threadID: string,\n- localID: string,\n- text: string,\n- ) => Promise<SendMessageResult>,\n|};\nclass FailedSend extends React.PureComponent<Props> {\nstatic propTypes = {\n@@ -55,13 +40,17 @@ class FailedSend extends React.PureComponent<Props> {\nthreadInfo: threadInfoPropType.isRequired,\nchatInputState: chatInputStatePropType.isRequired,\nrawMessageInfo: PropTypes.object.isRequired,\n- dispatchActionPromise: PropTypes.func.isRequired,\n- sendTextMessage: PropTypes.func.isRequired,\n};\nretryingText = false;\nretryingMedia = false;\ncomponentDidUpdate(prevProps: Props) {\n+ if (\n+ (this.props.rawMessageInfo.type === messageTypes.IMAGES ||\n+ this.props.rawMessageInfo.type === messageTypes.MULTIMEDIA) &&\n+ (prevProps.rawMessageInfo.type === messageTypes.IMAGES ||\n+ prevProps.rawMessageInfo.type === messageTypes.MULTIMEDIA)\n+ ) {\nconst isFailed = multimediaMessageSendFailed(\nthis.props.item,\nthis.props.chatInputState,\n@@ -79,6 +68,22 @@ class FailedSend extends React.PureComponent<Props> {\nif ((isFailed && !wasFailed) || (isDone && !wasDone)) {\nthis.retryingMedia = false;\n}\n+ } else if (\n+ this.props.rawMessageInfo.type === messageTypes.TEXT &&\n+ prevProps.rawMessageInfo.type === messageTypes.TEXT\n+ ) {\n+ const isFailed = textMessageSendFailed(this.props.item);\n+ const wasFailed = textMessageSendFailed(prevProps.item);\n+ const isDone =\n+ this.props.item.messageInfo.id !== null &&\n+ this.props.item.messageInfo.id !== undefined;\n+ const wasDone =\n+ prevProps.item.messageInfo.id !== null &&\n+ prevProps.item.messageInfo.id !== undefined;\n+ if ((isFailed && !wasFailed) || (isDone && !wasDone)) {\n+ this.retryingText = false;\n+ }\n+ }\n}\nrender() {\n@@ -100,13 +105,11 @@ class FailedSend extends React.PureComponent<Props> {\nif (this.retryingText) {\nreturn;\n}\n- const newRawMessageInfo = { ...rawMessageInfo, time: Date.now() };\n- this.props.dispatchActionPromise(\n- sendTextMessageActionTypes,\n- this.sendTextMessageAction(newRawMessageInfo),\n- undefined,\n- newRawMessageInfo,\n- );\n+ this.retryingText = true;\n+ this.props.chatInputState.sendTextMessage({\n+ ...rawMessageInfo,\n+ time: Date.now(),\n+ });\n} else if (\nrawMessageInfo.type === messageTypes.IMAGES ||\nrawMessageInfo.type === messageTypes.MULTIMEDIA\n@@ -120,36 +123,6 @@ class FailedSend extends React.PureComponent<Props> {\nthis.props.chatInputState.retryMultimediaMessage(localID);\n}\n};\n-\n- async sendTextMessageAction(\n- messageInfo: RawTextMessageInfo,\n- ): Promise<SendMessagePayload> {\n- this.retryingText = true;\n- try {\n- const { localID } = messageInfo;\n- invariant(\n- localID !== null && localID !== undefined,\n- 'localID should be set',\n- );\n- const result = await this.props.sendTextMessage(\n- messageInfo.threadID,\n- localID,\n- messageInfo.text,\n- );\n- return {\n- localID,\n- serverID: result.id,\n- threadID: messageInfo.threadID,\n- time: result.time,\n- };\n- } catch (e) {\n- e.localID = messageInfo.localID;\n- e.threadID = messageInfo.threadID;\n- throw e;\n- } finally {\n- this.retryingText = false;\n- }\n- }\n}\nexport default connect(\n@@ -167,5 +140,4 @@ export default connect(\n);\nreturn { rawMessageInfo };\n},\n- { sendTextMessage },\n)(FailedSend);\n" }, { "change_type": "ADD", "old_path": null, "new_path": "web/chat/text-message-send-failed.js", "diff": "+// @flow\n+\n+import type { ChatMessageInfoItem } from 'lib/selectors/chat-selectors';\n+import { messageTypes } from 'lib/types/message-types';\n+\n+export default function textMessageSendFailed(item: ChatMessageInfoItem) {\n+ const {\n+ id,\n+ creator: { isViewer },\n+ type,\n+ } = item.messageInfo;\n+ return !!(\n+ isViewer &&\n+ type === messageTypes.TEXT &&\n+ (id === null || id === undefined) &&\n+ item.localMessageInfo &&\n+ item.localMessageInfo.sendFailed\n+ );\n+}\n" }, { "change_type": "MODIFY", "old_path": "web/chat/text-message.react.js", "new_path": "web/chat/text-message.react.js", "diff": "@@ -23,6 +23,7 @@ import { onlyEmojiRegex } from 'lib/shared/emojis';\nimport css from './chat-message-list.css';\nimport ComposedMessage from './composed-message.react';\n+import textMessageSendFailed from './text-message-send-failed';\ntype Props = {|\nitem: ChatMessageInfoItem,\n@@ -58,9 +59,11 @@ class TextMessage extends React.PureComponent<Props> {\nthis.props.item.messageInfo.type === messageTypes.TEXT,\n'TextMessage should only be used for messageTypes.TEXT',\n);\n- const { text, id, creator } = this.props.item.messageInfo;\n+ const {\n+ text,\n+ creator: { isViewer },\n+ } = this.props.item.messageInfo;\n- const { isViewer } = creator;\nconst onlyEmoji = onlyEmojiRegex.test(text);\nconst messageClassName = classNames({\n[css.textMessage]: true,\n@@ -79,17 +82,11 @@ class TextMessage extends React.PureComponent<Props> {\nmessageStyle.color = 'black';\n}\n- const sendFailed =\n- isViewer &&\n- (id === null || id === undefined) &&\n- this.props.item.localMessageInfo &&\n- this.props.item.localMessageInfo.sendFailed;\n-\nreturn (\n<ComposedMessage\nitem={this.props.item}\nthreadInfo={this.props.threadInfo}\n- sendFailed={!!sendFailed}\n+ sendFailed={textMessageSendFailed(this.props.item)}\nsetMouseOver={this.props.setMouseOver}\nchatInputState={this.props.chatInputState}\n>\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[web] Move sendTextMessage to ChatInputStateContainer
129,187
28.03.2020 01:09:41
14,400
c434645ab7b0ae193959fd376f2105251c4a1d05
[native] Fix lint-staged to not report eslint ignore files
[ { "change_type": "MODIFY", "old_path": ".lintstagedrc.js", "new_path": ".lintstagedrc.js", "diff": "@@ -3,7 +3,7 @@ const { CLIEngine } = require('eslint');\nconst cli = new CLIEngine({ });\nmodule.exports = {\n- \"*.js\": \"eslint --cache --fix\",\n+ '*.js': files => 'eslint --cache --fix --max-warnings=0 ' + files.filter(file => !cli.isPathIgnored(file)).join(' '),\n\"lib/**/*.js\": function libFlow(files) { return \"yarn workspace lib flow --quiet\" },\n\"web/**/*.js\": function webFlow(files) { return \"yarn workspace web flow --quiet\" },\n\"native/**/*.js\": function nativeFlow(files) { return \"yarn workspace native flow --quiet\" },\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Fix lint-staged to not report eslint ignore files
129,187
28.03.2020 01:09:59
14,400
3719c59f85a9950462bd291e19b11faa17f050f0
[native] Custom ChatRouter
[ { "change_type": "MODIFY", "old_path": "native/chat/chat-input-state-container.react.js", "new_path": "native/chat/chat-input-state-container.react.js", "diff": "@@ -105,6 +105,7 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\nstate = {\npendingUploads: {},\n};\n+ sendCallbacks: Array<() => void> = [];\nstatic getCompletedUploads(props: Props, state: State): CompletedUploads {\nconst completedUploads = {};\n@@ -274,10 +275,12 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\nsendMultimediaMessage: this.sendMultimediaMessage,\nmessageHasUploadFailure: this.messageHasUploadFailure,\nretryMultimediaMessage: this.retryMultimediaMessage,\n+ registerSendCallback: this.registerSendCallback,\n}),\n);\nsendTextMessage = (messageInfo: RawTextMessageInfo) => {\n+ this.sendCallbacks.forEach(callback => callback());\nthis.props.dispatchActionPromise(\nsendTextMessageActionTypes,\nthis.sendTextMessageAction(messageInfo),\n@@ -317,6 +320,7 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\nthreadID: string,\nselections: $ReadOnlyArray<MediaSelection>,\n) => {\n+ this.sendCallbacks.forEach(callback => callback());\nconst localMessageID = `local${this.props.nextLocalID}`;\nconst selectionsWithIDs = selections.map(selection => ({\nselection,\n@@ -709,6 +713,10 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\nawait this.uploadFiles(localMessageID, selectionsWithIDs);\n};\n+ registerSendCallback = (callback: () => void) => {\n+ this.sendCallbacks.push(callback);\n+ };\n+\nrender() {\nconst chatInputState = this.chatInputStateSelector(this.state);\nreturn (\n" }, { "change_type": "MODIFY", "old_path": "native/chat/chat-input-state.js", "new_path": "native/chat/chat-input-state.js", "diff": "@@ -41,6 +41,7 @@ export type ChatInputState = {|\n) => Promise<void>,\nmessageHasUploadFailure: (localMessageID: string) => boolean,\nretryMultimediaMessage: (localMessageID: string) => Promise<void>,\n+ registerSendCallback: (() => void) => void,\n|};\nconst chatInputStatePropType = PropTypes.shape({\n" }, { "change_type": "DELETE", "old_path": "native/chat/chat-navigator.react.js", "new_path": null, "diff": "-// @flow\n-\n-import type {\n- NavigationScreenProp,\n- NavigationStateRoute,\n-} from 'react-navigation';\n-\n-import * as React from 'react';\n-import { createStackNavigator } from 'react-navigation-stack';\n-\n-import ChatThreadList from './chat-thread-list.react';\n-import MessageListContainer from './message-list-container.react';\n-import ComposeThread from './compose-thread.react';\n-import ThreadSettings from './settings/thread-settings.react';\n-import { getChatScreen } from './chat-screen-registry';\n-import DeleteThread from './settings/delete-thread.react';\n-import ChatIcon from './chat-icon.react';\n-import {\n- ComposeThreadRouteName,\n- DeleteThreadRouteName,\n- ThreadSettingsRouteName,\n- MessageListRouteName,\n- ChatThreadListRouteName,\n-} from '../navigation/route-names';\n-import HeaderBackButton from '../navigation/header-back-button.react';\n-import ChatHeader from './chat-header.react';\n-\n-const ChatNavigator = createStackNavigator(\n- {\n- [ChatThreadListRouteName]: ChatThreadList,\n- [MessageListRouteName]: MessageListContainer,\n- [ComposeThreadRouteName]: ComposeThread,\n- [ThreadSettingsRouteName]: ThreadSettings,\n- [DeleteThreadRouteName]: DeleteThread,\n- },\n- {\n- defaultNavigationOptions: ({ navigation }) => ({\n- header: ChatHeader,\n- headerLeft: navigation.isFirstRouteInParent()\n- ? undefined\n- : HeaderBackButton,\n- }),\n- },\n-);\n-ChatNavigator.navigationOptions = {\n- // eslint-disable-next-line react/display-name\n- tabBarIcon: ({ tintColor }) => <ChatIcon color={tintColor} />,\n- tabBarOnPress: ({\n- navigation,\n- defaultHandler,\n- }: {\n- navigation: NavigationScreenProp<NavigationStateRoute>,\n- defaultHandler: () => void,\n- }) => {\n- if (!navigation.isFocused()) {\n- defaultHandler();\n- return;\n- }\n- const state = navigation.state;\n- const currentRoute = state.routes[state.index];\n- const chatScreen = getChatScreen(currentRoute.key);\n- if (!chatScreen) {\n- return;\n- }\n- if (chatScreen.canReset) {\n- navigation.goBack(state.routes[1].key);\n- }\n- },\n-};\n-\n-export default ChatNavigator;\n" }, { "change_type": "ADD", "old_path": null, "new_path": "native/chat/chat-router.js", "diff": "+// @flow\n+\n+import {\n+ StackRouter,\n+ type NavigationAction,\n+ type NavigationState,\n+ type NavigationRoute,\n+ type NavigationRouteConfigMap,\n+ type NavigationStackRouterConfig,\n+} from 'react-navigation';\n+\n+import { removeScreensFromStack } from '../navigation/navigation-setup';\n+\n+type ClearScreensAction = {|\n+ +type: 'CLEAR_SCREENS',\n+ +routeNames: $ReadOnlyArray<string>,\n+|};\n+\n+const defaultConfig = Object.freeze({});\n+function ChatRouter(\n+ routeConfigMap: NavigationRouteConfigMap,\n+ stackConfig?: NavigationStackRouterConfig = defaultConfig,\n+) {\n+ const stackRouter = StackRouter(routeConfigMap, stackConfig);\n+ return {\n+ ...stackRouter,\n+ getStateForAction: (\n+ action: NavigationAction | ClearScreensAction,\n+ lastState: ?NavigationState,\n+ ) => {\n+ if (action.type === 'CLEAR_SCREENS') {\n+ const { routeNames } = action;\n+ if (!lastState) {\n+ return lastState;\n+ }\n+ return removeScreensFromStack(lastState, (route: NavigationRoute) =>\n+ routeNames.includes(route.routeName) ? 'remove' : 'keep',\n+ );\n+ } else {\n+ return stackRouter.getStateForAction(action, lastState);\n+ }\n+ },\n+ getActionCreators: (route: NavigationRoute, navStateKey: ?string) => ({\n+ ...stackRouter.getActionCreators(route, navStateKey),\n+ clearScreens: (routeNames: $ReadOnlyArray<string>) => ({\n+ type: 'CLEAR_SCREENS',\n+ routeNames,\n+ }),\n+ }),\n+ };\n+}\n+\n+export default ChatRouter;\n" }, { "change_type": "MODIFY", "old_path": "native/chat/chat.react.js", "new_path": "native/chat/chat.react.js", "diff": "// @flow\nimport * as React from 'react';\n-import { StyleSheet } from 'react-native';\n+import {\n+ type NavigationScreenProp,\n+ type NavigationStateRoute,\n+ type NavigationRouteConfigMap,\n+ type NavigationState,\n+ createKeyboardAwareNavigator,\n+ createNavigator,\n+} from 'react-navigation';\n+import {\n+ StackView,\n+ type StackNavigatorConfig,\n+ type NavigationStackScreenOptions,\n+ type NavigationStackProp,\n+} from 'react-navigation-stack';\nimport hoistNonReactStatics from 'hoist-non-react-statics';\n+import { StyleSheet } from 'react-native';\n-import ChatNavigator from './chat-navigator.react';\n+import ChatThreadList from './chat-thread-list.react';\n+import MessageListContainer from './message-list-container.react';\n+import ComposeThread from './compose-thread.react';\n+import ThreadSettings from './settings/thread-settings.react';\n+import { getChatScreen } from './chat-screen-registry';\n+import DeleteThread from './settings/delete-thread.react';\n+import ChatIcon from './chat-icon.react';\n+import {\n+ ComposeThreadRouteName,\n+ DeleteThreadRouteName,\n+ ThreadSettingsRouteName,\n+ MessageListRouteName,\n+ ChatThreadListRouteName,\n+} from '../navigation/route-names';\n+import HeaderBackButton from '../navigation/header-back-button.react';\n+import ChatHeader from './chat-header.react';\n+import ChatRouter from './chat-router';\n+import {\n+ type ChatInputState,\n+ chatInputStatePropType,\n+ withChatInputState,\n+} from './chat-input-state';\nimport KeyboardAvoidingView from '../keyboard/keyboard-avoiding-view.react';\nimport MessageStorePruner from './message-store-pruner.react';\n-class Chat extends React.PureComponent<{ ... }> {\n+type NavigationProp = NavigationStackProp<NavigationState> & {\n+ clearScreens: (routeNames: $ReadOnlyArray<string>) => void,\n+};\n+type Props = {| navigation: NavigationProp |};\n+type StackViewProps = React.ElementConfig<typeof StackView> & {\n+ +navigation: NavigationProp,\n+};\n+\n+function createChatNavigator(\n+ routeConfigMap: NavigationRouteConfigMap,\n+ stackConfig?: StackNavigatorConfig = {},\n+) {\n+ const {\n+ initialRouteName,\n+ initialRouteParams,\n+ paths,\n+ navigationOptions,\n+ defaultNavigationOptions,\n+ initialRouteKey,\n+ ...navigatorConfig\n+ } = stackConfig;\n+ const routerConfig = {\n+ initialRouteName,\n+ initialRouteParams,\n+ paths,\n+ navigationOptions,\n+ defaultNavigationOptions,\n+ initialRouteKey,\n+ };\n+ return createKeyboardAwareNavigator<Props>(\n+ createNavigator<\n+ NavigationStackScreenOptions,\n+ NavigationState,\n+ StackNavigatorConfig,\n+ NavigationProp,\n+ StackViewProps,\n+ >(StackView, ChatRouter(routeConfigMap, routerConfig), navigatorConfig),\n+ navigatorConfig,\n+ );\n+}\n+\n+const ChatNavigator = createChatNavigator(\n+ {\n+ [ChatThreadListRouteName]: ChatThreadList,\n+ [MessageListRouteName]: MessageListContainer,\n+ [ComposeThreadRouteName]: ComposeThread,\n+ [ThreadSettingsRouteName]: ThreadSettings,\n+ [DeleteThreadRouteName]: DeleteThread,\n+ },\n+ {\n+ defaultNavigationOptions: ({ navigation }) => ({\n+ header: ChatHeader,\n+ headerLeft: navigation.isFirstRouteInParent()\n+ ? undefined\n+ : HeaderBackButton,\n+ }),\n+ },\n+);\n+ChatNavigator.navigationOptions = {\n+ // eslint-disable-next-line react/display-name\n+ tabBarIcon: ({ tintColor }) => <ChatIcon color={tintColor} />,\n+ tabBarOnPress: ({\n+ navigation,\n+ defaultHandler,\n+ }: {\n+ navigation: NavigationScreenProp<NavigationStateRoute>,\n+ defaultHandler: () => void,\n+ }) => {\n+ if (!navigation.isFocused()) {\n+ defaultHandler();\n+ return;\n+ }\n+ const state = navigation.state;\n+ const currentRoute = state.routes[state.index];\n+ const chatScreen = getChatScreen(currentRoute.key);\n+ if (!chatScreen) {\n+ return;\n+ }\n+ if (chatScreen.canReset) {\n+ navigation.goBack(state.routes[1].key);\n+ }\n+ },\n+};\n+\n+type WrappedProps = {\n+ ...Props,\n+ // withChatInputState\n+ chatInputState: ?ChatInputState,\n+};\n+class WrappedChatNavigator extends React.PureComponent<WrappedProps> {\n+ static propTypes = {\n+ chatInputState: chatInputStatePropType,\n+ };\n+\n+ componentDidUpdate(prevProps: WrappedProps) {\n+ const { navigation, chatInputState } = this.props;\n+ if (chatInputState && prevProps.navigation !== navigation) {\n+ chatInputState.registerSendCallback(() =>\n+ navigation.clearScreens([ComposeThreadRouteName]),\n+ );\n+ }\n+ }\n+\nrender() {\n+ const { chatInputState, ...props } = this.props;\nreturn (\n<KeyboardAvoidingView style={styles.keyboardAvoidingView}>\n- <ChatNavigator {...this.props} />\n+ <ChatNavigator {...props} />\n<MessageStorePruner />\n</KeyboardAvoidingView>\n);\n@@ -25,6 +163,11 @@ const styles = StyleSheet.create({\n},\n});\n-hoistNonReactStatics(Chat, ChatNavigator);\n+const ConnectedWrappedChatNavigator = withChatInputState(WrappedChatNavigator);\n+\n+function FinalChatNavigator(props: Props) {\n+ return <ConnectedWrappedChatNavigator {...props} />;\n+}\n+hoistNonReactStatics(FinalChatNavigator, ChatNavigator);\n-export default Chat;\n+export default FinalChatNavigator;\n" }, { "change_type": "MODIFY", "old_path": "native/flow-typed/npm/@react-navigation/core_v3.x.x.js", "new_path": "native/flow-typed/npm/@react-navigation/core_v3.x.x.js", "diff": "@@ -133,7 +133,7 @@ declare module '@react-navigation/core' {\n|};\ndeclare export type NavigationJumpToAction = {|\n- +type: 'Navigation/JUMP_TO';\n+ +type: 'Navigation/JUMP_TO',\n+preserveFocus: boolean,\n+routeName: string,\n+key?: string,\n@@ -260,6 +260,11 @@ declare module '@react-navigation/core' {\n* {routeName: 'Foo', key: '123'}\n*/\ngetScreenOptions: NavigationScreenOptionsGetter<Options>,\n+\n+ getActionCreators: (\n+ route: NavigationRoute,\n+ navStateKey: ?string,\n+ ) => { [name: string]: (...args: Array<any>) => any },\n};\ndeclare export type NavigationScreenOptions = {\n@@ -401,7 +406,7 @@ declare module '@react-navigation/core' {\n};\ndeclare export type NavigationNavigatorProps<O: {}, S: {}> = $Shape<{\n- navigation: NavigationScreenProp<S>,\n+ +navigation: NavigationScreenProp<S>,\nscreenProps?: NavigationScreenProps,\nnavigationOptions?: O,\ntheme?: SupportedThemes | 'no-preference',\n@@ -778,13 +783,19 @@ declare module '@react-navigation/core' {\ngetCurrentNavigation: () => ?NavigationScreenProp<State>\n): NavigationScreenProp<State>;\n- declare type _NavigationView<O, S, N: NavigationScreenProp<S>> = React$ComponentType<{\n+ declare type _NavigationViewProps<S, N: NavigationScreenProp<S>> = {\ndescriptors: { [key: string]: NavigationDescriptor },\n- navigation: N,\n+ +navigation: N,\nnavigationConfig: *,\n- }>;\n- declare export function createNavigator<O: *, S: *, NavigatorConfig: *, N: NavigationScreenProp<S>>(\n- view: _NavigationView<O, S, N>,\n+ };\n+ declare export function createNavigator<\n+ O: *,\n+ S: *,\n+ NavigatorConfig: *,\n+ N: NavigationScreenProp<S>,\n+ ViewProps: _NavigationViewProps<S, N>,\n+ >(\n+ view: React$ComponentType<ViewProps>,\nrouter: NavigationRouter<S, O>,\nnavigatorConfig?: NavigatorConfig\n): NavigationNavigator<S, O, *>;\n" }, { "change_type": "MODIFY", "old_path": "native/flow-typed/npm/react-navigation-stack_v1.x.x.js", "new_path": "native/flow-typed/npm/react-navigation-stack_v1.x.x.js", "diff": "@@ -133,7 +133,7 @@ declare module 'react-navigation-stack' {\n|};\ndeclare export type NavigationJumpToAction = {|\n- +type: 'Navigation/JUMP_TO';\n+ +type: 'Navigation/JUMP_TO',\n+preserveFocus: boolean,\n+routeName: string,\n+key?: string,\n@@ -260,6 +260,11 @@ declare module 'react-navigation-stack' {\n* {routeName: 'Foo', key: '123'}\n*/\ngetScreenOptions: NavigationScreenOptionsGetter<Options>,\n+\n+ getActionCreators: (\n+ route: NavigationRoute,\n+ navStateKey: ?string,\n+ ) => { [name: string]: (...args: Array<any>) => any },\n};\ndeclare export type NavigationScreenOptions = {\n@@ -401,7 +406,7 @@ declare module 'react-navigation-stack' {\n};\ndeclare export type NavigationNavigatorProps<O: {}, S: {}> = $Shape<{\n- navigation: NavigationScreenProp<S>,\n+ +navigation: NavigationScreenProp<S>,\nscreenProps?: NavigationScreenProps,\nnavigationOptions?: O,\ntheme?: SupportedThemes | 'no-preference',\n@@ -826,7 +831,7 @@ declare module 'react-navigation-stack' {\n};\ndeclare type _StackViewProps = {\n- navigation: NavigationStackProp<NavigationState>,\n+ +navigation: NavigationStackProp<NavigationState>,\ndescriptors: { [key: string]: NavigationDescriptor },\nnavigationConfig: NavigationStackViewConfig,\nonTransitionStart?: (\n" }, { "change_type": "MODIFY", "old_path": "native/flow-typed/npm/react-navigation-tabs_v2.x.x.js", "new_path": "native/flow-typed/npm/react-navigation-tabs_v2.x.x.js", "diff": "@@ -133,7 +133,7 @@ declare module 'react-navigation-tabs' {\n|};\ndeclare export type NavigationJumpToAction = {|\n- +type: 'Navigation/JUMP_TO';\n+ +type: 'Navigation/JUMP_TO',\n+preserveFocus: boolean,\n+routeName: string,\n+key?: string,\n@@ -260,6 +260,11 @@ declare module 'react-navigation-tabs' {\n* {routeName: 'Foo', key: '123'}\n*/\ngetScreenOptions: NavigationScreenOptionsGetter<Options>,\n+\n+ getActionCreators: (\n+ route: NavigationRoute,\n+ navStateKey: ?string,\n+ ) => { [name: string]: (...args: Array<any>) => any },\n};\ndeclare export type NavigationScreenOptions = {\n@@ -401,7 +406,7 @@ declare module 'react-navigation-tabs' {\n};\ndeclare export type NavigationNavigatorProps<O: {}, S: {}> = $Shape<{\n- navigation: NavigationScreenProp<S>,\n+ +navigation: NavigationScreenProp<S>,\nscreenProps?: NavigationScreenProps,\nnavigationOptions?: O,\ntheme?: SupportedThemes | 'no-preference',\n" }, { "change_type": "MODIFY", "old_path": "native/flow-typed/npm/react-navigation_v4.x.x.js", "new_path": "native/flow-typed/npm/react-navigation_v4.x.x.js", "diff": "@@ -133,7 +133,7 @@ declare module 'react-navigation' {\n|};\ndeclare export type NavigationJumpToAction = {|\n- +type: 'Navigation/JUMP_TO';\n+ +type: 'Navigation/JUMP_TO',\n+preserveFocus: boolean,\n+routeName: string,\n+key?: string,\n@@ -260,6 +260,11 @@ declare module 'react-navigation' {\n* {routeName: 'Foo', key: '123'}\n*/\ngetScreenOptions: NavigationScreenOptionsGetter<Options>,\n+\n+ getActionCreators: (\n+ route: NavigationRoute,\n+ navStateKey: ?string,\n+ ) => { [name: string]: (...args: Array<any>) => any },\n};\ndeclare export type NavigationScreenOptions = {\n@@ -401,7 +406,7 @@ declare module 'react-navigation' {\n};\ndeclare export type NavigationNavigatorProps<O: {}, S: {}> = $Shape<{\n- navigation: NavigationScreenProp<S>,\n+ +navigation: NavigationScreenProp<S>,\nscreenProps?: NavigationScreenProps,\nnavigationOptions?: O,\ntheme?: SupportedThemes | 'no-preference',\n@@ -778,13 +783,19 @@ declare module 'react-navigation' {\ngetCurrentNavigation: () => ?NavigationScreenProp<State>\n): NavigationScreenProp<State>;\n- declare type _NavigationView<O, S, N: NavigationScreenProp<S>> = React$ComponentType<{\n+ declare type _NavigationViewProps<S, N: NavigationScreenProp<S>> = {\ndescriptors: { [key: string]: NavigationDescriptor },\n- navigation: N,\n+ +navigation: N,\nnavigationConfig: *,\n- }>;\n- declare export function createNavigator<O: *, S: *, NavigatorConfig: *, N: NavigationScreenProp<S>>(\n- view: _NavigationView<O, S, N>,\n+ };\n+ declare export function createNavigator<\n+ O: *,\n+ S: *,\n+ NavigatorConfig: *,\n+ N: NavigationScreenProp<S>,\n+ ViewProps: _NavigationViewProps<S, N>,\n+ >(\n+ view: React$ComponentType<ViewProps>,\nrouter: NavigationRouter<S, O>,\nnavigatorConfig?: NavigatorConfig\n): NavigationNavigator<S, O, *>;\n@@ -940,7 +951,7 @@ declare module 'react-navigation' {\ndeclare export function createKeyboardAwareNavigator<Props: {}>(\nComp: React$ComponentType<Props>,\nstackConfig: {}\n- ): React$ComponentType<Props>;\n+ ): NavigationNavigator<NavigationState, *, Props>;\ndeclare type _InjectedOrientationProps = { isLandscape: boolean };\ndeclare export function withOrientation<P: _InjectedOrientationProps>(\n" }, { "change_type": "MODIFY", "old_path": "native/navigation/overlay-navigator.react.js", "new_path": "native/navigation/overlay-navigator.react.js", "diff": "@@ -21,6 +21,7 @@ import {\nimport { StackRouter, createNavigator, StackActions } from 'react-navigation';\nimport { Transitioner } from 'react-navigation-stack';\nimport Animated, { Easing } from 'react-native-reanimated';\n+import PropTypes from 'prop-types';\nconst OverlayPositionContext: React.Context<Animated.Value> = React.createContext(\nnull,\n@@ -49,6 +50,7 @@ function createOverlayNavigator(\nNavigationState,\nStackNavigatorConfig,\nNavigationStackProp<NavigationState>,\n+ OverlayNavigatorProps,\n>(\nOverlayNavigator,\nStackRouter(routeConfigMap, stackRouterConfig),\n@@ -56,12 +58,18 @@ function createOverlayNavigator(\n);\n}\n-type Props = $ReadOnly<{\n+type OverlayNavigatorProps = {\nnavigation: NavigationStackProp<NavigationState>,\ndescriptors: { [key: string]: NavigationDescriptor },\nnavigationConfig: StackNavigatorConfig,\n-}>;\n+};\n+type Props = $ReadOnly<OverlayNavigatorProps>;\nclass OverlayNavigator extends React.PureComponent<Props> {\n+ static propTypes = {\n+ navigation: PropTypes.object.isRequired,\n+ descriptors: PropTypes.object.isRequired,\n+ navigationConfig: PropTypes.object.isRequired,\n+ };\nposition: Animated.Value;\nconstructor(props: Props) {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Custom ChatRouter
129,187
28.03.2020 01:17:34
14,400
c3fdcf24e25322e22daac406a43d91985638a7af
[native] Get rid of messageSentFromRoute
[ { "change_type": "MODIFY", "old_path": "native/redux/persist.js", "new_path": "native/redux/persist.js", "diff": "@@ -22,7 +22,6 @@ import { defaultNotifPermissionAlertInfo } from '../push/alerts';\nconst baseBlacklist = [\n'loadingStatuses',\n'foreground',\n- 'messageSentFromRoute',\n'dimensions',\n'connectivity',\n'deviceOrientation',\n@@ -153,6 +152,10 @@ const migrations = {\n},\nqueuedReports: [],\n}),\n+ [16]: state => ({\n+ ...state,\n+ messageSentFromRoute: undefined,\n+ }),\n};\nconst persistConfig = {\n" }, { "change_type": "MODIFY", "old_path": "native/redux/redux-setup.js", "new_path": "native/redux/redux-setup.js", "diff": "@@ -11,7 +11,6 @@ import {\ntype NotifPermissionAlertInfo,\ndefaultNotifPermissionAlertInfo,\n} from '../push/alerts';\n-import type { NavigationStateRoute, NavigationRoute } from 'react-navigation';\nimport {\ntype CalendarFilter,\ndefaultCalendarFilters,\n@@ -50,7 +49,6 @@ import {\nimport Orientation from 'react-native-orientation-locker';\nimport baseReducer from 'lib/reducers/master-reducer';\n-import { sendTextMessageActionTypes } from 'lib/actions/message-actions';\nimport { reduxLoggerMiddleware } from 'lib/utils/redux-logger';\nimport { invalidSessionDowngrade } from 'lib/shared/account-utils';\nimport {\n@@ -75,8 +73,6 @@ import {\nimport {\ndefaultNavInfo,\nreduceNavInfo,\n- removeScreensFromStack,\n- replaceChatRoute,\nresetNavInfoAndEnsureLoggedOutModalPresence,\n} from '../navigation/navigation-setup';\nimport { reduceThreadIDsToNotifIDs } from '../push/reducer';\n@@ -86,12 +82,6 @@ import {\nnatServer,\nsetCustomServer,\n} from '../utils/url-utils';\n-import {\n- assertNavigationRouteNotLeafNode,\n- currentLeafRoute,\n- findRouteIndexWithKey,\n-} from '../utils/navigation-utils';\n-import { ComposeThreadRouteName } from '../navigation/route-names';\nimport reactotron from '../reactotron';\nimport reduceDrafts from '../reducers/draft-reducer';\n@@ -112,7 +102,6 @@ export type AppState = {|\ncustomServer: ?string,\nthreadIDsToNotifIDs: { [threadID: string]: string[] },\nnotifPermissionAlertInfo: NotifPermissionAlertInfo,\n- messageSentFromRoute: $ReadOnlyArray<string>,\nconnection: ConnectionInfo,\nwatchedThreadIDs: $ReadOnlyArray<string>,\nforeground: boolean,\n@@ -159,7 +148,6 @@ const defaultState = ({\ncustomServer: natServer,\nthreadIDsToNotifIDs: {},\nnotifPermissionAlertInfo: defaultNotifPermissionAlertInfo,\n- messageSentFromRoute: [],\nconnection: defaultConnectionInfo(Platform.OS),\nwatchedThreadIDs: [],\nforeground: true,\n@@ -174,13 +162,6 @@ const defaultState = ({\nfrozen: false,\n}: AppState);\n-function chatRouteFromNavInfo(navInfo: NavInfo): NavigationStateRoute {\n- const navState = navInfo.navigationState;\n- const appRoute = assertNavigationRouteNotLeafNode(navState.routes[0]);\n- const tabRoute = assertNavigationRouteNotLeafNode(appRoute.routes[0]);\n- return assertNavigationRouteNotLeafNode(tabRoute.routes[1]);\n-}\n-\nfunction reducer(state: AppState = defaultState, action: *) {\nif (\n(action.type === setNewSessionActionType &&\n@@ -278,20 +259,6 @@ function reducer(state: AppState = defaultState, action: *) {\nconst oldState = state;\n- if (action.type === sendTextMessageActionTypes.started) {\n- const chatRoute = chatRouteFromNavInfo(state.navInfo);\n- const currentChatSubroute = currentLeafRoute(chatRoute);\n- const messageSentFromRoute = state.messageSentFromRoute.includes(\n- currentChatSubroute.key,\n- )\n- ? state.messageSentFromRoute\n- : [...state.messageSentFromRoute, currentChatSubroute.key];\n- state = {\n- ...state,\n- messageSentFromRoute,\n- };\n- }\n-\nif (action.type === setNewSessionActionType) {\nstate = {\n...state,\n@@ -326,42 +293,8 @@ function reducer(state: AppState = defaultState, action: *) {\ndrafts: reduceDrafts(state.drafts, action),\n};\n- let navInfo = reduceNavInfo(state, action, state.threadStore.threadInfos);\n+ const navInfo = reduceNavInfo(state, action, state.threadStore.threadInfos);\nif (navInfo && navInfo !== state.navInfo) {\n- const chatRoute = chatRouteFromNavInfo(navInfo);\n- const currentChatSubroute = currentLeafRoute(chatRoute);\n- if (currentChatSubroute.routeName === ComposeThreadRouteName) {\n- const oldChatRoute = chatRouteFromNavInfo(state.navInfo);\n- const oldRouteIndex = findRouteIndexWithKey(\n- oldChatRoute,\n- currentChatSubroute.key,\n- );\n- const oldNextRoute = oldChatRoute.routes[oldRouteIndex + 1];\n- if (\n- oldNextRoute &&\n- state.messageSentFromRoute.includes(oldNextRoute.key)\n- ) {\n- // This indicates that the user went to the compose thread screen, then\n- // saw that a thread already existed for the people they wanted to\n- // contact, and sent a message to that thread. We are now about to\n- // navigate back to that compose thread screen, but instead, since the\n- // user's intent has ostensibly already been satisfied, we will pop up\n- // to the screen right before that one.\n- const replaceFunc = (inChatRoute: NavigationStateRoute) =>\n- removeScreensFromStack(inChatRoute, (route: NavigationRoute) =>\n- route.key === currentChatSubroute.key ? 'remove' : 'keep',\n- );\n- navInfo = {\n- startDate: navInfo.startDate,\n- endDate: navInfo.endDate,\n- navigationState: replaceChatRoute(\n- navInfo.navigationState,\n- replaceFunc,\n- ),\n- };\n- }\n- }\n-\nstate = { ...state, navInfo };\n}\n@@ -432,18 +365,6 @@ function validateState(\n};\n}\n- const chatRoute = chatRouteFromNavInfo(state.navInfo);\n- const chatSubrouteKeys = new Set(chatRoute.routes.map(route => route.key));\n- const messageSentFromRoute = state.messageSentFromRoute.filter(key =>\n- chatSubrouteKeys.has(key),\n- );\n- if (messageSentFromRoute.length !== state.messageSentFromRoute.length) {\n- state = {\n- ...state,\n- messageSentFromRoute,\n- };\n- }\n-\nif (\naction.type !== REHYDRATE &&\n(!state.currentUserInfo || state.currentUserInfo.anonymous)\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Get rid of messageSentFromRoute
129,187
28.03.2020 23:14:30
14,400
3006ff305bd8b584056dffceafe8898f07b0aa3f
[native] Use popToTop when resetting chat navigator on chat tab press
[ { "change_type": "MODIFY", "old_path": "native/chat/chat.react.js", "new_path": "native/chat/chat.react.js", "diff": "import * as React from 'react';\nimport {\n- type NavigationScreenProp,\n- type NavigationStateRoute,\ntype NavigationRouteConfigMap,\ntype NavigationState,\ncreateKeyboardAwareNavigator,\n@@ -108,7 +106,7 @@ ChatNavigator.navigationOptions = {\nnavigation,\ndefaultHandler,\n}: {\n- navigation: NavigationScreenProp<NavigationStateRoute>,\n+ navigation: NavigationProp,\ndefaultHandler: () => void,\n}) => {\nif (!navigation.isFocused()) {\n@@ -122,7 +120,7 @@ ChatNavigator.navigationOptions = {\nreturn;\n}\nif (chatScreen.canReset) {\n- navigation.goBack(state.routes[1].key);\n+ navigation.popToTop();\n}\n},\n};\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Use popToTop when resetting chat navigator on chat tab press
129,187
28.03.2020 23:10:45
14,400
a7e80e5b5ef29030cb464fad09c257204f905124
[native] Move navigation for push notifs to use navigation prop
[ { "change_type": "MODIFY", "old_path": "lib/shared/notif-utils.js", "new_path": "lib/shared/notif-utils.js", "diff": "@@ -7,7 +7,7 @@ import {\ntype MessageType,\nmessageTypes,\n} from '../types/message-types';\n-import type { ThreadInfo, RawThreadInfo } from '../types/thread-types';\n+import type { ThreadInfo } from '../types/thread-types';\nimport type { RelativeUserInfo } from '../types/user-types';\nimport invariant from 'invariant';\n@@ -20,13 +20,6 @@ import { pluralize } from '../utils/text-utils';\nimport { values } from '../utils/objects';\nimport { contentStringForMediaArray } from './media-utils';\n-const notificationPressActionType = 'NOTIFICATION_PRESS';\n-\n-export type NotificationPressPayload = {\n- rawThreadInfo: RawThreadInfo,\n- clearChatRoutes: boolean,\n-};\n-\ntype NotifTexts = {|\nmerged: string,\nbody: string,\n@@ -518,7 +511,6 @@ function mergePrefixIntoBody(unmerged: Unmerged): Merged {\n}\nexport {\n- notificationPressActionType,\nnotifTextsForMessageInfo,\nnotifCollapseKeyForRawMessageInfo,\nmergePrefixIntoBody,\n" }, { "change_type": "MODIFY", "old_path": "native/chat/chat-router.js", "new_path": "native/chat/chat-router.js", "diff": "// @flow\n+import type { ThreadInfo } from 'lib/types/thread-types';\n+\nimport {\nStackRouter,\n+ NavigationActions,\ntype NavigationAction,\ntype NavigationState,\ntype NavigationRoute,\n@@ -10,11 +13,20 @@ import {\n} from 'react-navigation';\nimport { removeScreensFromStack } from '../navigation/navigation-setup';\n+import {\n+ ChatThreadListRouteName,\n+ MessageListRouteName,\n+} from '../navigation/route-names';\ntype ClearScreensAction = {|\n+type: 'CLEAR_SCREENS',\n+routeNames: $ReadOnlyArray<string>,\n|};\n+type ReplaceWithThreadAction = {|\n+ +type: 'REPLACE_WITH_THREAD',\n+ +threadInfo: ThreadInfo,\n+|};\n+type CustomNavigationAction = ClearScreensAction | ReplaceWithThreadAction;\nconst defaultConfig = Object.freeze({});\nfunction ChatRouter(\n@@ -25,7 +37,7 @@ function ChatRouter(\nreturn {\n...stackRouter,\ngetStateForAction: (\n- action: NavigationAction | ClearScreensAction,\n+ action: NavigationAction | CustomNavigationAction,\nlastState: ?NavigationState,\n) => {\nif (action.type === 'CLEAR_SCREENS') {\n@@ -36,6 +48,22 @@ function ChatRouter(\nreturn removeScreensFromStack(lastState, (route: NavigationRoute) =>\nrouteNames.includes(route.routeName) ? 'remove' : 'keep',\n);\n+ } else if (action.type === 'REPLACE_WITH_THREAD') {\n+ const { threadInfo } = action;\n+ if (!lastState) {\n+ return lastState;\n+ }\n+ const clearedState = removeScreensFromStack(\n+ lastState,\n+ (route: NavigationRoute) =>\n+ route.routeName === ChatThreadListRouteName ? 'keep' : 'remove',\n+ );\n+ const navigateAction = NavigationActions.navigate({\n+ routeName: MessageListRouteName,\n+ key: `${MessageListRouteName}${threadInfo.id}`,\n+ params: { threadInfo },\n+ });\n+ return stackRouter.getStateForAction(navigateAction, clearedState);\n} else {\nreturn stackRouter.getStateForAction(action, lastState);\n}\n@@ -46,6 +74,10 @@ function ChatRouter(\ntype: 'CLEAR_SCREENS',\nrouteNames,\n}),\n+ replaceWithThread: (threadInfo: ThreadInfo) => ({\n+ type: 'REPLACE_WITH_THREAD',\n+ threadInfo,\n+ }),\n}),\n};\n}\n" }, { "change_type": "MODIFY", "old_path": "native/navigation/navigation-setup.js", "new_path": "native/navigation/navigation-setup.js", "diff": "@@ -15,7 +15,6 @@ import type {\n} from 'react-navigation-stack';\nimport type { AppState } from '../redux/redux-setup';\nimport type { SetSessionPayload } from 'lib/types/session-types';\n-import type { NotificationPressPayload } from 'lib/shared/notif-utils';\nimport type { AndroidNotificationActions } from '../push/reducer';\nimport type { UserInfo } from 'lib/types/user-types';\n@@ -30,6 +29,7 @@ import React from 'react';\nimport PropTypes from 'prop-types';\nimport { useScreens } from 'react-native-screens';\nimport hoistNonReactStatics from 'hoist-non-react-statics';\n+import { PersistGate } from 'redux-persist/integration/react';\nimport { infoFromURL } from 'lib/utils/url-utils';\nimport { fifteenDaysEarlier, fifteenDaysLater } from 'lib/utils/date-utils';\n@@ -45,7 +45,6 @@ import {\ndeleteThreadActionTypes,\nnewThreadActionTypes,\n} from 'lib/actions/thread-actions';\n-import { notificationPressActionType } from 'lib/shared/notif-utils';\nimport { threadInfoFromRawThreadInfo } from 'lib/shared/thread-utils';\nimport Calendar from '../calendar/calendar.react';\n@@ -109,6 +108,8 @@ import ThreadSettingsMemberTooltipModal from '../chat/settings/thread-settings-m\nimport CameraModal from '../media/camera-modal.react';\nimport TabBar from './tab-bar.react';\nimport { connectNav, type NavContextType } from './navigation-context';\n+import PushHandler from '../push/push-handler.react';\n+import { getPersistor } from '../redux/persist';\n// eslint-disable-next-line react-hooks/rules-of-hooks\nuseScreens();\n@@ -129,10 +130,6 @@ export type Action =\n| NavigationAction\n| {| type: 'HANDLE_URL', payload: string |}\n| {| type: 'NAVIGATE_TO_APP', payload: null |}\n- | {|\n- type: 'NOTIFICATION_PRESS',\n- payload: NotificationPressPayload,\n- |}\n| AndroidNotificationActions\n| {| type: 'RECORD_NOTIF_PERMISSION_ALERT', time: number |}\n| {| type: 'BACKGROUND' |}\n@@ -220,6 +217,9 @@ class WrappedAppNavigator extends React.PureComponent<WrappedAppNavigatorProps>\n<OverlayableScrollViewStateContainer>\n<KeyboardStateContainer>\n<AppNavigator navigation={this.props.navigation} />\n+ <PersistGate persistor={getPersistor()}>\n+ <PushHandler navigation={this.props.navigation} />\n+ </PersistGate>\n</KeyboardStateContainer>\n</OverlayableScrollViewStateContainer>\n</ChatInputStateContainer>\n@@ -430,17 +430,6 @@ function reduceNavInfo(\nstate.userInfos,\n),\n};\n- } else if (action.type === notificationPressActionType) {\n- return {\n- startDate: navInfoState.startDate,\n- endDate: navInfoState.endDate,\n- navigationState: handleNotificationPress(\n- navInfoState.navigationState,\n- action.payload,\n- state.currentUserInfo && state.currentUserInfo.id,\n- state.userInfos,\n- ),\n- };\n}\nreturn navInfoState;\n}\n@@ -733,134 +722,6 @@ function handleNewThread(\nreturn replaceChatRoute(state, replaceFunc);\n}\n-function replaceChatStackWithThread(\n- state: NavigationState,\n- rawThreadInfo: RawThreadInfo,\n- viewerID: ?string,\n- userInfos: { [id: string]: UserInfo },\n-): NavigationState {\n- const threadInfo = threadInfoFromRawThreadInfo(\n- rawThreadInfo,\n- viewerID,\n- userInfos,\n- );\n- const replaceFunc = (chatRoute: NavigationStateRoute) => {\n- const newChatRoute = removeScreensFromStack(\n- chatRoute,\n- (route: NavigationRoute) =>\n- route.routeName === ChatThreadListRouteName ? 'break' : 'remove',\n- );\n- const key =\n- `${MessageListRouteName}${threadInfo.id}:` +\n- getUniqueMessageListRouteKey();\n- return {\n- ...newChatRoute,\n- routes: [\n- ...newChatRoute.routes,\n- {\n- key,\n- routeName: MessageListRouteName,\n- params: { threadInfo },\n- },\n- ],\n- index: newChatRoute.routes.length,\n- };\n- };\n- return replaceChatRoute(state, replaceFunc);\n-}\n-\n-function handleNotificationPress(\n- state: NavigationState,\n- payload: NotificationPressPayload,\n- viewerID: ?string,\n- userInfos: { [id: string]: UserInfo },\n-): NavigationState {\n- const appRoute = assertNavigationRouteNotLeafNode(state.routes[0]);\n- const tabRoute = assertNavigationRouteNotLeafNode(appRoute.routes[0]);\n- const chatRoute = assertNavigationRouteNotLeafNode(tabRoute.routes[1]);\n-\n- const currentChatRoute = chatRoute.routes[chatRoute.index];\n- if (\n- state.index === 0 &&\n- appRoute.index === 0 &&\n- tabRoute.index === 1 &&\n- currentChatRoute.routeName === MessageListRouteName &&\n- getThreadIDFromParams(currentChatRoute) === payload.rawThreadInfo.id\n- ) {\n- return state;\n- }\n-\n- if (payload.clearChatRoutes) {\n- const replacedState = replaceChatStackWithThread(\n- state,\n- payload.rawThreadInfo,\n- viewerID,\n- userInfos,\n- );\n- const replacedAppRoute = assertNavigationRouteNotLeafNode(\n- replacedState.routes[0],\n- );\n- return {\n- ...replacedState,\n- index: 0,\n- routes: [\n- {\n- ...replacedState.routes[0],\n- index: 0,\n- routes: [\n- {\n- ...replacedAppRoute.routes[0],\n- index: 1,\n- },\n- ],\n- },\n- ],\n- isTransitioning: true,\n- };\n- }\n-\n- const threadInfo = threadInfoFromRawThreadInfo(\n- payload.rawThreadInfo,\n- viewerID,\n- userInfos,\n- );\n- const key =\n- `${MessageListRouteName}${threadInfo.id}:` + getUniqueMessageListRouteKey();\n- const newChatRoute = {\n- ...chatRoute,\n- routes: [\n- ...chatRoute.routes,\n- {\n- key,\n- routeName: MessageListRouteName,\n- params: { threadInfo },\n- },\n- ],\n- index: chatRoute.routes.length,\n- };\n-\n- const newTabRoutes = [...tabRoute.routes];\n- newTabRoutes[1] = newChatRoute;\n- return {\n- ...state,\n- index: 0,\n- routes: [\n- {\n- ...appRoute,\n- index: 0,\n- routes: [\n- {\n- ...tabRoute,\n- index: 1,\n- routes: newTabRoutes,\n- },\n- ],\n- },\n- ],\n- isTransitioning: true,\n- };\n-}\n-\nexport {\nRootNavigator,\ndefaultNavInfo,\n" }, { "change_type": "MODIFY", "old_path": "native/push/push-handler.react.js", "new_path": "native/push/push-handler.react.js", "diff": "@@ -6,10 +6,7 @@ import type {\nDispatchActionPayload,\nDispatchActionPromise,\n} from 'lib/utils/action-utils';\n-import {\n- type RawThreadInfo,\n- rawThreadInfoPropType,\n-} from 'lib/types/thread-types';\n+import { type ThreadInfo, threadInfoPropType } from 'lib/types/thread-types';\nimport {\ntype NotifPermissionAlertInfo,\nnotifPermissionAlertInfoPropType,\n@@ -20,6 +17,12 @@ import {\n} from 'lib/types/socket-types';\nimport type { RemoteMessage, NotificationOpen } from 'react-native-firebase';\nimport { type GlobalTheme, globalThemePropType } from '../types/themes';\n+import {\n+ type NavigationScreenProp,\n+ type NavigationState,\n+ type NavigationNavigateAction,\n+ NavigationActions,\n+} from 'react-navigation';\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\n@@ -38,15 +41,15 @@ import {\n} from 'react-native-in-app-message';\nimport { connect } from 'lib/utils/redux-utils';\n-import { unreadCount } from 'lib/selectors/thread-selectors';\n+import {\n+ unreadCount,\n+ threadInfoSelector,\n+} from 'lib/selectors/thread-selectors';\nimport {\nsetDeviceTokenActionTypes,\nsetDeviceToken,\n} from 'lib/actions/device-actions';\n-import {\n- notificationPressActionType,\n- mergePrefixIntoBody,\n-} from 'lib/shared/notif-utils';\n+import { mergePrefixIntoBody } from 'lib/shared/notif-utils';\nimport {\nrecordNotifPermissionAlertActionType,\n@@ -72,6 +75,12 @@ import {\nconnectNav,\ntype NavContextType,\n} from '../navigation/navigation-context';\n+import {\n+ withRootContext,\n+ type RootContextType,\n+ rootContextPropType,\n+} from '../root-context';\n+import { ChatRouteName, MessageListRouteName } from '../navigation/route-names';\nYellowBox.ignoreWarnings([\n'Require cycle: ../node_modules/react-native-firebase',\n@@ -82,13 +91,13 @@ const supportsTapticFeedback =\nPlatform.OS === 'ios' && parseInt(Platform.Version, 10) >= 10;\ntype Props = {\n- detectUnsupervisedBackground: ?(alreadyClosed: boolean) => boolean,\n+ navigation: NavigationScreenProp<NavigationState>,\n// Redux state\nunreadCount: number,\nactiveThread: ?string,\nappLoggedIn: boolean,\ndeviceToken: ?string,\n- rawThreadInfos: { [id: string]: RawThreadInfo },\n+ threadInfos: { [id: string]: ThreadInfo },\nnotifPermissionAlertInfo: NotifPermissionAlertInfo,\nconnection: ConnectionInfo,\nupdatesCurrentAsOf: number,\n@@ -101,6 +110,8 @@ type Props = {\ndeviceToken: string,\ndeviceType: DeviceType,\n) => Promise<string>,\n+ // withRootContext\n+ rootContext: ?RootContextType,\n};\ntype State = {|\ninAppNotifProps: ?{|\n@@ -111,12 +122,14 @@ type State = {|\n|};\nclass PushHandler extends React.PureComponent<Props, State> {\nstatic propTypes = {\n- detectUnsupervisedBackground: PropTypes.func,\n+ navigation: PropTypes.shape({\n+ navigate: PropTypes.func.isRequired,\n+ }).isRequired,\nunreadCount: PropTypes.number.isRequired,\nactiveThread: PropTypes.string,\nappLoggedIn: PropTypes.bool.isRequired,\ndeviceToken: PropTypes.string,\n- rawThreadInfos: PropTypes.objectOf(rawThreadInfoPropType).isRequired,\n+ threadInfos: PropTypes.objectOf(threadInfoPropType).isRequired,\nnotifPermissionAlertInfo: notifPermissionAlertInfoPropType.isRequired,\nconnection: connectionInfoPropType.isRequired,\nupdatesCurrentAsOf: PropTypes.number.isRequired,\n@@ -124,6 +137,7 @@ class PushHandler extends React.PureComponent<Props, State> {\ndispatchActionPayload: PropTypes.func.isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\nsetDeviceToken: PropTypes.func.isRequired,\n+ rootContext: rootContextPropType,\n};\nstate = {\ninAppNotifProps: null,\n@@ -248,9 +262,9 @@ class PushHandler extends React.PureComponent<Props, State> {\n}\nfor (let threadID of this.openThreadOnceReceived) {\n- const rawThreadInfo = this.props.rawThreadInfos[threadID];\n- if (rawThreadInfo) {\n- this.navigateToThread(rawThreadInfo, false);\n+ const threadInfo = this.props.threadInfos[threadID];\n+ if (threadInfo) {\n+ this.navigateToThread(threadInfo, false);\nthis.openThreadOnceReceived.clear();\nbreak;\n}\n@@ -439,17 +453,32 @@ class PushHandler extends React.PureComponent<Props, State> {\n}\n};\n- navigateToThread(rawThreadInfo: RawThreadInfo, clearChatRoutes: boolean) {\n- this.props.dispatchActionPayload(notificationPressActionType, {\n- rawThreadInfo,\n- clearChatRoutes,\n+ navigateToThread(threadInfo: ThreadInfo, clearChatRoutes: boolean) {\n+ if (clearChatRoutes) {\n+ const replaceAction: NavigationNavigateAction = ({\n+ type: 'REPLACE_WITH_THREAD',\n+ threadInfo,\n+ }: any);\n+ this.props.navigation.navigate({\n+ routeName: ChatRouteName,\n+ action: replaceAction,\n});\n+ } else {\n+ this.props.navigation.navigate({\n+ routeName: ChatRouteName,\n+ action: NavigationActions.navigate({\n+ routeName: MessageListRouteName,\n+ key: `${MessageListRouteName}${threadInfo.id}`,\n+ params: { threadInfo },\n+ }),\n+ });\n+ }\n}\nonPressNotificationForThread(threadID: string, clearChatRoutes: boolean) {\n- const rawThreadInfo = this.props.rawThreadInfos[threadID];\n- if (rawThreadInfo) {\n- this.navigateToThread(rawThreadInfo, clearChatRoutes);\n+ const threadInfo = this.props.threadInfos[threadID];\n+ if (threadInfo) {\n+ this.navigateToThread(threadInfo, clearChatRoutes);\n} else {\nthis.openThreadOnceReceived.add(threadID);\n}\n@@ -497,8 +526,8 @@ class PushHandler extends React.PureComponent<Props, State> {\n};\niosNotificationOpened = notification => {\n- if (this.props.detectUnsupervisedBackground) {\n- this.props.detectUnsupervisedBackground(false);\n+ if (this.props.rootContext) {\n+ this.props.rootContext.detectUnsupervisedBackground(false);\n}\nconst threadID = notification.getData().threadID;\nif (!threadID) {\n@@ -537,16 +566,16 @@ class PushHandler extends React.PureComponent<Props, State> {\n}\nandroidNotificationOpened = async (notificationOpen: NotificationOpen) => {\n- if (this.props.detectUnsupervisedBackground) {\n- this.props.detectUnsupervisedBackground(false);\n+ if (this.props.rootContext) {\n+ this.props.rootContext.detectUnsupervisedBackground(false);\n}\nconst { threadID } = notificationOpen.notification.data;\nthis.onPressNotificationForThread(threadID, true);\n};\nandroidMessageReceived = async (message: RemoteMessage) => {\n- if (this.props.detectUnsupervisedBackground) {\n- this.props.detectUnsupervisedBackground(false);\n+ if (this.props.rootContext) {\n+ this.props.rootContext.detectUnsupervisedBackground(false);\n}\nhandleAndroidMessage(\nmessage,\n@@ -584,12 +613,12 @@ export default connectNav((context: ?NavContextType) => ({\n(state: AppState) => ({\nunreadCount: unreadCount(state),\ndeviceToken: state.deviceToken,\n- rawThreadInfos: state.threadStore.threadInfos,\n+ threadInfos: threadInfoSelector(state),\nnotifPermissionAlertInfo: state.notifPermissionAlertInfo,\nconnection: state.connection,\nupdatesCurrentAsOf: state.updatesCurrentAsOf,\nactiveTheme: state.globalThemeInfo.activeTheme,\n}),\n{ setDeviceToken },\n- )(PushHandler),\n+ )(withRootContext(PushHandler)),\n);\n" }, { "change_type": "ADD", "old_path": null, "new_path": "native/root-context.js", "diff": "+// @flow\n+\n+import * as React from 'react';\n+import hoistNonReactStatics from 'hoist-non-react-statics';\n+import PropTypes from 'prop-types';\n+\n+export type RootContextType = {|\n+ detectUnsupervisedBackground: (alreadyClosed: boolean) => boolean,\n+|};\n+\n+const RootContext = React.createContext<?RootContextType>(null);\n+\n+function withRootContext<\n+ AllProps: {},\n+ ComponentType: React.ComponentType<AllProps>,\n+>(\n+ Component: ComponentType,\n+): React.ComponentType<\n+ $Diff<React.ElementConfig<ComponentType>, { rootContext: ?RootContextType }>,\n+> &\n+ ComponentType {\n+ function RootContextHOC(\n+ props: $Diff<\n+ React.ElementConfig<ComponentType>,\n+ { rootContext: ?RootContextType },\n+ >,\n+ ) {\n+ return (\n+ <RootContext.Consumer>\n+ {value => <Component {...props} rootContext={value} />}\n+ </RootContext.Consumer>\n+ );\n+ }\n+ const MemoizedRootContextHOC = React.memo(RootContextHOC);\n+ hoistNonReactStatics(MemoizedRootContextHOC, Component);\n+ // $FlowFixMe React.memo typing fixed in later version of Flow\n+ return MemoizedRootContextHOC;\n+}\n+\n+const rootContextPropType = PropTypes.shape({\n+ detectUnsupervisedBackground: PropTypes.func.isRequired,\n+});\n+\n+export { RootContext, withRootContext, rootContextPropType };\n" }, { "change_type": "MODIFY", "old_path": "native/root.react.js", "new_path": "native/root.react.js", "diff": "@@ -36,7 +36,6 @@ import ErrorBoundary from './error-boundary.react';\nimport DisconnectedBarVisibilityHandler from './navigation/disconnected-bar-visibility-handler.react';\nimport DimensionsUpdater from './redux/dimensions-updater.react';\nimport ConnectivityUpdater from './redux/connectivity-updater.react';\n-import PushHandler from './push/push-handler.react';\nimport ThemeHandler from './themes/theme-handler.react';\nimport OrientationHandler from './navigation/orientation-handler.react';\nimport Socket from './socket.react';\n@@ -46,6 +45,7 @@ import {\ntype NavContextType,\n} from './navigation/navigation-context';\nimport { setGlobalNavContext } from './navigation/icky-global';\n+import { RootContext, type RootContextType } from './root-context';\nif (Platform.OS === 'android') {\nUIManager.setLayoutAnimationEnabledExperimental &&\n@@ -65,8 +65,8 @@ type Props = {\ndispatchActionPayload: DispatchActionPayload,\n};\ntype State = {|\n- detectUnsupervisedBackground: ?(alreadyClosed: boolean) => boolean,\nnavContext: ?NavContextType,\n+ rootContext: ?RootContextType,\n|};\nclass Root extends React.PureComponent<Props, State> {\nstatic propTypes = {\n@@ -81,8 +81,8 @@ class Root extends React.PureComponent<Props, State> {\nsuper(props);\nconst navContext = { state: props.navigationState };\nthis.state = {\n- detectUnsupervisedBackground: null,\nnavContext,\n+ rootContext: null,\n};\nsetGlobalNavContext(navContext);\n}\n@@ -145,7 +145,6 @@ class Root extends React.PureComponent<Props, State> {\n};\nrender() {\n- const { detectUnsupervisedBackground } = this.state;\nconst { detectUnsupervisedBackgroundRef } = this;\nconst reactNavigationTheme = this.props.activeTheme\n? this.props.activeTheme\n@@ -158,9 +157,6 @@ class Root extends React.PureComponent<Props, State> {\n<DisconnectedBarVisibilityHandler />\n<DimensionsUpdater />\n<ConnectivityUpdater />\n- <PushHandler\n- detectUnsupervisedBackground={detectUnsupervisedBackground}\n- />\n<ThemeHandler />\n<OrientationHandler />\n</>\n@@ -168,6 +164,7 @@ class Root extends React.PureComponent<Props, State> {\nreturn (\n<View style={styles.app}>\n<NavContext.Provider value={this.state.navContext}>\n+ <RootContext.Provider value={this.state.rootContext}>\n<ConnectedStatusBar />\n<PersistGate persistor={getPersistor()}>{gated}</PersistGate>\n<ReduxifiedRootNavigator\n@@ -175,6 +172,7 @@ class Root extends React.PureComponent<Props, State> {\ndispatch={this.props.dispatch}\ntheme={reactNavigationTheme}\n/>\n+ </RootContext.Provider>\n</NavContext.Provider>\n</View>\n);\n@@ -183,7 +181,10 @@ class Root extends React.PureComponent<Props, State> {\ndetectUnsupervisedBackgroundRef = (\ndetectUnsupervisedBackground: ?(alreadyClosed: boolean) => boolean,\n) => {\n- this.setState({ detectUnsupervisedBackground });\n+ const rootContext = detectUnsupervisedBackground\n+ ? { detectUnsupervisedBackground }\n+ : null;\n+ this.setState({ rootContext });\n};\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Move navigation for push notifs to use navigation prop
129,187
30.03.2020 11:02:14
14,400
d5629b3a18fe49e21384a7f4093854691d48d231
[native] Include dispatch in NavigationContext
[ { "change_type": "MODIFY", "old_path": "native/navigation/navigation-context.js", "new_path": "native/navigation/navigation-context.js", "diff": "// @flow\n-import type { NavigationState } from 'react-navigation';\n+import type { NavigationState, NavigationDispatch } from 'react-navigation';\nimport * as React from 'react';\nimport hoistNonReactStatics from 'hoist-non-react-statics';\nexport type NavContextType = {|\nstate: NavigationState,\n+ dispatch: NavigationDispatch,\n|};\nconst NavContext = React.createContext<?NavContextType>(null);\n" }, { "change_type": "MODIFY", "old_path": "native/redux/redux-setup.js", "new_path": "native/redux/redux-setup.js", "diff": "@@ -308,9 +308,11 @@ function validateState(\n): AppState {\nconst oldActiveThread = activeThreadSelector({\nstate: oldState.navInfo.navigationState,\n+ dispatch: () => true,\n});\nconst activeThread = activeThreadSelector({\nstate: state.navInfo.navigationState,\n+ dispatch: () => true,\n});\nif (\nactiveThread &&\n" }, { "change_type": "MODIFY", "old_path": "native/root.react.js", "new_path": "native/root.react.js", "diff": "@@ -79,7 +79,10 @@ class Root extends React.PureComponent<Props, State> {\nconstructor(props: Props) {\nsuper(props);\n- const navContext = { state: props.navigationState };\n+ const navContext = {\n+ state: props.navigationState,\n+ dispatch: props.dispatch,\n+ };\nthis.state = {\nnavContext,\nrootContext: null,\n@@ -112,8 +115,14 @@ class Root extends React.PureComponent<Props, State> {\n}\ncomponentDidUpdate(prevProps: Props) {\n- if (this.props.navigationState !== prevProps.navigationState) {\n- const navContext = { state: this.props.navigationState };\n+ if (\n+ this.props.navigationState !== prevProps.navigationState ||\n+ this.props.dispatch !== prevProps.dispatch\n+ ) {\n+ const navContext = {\n+ state: this.props.navigationState,\n+ dispatch: this.props.dispatch,\n+ };\nthis.setState({ navContext });\nsetGlobalNavContext(navContext);\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Include dispatch in NavigationContext
129,187
30.03.2020 11:18:29
14,400
87133da00ada5c55c70b3c9d7c6cb1c84b88c0b8
[native] Avoid appLoggedIn in handlers We will be using Redux state instead, and setting up nav state to depend on Redux state
[ { "change_type": "MODIFY", "old_path": "native/push/push-handler.react.js", "new_path": "native/push/push-handler.react.js", "diff": "@@ -55,10 +55,7 @@ import {\nrecordNotifPermissionAlertActionType,\nclearAndroidNotificationsActionType,\n} from '../redux/action-types';\n-import {\n- activeThreadSelector,\n- appLoggedInSelector,\n-} from '../navigation/nav-selectors';\n+import { activeThreadSelector } from '../navigation/nav-selectors';\nimport {\nrequestIOSPushPermissions,\niosPushPermissionResponseReceived,\n@@ -92,16 +89,17 @@ const supportsTapticFeedback =\ntype Props = {\nnavigation: NavigationScreenProp<NavigationState>,\n+ // Navigation state\n+ activeThread: ?string,\n// Redux state\nunreadCount: number,\n- activeThread: ?string,\n- appLoggedIn: boolean,\ndeviceToken: ?string,\nthreadInfos: { [id: string]: ThreadInfo },\nnotifPermissionAlertInfo: NotifPermissionAlertInfo,\nconnection: ConnectionInfo,\nupdatesCurrentAsOf: number,\nactiveTheme: ?GlobalTheme,\n+ loggedIn: boolean,\n// Redux dispatch functions\ndispatchActionPayload: DispatchActionPayload,\ndispatchActionPromise: DispatchActionPromise,\n@@ -125,15 +123,15 @@ class PushHandler extends React.PureComponent<Props, State> {\nnavigation: PropTypes.shape({\nnavigate: PropTypes.func.isRequired,\n}).isRequired,\n- unreadCount: PropTypes.number.isRequired,\nactiveThread: PropTypes.string,\n- appLoggedIn: PropTypes.bool.isRequired,\n+ unreadCount: PropTypes.number.isRequired,\ndeviceToken: PropTypes.string,\nthreadInfos: PropTypes.objectOf(threadInfoPropType).isRequired,\nnotifPermissionAlertInfo: notifPermissionAlertInfoPropType.isRequired,\nconnection: connectionInfoPropType.isRequired,\nupdatesCurrentAsOf: PropTypes.number.isRequired,\nactiveTheme: globalThemePropType,\n+ loggedIn: PropTypes.bool.isRequired,\ndispatchActionPayload: PropTypes.func.isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\nsetDeviceToken: PropTypes.func.isRequired,\n@@ -239,7 +237,7 @@ class PushHandler extends React.PureComponent<Props, State> {\n};\nonForeground() {\n- if (this.props.appLoggedIn) {\n+ if (this.props.loggedIn) {\nthis.ensurePushNotifsEnabled();\n} else if (this.props.deviceToken) {\n// We do this in case there was a crash, so we can clear deviceToken from\n@@ -271,7 +269,7 @@ class PushHandler extends React.PureComponent<Props, State> {\n}\nif (\n- (this.props.appLoggedIn && !prevProps.appLoggedIn) ||\n+ (this.props.loggedIn && !prevProps.loggedIn) ||\n(!this.props.deviceToken && prevProps.deviceToken)\n) {\nthis.ensurePushNotifsEnabled();\n@@ -336,7 +334,7 @@ class PushHandler extends React.PureComponent<Props, State> {\n}\nasync ensurePushNotifsEnabled() {\n- if (!this.props.appLoggedIn) {\n+ if (!this.props.loggedIn) {\nreturn;\n}\nif (Platform.OS === 'ios') {\n@@ -409,7 +407,7 @@ class PushHandler extends React.PureComponent<Props, State> {\n}\nfailedToRegisterPushPermissions = () => {\n- if (!this.props.appLoggedIn) {\n+ if (!this.props.loggedIn) {\nreturn;\n}\nconst deviceType = Platform.OS;\n@@ -607,7 +605,6 @@ AppRegistry.registerHeadlessTask(\nexport default connectNav((context: ?NavContextType) => ({\nactiveThread: activeThreadSelector(context),\n- appLoggedIn: appLoggedInSelector(context),\n}))(\nconnect(\n(state: AppState) => ({\n@@ -618,6 +615,11 @@ export default connectNav((context: ?NavContextType) => ({\nconnection: state.connection,\nupdatesCurrentAsOf: state.updatesCurrentAsOf,\nactiveTheme: state.globalThemeInfo.activeTheme,\n+ loggedIn: !!(\n+ state.currentUserInfo &&\n+ !state.currentUserInfo.anonymous &&\n+ true\n+ ),\n}),\n{ setDeviceToken },\n)(withRootContext(PushHandler)),\n" }, { "change_type": "MODIFY", "old_path": "native/socket.react.js", "new_path": "native/socket.react.js", "diff": "@@ -15,7 +15,6 @@ import {\n} from './selectors/socket-selectors';\nimport {\nactiveThreadSelector,\n- appLoggedInSelector,\nnativeCalendarQuery,\n} from './navigation/nav-selectors';\nimport {\n@@ -24,7 +23,6 @@ import {\n} from './navigation/navigation-context';\nexport default connectNav((context: ?NavContextType) => ({\n- appLoggedIn: appLoggedInSelector(context),\nrawActiveThread: activeThreadSelector(context),\nnavContext: context,\n}))(\n@@ -32,13 +30,11 @@ export default connectNav((context: ?NavContextType) => ({\n(\nstate: AppState,\nownProps: {\n- appLoggedIn: boolean,\nrawActiveThread: boolean,\nnavContext: ?NavContextType,\n},\n) => {\nconst active =\n- ownProps.appLoggedIn &&\n!!state.currentUserInfo &&\n!state.currentUserInfo.anonymous &&\nstate.foreground;\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Avoid appLoggedIn in handlers We will be using Redux state instead, and setting up nav state to depend on Redux state
129,187
30.03.2020 14:32:40
14,400
81745318f0ce0dc34c21023497f356bd4f4a4f0c
[native] Extract AppNavigator, RootNavigator, and RootRouter
[ { "change_type": "MODIFY", "old_path": "native/chat/chat-router.js", "new_path": "native/chat/chat-router.js", "diff": "@@ -26,7 +26,10 @@ type ReplaceWithThreadAction = {|\n+type: 'REPLACE_WITH_THREAD',\n+threadInfo: ThreadInfo,\n|};\n-type CustomNavigationAction = ClearScreensAction | ReplaceWithThreadAction;\n+export type ChatRouterNavigationAction =\n+ | NavigationAction\n+ | ClearScreensAction\n+ | ReplaceWithThreadAction;\nconst defaultConfig = Object.freeze({});\nfunction ChatRouter(\n@@ -37,7 +40,7 @@ function ChatRouter(\nreturn {\n...stackRouter,\ngetStateForAction: (\n- action: NavigationAction | CustomNavigationAction,\n+ action: ChatRouterNavigationAction,\nlastState: ?NavigationState,\n) => {\nif (action.type === 'CLEAR_SCREENS') {\n" }, { "change_type": "ADD", "old_path": null, "new_path": "native/navigation/app-navigator.react.js", "diff": "+// @flow\n+\n+import type { NavigationStackProp } from 'react-navigation-stack';\n+import type { NavigationStateRoute } from 'react-navigation';\n+\n+import * as React from 'react';\n+import PropTypes from 'prop-types';\n+import { createBottomTabNavigator } from 'react-navigation-tabs';\n+import hoistNonReactStatics from 'hoist-non-react-statics';\n+import { PersistGate } from 'redux-persist/integration/react';\n+import { BackHandler } from 'react-native';\n+\n+import {\n+ CalendarRouteName,\n+ ChatRouteName,\n+ MoreRouteName,\n+ TabNavigatorRouteName,\n+ MultimediaModalRouteName,\n+ MultimediaTooltipModalRouteName,\n+ ActionResultModalRouteName,\n+ TextMessageTooltipModalRouteName,\n+ ThreadSettingsMemberTooltipModalRouteName,\n+ CameraModalRouteName,\n+} from './route-names';\n+import Calendar from '../calendar/calendar.react';\n+import Chat from '../chat/chat.react';\n+import More from '../more/more.react';\n+import TabBar from './tab-bar.react';\n+import { createOverlayNavigator } from './overlay-navigator.react';\n+import MultimediaModal from '../media/multimedia-modal.react';\n+import { MultimediaTooltipModal } from '../chat/multimedia-tooltip-modal.react';\n+import ActionResultModal from './action-result-modal.react';\n+import { TextMessageTooltipModal } from '../chat/text-message-tooltip-modal.react';\n+import ThreadSettingsMemberTooltipModal from '../chat/settings/thread-settings-member-tooltip-modal.react';\n+import CameraModal from '../media/camera-modal.react';\n+import ChatInputStateContainer from '../chat/chat-input-state-container.react';\n+import OverlayableScrollViewStateContainer from './overlayable-scroll-view-state-container.react';\n+import KeyboardStateContainer from '../keyboard/keyboard-state-container.react';\n+import PushHandler from '../push/push-handler.react';\n+import { getPersistor } from '../redux/persist';\n+import { connectNav, type NavContextType } from './navigation-context';\n+import {\n+ appLoggedInSelector,\n+ appCanRespondToBackButtonSelector,\n+} from './nav-selectors';\n+\n+const TabNavigator = createBottomTabNavigator(\n+ {\n+ [CalendarRouteName]: { screen: Calendar },\n+ [ChatRouteName]: { screen: Chat },\n+ [MoreRouteName]: { screen: More },\n+ },\n+ {\n+ initialRouteName: CalendarRouteName,\n+ lazy: false,\n+ tabBarComponent: TabBar,\n+ tabBarOptions: {\n+ keyboardHidesTabBar: false,\n+ },\n+ },\n+);\n+\n+const AppNavigator = createOverlayNavigator({\n+ [TabNavigatorRouteName]: TabNavigator,\n+ [MultimediaModalRouteName]: MultimediaModal,\n+ [MultimediaTooltipModalRouteName]: MultimediaTooltipModal,\n+ [ActionResultModalRouteName]: ActionResultModal,\n+ [TextMessageTooltipModalRouteName]: TextMessageTooltipModal,\n+ [ThreadSettingsMemberTooltipModalRouteName]: ThreadSettingsMemberTooltipModal,\n+ [CameraModalRouteName]: CameraModal,\n+});\n+\n+type WrappedAppNavigatorProps = {|\n+ navigation: NavigationStackProp<NavigationStateRoute>,\n+ isForeground: boolean,\n+ appCanRespondToBackButton: boolean,\n+|};\n+class WrappedAppNavigator extends React.PureComponent<WrappedAppNavigatorProps> {\n+ static propTypes = {\n+ navigation: PropTypes.shape({\n+ goBack: PropTypes.func.isRequired,\n+ }).isRequired,\n+ isForeground: PropTypes.bool.isRequired,\n+ appCanRespondToBackButton: PropTypes.bool.isRequired,\n+ };\n+\n+ componentDidMount() {\n+ if (this.props.isForeground) {\n+ this.onForeground();\n+ }\n+ }\n+\n+ componentWillUnmount() {\n+ if (this.props.isForeground) {\n+ this.onBackground();\n+ }\n+ }\n+\n+ componentDidUpdate(prevProps: WrappedAppNavigatorProps) {\n+ if (this.props.isForeground && !prevProps.isForeground) {\n+ this.onForeground();\n+ } else if (!this.props.isForeground && prevProps.isForeground) {\n+ this.onBackground();\n+ }\n+ }\n+\n+ onForeground() {\n+ BackHandler.addEventListener('hardwareBackPress', this.hardwareBack);\n+ }\n+\n+ onBackground() {\n+ BackHandler.removeEventListener('hardwareBackPress', this.hardwareBack);\n+ }\n+\n+ hardwareBack = () => {\n+ if (!this.props.appCanRespondToBackButton) {\n+ return false;\n+ }\n+ this.props.navigation.goBack(null);\n+ return true;\n+ };\n+\n+ render() {\n+ return (\n+ <ChatInputStateContainer>\n+ <OverlayableScrollViewStateContainer>\n+ <KeyboardStateContainer>\n+ <AppNavigator navigation={this.props.navigation} />\n+ <PersistGate persistor={getPersistor()}>\n+ <PushHandler navigation={this.props.navigation} />\n+ </PersistGate>\n+ </KeyboardStateContainer>\n+ </OverlayableScrollViewStateContainer>\n+ </ChatInputStateContainer>\n+ );\n+ }\n+}\n+\n+const ReduxWrappedAppNavigator = connectNav((context: ?NavContextType) => ({\n+ appCanRespondToBackButton: appCanRespondToBackButtonSelector(context),\n+ isForeground: appLoggedInSelector(context),\n+}))(WrappedAppNavigator);\n+hoistNonReactStatics(ReduxWrappedAppNavigator, AppNavigator);\n+\n+export default ReduxWrappedAppNavigator;\n" }, { "change_type": "MODIFY", "old_path": "native/navigation/navigation-setup.js", "new_path": "native/navigation/navigation-setup.js", "diff": "@@ -9,27 +9,14 @@ import type {\nNavigationRoute,\nNavigationStateRoute,\n} from 'react-navigation';\n-import type {\n- NavigationStackProp,\n- NavigationStackTransitionProps,\n-} from 'react-navigation-stack';\nimport type { AppState } from '../redux/redux-setup';\nimport type { SetSessionPayload } from 'lib/types/session-types';\nimport type { AndroidNotificationActions } from '../push/reducer';\nimport type { UserInfo } from 'lib/types/user-types';\n-import { createBottomTabNavigator } from 'react-navigation-tabs';\n-import {\n- createStackNavigator,\n- StackViewTransitionConfigs,\n-} from 'react-navigation-stack';\nimport invariant from 'invariant';\n-import { Alert, BackHandler, Platform, Keyboard } from 'react-native';\n-import React from 'react';\n-import PropTypes from 'prop-types';\n+import { Alert, Platform } from 'react-native';\nimport { useScreens } from 'react-native-screens';\n-import hoistNonReactStatics from 'hoist-non-react-statics';\n-import { PersistGate } from 'redux-persist/integration/react';\nimport { infoFromURL } from 'lib/utils/url-utils';\nimport { fifteenDaysEarlier, fifteenDaysLater } from 'lib/utils/date-utils';\n@@ -47,15 +34,6 @@ import {\n} from 'lib/actions/thread-actions';\nimport { threadInfoFromRawThreadInfo } from 'lib/shared/thread-utils';\n-import Calendar from '../calendar/calendar.react';\n-import Chat from '../chat/chat.react';\n-import More from '../more/more.react';\n-import LoggedOutModal from '../account/logged-out-modal.react';\n-import VerificationModal from '../account/verification-modal.react';\n-import {\n- appLoggedInSelector,\n- appCanRespondToBackButtonSelector,\n-} from './nav-selectors';\nimport {\nassertNavigationRouteNotLeafNode,\ngetThreadIDFromParams,\n@@ -74,42 +52,13 @@ import {\nChatRouteName,\nChatThreadListRouteName,\nCalendarRouteName,\n- ThreadPickerModalRouteName,\n- AddUsersModalRouteName,\n- CustomServerModalRouteName,\n- ColorPickerModalRouteName,\n- ComposeSubthreadModalRouteName,\n- MultimediaModalRouteName,\n- MultimediaTooltipModalRouteName,\n- ActionResultModalRouteName,\n- TextMessageTooltipModalRouteName,\n- ThreadSettingsMemberTooltipModalRouteName,\n- CameraModalRouteName,\naccountModals,\n} from './route-names';\nimport {\nhandleURLActionType,\nnavigateToAppActionType,\n} from '../redux/action-types';\n-import ThreadPickerModal from '../calendar/thread-picker-modal.react';\n-import AddUsersModal from '../chat/settings/add-users-modal.react';\n-import CustomServerModal from '../more/custom-server-modal.react';\n-import ColorPickerModal from '../chat/settings/color-picker-modal.react';\n-import ComposeSubthreadModal from '../chat/settings/compose-subthread-modal.react';\n-import { createOverlayNavigator } from './overlay-navigator.react';\n-import MultimediaModal from '../media/multimedia-modal.react';\n-import { MultimediaTooltipModal } from '../chat/multimedia-tooltip-modal.react';\n-import ChatInputStateContainer from '../chat/chat-input-state-container.react';\n-import OverlayableScrollViewStateContainer from './overlayable-scroll-view-state-container.react';\n-import KeyboardStateContainer from '../keyboard/keyboard-state-container.react';\n-import ActionResultModal from './action-result-modal.react';\n-import { TextMessageTooltipModal } from '../chat/text-message-tooltip-modal.react';\n-import ThreadSettingsMemberTooltipModal from '../chat/settings/thread-settings-member-tooltip-modal.react';\n-import CameraModal from '../media/camera-modal.react';\n-import TabBar from './tab-bar.react';\n-import { connectNav, type NavContextType } from './navigation-context';\n-import PushHandler from '../push/push-handler.react';\n-import { getPersistor } from '../redux/persist';\n+import RootNavigator from './root-navigator.react';\n// eslint-disable-next-line react-hooks/rules-of-hooks\nuseScreens();\n@@ -135,177 +84,6 @@ export type Action =\n| {| type: 'BACKGROUND' |}\n| {| type: 'FOREGROUND' |};\n-const TabNavigator = createBottomTabNavigator(\n- {\n- [CalendarRouteName]: { screen: Calendar },\n- [ChatRouteName]: { screen: Chat },\n- [MoreRouteName]: { screen: More },\n- },\n- {\n- initialRouteName: CalendarRouteName,\n- lazy: false,\n- tabBarComponent: TabBar,\n- tabBarOptions: {\n- keyboardHidesTabBar: false,\n- },\n- },\n-);\n-\n-const AppNavigator = createOverlayNavigator({\n- [TabNavigatorRouteName]: TabNavigator,\n- [MultimediaModalRouteName]: MultimediaModal,\n- [MultimediaTooltipModalRouteName]: MultimediaTooltipModal,\n- [ActionResultModalRouteName]: ActionResultModal,\n- [TextMessageTooltipModalRouteName]: TextMessageTooltipModal,\n- [ThreadSettingsMemberTooltipModalRouteName]: ThreadSettingsMemberTooltipModal,\n- [CameraModalRouteName]: CameraModal,\n-});\n-\n-type WrappedAppNavigatorProps = {|\n- navigation: NavigationStackProp<NavigationStateRoute>,\n- isForeground: boolean,\n- appCanRespondToBackButton: boolean,\n-|};\n-class WrappedAppNavigator extends React.PureComponent<WrappedAppNavigatorProps> {\n- static propTypes = {\n- navigation: PropTypes.shape({\n- goBack: PropTypes.func.isRequired,\n- }).isRequired,\n- isForeground: PropTypes.bool.isRequired,\n- appCanRespondToBackButton: PropTypes.bool.isRequired,\n- };\n-\n- componentDidMount() {\n- if (this.props.isForeground) {\n- this.onForeground();\n- }\n- }\n-\n- componentWillUnmount() {\n- if (this.props.isForeground) {\n- this.onBackground();\n- }\n- }\n-\n- componentDidUpdate(prevProps: WrappedAppNavigatorProps) {\n- if (this.props.isForeground && !prevProps.isForeground) {\n- this.onForeground();\n- } else if (!this.props.isForeground && prevProps.isForeground) {\n- this.onBackground();\n- }\n- }\n-\n- onForeground() {\n- BackHandler.addEventListener('hardwareBackPress', this.hardwareBack);\n- }\n-\n- onBackground() {\n- BackHandler.removeEventListener('hardwareBackPress', this.hardwareBack);\n- }\n-\n- hardwareBack = () => {\n- if (!this.props.appCanRespondToBackButton) {\n- return false;\n- }\n- this.props.navigation.goBack(null);\n- return true;\n- };\n-\n- render() {\n- return (\n- <ChatInputStateContainer>\n- <OverlayableScrollViewStateContainer>\n- <KeyboardStateContainer>\n- <AppNavigator navigation={this.props.navigation} />\n- <PersistGate persistor={getPersistor()}>\n- <PushHandler navigation={this.props.navigation} />\n- </PersistGate>\n- </KeyboardStateContainer>\n- </OverlayableScrollViewStateContainer>\n- </ChatInputStateContainer>\n- );\n- }\n-}\n-\n-const ReduxWrappedAppNavigator = connectNav((context: ?NavContextType) => ({\n- appCanRespondToBackButton: appCanRespondToBackButtonSelector(context),\n- isForeground: appLoggedInSelector(context),\n-}))(WrappedAppNavigator);\n-hoistNonReactStatics(ReduxWrappedAppNavigator, AppNavigator);\n-\n-const RootNavigator = createStackNavigator(\n- {\n- [LoggedOutModalRouteName]: LoggedOutModal,\n- [VerificationModalRouteName]: VerificationModal,\n- [AppRouteName]: ReduxWrappedAppNavigator,\n- [ThreadPickerModalRouteName]: ThreadPickerModal,\n- [AddUsersModalRouteName]: AddUsersModal,\n- [CustomServerModalRouteName]: CustomServerModal,\n- [ColorPickerModalRouteName]: ColorPickerModal,\n- [ComposeSubthreadModalRouteName]: ComposeSubthreadModal,\n- },\n- {\n- headerMode: 'none',\n- mode: 'modal',\n- transparentCard: true,\n- disableKeyboardHandling: true,\n- onTransitionStart: (\n- transitionProps: NavigationStackTransitionProps,\n- prevTransitionProps: ?NavigationStackTransitionProps,\n- ) => {\n- if (!prevTransitionProps) {\n- return;\n- }\n- const { scene } = transitionProps;\n- const { route } = scene;\n- const { scene: prevScene } = prevTransitionProps;\n- const { route: prevRoute } = prevScene;\n- if (route.key === prevRoute.key) {\n- return;\n- }\n- if (\n- route.routeName !== AppRouteName ||\n- prevRoute.routeName !== ThreadPickerModalRouteName\n- ) {\n- Keyboard.dismiss();\n- }\n- },\n- transitionConfig: (\n- transitionProps: NavigationStackTransitionProps,\n- prevTransitionProps: ?NavigationStackTransitionProps,\n- isModal: boolean,\n- ) => {\n- const defaultConfig = StackViewTransitionConfigs.defaultTransitionConfig(\n- transitionProps,\n- prevTransitionProps,\n- isModal,\n- );\n- return {\n- ...defaultConfig,\n- screenInterpolator: sceneProps => {\n- const {\n- opacity: defaultOpacity,\n- ...defaultInterpolation\n- } = defaultConfig.screenInterpolator(sceneProps);\n- const { position, scene } = sceneProps;\n- const { index, route } = scene;\n- if (\n- accountModals.includes(route.routeName) ||\n- route.routeName === AppRouteName\n- ) {\n- return defaultInterpolation;\n- }\n- const opacity = position.interpolate({\n- inputRange: [index - 1, index],\n- outputRange: ([0, 1]: number[]),\n- });\n- return { ...defaultInterpolation, opacity };\n- },\n- };\n- },\n- },\n-);\n-\nconst defaultNavigationState = {\nindex: 1,\nroutes: [\n@@ -723,7 +501,6 @@ function handleNewThread(\n}\nexport {\n- RootNavigator,\ndefaultNavInfo,\nreduceNavInfo,\nremoveScreensFromStack,\n" }, { "change_type": "ADD", "old_path": null, "new_path": "native/navigation/root-navigator.react.js", "diff": "+// @flow\n+\n+import * as React from 'react';\n+import {\n+ type NavigationRouteConfigMap,\n+ type NavigationState,\n+ createNavigator,\n+} from 'react-navigation';\n+import {\n+ StackView,\n+ StackViewTransitionConfigs,\n+ type StackNavigatorConfig,\n+ type NavigationStackScreenOptions,\n+ type NavigationStackProp,\n+ type NavigationStackTransitionProps,\n+} from 'react-navigation-stack';\n+import { Keyboard } from 'react-native';\n+\n+import {\n+ LoggedOutModalRouteName,\n+ VerificationModalRouteName,\n+ AppRouteName,\n+ ThreadPickerModalRouteName,\n+ AddUsersModalRouteName,\n+ CustomServerModalRouteName,\n+ ColorPickerModalRouteName,\n+ ComposeSubthreadModalRouteName,\n+ accountModals,\n+} from './route-names';\n+import LoggedOutModal from '../account/logged-out-modal.react';\n+import VerificationModal from '../account/verification-modal.react';\n+import AppNavigator from './app-navigator.react';\n+import ThreadPickerModal from '../calendar/thread-picker-modal.react';\n+import AddUsersModal from '../chat/settings/add-users-modal.react';\n+import CustomServerModal from '../more/custom-server-modal.react';\n+import ColorPickerModal from '../chat/settings/color-picker-modal.react';\n+import ComposeSubthreadModal from '../chat/settings/compose-subthread-modal.react';\n+import RootRouter from './root-router';\n+\n+type NavigationProp = NavigationStackProp<NavigationState> & {\n+ logIn: () => void,\n+ logOut: () => void,\n+};\n+type StackViewProps = React.ElementConfig<typeof StackView> & {\n+ +navigation: NavigationProp,\n+};\n+\n+function createRootNavigator(\n+ routeConfigMap: NavigationRouteConfigMap,\n+ stackConfig?: StackNavigatorConfig = {},\n+) {\n+ const {\n+ initialRouteName,\n+ initialRouteParams,\n+ paths,\n+ navigationOptions,\n+ defaultNavigationOptions,\n+ initialRouteKey,\n+ ...navigatorConfig\n+ } = stackConfig;\n+ const routerConfig = {\n+ initialRouteName,\n+ initialRouteParams,\n+ paths,\n+ navigationOptions,\n+ defaultNavigationOptions,\n+ initialRouteKey,\n+ };\n+ return createNavigator<\n+ NavigationStackScreenOptions,\n+ NavigationState,\n+ StackNavigatorConfig,\n+ NavigationProp,\n+ StackViewProps,\n+ >(StackView, RootRouter(routeConfigMap, routerConfig), navigatorConfig);\n+}\n+\n+const RootNavigator = createRootNavigator(\n+ {\n+ [LoggedOutModalRouteName]: LoggedOutModal,\n+ [VerificationModalRouteName]: VerificationModal,\n+ [AppRouteName]: AppNavigator,\n+ [ThreadPickerModalRouteName]: ThreadPickerModal,\n+ [AddUsersModalRouteName]: AddUsersModal,\n+ [CustomServerModalRouteName]: CustomServerModal,\n+ [ColorPickerModalRouteName]: ColorPickerModal,\n+ [ComposeSubthreadModalRouteName]: ComposeSubthreadModal,\n+ },\n+ {\n+ headerMode: 'none',\n+ mode: 'modal',\n+ transparentCard: true,\n+ disableKeyboardHandling: true,\n+ onTransitionStart: (\n+ transitionProps: NavigationStackTransitionProps,\n+ prevTransitionProps: ?NavigationStackTransitionProps,\n+ ) => {\n+ if (!prevTransitionProps) {\n+ return;\n+ }\n+ const { scene } = transitionProps;\n+ const { route } = scene;\n+ const { scene: prevScene } = prevTransitionProps;\n+ const { route: prevRoute } = prevScene;\n+ if (route.key === prevRoute.key) {\n+ return;\n+ }\n+ if (\n+ route.routeName !== AppRouteName ||\n+ prevRoute.routeName !== ThreadPickerModalRouteName\n+ ) {\n+ Keyboard.dismiss();\n+ }\n+ },\n+ transitionConfig: (\n+ transitionProps: NavigationStackTransitionProps,\n+ prevTransitionProps: ?NavigationStackTransitionProps,\n+ isModal: boolean,\n+ ) => {\n+ const defaultConfig = StackViewTransitionConfigs.defaultTransitionConfig(\n+ transitionProps,\n+ prevTransitionProps,\n+ isModal,\n+ );\n+ return {\n+ ...defaultConfig,\n+ screenInterpolator: sceneProps => {\n+ const {\n+ opacity: defaultOpacity,\n+ ...defaultInterpolation\n+ } = defaultConfig.screenInterpolator(sceneProps);\n+ const { position, scene } = sceneProps;\n+ const { index, route } = scene;\n+ if (\n+ accountModals.includes(route.routeName) ||\n+ route.routeName === AppRouteName\n+ ) {\n+ return defaultInterpolation;\n+ }\n+ const opacity = position.interpolate({\n+ inputRange: [index - 1, index],\n+ outputRange: ([0, 1]: number[]),\n+ });\n+ return { ...defaultInterpolation, opacity };\n+ },\n+ };\n+ },\n+ },\n+);\n+\n+export default RootNavigator;\n" }, { "change_type": "ADD", "old_path": null, "new_path": "native/navigation/root-router.js", "diff": "+// @flow\n+\n+import {\n+ StackRouter,\n+ type NavigationAction,\n+ type NavigationState,\n+ type NavigationRouteConfigMap,\n+ type NavigationStackRouterConfig,\n+} from 'react-navigation';\n+\n+type LogInAction = {|\n+ +type: 'LOG_IN',\n+|};\n+type LogOutAction = {|\n+ +type: 'LOG_OUT',\n+|};\n+export type RootRouterNavigationAction =\n+ | NavigationAction\n+ | LogInAction\n+ | LogOutAction;\n+\n+const defaultConfig = Object.freeze({});\n+function RootRouter(\n+ routeConfigMap: NavigationRouteConfigMap,\n+ stackConfig?: NavigationStackRouterConfig = defaultConfig,\n+) {\n+ const stackRouter = StackRouter(routeConfigMap, stackConfig);\n+ return {\n+ ...stackRouter,\n+ getStateForAction: (\n+ action: RootRouterNavigationAction,\n+ lastState: ?NavigationState,\n+ ) => {\n+ if (action.type === 'LOG_IN') {\n+ return lastState;\n+ } else if (action.type === 'LOG_OUT') {\n+ return lastState;\n+ } else {\n+ return stackRouter.getStateForAction(action, lastState);\n+ }\n+ },\n+ };\n+}\n+\n+export default RootRouter;\n" }, { "change_type": "MODIFY", "old_path": "native/root.react.js", "new_path": "native/root.react.js", "diff": "@@ -28,7 +28,7 @@ import {\nforegroundActionType,\n} from 'lib/reducers/foreground-reducer';\n-import { RootNavigator } from './navigation/navigation-setup';\n+import RootNavigator from './navigation/root-navigator.react';\nimport { handleURLActionType } from './redux/action-types';\nimport { store, appBecameInactive } from './redux/redux-setup';\nimport ConnectedStatusBar from './connected-status-bar.react';\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Extract AppNavigator, RootNavigator, and RootRouter
129,187
30.03.2020 14:46:29
14,400
8d65d535052ed11a43a484424c94c8e0e08fbcb8
[native] NavigationHandler
[ { "change_type": "MODIFY", "old_path": "native/navigation/navigation-context.js", "new_path": "native/navigation/navigation-context.js", "diff": "// @flow\n-import type { NavigationState, NavigationDispatch } from 'react-navigation';\n+import type { NavigationState, NavigationAction } from 'react-navigation';\n+import type { RootRouterNavigationAction } from './root-router';\n+import type { ChatRouterNavigationAction } from '../chat/chat-router';\nimport * as React from 'react';\nimport hoistNonReactStatics from 'hoist-non-react-statics';\n+export type NavAction =\n+ | NavigationAction\n+ | RootRouterNavigationAction\n+ | ChatRouterNavigationAction;\nexport type NavContextType = {|\nstate: NavigationState,\n- dispatch: NavigationDispatch,\n+ dispatch: (action: NavAction) => boolean,\n|};\nconst NavContext = React.createContext<?NavContextType>(null);\n" }, { "change_type": "ADD", "old_path": null, "new_path": "native/navigation/navigation-handler.react.js", "diff": "+// @flow\n+\n+import type { AppState } from '../redux/redux-setup';\n+\n+import * as React from 'react';\n+\n+import { connect } from 'lib/utils/redux-utils';\n+\n+import {\n+ NavContext,\n+ connectNav,\n+ type NavContextType,\n+} from './navigation-context';\n+import { appLoggedInSelector } from './nav-selectors';\n+\n+type Props = {|\n+ // Navigation state\n+ navLoggedIn: boolean,\n+ // Redux state\n+ loggedIn: boolean,\n+|};\n+function NavigationHandler(props: Props) {\n+ const { navLoggedIn, loggedIn } = props;\n+\n+ const navContext = React.useContext(NavContext);\n+\n+ const prevLoggedIn = React.useRef();\n+\n+ React.useEffect(() => {\n+ if (!navContext) {\n+ return;\n+ }\n+ if (loggedIn && !prevLoggedIn.current && !navLoggedIn) {\n+ navContext.dispatch({ type: 'LOG_IN' });\n+ } else if (!loggedIn && prevLoggedIn.current && navLoggedIn) {\n+ navContext.dispatch({ type: 'LOG_OUT' });\n+ }\n+ }, [navLoggedIn, loggedIn, navContext]);\n+\n+ React.useEffect(() => {\n+ prevLoggedIn.current = loggedIn;\n+ });\n+\n+ return null;\n+}\n+\n+export default connectNav((context: ?NavContextType) => ({\n+ navLoggedIn: appLoggedInSelector(context),\n+}))(\n+ connect((state: AppState) => ({\n+ loggedIn: !!(\n+ state.currentUserInfo &&\n+ !state.currentUserInfo.anonymous &&\n+ true\n+ ),\n+ }))(NavigationHandler),\n+);\n" }, { "change_type": "MODIFY", "old_path": "native/root.react.js", "new_path": "native/root.react.js", "diff": "// @flow\n-import type { NavigationState, NavigationAction } from 'react-navigation';\n+import type { NavigationState } from 'react-navigation';\nimport { type GlobalTheme, globalThemePropType } from './types/themes';\nimport type { Dispatch } from 'lib/types/redux-types';\nimport type { AppState } from './redux/redux-setup';\nimport type { DispatchActionPayload } from 'lib/utils/action-utils';\n+import type { NavAction } from './navigation/navigation-context';\nimport * as React from 'react';\nimport { Provider } from 'react-redux';\n@@ -46,6 +47,7 @@ import {\n} from './navigation/navigation-context';\nimport { setGlobalNavContext } from './navigation/icky-global';\nimport { RootContext, type RootContextType } from './root-context';\n+import NavigationHandler from './navigation/navigation-handler.react';\nif (Platform.OS === 'android') {\nUIManager.setLayoutAnimationEnabledExperimental &&\n@@ -54,7 +56,7 @@ if (Platform.OS === 'android') {\nconst ReduxifiedRootNavigator = createReduxContainer(RootNavigator);\n-type NativeDispatch = Dispatch & ((action: NavigationAction) => boolean);\n+type NativeDispatch = Dispatch & ((action: NavAction) => boolean);\ntype Props = {\n// Redux state\n@@ -181,6 +183,7 @@ class Root extends React.PureComponent<Props, State> {\ndispatch={this.props.dispatch}\ntheme={reactNavigationTheme}\n/>\n+ <NavigationHandler />\n</RootContext.Provider>\n</NavContext.Provider>\n</View>\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] NavigationHandler
129,187
30.03.2020 15:25:33
14,400
1552c15b9e35a3f1d606fa1bac3a33682d454688
[native] Extract removeScreensFromStack
[ { "change_type": "MODIFY", "old_path": "native/chat/chat-router.js", "new_path": "native/chat/chat-router.js", "diff": "@@ -12,11 +12,11 @@ import {\ntype NavigationStackRouterConfig,\n} from 'react-navigation';\n-import { removeScreensFromStack } from '../navigation/navigation-setup';\nimport {\nChatThreadListRouteName,\nMessageListRouteName,\n} from '../navigation/route-names';\n+import { removeScreensFromStack } from '../utils/navigation-utils';\ntype ClearScreensAction = {|\n+type: 'CLEAR_SCREENS',\n" }, { "change_type": "MODIFY", "old_path": "native/navigation/navigation-setup.js", "new_path": "native/navigation/navigation-setup.js", "diff": "@@ -14,7 +14,6 @@ import type { SetSessionPayload } from 'lib/types/session-types';\nimport type { AndroidNotificationActions } from '../push/reducer';\nimport type { UserInfo } from 'lib/types/user-types';\n-import invariant from 'invariant';\nimport { Alert, Platform } from 'react-native';\nimport { useScreens } from 'react-native-screens';\n@@ -37,6 +36,7 @@ import { threadInfoFromRawThreadInfo } from 'lib/shared/thread-utils';\nimport {\nassertNavigationRouteNotLeafNode,\ngetThreadIDFromParams,\n+ removeScreensFromStack,\n} from '../utils/navigation-utils';\nimport {\nAppRouteName,\n@@ -252,50 +252,6 @@ function handleURL(state: NavigationState, url: string): NavigationState {\n};\n}\n-// This function walks from the back of the stack and calls filterFunc on each\n-// screen until the stack is exhausted or filterFunc returns \"break\". A screen\n-// will be removed if and only if filterFunc returns \"remove\" (not \"break\").\n-function removeScreensFromStack<S: NavigationState>(\n- state: S,\n- filterFunc: (route: NavigationRoute) => 'keep' | 'remove' | 'break',\n-): S {\n- const newRoutes = [];\n- let newIndex = state.index;\n- let screenRemoved = false;\n- let breakActivated = false;\n- for (let i = state.routes.length - 1; i >= 0; i--) {\n- const route = state.routes[i];\n- if (breakActivated) {\n- newRoutes.unshift(route);\n- continue;\n- }\n- const result = filterFunc(route);\n- if (result === 'break') {\n- breakActivated = true;\n- }\n- if (breakActivated || result === 'keep') {\n- newRoutes.unshift(route);\n- continue;\n- }\n- screenRemoved = true;\n- if (newIndex >= i) {\n- invariant(\n- newIndex !== 0,\n- 'Attempting to remove current route and all before it',\n- );\n- newIndex--;\n- }\n- }\n- if (!screenRemoved) {\n- return state;\n- }\n- return {\n- ...state,\n- index: newIndex,\n- routes: newRoutes,\n- };\n-}\n-\nfunction removeRootModals(\nstate: NavigationState,\nmodalRouteNames: string[],\n@@ -503,7 +459,6 @@ function handleNewThread(\nexport {\ndefaultNavInfo,\nreduceNavInfo,\n- removeScreensFromStack,\nreplaceChatRoute,\nresetNavInfoAndEnsureLoggedOutModalPresence,\n};\n" }, { "change_type": "MODIFY", "old_path": "native/utils/navigation-utils.js", "new_path": "native/utils/navigation-utils.js", "diff": "@@ -102,9 +102,54 @@ function findRouteIndexWithKey(state: NavigationState, key: string): ?number {\nreturn null;\n}\n+// This function walks from the back of the stack and calls filterFunc on each\n+// screen until the stack is exhausted or filterFunc returns \"break\". A screen\n+// will be removed if and only if filterFunc returns \"remove\" (not \"break\").\n+function removeScreensFromStack<S: NavigationState>(\n+ state: S,\n+ filterFunc: (route: NavigationRoute) => 'keep' | 'remove' | 'break',\n+): S {\n+ const newRoutes = [];\n+ let newIndex = state.index;\n+ let screenRemoved = false;\n+ let breakActivated = false;\n+ for (let i = state.routes.length - 1; i >= 0; i--) {\n+ const route = state.routes[i];\n+ if (breakActivated) {\n+ newRoutes.unshift(route);\n+ continue;\n+ }\n+ const result = filterFunc(route);\n+ if (result === 'break') {\n+ breakActivated = true;\n+ }\n+ if (breakActivated || result === 'keep') {\n+ newRoutes.unshift(route);\n+ continue;\n+ }\n+ screenRemoved = true;\n+ if (newIndex >= i) {\n+ invariant(\n+ newIndex !== 0,\n+ 'Attempting to remove current route and all before it',\n+ );\n+ newIndex--;\n+ }\n+ }\n+ if (!screenRemoved) {\n+ return state;\n+ }\n+ return {\n+ ...state,\n+ index: newIndex,\n+ routes: newRoutes,\n+ };\n+}\n+\nexport {\nassertNavigationRouteNotLeafNode,\ngetThreadIDFromParams,\ncurrentLeafRoute,\nfindRouteIndexWithKey,\n+ removeScreensFromStack,\n};\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Extract removeScreensFromStack
129,187
30.03.2020 17:30:50
14,400
edea8b5651fbe1d56f1a385365f73439193e0fa0
[native] Update react-redux libdef
[ { "change_type": "RENAME", "old_path": "native/flow-typed/npm/react-redux_v5.x.x.js", "new_path": "native/flow-typed/npm/react-redux_v7.x.x.js", "diff": "-// flow-typed signature: be1a6a9041ded9d5eb2308664fa10a77\n-// flow-typed version: c6154227d1/react-redux_v5.x.x/flow_>=v0.89.x <=v0.103.x\n+// flow-typed signature: d2ddacbbca9700881249a9435381e689\n+// flow-typed version: c6154227d1/react-redux_v7.x.x/flow_>=v0.89.x <=v0.103.x\n/**\nThe order of type arguments for connect() is as follows:\n@@ -27,6 +27,7 @@ Decrypting the abbreviations:\nRMP = Returned merge props\nCP = Props for returned component\nCom = React Component\n+ SS = Selected state\nST = Static properties of Com\nEFO = Extra factory options (used only in connectAdvanced)\n*/\n@@ -38,7 +39,7 @@ declare module \"react-redux\" {\ndeclare export type Options<S, OP, SP, MP> = {|\npure?: boolean,\n- withRef?: boolean,\n+ forwardRef?: boolean,\nareStatesEqual?: (next: S, prev: S) => boolean,\nareOwnPropsEqual?: (next: OP, prev: OP) => boolean,\nareStatePropsEqual?: (next: SP, prev: SP) => boolean,\n@@ -198,6 +199,19 @@ declare module \"react-redux\" {\noptions?: ?Options<S, OP, SP, P>,\n): Connector<P, OP, P>;\n+ // ------------------------------------------------------------\n+ // Typings for Hooks\n+ // ------------------------------------------------------------\n+\n+ declare export function useDispatch<D>(): D;\n+\n+ declare export function useSelector<S, SS>(\n+ selector: (state: S) => SS,\n+ equalityFn?: (a: SS, b: SS) => boolean,\n+ ): SS;\n+\n+ declare export function useStore<Store>(): Store;\n+\n// ------------------------------------------------------------\n// Typings for Provider\n// ------------------------------------------------------------\n@@ -222,7 +236,7 @@ declare module \"react-redux\" {\nrenderCountProp?: string,\nshouldHandleStateChanges?: boolean,\nstoreKey?: string,\n- withRef?: boolean,\n+ forwardRef?: boolean,\n};\ndeclare type SelectorFactoryOptions<Com> = {\n@@ -231,7 +245,7 @@ declare module \"react-redux\" {\nrenderCountProp: ?string,\nshouldHandleStateChanges: boolean,\nstoreKey: string,\n- withRef: boolean,\n+ forwardRef: boolean,\ndisplayName: string,\nwrappedComponentName: string,\nWrappedComponent: Com,\n@@ -272,5 +286,8 @@ declare module \"react-redux\" {\ncreateProvider: typeof createProvider,\nconnect: typeof connect,\nconnectAdvanced: typeof connectAdvanced,\n+ useDispatch: typeof useDispatch,\n+ useSelector: typeof useSelector,\n+ useStore: typeof useStore,\n};\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Update react-redux libdef
129,187
30.03.2020 17:53:18
14,400
93998c12e8f1ef3ebbf7405ab18a7740470d97cd
[native] useIsAppLoggedIn
[ { "change_type": "MODIFY", "old_path": "native/navigation/nav-selectors.js", "new_path": "native/navigation/nav-selectors.js", "diff": "@@ -7,6 +7,7 @@ import type { CalendarQuery } from 'lib/types/entry-types';\nimport type { GlobalTheme } from '../types/themes';\nimport type { NavPlusRedux } from '../types/selector-types';\n+import * as React from 'react';\nimport { createSelector } from 'reselect';\nimport _memoize from 'lodash/memoize';\n@@ -25,11 +26,12 @@ import {\naccountModals,\nscrollBlockingChatModals,\nchatRootModals,\n-} from '../navigation/route-names';\n+} from './route-names';\nimport {\nassertNavigationRouteNotLeafNode,\ngetThreadIDFromParams,\n} from '../utils/navigation-utils';\n+import { NavContext } from './navigation-context';\nconst baseCreateIsForegroundSelector = (routeName: string) =>\ncreateSelector(\n@@ -60,6 +62,17 @@ const appLoggedInSelector: (\n),\n);\n+function useIsAppLoggedIn() {\n+ const navContext = React.useContext(NavContext);\n+ return React.useMemo(() => {\n+ if (!navContext) {\n+ return false;\n+ }\n+ const { state } = navContext;\n+ return !accountModals.includes(state.routes[state.index].routeName);\n+ }, [navContext]);\n+}\n+\nconst foregroundKeySelector: (\ncontext: ?NavContextType,\n) => ?string = createSelector(\n@@ -286,6 +299,7 @@ const nonThreadCalendarQuery: (\nexport {\ncreateIsForegroundSelector,\nappLoggedInSelector,\n+ useIsAppLoggedIn,\nforegroundKeySelector,\ncreateActiveTabSelector,\nscrollBlockingChatModalsClosedSelector,\n" }, { "change_type": "MODIFY", "old_path": "native/navigation/navigation-handler.react.js", "new_path": "native/navigation/navigation-handler.react.js", "diff": "@@ -6,12 +6,8 @@ import * as React from 'react';\nimport { connect } from 'lib/utils/redux-utils';\n-import {\n- NavContext,\n- connectNav,\n- type NavContextType,\n-} from './navigation-context';\n-import { appLoggedInSelector } from './nav-selectors';\n+import { NavContext } from './navigation-context';\n+import { useIsAppLoggedIn } from './nav-selectors';\ntype Props = {|\n// Navigation state\n@@ -20,9 +16,10 @@ type Props = {|\nloggedIn: boolean,\n|};\nfunction NavigationHandler(props: Props) {\n- const { navLoggedIn, loggedIn } = props;\n+ const { loggedIn } = props;\nconst navContext = React.useContext(NavContext);\n+ const navLoggedIn = useIsAppLoggedIn();\nconst prevLoggedIn = React.useRef();\n@@ -44,14 +41,10 @@ function NavigationHandler(props: Props) {\nreturn null;\n}\n-export default connectNav((context: ?NavContextType) => ({\n- navLoggedIn: appLoggedInSelector(context),\n-}))(\n- connect((state: AppState) => ({\n+export default connect((state: AppState) => ({\nloggedIn: !!(\nstate.currentUserInfo &&\n!state.currentUserInfo.anonymous &&\ntrue\n),\n- }))(NavigationHandler),\n-);\n+}))(NavigationHandler);\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] useIsAppLoggedIn
129,187
30.03.2020 18:30:17
14,400
de78afca5a177ed1ab0aa0771721b0087e57a1ac
[native] AppNavigator to hook
[ { "change_type": "MODIFY", "old_path": "native/navigation/app-navigator.react.js", "new_path": "native/navigation/app-navigator.react.js", "diff": "@@ -4,7 +4,6 @@ import type { NavigationStackProp } from 'react-navigation-stack';\nimport type { NavigationStateRoute } from 'react-navigation';\nimport * as React from 'react';\n-import PropTypes from 'prop-types';\nimport { createBottomTabNavigator } from 'react-navigation-tabs';\nimport hoistNonReactStatics from 'hoist-non-react-statics';\nimport { PersistGate } from 'redux-persist/integration/react';\n@@ -21,6 +20,7 @@ import {\nTextMessageTooltipModalRouteName,\nThreadSettingsMemberTooltipModalRouteName,\nCameraModalRouteName,\n+ AppRouteName,\n} from './route-names';\nimport Calendar from '../calendar/calendar.react';\nimport Chat from '../chat/chat.react';\n@@ -38,11 +38,9 @@ import OverlayableScrollViewStateContainer from './overlayable-scroll-view-state\nimport KeyboardStateContainer from '../keyboard/keyboard-state-container.react';\nimport PushHandler from '../push/push-handler.react';\nimport { getPersistor } from '../redux/persist';\n-import { connectNav, type NavContextType } from './navigation-context';\n-import {\n- appLoggedInSelector,\n- appCanRespondToBackButtonSelector,\n-} from './nav-selectors';\n+import { NavContext } from './navigation-context';\n+import { useIsAppLoggedIn } from './nav-selectors';\n+import { assertNavigationRouteNotLeafNode } from '../utils/navigation-utils';\nconst TabNavigator = createBottomTabNavigator(\n{\n@@ -70,76 +68,74 @@ const AppNavigator = createOverlayNavigator({\n[CameraModalRouteName]: CameraModal,\n});\n-type WrappedAppNavigatorProps = {|\n+type Props = {|\nnavigation: NavigationStackProp<NavigationStateRoute>,\n- isForeground: boolean,\n- appCanRespondToBackButton: boolean,\n|};\n-class WrappedAppNavigator extends React.PureComponent<WrappedAppNavigatorProps> {\n- static propTypes = {\n- navigation: PropTypes.shape({\n- goBack: PropTypes.func.isRequired,\n- }).isRequired,\n- isForeground: PropTypes.bool.isRequired,\n- appCanRespondToBackButton: PropTypes.bool.isRequired,\n- };\n-\n- componentDidMount() {\n- if (this.props.isForeground) {\n- this.onForeground();\n- }\n- }\n-\n- componentWillUnmount() {\n- if (this.props.isForeground) {\n- this.onBackground();\n- }\n- }\n-\n- componentDidUpdate(prevProps: WrappedAppNavigatorProps) {\n- if (this.props.isForeground && !prevProps.isForeground) {\n- this.onForeground();\n- } else if (!this.props.isForeground && prevProps.isForeground) {\n- this.onBackground();\n- }\n- }\n-\n- onForeground() {\n- BackHandler.addEventListener('hardwareBackPress', this.hardwareBack);\n- }\n-\n- onBackground() {\n- BackHandler.removeEventListener('hardwareBackPress', this.hardwareBack);\n- }\n-\n- hardwareBack = () => {\n- if (!this.props.appCanRespondToBackButton) {\n- return false;\n- }\n- this.props.navigation.goBack(null);\n- return true;\n- };\n-\n- render() {\n+function WrappedAppNavigator(props: Props) {\n+ const { navigation } = props;\n+ const isForeground = useIsAppLoggedIn();\n+ const backButtonHandler = isForeground ? (\n+ <BackButtonHandler navigation={navigation} />\n+ ) : null;\nreturn (\n<ChatInputStateContainer>\n<OverlayableScrollViewStateContainer>\n<KeyboardStateContainer>\n- <AppNavigator navigation={this.props.navigation} />\n+ <AppNavigator navigation={navigation} />\n<PersistGate persistor={getPersistor()}>\n- <PushHandler navigation={this.props.navigation} />\n+ <PushHandler navigation={navigation} />\n</PersistGate>\n+ {backButtonHandler}\n</KeyboardStateContainer>\n</OverlayableScrollViewStateContainer>\n</ChatInputStateContainer>\n);\n}\n+hoistNonReactStatics(WrappedAppNavigator, AppNavigator);\n+\n+function BackButtonHandler(props: Props) {\n+ const { navigation } = props;\n+ const appCanRespondToBackButton = useAppCanRespondToBackButton();\n+ const hardwareBack = React.useCallback(() => {\n+ if (!appCanRespondToBackButton) {\n+ return false;\n+ }\n+ navigation.goBack(null);\n+ return true;\n+ }, [appCanRespondToBackButton, navigation]);\n+ React.useEffect(() => {\n+ BackHandler.addEventListener('hardwareBackPress', hardwareBack);\n+ return () => {\n+ BackHandler.removeEventListener('hardwareBackPress', hardwareBack);\n+ };\n+ }, [hardwareBack]);\n+ return null;\n}\n-const ReduxWrappedAppNavigator = connectNav((context: ?NavContextType) => ({\n- appCanRespondToBackButton: appCanRespondToBackButtonSelector(context),\n- isForeground: appLoggedInSelector(context),\n-}))(WrappedAppNavigator);\n-hoistNonReactStatics(ReduxWrappedAppNavigator, AppNavigator);\n+function useAppCanRespondToBackButton() {\n+ const navContext = React.useContext(NavContext);\n+ return React.useMemo(() => {\n+ if (!navContext) {\n+ return false;\n+ }\n+ const { state } = navContext;\n+ const currentRootSubroute = state.routes[state.index];\n+ if (currentRootSubroute.routeName !== AppRouteName) {\n+ return false;\n+ }\n+ const appRoute = assertNavigationRouteNotLeafNode(currentRootSubroute);\n+ const currentAppSubroute = appRoute.routes[appRoute.index];\n+ if (currentAppSubroute.routeName !== TabNavigatorRouteName) {\n+ return true;\n+ }\n+ const tabRoute = assertNavigationRouteNotLeafNode(currentAppSubroute);\n+ const currentTabSubroute = tabRoute.routes[tabRoute.index];\n+ return (\n+ currentTabSubroute.index !== null &&\n+ currentTabSubroute.index !== undefined &&\n+ currentTabSubroute.index > 0\n+ );\n+ }, [navContext]);\n+}\n-export default ReduxWrappedAppNavigator;\n+export default WrappedAppNavigator;\n" }, { "change_type": "MODIFY", "old_path": "native/navigation/nav-selectors.js", "new_path": "native/navigation/nav-selectors.js", "diff": "@@ -51,17 +51,6 @@ const createIsForegroundSelector: (\nbaseCreateIsForegroundSelector,\n);\n-const appLoggedInSelector: (\n- context: ?NavContextType,\n-) => boolean = createSelector(\n- (context: ?NavContextType) => context && context.state,\n- (navigationState: ?NavigationState) =>\n- !!navigationState &&\n- !accountModals.includes(\n- navigationState.routes[navigationState.index].routeName,\n- ),\n-);\n-\nfunction useIsAppLoggedIn() {\nconst navContext = React.useContext(NavContext);\nreturn React.useMemo(() => {\n@@ -225,33 +214,6 @@ const activeMessageListSelector: (\nactiveThread(navigationState, [MessageListRouteName]),\n);\n-const appCanRespondToBackButtonSelector: (\n- context: ?NavContextType,\n-) => boolean = createSelector(\n- (context: ?NavContextType) => context && context.state,\n- (navigationState: ?NavigationState): boolean => {\n- if (!navigationState) {\n- return false;\n- }\n- const currentRootSubroute = navigationState.routes[navigationState.index];\n- if (currentRootSubroute.routeName !== AppRouteName) {\n- return false;\n- }\n- const appRoute = assertNavigationRouteNotLeafNode(currentRootSubroute);\n- const currentAppSubroute = appRoute.routes[appRoute.index];\n- if (currentAppSubroute.routeName !== TabNavigatorRouteName) {\n- return true;\n- }\n- const tabRoute = assertNavigationRouteNotLeafNode(currentAppSubroute);\n- const currentTabSubroute = tabRoute.routes[tabRoute.index];\n- return (\n- currentTabSubroute.index !== null &&\n- currentTabSubroute.index !== undefined &&\n- currentTabSubroute.index > 0\n- );\n- },\n-);\n-\nconst calendarTabActiveSelector = createActiveTabSelector(CalendarRouteName);\nconst threadPickerActiveSelector = createIsForegroundSelector(\nThreadPickerModalRouteName,\n@@ -298,7 +260,6 @@ const nonThreadCalendarQuery: (\nexport {\ncreateIsForegroundSelector,\n- appLoggedInSelector,\nuseIsAppLoggedIn,\nforegroundKeySelector,\ncreateActiveTabSelector,\n@@ -307,7 +268,6 @@ export {\noverlayTransitioningSelector,\nactiveThreadSelector,\nactiveMessageListSelector,\n- appCanRespondToBackButtonSelector,\ncalendarActiveSelector,\nnativeCalendarQuery,\nnonThreadCalendarQuery,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] AppNavigator to hook
129,187
30.03.2020 21:08:55
14,400
fb8f74990911e45813576c4decb525002b3b3d77
[native] Use NavigationHandler and RootRouter to handle log ins
[ { "change_type": "MODIFY", "old_path": "native/account/logged-out-modal.react.js", "new_path": "native/account/logged-out-modal.react.js", "diff": "// @flow\nimport type { NavigationScreenProp, NavigationRoute } from 'react-navigation';\n-import type {\n- DispatchActionPayload,\n- DispatchActionPromise,\n-} from 'lib/utils/action-utils';\n+import type { DispatchActionPayload } from 'lib/utils/action-utils';\nimport type { Dispatch } from 'lib/types/redux-types';\nimport type { AppState } from '../redux/redux-setup';\nimport type { KeyboardEvent, EmitterSubscription } from '../keyboard/keyboard';\n@@ -49,10 +46,7 @@ import LogInPanelContainer from './log-in-panel-container.react';\nimport RegisterPanel from './register-panel.react';\nimport ConnectedStatusBar from '../connected-status-bar.react';\nimport { createIsForegroundSelector } from '../navigation/nav-selectors';\n-import {\n- navigateToAppActionType,\n- resetUserStateActionType,\n-} from '../redux/action-types';\n+import { resetUserStateActionType } from '../redux/action-types';\nimport { splashBackgroundURI } from './background-info';\nimport { splashStyleSelector } from '../splash';\nimport {\n@@ -70,6 +64,7 @@ import SafeAreaView from '../components/safe-area-view.react';\nimport {\nconnectNav,\ntype NavContextType,\n+ navContextPropType,\n} from '../navigation/navigation-context';\nlet initialAppLoad = true;\n@@ -77,19 +72,20 @@ let initialAppLoad = true;\ntype LoggedOutMode = 'loading' | 'prompt' | 'log-in' | 'register';\ntype Props = {\nnavigation: NavigationScreenProp<NavigationRoute>,\n+ // Navigation state\n+ isForeground: boolean,\n+ navContext: ?NavContextType,\n// Redux state\nrehydrateConcluded: boolean,\ncookie: ?string,\nurlPrefix: string,\nloggedIn: boolean,\n- isForeground: boolean,\ndimensions: Dimensions,\ncontentVerticalOffset: number,\nsplashStyle: ImageStyle,\n// Redux dispatch functions\ndispatch: Dispatch,\ndispatchActionPayload: DispatchActionPayload,\n- dispatchActionPromise: DispatchActionPromise,\n};\ntype State = {\nmode: LoggedOutMode,\n@@ -109,16 +105,16 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\nnavigate: PropTypes.func.isRequired,\ngoBack: PropTypes.func.isRequired,\n}).isRequired,\n+ isForeground: PropTypes.bool.isRequired,\n+ navContext: navContextPropType,\nrehydrateConcluded: PropTypes.bool.isRequired,\ncookie: PropTypes.string,\nurlPrefix: PropTypes.string.isRequired,\nloggedIn: PropTypes.bool.isRequired,\n- isForeground: PropTypes.bool.isRequired,\ndimensions: dimensionsPropType.isRequired,\ncontentVerticalOffset: PropTypes.number.isRequired,\ndispatch: PropTypes.func.isRequired,\ndispatchActionPayload: PropTypes.func.isRequired,\n- dispatchActionPromise: PropTypes.func.isRequired,\n};\nstatic navigationOptions = {\n@@ -213,14 +209,8 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\ncomponentDidMount() {\nthis.mounted = true;\n- if (this.props.rehydrateConcluded && !__DEV__) {\n- // If rehydrate concludes before the first time LoggedOutModal is mounted\n- // on dev mode, it's probably because the dev started with logged-in nav\n- // state and then logged out. In this case we don't want to call\n- // onInitialAppLoad. However, if the same thing happens in release mode,\n- // it's probably because Android rehydrated as a result of a notification.\n- // In this case, we still want to call onInitialAppLoad.\n- this.onInitialAppLoad();\n+ if (this.props.rehydrateConcluded) {\n+ this.onInitialAppLoad(true);\n}\nif (this.props.isForeground) {\nthis.onForeground();\n@@ -236,7 +226,7 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\ncomponentDidUpdate(prevProps: Props) {\nif (!prevProps.rehydrateConcluded && this.props.rehydrateConcluded) {\n- this.onInitialAppLoad();\n+ this.onInitialAppLoad(false);\n}\nif (!prevProps.isForeground && this.props.isForeground) {\nthis.onForeground();\n@@ -265,75 +255,57 @@ class LoggedOutModal extends React.PureComponent<Props, State> {\n// This gets triggered when an app is killed and restarted\n// Not when it is returned from being backgrounded\n- async onInitialAppLoad() {\n+ async onInitialAppLoad(startedWithPrompt: boolean) {\nif (!initialAppLoad) {\nreturn;\n}\ninitialAppLoad = false;\n- let { cookie } = this.props;\n- const { urlPrefix } = this.props;\n- const showPrompt = () => {\n- this.nextMode = 'prompt';\n- this.guardedSetState({ mode: 'prompt' });\n- Animated.timing(this.state.buttonOpacity, {\n- duration: 250,\n- easing: Easing.out(Easing.ease),\n- toValue: 1.0,\n- }).start();\n- };\n-\n- // If we're not logged in, try native credentials\n- if (!this.props.loggedIn && (!cookie || !cookie.startsWith('user='))) {\n- // If this succeeds it will dispatch LOG_IN_SUCCESS\n- const sessionChange = await fetchNewCookieFromNativeCredentials(\n- this.props.dispatch,\n- cookie,\n- urlPrefix,\n- appStartNativeCredentialsAutoLogIn,\n- );\n- if (!sessionChange) {\n- showPrompt();\n- return;\n- }\n- const newCookie = sessionChange.cookie;\n- if (!newCookie || !newCookie.startsWith('user=')) {\n- showPrompt();\n- }\n+ const { loggedIn, cookie, urlPrefix, dispatch } = this.props;\n+ const hasUserCookie = cookie && cookie.startsWith('user=');\n+ if (loggedIn && hasUserCookie) {\nreturn;\n}\n- // Are we possibly already logged in?\n- if (this.props.loggedIn) {\n- if (cookie && cookie.startsWith('user=')) {\n- this.props.dispatchActionPayload(navigateToAppActionType, null);\n- return;\n- }\n- // This is an unusual error state that should never happen\n+ if (!__DEV__) {\n+ const actionSource = loggedIn\n+ ? appStartReduxLoggedInButInvalidCookie\n+ : appStartNativeCredentialsAutoLogIn;\nconst sessionChange = await fetchNewCookieFromNativeCredentials(\n- this.props.dispatch,\n+ dispatch,\ncookie,\nurlPrefix,\n- appStartReduxLoggedInButInvalidCookie,\n+ actionSource,\n);\n- const newCookie = sessionChange ? sessionChange.cookie : null;\n- if (newCookie && newCookie.startsWith('user=')) {\n- // If this happens we know that LOG_IN_SUCCESS has been dispatched\n+ if (\n+ sessionChange &&\n+ sessionChange.cookie &&\n+ sessionChange.cookie.startsWith('user=')\n+ ) {\n+ // success! we can expect subsequent actions to fix up the state\nreturn;\n}\n- // Looks like we failed to recover. We'll handle resetting Redux state to\n- // match our cookie in the reset call below\n- if (newCookie) {\n- cookie = newCookie;\n- }\n}\n- // We are here either because the user cookie exists but Redux says we're\n- // not logged in, or because Redux says we're logged in but we don't have\n- // a user cookie and we failed to acquire one above\n+ if (loggedIn || hasUserCookie) {\nthis.props.dispatchActionPayload(resetUserStateActionType, null);\n}\n+ if (!startedWithPrompt) {\n+ this.showPrompt();\n+ }\n+ }\n+\n+ showPrompt = () => {\n+ this.nextMode = 'prompt';\n+ this.guardedSetState({ mode: 'prompt' });\n+ Animated.timing(this.state.buttonOpacity, {\n+ duration: 250,\n+ easing: Easing.out(Easing.ease),\n+ toValue: 1.0,\n+ }).start();\n+ };\n+\nhardwareBack = () => {\nif (this.nextMode === 'log-in') {\ninvariant(this.logInPanelContainer, 'ref should be set');\n@@ -787,10 +759,15 @@ const isForegroundSelector = createIsForegroundSelector(\n);\nexport default connectNav((context: ?NavContextType) => ({\nisForeground: isForegroundSelector(context),\n+ navContext: context,\n}))(\nconnect(\n- (state: AppState) => ({\n- rehydrateConcluded: !!(state._persist && state._persist.rehydrated),\n+ (state: AppState, ownProps: { navContext: ?NavContextType }) => ({\n+ rehydrateConcluded: !!(\n+ state._persist &&\n+ state._persist.rehydrated &&\n+ ownProps.navContext\n+ ),\ncookie: state.cookie,\nurlPrefix: state.urlPrefix,\nloggedIn: !!(\n" }, { "change_type": "MODIFY", "old_path": "native/account/verification-modal.react.js", "new_path": "native/account/verification-modal.react.js", "diff": "@@ -5,10 +5,7 @@ import type {\nNavigationLeafRoute,\n} from 'react-navigation';\nimport type { AppState } from '../redux/redux-setup';\n-import type {\n- DispatchActionPayload,\n- DispatchActionPromise,\n-} from 'lib/utils/action-utils';\n+import type { DispatchActionPromise } from 'lib/utils/action-utils';\nimport {\ntype VerifyField,\nverifyField,\n@@ -50,7 +47,6 @@ import { dimensionsSelector } from '../selectors/dimension-selectors';\nimport ConnectedStatusBar from '../connected-status-bar.react';\nimport ResetPasswordPanel from './reset-password-panel.react';\nimport { createIsForegroundSelector } from '../navigation/nav-selectors';\n-import { navigateToAppActionType } from '../redux/action-types';\nimport { splashBackgroundURI } from './background-info';\nimport { splashStyleSelector } from '../splash';\nimport {\n@@ -63,6 +59,7 @@ import SafeAreaView from '../components/safe-area-view.react';\nimport {\nconnectNav,\ntype NavContextType,\n+ navContextPropType,\n} from '../navigation/navigation-context';\ntype VerificationModalMode = 'simple-text' | 'reset-password';\n@@ -70,12 +67,13 @@ type Props = {\nnavigation: {\nstate: { params: { verifyCode: string } },\n} & NavigationScreenProp<NavigationLeafRoute>,\n- // Redux state\n+ // Navigation state\nisForeground: boolean,\n+ navContext: ?NavContextType,\n+ // Redux state\ndimensions: Dimensions,\nsplashStyle: ImageStyle,\n// Redux dispatch functions\n- dispatchActionPayload: DispatchActionPayload,\ndispatchActionPromise: DispatchActionPromise,\n// async functions that hit server APIs\nhandleVerificationCode: (\n@@ -102,8 +100,8 @@ class VerificationModal extends React.PureComponent<Props, State> {\ngoBack: PropTypes.func.isRequired,\n}).isRequired,\nisForeground: PropTypes.bool.isRequired,\n+ navContext: navContextPropType,\ndimensions: dimensionsPropType.isRequired,\n- dispatchActionPayload: PropTypes.func.isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\nhandleVerificationCode: PropTypes.func.isRequired,\n};\n@@ -241,7 +239,8 @@ class VerificationModal extends React.PureComponent<Props, State> {\nasync inCoupleSecondsNavigateToApp() {\nawait sleep(1750);\n- this.props.dispatchActionPayload(navigateToAppActionType, null);\n+ invariant(this.props.navContext, 'navContext should be non-null');\n+ this.props.navContext.dispatch({ type: 'LOG_IN' });\n}\nasync handleVerificationCodeAction() {\n@@ -512,6 +511,7 @@ const isForegroundSelector = createIsForegroundSelector(\n);\nexport default connectNav((context: ?NavContextType) => ({\nisForeground: isForegroundSelector(context),\n+ navContext: context,\n}))(\nconnect(\n(state: AppState) => ({\n" }, { "change_type": "MODIFY", "old_path": "native/navigation/navigation-context.js", "new_path": "native/navigation/navigation-context.js", "diff": "@@ -6,6 +6,7 @@ import type { ChatRouterNavigationAction } from '../chat/chat-router';\nimport * as React from 'react';\nimport hoistNonReactStatics from 'hoist-non-react-statics';\n+import PropTypes from 'prop-types';\nexport type NavAction =\n| NavigationAction\n@@ -16,6 +17,11 @@ export type NavContextType = {|\ndispatch: (action: NavAction) => boolean,\n|};\n+const navContextPropType = PropTypes.shape({\n+ state: PropTypes.object.isRequired,\n+ dispatch: PropTypes.func.isRequired,\n+});\n+\nconst NavContext = React.createContext<?NavContextType>(null);\nfunction withNavContext<\n@@ -77,4 +83,4 @@ function connectNav<\n};\n}\n-export { NavContext, withNavContext, connectNav };\n+export { NavContext, withNavContext, connectNav, navContextPropType };\n" }, { "change_type": "MODIFY", "old_path": "native/navigation/navigation-handler.react.js", "new_path": "native/navigation/navigation-handler.react.js", "diff": "import type { AppState } from '../redux/redux-setup';\nimport * as React from 'react';\n+import { useSelector } from 'react-redux';\n-import { connect } from 'lib/utils/redux-utils';\n-\n-import { NavContext } from './navigation-context';\n+import { NavContext, type NavAction } from './navigation-context';\nimport { useIsAppLoggedIn } from './nav-selectors';\n-type Props = {|\n- // Navigation state\n+function NavigationHandler() {\n+ const navContext = React.useContext(NavContext);\n+\n+ const reduxRehydrated = useSelector(\n+ (state: AppState) => !!(state._persist && state._persist.rehydrated),\n+ );\n+ const loggedIn = useSelector(\n+ (state: AppState) =>\n+ !!(\n+ state.currentUserInfo &&\n+ !state.currentUserInfo.anonymous &&\n+ state.cookie &&\n+ state.cookie.startsWith('user=')\n+ ),\n+ );\n+\n+ const navLoggedIn = useIsAppLoggedIn();\n+\n+ if (navContext && reduxRehydrated) {\n+ return (\n+ <LogInHandler\n+ navLoggedIn={navLoggedIn}\n+ loggedIn={loggedIn}\n+ dispatch={navContext.dispatch}\n+ />\n+ );\n+ }\n+\n+ return null;\n+}\n+\n+type LogInHandlerProps = {|\nnavLoggedIn: boolean,\n- // Redux state\nloggedIn: boolean,\n+ dispatch: (action: NavAction) => boolean,\n|};\n-function NavigationHandler(props: Props) {\n- const { loggedIn } = props;\n-\n- const navContext = React.useContext(NavContext);\n- const navLoggedIn = useIsAppLoggedIn();\n+const LogInHandler = React.memo<LogInHandlerProps>(\n+ (props: LogInHandlerProps) => {\n+ const { navLoggedIn, loggedIn, dispatch } = props;\n- const prevLoggedIn = React.useRef();\n+ const prevLoggedInRef = React.useRef();\n+ React.useEffect(() => {\n+ prevLoggedInRef.current = loggedIn;\n+ });\n+ const prevLoggedIn = prevLoggedInRef.current;\nReact.useEffect(() => {\n- if (!navContext) {\n+ if (loggedIn === prevLoggedIn) {\nreturn;\n}\n- if (loggedIn && !prevLoggedIn.current && !navLoggedIn) {\n- navContext.dispatch({ type: 'LOG_IN' });\n- } else if (!loggedIn && prevLoggedIn.current && navLoggedIn) {\n- navContext.dispatch({ type: 'LOG_OUT' });\n+ if (loggedIn && !navLoggedIn) {\n+ dispatch({ type: 'LOG_IN' });\n+ } else if (!loggedIn && navLoggedIn) {\n+ dispatch({ type: 'LOG_OUT' });\n}\n- }, [navLoggedIn, loggedIn, navContext]);\n-\n- React.useEffect(() => {\n- prevLoggedIn.current = loggedIn;\n- });\n+ }, [navLoggedIn, prevLoggedIn, loggedIn, dispatch]);\nreturn null;\n-}\n+ },\n+);\n+LogInHandler.displayName = 'LogInHandler';\n-export default connect((state: AppState) => ({\n- loggedIn: !!(\n- state.currentUserInfo &&\n- !state.currentUserInfo.anonymous &&\n- true\n- ),\n-}))(NavigationHandler);\n+export default NavigationHandler;\n" }, { "change_type": "MODIFY", "old_path": "native/navigation/navigation-setup.js", "new_path": "native/navigation/navigation-setup.js", "diff": "@@ -23,8 +23,6 @@ import { setNewSessionActionType } from 'lib/utils/action-utils';\nimport {\nlogOutActionTypes,\ndeleteAccountActionTypes,\n- logInActionTypes,\n- registerActionTypes,\n} from 'lib/actions/user-actions';\nimport {\nleaveThreadActionTypes,\n@@ -54,10 +52,7 @@ import {\nCalendarRouteName,\naccountModals,\n} from './route-names';\n-import {\n- handleURLActionType,\n- navigateToAppActionType,\n-} from '../redux/action-types';\n+import { handleURLActionType } from '../redux/action-types';\nimport RootNavigator from './root-navigator.react';\n// eslint-disable-next-line react-hooks/rules-of-hooks\n@@ -78,7 +73,6 @@ export type Action =\n| BaseAction\n| NavigationAction\n| {| type: 'HANDLE_URL', payload: string |}\n- | {| type: 'NAVIGATE_TO_APP', payload: null |}\n| AndroidNotificationActions\n| {| type: 'RECORD_NOTIF_PERMISSION_ALERT', time: number |}\n| {| type: 'BACKGROUND' |}\n@@ -165,19 +159,6 @@ function reduceNavInfo(\nendDate: navInfoState.endDate,\nnavigationState: handleURL(navInfoState.navigationState, action.payload),\n};\n- } else if (\n- action.type === logInActionTypes.success ||\n- action.type === registerActionTypes.success ||\n- action.type === navigateToAppActionType\n- ) {\n- return {\n- startDate: navInfoState.startDate,\n- endDate: navInfoState.endDate,\n- navigationState: removeRootModals(\n- navInfoState.navigationState,\n- accountModals,\n- ),\n- };\n} else if (\naction.type === logOutActionTypes.started ||\naction.type === deleteAccountActionTypes.success\n@@ -252,22 +233,6 @@ function handleURL(state: NavigationState, url: string): NavigationState {\n};\n}\n-function removeRootModals(\n- state: NavigationState,\n- modalRouteNames: string[],\n-): NavigationState {\n- const newState = removeScreensFromStack(state, (route: NavigationRoute) =>\n- modalRouteNames.includes(route.routeName) ? 'remove' : 'keep',\n- );\n- if (newState === state) {\n- return state;\n- }\n- return {\n- ...newState,\n- isTransitioning: true,\n- };\n-}\n-\nfunction resetNavInfoAndEnsureLoggedOutModalPresence(state: NavInfo): NavInfo {\nlet navigationState = { ...state.navigationState };\nnavigationState.routes[0] = defaultNavInfo.navigationState.routes[0];\n" }, { "change_type": "MODIFY", "old_path": "native/navigation/root-router.js", "new_path": "native/navigation/root-router.js", "diff": "@@ -4,10 +4,14 @@ import {\nStackRouter,\ntype NavigationAction,\ntype NavigationState,\n+ type NavigationRoute,\ntype NavigationRouteConfigMap,\ntype NavigationStackRouterConfig,\n} from 'react-navigation';\n+import { removeScreensFromStack } from '../utils/navigation-utils';\n+import { accountModals } from './route-names';\n+\ntype LogInAction = {|\n+type: 'LOG_IN',\n|};\n@@ -32,7 +36,21 @@ function RootRouter(\nlastState: ?NavigationState,\n) => {\nif (action.type === 'LOG_IN') {\n+ if (!lastState) {\n+ return lastState;\n+ }\n+ const newState = removeScreensFromStack(\n+ lastState,\n+ (route: NavigationRoute) =>\n+ accountModals.includes(route.routeName) ? 'remove' : 'keep',\n+ );\n+ if (newState === lastState) {\nreturn lastState;\n+ }\n+ return {\n+ ...newState,\n+ isTransitioning: true,\n+ };\n} else if (action.type === 'LOG_OUT') {\nreturn lastState;\n} else {\n" }, { "change_type": "MODIFY", "old_path": "native/redux/action-types.js", "new_path": "native/redux/action-types.js", "diff": "import { saveMessagesActionType } from 'lib/actions/message-actions';\nexport const handleURLActionType = 'HANDLE_URL';\n-export const navigateToAppActionType = 'NAVIGATE_TO_APP';\nexport const resetUserStateActionType = 'RESET_USER_STATE';\nexport const recordNotifPermissionAlertActionType =\n'RECORD_NOTIF_PERMISSION_ALERT';\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Use NavigationHandler and RootRouter to handle log ins
129,187
30.03.2020 22:44:23
14,400
d0b49b2864c3e1ccb173b1f5c209cd4c1bc76d8e
[native] Keep VerificationModal visible for a couple seconds after success
[ { "change_type": "MODIFY", "old_path": "native/account/reset-password-panel.react.js", "new_path": "native/account/reset-password-panel.react.js", "diff": "@@ -48,7 +48,7 @@ type Props = {\nverifyCode: string,\nusername: string,\nonePasswordSupported: boolean,\n- onSuccess: () => void,\n+ onSuccess: () => Promise<void>,\nsetActiveAlert: (activeAlert: boolean) => void,\nopacityValue: Animated.Value,\n// Redux state\n@@ -214,7 +214,7 @@ class ResetPasswordPanel extends React.PureComponent<Props, State> {\npassword: this.state.passwordInputText,\n});\nthis.props.setActiveAlert(false);\n- this.props.onSuccess();\n+ await this.props.onSuccess();\nreturn result;\n} catch (e) {\nif (e.message === 'client_version_unsupported') {\n" }, { "change_type": "MODIFY", "old_path": "native/account/verification-modal.react.js", "new_path": "native/account/verification-modal.react.js", "diff": "@@ -59,7 +59,6 @@ import SafeAreaView from '../components/safe-area-view.react';\nimport {\nconnectNav,\ntype NavContextType,\n- navContextPropType,\n} from '../navigation/navigation-context';\ntype VerificationModalMode = 'simple-text' | 'reset-password';\n@@ -69,7 +68,6 @@ type Props = {\n} & NavigationScreenProp<NavigationLeafRoute>,\n// Navigation state\nisForeground: boolean,\n- navContext: ?NavContextType,\n// Redux state\ndimensions: Dimensions,\nsplashStyle: ImageStyle,\n@@ -100,7 +98,6 @@ class VerificationModal extends React.PureComponent<Props, State> {\ngoBack: PropTypes.func.isRequired,\n}).isRequired,\nisForeground: PropTypes.bool.isRequired,\n- navContext: navContextPropType,\ndimensions: dimensionsPropType.isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\nhandleVerificationCode: PropTypes.func.isRequired,\n@@ -208,7 +205,7 @@ class VerificationModal extends React.PureComponent<Props, State> {\nreturn true;\n};\n- onResetPasswordSuccess = () => {\n+ onResetPasswordSuccess = async () => {\nlet opacityListenerID: ?string = null;\nconst opacityListener = (animatedUpdate: { value: number }) => {\nif (animatedUpdate.value === 0) {\n@@ -234,14 +231,10 @@ class VerificationModal extends React.PureComponent<Props, State> {\nthis.animateKeyboardDownOrBackToSimpleText(null);\n}\n- this.inCoupleSecondsNavigateToApp();\n- };\n-\n- async inCoupleSecondsNavigateToApp() {\n+ // Wait a couple seconds before letting the SUCCESS action propagate and\n+ // clear VerificationModal\nawait sleep(1750);\n- invariant(this.props.navContext, 'navContext should be non-null');\n- this.props.navContext.dispatch({ type: 'LOG_IN' });\n- }\n+ };\nasync handleVerificationCodeAction() {\nconst code = this.props.navigation.state.params.verifyCode;\n@@ -511,7 +504,6 @@ const isForegroundSelector = createIsForegroundSelector(\n);\nexport default connectNav((context: ?NavContextType) => ({\nisForeground: isForegroundSelector(context),\n- navContext: context,\n}))(\nconnect(\n(state: AppState) => ({\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Keep VerificationModal visible for a couple seconds after success
129,187
30.03.2020 23:40:09
14,400
696b08d48c98d0126a7d8e79dad9556764f3a74f
[native] Use NavigationHandler and RootRouter to handle log outs
[ { "change_type": "ADD", "old_path": null, "new_path": "native/navigation/default-state.js", "diff": "+// @flow\n+\n+import type { BaseNavInfo } from 'lib/types/nav-types';\n+import type { NavigationState } from 'react-navigation';\n+\n+import { fifteenDaysEarlier, fifteenDaysLater } from 'lib/utils/date-utils';\n+\n+import {\n+ AppRouteName,\n+ TabNavigatorRouteName,\n+ LoggedOutModalRouteName,\n+ MoreRouteName,\n+ MoreScreenRouteName,\n+ ChatRouteName,\n+ ChatThreadListRouteName,\n+ CalendarRouteName,\n+} from './route-names';\n+\n+export type NavInfo = {|\n+ ...$Exact<BaseNavInfo>,\n+ navigationState: NavigationState,\n+|};\n+\n+const defaultNavigationState = {\n+ index: 1,\n+ routes: [\n+ {\n+ key: 'App',\n+ routeName: AppRouteName,\n+ index: 0,\n+ routes: [\n+ {\n+ key: 'TabNavigator',\n+ routeName: TabNavigatorRouteName,\n+ index: 1,\n+ routes: [\n+ { key: 'Calendar', routeName: CalendarRouteName },\n+ {\n+ key: 'Chat',\n+ routeName: ChatRouteName,\n+ index: 0,\n+ routes: [\n+ { key: 'ChatThreadList', routeName: ChatThreadListRouteName },\n+ ],\n+ },\n+ {\n+ key: 'More',\n+ routeName: MoreRouteName,\n+ index: 0,\n+ routes: [{ key: 'MoreScreen', routeName: MoreScreenRouteName }],\n+ },\n+ ],\n+ },\n+ ],\n+ },\n+ { key: 'LoggedOutModal', routeName: LoggedOutModalRouteName },\n+ ],\n+};\n+\n+const defaultNavInfo: NavInfo = {\n+ startDate: fifteenDaysEarlier().valueOf(),\n+ endDate: fifteenDaysLater().valueOf(),\n+ navigationState: defaultNavigationState,\n+};\n+\n+export { defaultNavInfo };\n" }, { "change_type": "RENAME", "old_path": "native/navigation/navigation-setup.js", "new_path": "native/navigation/nav-reducer.js", "diff": "// @flow\n-import type { BaseAction } from 'lib/types/redux-types';\n-import type { BaseNavInfo } from 'lib/types/nav-types';\nimport type { RawThreadInfo, LeaveThreadPayload } from 'lib/types/thread-types';\nimport type {\nNavigationState,\n- NavigationAction,\nNavigationRoute,\nNavigationStateRoute,\n} from 'react-navigation';\nimport type { AppState } from '../redux/redux-setup';\nimport type { SetSessionPayload } from 'lib/types/session-types';\n-import type { AndroidNotificationActions } from '../push/reducer';\nimport type { UserInfo } from 'lib/types/user-types';\n+import type { NavInfo } from './default-state';\nimport { Alert, Platform } from 'react-native';\nimport { useScreens } from 'react-native-screens';\nimport { infoFromURL } from 'lib/utils/url-utils';\n-import { fifteenDaysEarlier, fifteenDaysLater } from 'lib/utils/date-utils';\nimport { setNewSessionActionType } from 'lib/utils/action-utils';\n-import {\n- logOutActionTypes,\n- deleteAccountActionTypes,\n-} from 'lib/actions/user-actions';\nimport {\nleaveThreadActionTypes,\ndeleteThreadActionTypes,\n@@ -37,20 +29,11 @@ import {\nremoveScreensFromStack,\n} from '../utils/navigation-utils';\nimport {\n- AppRouteName,\n- TabNavigatorRouteName,\nComposeThreadRouteName,\nDeleteThreadRouteName,\nThreadSettingsRouteName,\nMessageListRouteName,\nVerificationModalRouteName,\n- LoggedOutModalRouteName,\n- MoreRouteName,\n- MoreScreenRouteName,\n- ChatRouteName,\n- ChatThreadListRouteName,\n- CalendarRouteName,\n- accountModals,\n} from './route-names';\nimport { handleURLActionType } from '../redux/action-types';\nimport RootNavigator from './root-navigator.react';\n@@ -58,68 +41,12 @@ import RootNavigator from './root-navigator.react';\n// eslint-disable-next-line react-hooks/rules-of-hooks\nuseScreens();\n-export type NavInfo = {|\n- ...$Exact<BaseNavInfo>,\n- navigationState: NavigationState,\n-|};\n-\nconst messageListRouteBase = Date.now();\nlet messageListRouteIndex = 0;\nfunction getUniqueMessageListRouteKey() {\nreturn `${messageListRouteBase}-${messageListRouteIndex++}`;\n}\n-export type Action =\n- | BaseAction\n- | NavigationAction\n- | {| type: 'HANDLE_URL', payload: string |}\n- | AndroidNotificationActions\n- | {| type: 'RECORD_NOTIF_PERMISSION_ALERT', time: number |}\n- | {| type: 'BACKGROUND' |}\n- | {| type: 'FOREGROUND' |};\n-\n-const defaultNavigationState = {\n- index: 1,\n- routes: [\n- {\n- key: 'App',\n- routeName: AppRouteName,\n- index: 0,\n- routes: [\n- {\n- key: 'TabNavigator',\n- routeName: TabNavigatorRouteName,\n- index: 1,\n- routes: [\n- { key: 'Calendar', routeName: CalendarRouteName },\n- {\n- key: 'Chat',\n- routeName: ChatRouteName,\n- index: 0,\n- routes: [\n- { key: 'ChatThreadList', routeName: ChatThreadListRouteName },\n- ],\n- },\n- {\n- key: 'More',\n- routeName: MoreRouteName,\n- index: 0,\n- routes: [{ key: 'MoreScreen', routeName: MoreScreenRouteName }],\n- },\n- ],\n- },\n- ],\n- },\n- { key: 'LoggedOutModal', routeName: LoggedOutModalRouteName },\n- ],\n-};\n-\n-const defaultNavInfo: NavInfo = {\n- startDate: fifteenDaysEarlier().valueOf(),\n- endDate: fifteenDaysLater().valueOf(),\n- navigationState: defaultNavigationState,\n-};\n-\nfunction reduceNavInfo(\nstate: AppState,\naction: *,\n@@ -159,13 +86,8 @@ function reduceNavInfo(\nendDate: navInfoState.endDate,\nnavigationState: handleURL(navInfoState.navigationState, action.payload),\n};\n- } else if (\n- action.type === logOutActionTypes.started ||\n- action.type === deleteAccountActionTypes.success\n- ) {\n- return resetNavInfoAndEnsureLoggedOutModalPresence(navInfoState);\n} else if (action.type === setNewSessionActionType) {\n- return logOutIfCookieInvalidated(navInfoState, action.payload);\n+ sessionInvalidationAlert(action.payload);\n} else if (\naction.type === leaveThreadActionTypes.success ||\naction.type === deleteThreadActionTypes.success\n@@ -233,60 +155,9 @@ function handleURL(state: NavigationState, url: string): NavigationState {\n};\n}\n-function resetNavInfoAndEnsureLoggedOutModalPresence(state: NavInfo): NavInfo {\n- let navigationState = { ...state.navigationState };\n- navigationState.routes[0] = defaultNavInfo.navigationState.routes[0];\n-\n- let loggedOutModalFound = false;\n- navigationState = removeScreensFromStack(\n- navigationState,\n- (route: NavigationRoute) => {\n- const { routeName } = route;\n- if (routeName === LoggedOutModalRouteName) {\n- loggedOutModalFound = true;\n- }\n- return routeName === AppRouteName || accountModals.includes(routeName)\n- ? 'keep'\n- : 'remove';\n- },\n- );\n-\n- if (!loggedOutModalFound) {\n- const [appRoute, ...restRoutes] = navigationState.routes;\n- navigationState = {\n- ...navigationState,\n- index: navigationState.index + 1,\n- routes: [\n- appRoute,\n- { key: 'LoggedOutModal', routeName: LoggedOutModalRouteName },\n- ...restRoutes,\n- ],\n- };\n- if (navigationState.index === 1) {\n- navigationState = {\n- ...navigationState,\n- isTransitioning: true,\n- };\n- }\n- }\n-\n- return {\n- startDate: defaultNavInfo.startDate,\n- endDate: defaultNavInfo.endDate,\n- navigationState,\n- };\n-}\n-\n-function logOutIfCookieInvalidated(\n- state: NavInfo,\n- payload: SetSessionPayload,\n-): NavInfo {\n+function sessionInvalidationAlert(payload: SetSessionPayload) {\nif (!payload.sessionChange.cookieInvalidated) {\n- return state;\n- }\n- const newState = resetNavInfoAndEnsureLoggedOutModalPresence(state);\n- if (state.navigationState === newState.navigationState) {\n- return newState;\n+ return;\n}\nif (payload.error === 'client_version_unsupported') {\nconst app = Platform.select({\n@@ -307,7 +178,6 @@ function logOutIfCookieInvalidated(\n[{ text: 'OK' }],\n);\n}\n- return newState;\n}\nfunction replaceChatRoute(\n@@ -421,9 +291,4 @@ function handleNewThread(\nreturn replaceChatRoute(state, replaceFunc);\n}\n-export {\n- defaultNavInfo,\n- reduceNavInfo,\n- replaceChatRoute,\n- resetNavInfoAndEnsureLoggedOutModalPresence,\n-};\n+export default reduceNavInfo;\n" }, { "change_type": "MODIFY", "old_path": "native/navigation/root-router.js", "new_path": "native/navigation/root-router.js", "diff": "@@ -10,7 +10,12 @@ import {\n} from 'react-navigation';\nimport { removeScreensFromStack } from '../utils/navigation-utils';\n-import { accountModals } from './route-names';\n+import {\n+ accountModals,\n+ LoggedOutModalRouteName,\n+ AppRouteName,\n+} from './route-names';\n+import { defaultNavInfo } from './default-state';\ntype LogInAction = {|\n+type: 'LOG_IN',\n@@ -52,7 +57,54 @@ function RootRouter(\nisTransitioning: true,\n};\n} else if (action.type === 'LOG_OUT') {\n+ if (!lastState) {\nreturn lastState;\n+ }\n+ let newState = { ...lastState };\n+ newState.routes[0] = defaultNavInfo.navigationState.routes[0];\n+\n+ const initialKey = newState.routes[newState.index].key;\n+ let loggedOutModalFound = false;\n+ newState = removeScreensFromStack(\n+ newState,\n+ (route: NavigationRoute) => {\n+ const { routeName } = route;\n+ if (routeName === LoggedOutModalRouteName) {\n+ loggedOutModalFound = true;\n+ }\n+ return routeName === AppRouteName ||\n+ accountModals.includes(routeName)\n+ ? 'keep'\n+ : 'remove';\n+ },\n+ );\n+\n+ let isTransitioning =\n+ newState.routes[newState.index].key === initialKey;\n+ if (!loggedOutModalFound) {\n+ const [appRoute, ...restRoutes] = newState.routes;\n+ newState = {\n+ ...newState,\n+ index: newState.index + 1,\n+ routes: [\n+ appRoute,\n+ { key: 'LoggedOutModal', routeName: LoggedOutModalRouteName },\n+ ...restRoutes,\n+ ],\n+ };\n+ if (newState.index === 1) {\n+ isTransitioning = true;\n+ }\n+ }\n+\n+ if (isTransitioning) {\n+ newState = {\n+ ...newState,\n+ isTransitioning,\n+ };\n+ }\n+\n+ return newState;\n} else {\nreturn stackRouter.getStateForAction(action, lastState);\n}\n" }, { "change_type": "MODIFY", "old_path": "native/redux/redux-setup.js", "new_path": "native/redux/redux-setup.js", "diff": "@@ -5,7 +5,6 @@ import { type EntryStore } from 'lib/types/entry-types';\nimport type { LoadingStatus } from 'lib/types/loading-types';\nimport type { CurrentUserInfo, UserInfo } from 'lib/types/user-types';\nimport type { MessageStore } from 'lib/types/message-types';\n-import type { NavInfo } from '../navigation/navigation-setup';\nimport type { PersistState } from 'redux-persist/src/types';\nimport {\ntype NotifPermissionAlertInfo,\n@@ -39,7 +38,7 @@ import type { ClientReportCreationRequest } from 'lib/types/report-types';\nimport thunk from 'redux-thunk';\nimport { createStore, applyMiddleware, type Store, compose } from 'redux';\n-import { persistStore, persistReducer, REHYDRATE } from 'redux-persist';\n+import { persistStore, persistReducer } from 'redux-persist';\nimport { createReactNavigationReduxMiddleware } from 'react-navigation-redux-helpers';\nimport {\nAppState as NativeAppState,\n@@ -70,11 +69,8 @@ import {\nupdateDeviceOrientationActionType,\nbackgroundActionTypes,\n} from './action-types';\n-import {\n- defaultNavInfo,\n- reduceNavInfo,\n- resetNavInfoAndEnsureLoggedOutModalPresence,\n-} from '../navigation/navigation-setup';\n+import reduceNavInfo from '../navigation/nav-reducer';\n+import { type NavInfo, defaultNavInfo } from '../navigation/default-state';\nimport { reduceThreadIDsToNotifIDs } from '../push/reducer';\nimport { persistConfig, setPersistor } from './persist';\nimport {\n@@ -367,16 +363,6 @@ function validateState(\n};\n}\n- if (\n- action.type !== REHYDRATE &&\n- (!state.currentUserInfo || state.currentUserInfo.anonymous)\n- ) {\n- const navInfo = resetNavInfoAndEnsureLoggedOutModalPresence(state.navInfo);\n- if (navInfo.navigationState !== state.navInfo.navigationState) {\n- state = { ...state, navInfo };\n- }\n- }\n-\nreturn state;\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Use NavigationHandler and RootRouter to handle log outs
129,187
31.03.2020 17:58:11
14,400
b1e952ed28d0689f1da2488d5343d4e56ed40ed6
[native] getThreadIDFromRoute
[ { "change_type": "MODIFY", "old_path": "native/navigation/nav-reducer.js", "new_path": "native/navigation/nav-reducer.js", "diff": "@@ -26,11 +26,11 @@ import { threadInfoFromRawThreadInfo } from 'lib/shared/thread-utils';\nimport {\nassertNavigationRouteNotLeafNode,\ngetThreadIDFromParams,\n+ getThreadIDFromRoute,\nremoveScreensFromStack,\n} from '../utils/navigation-utils';\nimport {\nComposeThreadRouteName,\n- DeleteThreadRouteName,\nThreadSettingsRouteName,\nMessageListRouteName,\nVerificationModalRouteName,\n@@ -224,7 +224,7 @@ function popChatScreensForThreadID(\n) {\nreturn 'break';\n}\n- const threadID = getThreadIDFromParams(route);\n+ const threadID = getThreadIDFromParams(route.params);\nif (threadID !== actionPayload.threadID) {\nreturn 'break';\n}\n@@ -239,14 +239,10 @@ function filterChatScreensForThreadInfos(\n): NavigationState {\nconst replaceFunc = (chatRoute: NavigationStateRoute) =>\nremoveScreensFromStack(chatRoute, (route: NavigationRoute) => {\n- if (\n- route.routeName !== MessageListRouteName &&\n- route.routeName !== ThreadSettingsRouteName &&\n- route.routeName !== DeleteThreadRouteName\n- ) {\n+ const threadID = getThreadIDFromRoute(route);\n+ if (!threadID) {\nreturn 'keep';\n}\n- const threadID = getThreadIDFromParams(route);\nif (threadID in threadInfos) {\nreturn 'keep';\n}\n" }, { "change_type": "MODIFY", "old_path": "native/navigation/nav-selectors.js", "new_path": "native/navigation/nav-selectors.js", "diff": "@@ -29,7 +29,7 @@ import {\n} from './route-names';\nimport {\nassertNavigationRouteNotLeafNode,\n- getThreadIDFromParams,\n+ getThreadIDFromRoute,\n} from '../utils/navigation-utils';\nimport { NavContext } from './navigation-context';\n@@ -189,10 +189,7 @@ function activeThread(\n}\nconst chatRoute = assertNavigationRouteNotLeafNode(currentTabSubroute);\nconst currentChatSubroute = chatRoute.routes[chatRoute.index];\n- if (!validRouteNames.includes(currentChatSubroute.routeName)) {\n- return null;\n- }\n- return getThreadIDFromParams(currentChatSubroute);\n+ return getThreadIDFromRoute(currentChatSubroute, validRouteNames);\n}\nconst activeThreadSelector: (\n" }, { "change_type": "MODIFY", "old_path": "native/utils/navigation-utils.js", "new_path": "native/utils/navigation-utils.js", "diff": "@@ -10,6 +10,12 @@ import type {\nimport invariant from 'invariant';\n+import {\n+ MessageListRouteName,\n+ ThreadSettingsRouteName,\n+ DeleteThreadRouteName,\n+} from '../navigation/route-names';\n+\nfunction assertNavigationRouteNotLeafNode(\nroute: NavigationRoute,\n): NavigationStateRoute {\n@@ -67,16 +73,31 @@ function assertNavigationRouteNotLeafNode(\n};\n}\n-function getThreadIDFromParams(object: { params?: NavigationParams }): string {\n+function getThreadIDFromParams(params: ?NavigationParams): string {\ninvariant(\n- object.params &&\n- object.params.threadInfo &&\n- typeof object.params.threadInfo === 'object' &&\n- object.params.threadInfo.id &&\n- typeof object.params.threadInfo.id === 'string',\n+ params &&\n+ params.threadInfo &&\n+ typeof params.threadInfo === 'object' &&\n+ params.threadInfo.id &&\n+ typeof params.threadInfo.id === 'string',\n\"there's no way in react-navigation/Flow to type this\",\n);\n- return object.params.threadInfo.id;\n+ return params.threadInfo.id;\n+}\n+\n+const defaultThreadIDRoutes = [\n+ MessageListRouteName,\n+ ThreadSettingsRouteName,\n+ DeleteThreadRouteName,\n+];\n+function getThreadIDFromRoute(\n+ route: NavigationRoute,\n+ routes?: $ReadOnlyArray<string> = defaultThreadIDRoutes,\n+) {\n+ if (!routes.includes(route.routeName)) {\n+ return null;\n+ }\n+ return getThreadIDFromParams(route.params);\n}\nfunction currentRouteRecurse(state: NavigationRoute): NavigationLeafRoute {\n@@ -149,6 +170,7 @@ function removeScreensFromStack<S: NavigationState>(\nexport {\nassertNavigationRouteNotLeafNode,\ngetThreadIDFromParams,\n+ getThreadIDFromRoute,\ncurrentLeafRoute,\nfindRouteIndexWithKey,\nremoveScreensFromStack,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] getThreadIDFromRoute
129,187
01.04.2020 10:20:51
14,400
b936c93f1b44c79944f97b07323aedfba2bc37e1
[native] Only count a thread MessageList as active thread For clearing notifs and badge count
[ { "change_type": "MODIFY", "old_path": "native/navigation/nav-selectors.js", "new_path": "native/navigation/nav-selectors.js", "diff": "@@ -17,7 +17,6 @@ import { nonThreadCalendarFiltersSelector } from 'lib/selectors/calendar-filter-\nimport {\nAppRouteName,\nTabNavigatorRouteName,\n- ThreadSettingsRouteName,\nMessageListRouteName,\nChatRouteName,\nCalendarRouteName,\n@@ -26,6 +25,7 @@ import {\naccountModals,\nscrollBlockingChatModals,\nchatRootModals,\n+ threadRoutes,\n} from './route-names';\nimport {\nassertNavigationRouteNotLeafNode,\n@@ -197,10 +197,7 @@ const activeThreadSelector: (\n) => ?string = createSelector(\n(context: ?NavContextType) => context && context.state,\n(navigationState: ?NavigationState): ?string =>\n- activeThread(navigationState, [\n- MessageListRouteName,\n- ThreadSettingsRouteName,\n- ]),\n+ activeThread(navigationState, threadRoutes),\n);\nconst activeMessageListSelector: (\n" }, { "change_type": "MODIFY", "old_path": "native/navigation/route-names.js", "new_path": "native/navigation/route-names.js", "diff": "@@ -61,3 +61,9 @@ export const chatRootModals = [\nColorPickerModalRouteName,\nComposeSubthreadModalRouteName,\n];\n+\n+export const threadRoutes = [\n+ MessageListRouteName,\n+ ThreadSettingsRouteName,\n+ DeleteThreadRouteName,\n+];\n" }, { "change_type": "MODIFY", "old_path": "native/push/push-handler.react.js", "new_path": "native/push/push-handler.react.js", "diff": "@@ -55,7 +55,7 @@ import {\nrecordNotifPermissionAlertActionType,\nclearAndroidNotificationsActionType,\n} from '../redux/action-types';\n-import { activeThreadSelector } from '../navigation/nav-selectors';\n+import { activeMessageListSelector } from '../navigation/nav-selectors';\nimport {\nrequestIOSPushPermissions,\niosPushPermissionResponseReceived,\n@@ -604,7 +604,7 @@ AppRegistry.registerHeadlessTask(\n);\nexport default connectNav((context: ?NavContextType) => ({\n- activeThread: activeThreadSelector(context),\n+ activeThread: activeMessageListSelector(context),\n}))(\nconnect(\n(state: AppState) => ({\n" }, { "change_type": "MODIFY", "old_path": "native/redux/redux-setup.js", "new_path": "native/redux/redux-setup.js", "diff": "@@ -55,7 +55,7 @@ import {\ndeleteAccountActionTypes,\n} from 'lib/actions/user-actions';\n-import { activeThreadSelector } from '../navigation/nav-selectors';\n+import { activeMessageListSelector } from '../navigation/nav-selectors';\nimport {\nresetUserStateActionType,\nrecordNotifPermissionAlertActionType,\n@@ -302,11 +302,11 @@ function validateState(\nstate: AppState,\naction: *,\n): AppState {\n- const oldActiveThread = activeThreadSelector({\n+ const oldActiveThread = activeMessageListSelector({\nstate: oldState.navInfo.navigationState,\ndispatch: () => true,\n});\n- const activeThread = activeThreadSelector({\n+ const activeThread = activeMessageListSelector({\nstate: state.navInfo.navigationState,\ndispatch: () => true,\n});\n" }, { "change_type": "MODIFY", "old_path": "native/socket.react.js", "new_path": "native/socket.react.js", "diff": "@@ -14,7 +14,7 @@ import {\nnativeSessionStateFuncSelector,\n} from './selectors/socket-selectors';\nimport {\n- activeThreadSelector,\n+ activeMessageListSelector,\nnativeCalendarQuery,\n} from './navigation/nav-selectors';\nimport {\n@@ -23,7 +23,7 @@ import {\n} from './navigation/navigation-context';\nexport default connectNav((context: ?NavContextType) => ({\n- rawActiveThread: activeThreadSelector(context),\n+ rawActiveThread: activeMessageListSelector(context),\nnavContext: context,\n}))(\nconnect(\n" }, { "change_type": "MODIFY", "old_path": "native/utils/navigation-utils.js", "new_path": "native/utils/navigation-utils.js", "diff": "@@ -10,11 +10,7 @@ import type {\nimport invariant from 'invariant';\n-import {\n- MessageListRouteName,\n- ThreadSettingsRouteName,\n- DeleteThreadRouteName,\n-} from '../navigation/route-names';\n+import { threadRoutes } from '../navigation/route-names';\nfunction assertNavigationRouteNotLeafNode(\nroute: NavigationRoute,\n@@ -85,14 +81,9 @@ function getThreadIDFromParams(params: ?NavigationParams): string {\nreturn params.threadInfo.id;\n}\n-const defaultThreadIDRoutes = [\n- MessageListRouteName,\n- ThreadSettingsRouteName,\n- DeleteThreadRouteName,\n-];\nfunction getThreadIDFromRoute(\nroute: NavigationRoute,\n- routes?: $ReadOnlyArray<string> = defaultThreadIDRoutes,\n+ routes?: $ReadOnlyArray<string> = threadRoutes,\n) {\nif (!routes.includes(route.routeName)) {\nreturn null;\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Only count a thread MessageList as active thread For clearing notifs and badge count
129,187
01.04.2020 09:59:49
14,400
938d5111e8762fce4c8903a1583201b69ea0d6f5
[native] ThreadScreenPruner
[ { "change_type": "MODIFY", "old_path": "native/chat/chat-router.js", "new_path": "native/chat/chat-router.js", "diff": "@@ -16,7 +16,10 @@ import {\nChatThreadListRouteName,\nMessageListRouteName,\n} from '../navigation/route-names';\n-import { removeScreensFromStack } from '../utils/navigation-utils';\n+import {\n+ removeScreensFromStack,\n+ getThreadIDFromRoute,\n+} from '../utils/navigation-utils';\ntype ClearScreensAction = {|\n+type: 'CLEAR_SCREENS',\n@@ -26,10 +29,15 @@ type ReplaceWithThreadAction = {|\n+type: 'REPLACE_WITH_THREAD',\n+threadInfo: ThreadInfo,\n|};\n+type ClearInvalidatedThreadsAction = {|\n+ +type: 'CLEAR_INVALIDATED_THREADS',\n+ +threadIDs: $ReadOnlyArray<string>,\n+|};\nexport type ChatRouterNavigationAction =\n| NavigationAction\n| ClearScreensAction\n- | ReplaceWithThreadAction;\n+ | ReplaceWithThreadAction\n+ | ClearInvalidatedThreadsAction;\nconst defaultConfig = Object.freeze({});\nfunction ChatRouter(\n@@ -48,9 +56,17 @@ function ChatRouter(\nif (!lastState) {\nreturn lastState;\n}\n- return removeScreensFromStack(lastState, (route: NavigationRoute) =>\n+ const lastActiveKey = lastState.routes[lastState.index].key;\n+ const newState = removeScreensFromStack(\n+ lastState,\n+ (route: NavigationRoute) =>\nrouteNames.includes(route.routeName) ? 'remove' : 'keep',\n);\n+ const newActiveKey = newState.routes[newState.index].key;\n+ if (lastActiveKey === newActiveKey) {\n+ return newState;\n+ }\n+ return { ...newState, isTransitioning: true };\n} else if (action.type === 'REPLACE_WITH_THREAD') {\nconst { threadInfo } = action;\nif (!lastState) {\n@@ -67,6 +83,22 @@ function ChatRouter(\nparams: { threadInfo },\n});\nreturn stackRouter.getStateForAction(navigateAction, clearedState);\n+ } else if (action.type === 'CLEAR_INVALIDATED_THREADS') {\n+ const threadIDs = new Set(action.threadIDs);\n+ if (!lastState) {\n+ return lastState;\n+ }\n+ const lastActiveKey = lastState.routes[lastState.index].key;\n+ const newState = removeScreensFromStack(\n+ lastState,\n+ (route: NavigationRoute) =>\n+ threadIDs.has(getThreadIDFromRoute(route)) ? 'remove' : 'keep',\n+ );\n+ const newActiveKey = newState.routes[newState.index].key;\n+ if (lastActiveKey === newActiveKey) {\n+ return newState;\n+ }\n+ return { ...newState, isTransitioning: true };\n} else {\nreturn stackRouter.getStateForAction(action, lastState);\n}\n@@ -81,6 +113,10 @@ function ChatRouter(\ntype: 'REPLACE_WITH_THREAD',\nthreadInfo,\n}),\n+ clearInvalidatedThreads: (threadIDs: $ReadOnlyArray<string>) => ({\n+ type: 'CLEAR_INVALIDATED_THREADS',\n+ threadIDs,\n+ }),\n}),\n};\n}\n" }, { "change_type": "MODIFY", "old_path": "native/chat/chat.react.js", "new_path": "native/chat/chat.react.js", "diff": "@@ -40,6 +40,7 @@ import {\n} from './chat-input-state';\nimport KeyboardAvoidingView from '../keyboard/keyboard-avoiding-view.react';\nimport MessageStorePruner from './message-store-pruner.react';\n+import ThreadScreenPruner from './thread-screen-pruner.react';\ntype NavigationProp = NavigationStackProp<NavigationState> & {\nclearScreens: (routeNames: $ReadOnlyArray<string>) => void,\n@@ -150,6 +151,7 @@ class WrappedChatNavigator extends React.PureComponent<WrappedProps> {\n<KeyboardAvoidingView style={styles.keyboardAvoidingView}>\n<ChatNavigator {...props} />\n<MessageStorePruner />\n+ <ThreadScreenPruner />\n</KeyboardAvoidingView>\n);\n}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "native/chat/thread-screen-pruner.react.js", "diff": "+// @flow\n+\n+import type { AppState } from '../redux/redux-setup';\n+\n+import * as React from 'react';\n+import { useSelector } from 'react-redux';\n+import { Alert } from 'react-native';\n+\n+import { NavContext } from '../navigation/navigation-context';\n+import {\n+ assertNavigationRouteNotLeafNode,\n+ getThreadIDFromRoute,\n+} from '../utils/navigation-utils';\n+import { useActiveThread } from '../navigation/nav-selectors';\n+\n+function ThreadScreenPruner() {\n+ const rawThreadInfos = useSelector(\n+ (state: AppState) => state.threadStore.threadInfos,\n+ );\n+\n+ const navContext = React.useContext(NavContext);\n+\n+ const chatRoute = React.useMemo(() => {\n+ if (!navContext) {\n+ return null;\n+ }\n+ const { state } = navContext;\n+ const appRoute = assertNavigationRouteNotLeafNode(state.routes[0]);\n+ const tabRoute = assertNavigationRouteNotLeafNode(appRoute.routes[0]);\n+ return assertNavigationRouteNotLeafNode(tabRoute.routes[1]);\n+ }, [navContext]);\n+\n+ const inStackThreadIDs = React.useMemo(() => {\n+ const threadIDs = new Set();\n+ if (!chatRoute) {\n+ return threadIDs;\n+ }\n+ for (let route of chatRoute.routes) {\n+ const threadID = getThreadIDFromRoute(route);\n+ if (threadID) {\n+ threadIDs.add(threadID);\n+ }\n+ }\n+ return threadIDs;\n+ }, [chatRoute]);\n+\n+ const pruneThreadIDs = React.useMemo(() => {\n+ const threadIDs = [];\n+ for (let threadID of inStackThreadIDs) {\n+ if (!rawThreadInfos[threadID]) {\n+ threadIDs.push(threadID);\n+ }\n+ }\n+ return threadIDs;\n+ }, [inStackThreadIDs, rawThreadInfos]);\n+\n+ const activeThreadID = useActiveThread();\n+\n+ React.useEffect(() => {\n+ if (pruneThreadIDs.length === 0 || !navContext) {\n+ return;\n+ }\n+ if (activeThreadID && pruneThreadIDs.includes(activeThreadID)) {\n+ Alert.alert(\n+ 'Thread invalidated',\n+ 'You no longer have permission to view this thread :(',\n+ [{ text: 'OK' }],\n+ );\n+ }\n+ navContext.dispatch({\n+ type: 'CLEAR_INVALIDATED_THREADS',\n+ threadIDs: pruneThreadIDs,\n+ });\n+ }, [pruneThreadIDs, navContext, activeThreadID]);\n+\n+ return null;\n+}\n+\n+export default ThreadScreenPruner;\n" }, { "change_type": "MODIFY", "old_path": "native/navigation/nav-reducer.js", "new_path": "native/navigation/nav-reducer.js", "diff": "@@ -26,7 +26,6 @@ import { threadInfoFromRawThreadInfo } from 'lib/shared/thread-utils';\nimport {\nassertNavigationRouteNotLeafNode,\ngetThreadIDFromParams,\n- getThreadIDFromRoute,\nremoveScreensFromStack,\n} from '../utils/navigation-utils';\nimport {\n@@ -47,11 +46,7 @@ function getUniqueMessageListRouteKey() {\nreturn `${messageListRouteBase}-${messageListRouteIndex++}`;\n}\n-function reduceNavInfo(\n- state: AppState,\n- action: *,\n- newThreadInfos: { [id: string]: RawThreadInfo },\n-): NavInfo {\n+function reduceNavInfo(state: AppState, action: *): NavInfo {\nlet navInfoState = state.navInfo;\n// React Navigation actions\nconst navigationState = RootNavigator.router.getStateForAction(\n@@ -66,19 +61,6 @@ function reduceNavInfo(\n};\n}\n- // Filtering out screens corresponding to deauthorized threads\n- const filteredNavigationState = filterChatScreensForThreadInfos(\n- navInfoState.navigationState,\n- newThreadInfos,\n- );\n- if (navInfoState.navigationState !== filteredNavigationState) {\n- navInfoState = {\n- startDate: navInfoState.startDate,\n- endDate: navInfoState.endDate,\n- navigationState: filteredNavigationState,\n- };\n- }\n-\n// Deep linking\nif (action.type === handleURLActionType) {\nreturn {\n@@ -233,24 +215,6 @@ function popChatScreensForThreadID(\nreturn replaceChatRoute(state, replaceFunc);\n}\n-function filterChatScreensForThreadInfos(\n- state: NavigationState,\n- threadInfos: { [id: string]: RawThreadInfo },\n-): NavigationState {\n- const replaceFunc = (chatRoute: NavigationStateRoute) =>\n- removeScreensFromStack(chatRoute, (route: NavigationRoute) => {\n- const threadID = getThreadIDFromRoute(route);\n- if (!threadID) {\n- return 'keep';\n- }\n- if (threadID in threadInfos) {\n- return 'keep';\n- }\n- return 'remove';\n- });\n- return replaceChatRoute(state, replaceFunc);\n-}\n-\nfunction handleNewThread(\nstate: NavigationState,\nrawThreadInfo: RawThreadInfo,\n" }, { "change_type": "MODIFY", "old_path": "native/navigation/nav-selectors.js", "new_path": "native/navigation/nav-selectors.js", "diff": "@@ -208,6 +208,17 @@ const activeMessageListSelector: (\nactiveThread(navigationState, [MessageListRouteName]),\n);\n+function useActiveThread() {\n+ const navContext = React.useContext(NavContext);\n+ return React.useMemo(() => {\n+ if (!navContext) {\n+ return null;\n+ }\n+ const { state } = navContext;\n+ return activeThread(state, threadRoutes);\n+ }, [navContext]);\n+}\n+\nconst calendarTabActiveSelector = createActiveTabSelector(CalendarRouteName);\nconst threadPickerActiveSelector = createIsForegroundSelector(\nThreadPickerModalRouteName,\n@@ -262,6 +273,7 @@ export {\noverlayTransitioningSelector,\nactiveThreadSelector,\nactiveMessageListSelector,\n+ useActiveThread,\ncalendarActiveSelector,\nnativeCalendarQuery,\nnonThreadCalendarQuery,\n" }, { "change_type": "MODIFY", "old_path": "native/redux/redux-setup.js", "new_path": "native/redux/redux-setup.js", "diff": "@@ -289,7 +289,7 @@ function reducer(state: AppState = defaultState, action: *) {\ndrafts: reduceDrafts(state.drafts, action),\n};\n- const navInfo = reduceNavInfo(state, action, state.threadStore.threadInfos);\n+ const navInfo = reduceNavInfo(state, action);\nif (navInfo && navInfo !== state.navInfo) {\nstate = { ...state, navInfo };\n}\n@@ -315,6 +315,7 @@ function validateState(\n(NativeAppState.currentState === 'active' ||\n(appLastBecameInactive + 10000 < Date.now() &&\n!backgroundActionTypes.has(action.type))) &&\n+ state.threadStore.threadInfos[activeThread] &&\nstate.threadStore.threadInfos[activeThread].currentUser.unread\n) {\n// Makes sure a currently focused thread is never unread. Note that we\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] ThreadScreenPruner
129,187
01.04.2020 10:56:45
14,400
3e415cec705033ec5cb48c94f5379ea1a72eed27
[native] Clear ComposeThreadRouteName with parentThreadID when thread invalidated
[ { "change_type": "MODIFY", "old_path": "native/navigation/route-names.js", "new_path": "native/navigation/route-names.js", "diff": "@@ -66,4 +66,5 @@ export const threadRoutes = [\nMessageListRouteName,\nThreadSettingsRouteName,\nDeleteThreadRouteName,\n+ ComposeThreadRouteName,\n];\n" }, { "change_type": "MODIFY", "old_path": "native/utils/navigation-utils.js", "new_path": "native/utils/navigation-utils.js", "diff": "@@ -10,7 +10,10 @@ import type {\nimport invariant from 'invariant';\n-import { threadRoutes } from '../navigation/route-names';\n+import {\n+ ComposeThreadRouteName,\n+ threadRoutes,\n+} from '../navigation/route-names';\nfunction assertNavigationRouteNotLeafNode(\nroute: NavigationRoute,\n@@ -81,6 +84,16 @@ function getThreadIDFromParams(params: ?NavigationParams): string {\nreturn params.threadInfo.id;\n}\n+function getParentThreadIDFromParams(params: ?NavigationParams): ?string {\n+ invariant(\n+ params &&\n+ (typeof params.parentThreadID === 'string' ||\n+ (typeof params.parentThreadID === 'object' && !params.parentThreadID)),\n+ \"there's no way in react-navigation/Flow to type this\",\n+ );\n+ return params.parentThreadID;\n+}\n+\nfunction getThreadIDFromRoute(\nroute: NavigationRoute,\nroutes?: $ReadOnlyArray<string> = threadRoutes,\n@@ -88,6 +101,9 @@ function getThreadIDFromRoute(\nif (!routes.includes(route.routeName)) {\nreturn null;\n}\n+ if (route.routeName === ComposeThreadRouteName) {\n+ return getParentThreadIDFromParams(route.params);\n+ }\nreturn getThreadIDFromParams(route.params);\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Clear ComposeThreadRouteName with parentThreadID when thread invalidated
129,187
01.04.2020 15:04:42
14,400
af1c2d35e3797c5348d12ec4718464c873033916
[native] ChatInputState.unregisterSendCallback
[ { "change_type": "MODIFY", "old_path": "native/chat/chat-input-state-container.react.js", "new_path": "native/chat/chat-input-state-container.react.js", "diff": "@@ -276,6 +276,7 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\nmessageHasUploadFailure: this.messageHasUploadFailure,\nretryMultimediaMessage: this.retryMultimediaMessage,\nregisterSendCallback: this.registerSendCallback,\n+ unregisterSendCallback: this.unregisterSendCallback,\n}),\n);\n@@ -717,6 +718,12 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\nthis.sendCallbacks.push(callback);\n};\n+ unregisterSendCallback = (callback: () => void) => {\n+ this.sendCallbacks = this.sendCallbacks.filter(\n+ candidate => candidate !== callback,\n+ );\n+ };\n+\nrender() {\nconst chatInputState = this.chatInputStateSelector(this.state);\nreturn (\n" }, { "change_type": "MODIFY", "old_path": "native/chat/chat-input-state.js", "new_path": "native/chat/chat-input-state.js", "diff": "@@ -42,6 +42,7 @@ export type ChatInputState = {|\nmessageHasUploadFailure: (localMessageID: string) => boolean,\nretryMultimediaMessage: (localMessageID: string) => Promise<void>,\nregisterSendCallback: (() => void) => void,\n+ unregisterSendCallback: (() => void) => void,\n|};\nconst chatInputStatePropType = PropTypes.shape({\n" }, { "change_type": "MODIFY", "old_path": "native/chat/chat.react.js", "new_path": "native/chat/chat.react.js", "diff": "// @flow\n+import type { ThreadInfo } from 'lib/types/thread-types';\n+\nimport * as React from 'react';\nimport {\ntype NavigationRouteConfigMap,\n@@ -33,17 +35,15 @@ import {\nimport HeaderBackButton from '../navigation/header-back-button.react';\nimport ChatHeader from './chat-header.react';\nimport ChatRouter from './chat-router';\n-import {\n- type ChatInputState,\n- chatInputStatePropType,\n- withChatInputState,\n-} from './chat-input-state';\n+import { ChatInputStateContext } from './chat-input-state';\nimport KeyboardAvoidingView from '../keyboard/keyboard-avoiding-view.react';\nimport MessageStorePruner from './message-store-pruner.react';\nimport ThreadScreenPruner from './thread-screen-pruner.react';\ntype NavigationProp = NavigationStackProp<NavigationState> & {\nclearScreens: (routeNames: $ReadOnlyArray<string>) => void,\n+ replaceWithThread: (threadInfo: ThreadInfo) => void,\n+ clearInvalidatedThreads: (threadIDs: $ReadOnlyArray<string>) => void,\n};\ntype Props = {| navigation: NavigationProp |};\ntype StackViewProps = React.ElementConfig<typeof StackView> & {\n@@ -126,27 +126,23 @@ ChatNavigator.navigationOptions = {\n},\n};\n-type WrappedProps = {\n- ...Props,\n- // withChatInputState\n- chatInputState: ?ChatInputState,\n-};\n-class WrappedChatNavigator extends React.PureComponent<WrappedProps> {\n- static propTypes = {\n- chatInputState: chatInputStatePropType,\n- };\n+function WrappedChatNavigator(props: Props) {\n+ const { navigation } = props;\n+ const chatInputState = React.useContext(ChatInputStateContext);\n- componentDidUpdate(prevProps: WrappedProps) {\n- const { navigation, chatInputState } = this.props;\n- if (chatInputState && prevProps.navigation !== navigation) {\n- chatInputState.registerSendCallback(() =>\n- navigation.clearScreens([ComposeThreadRouteName]),\n+ const clearScreens = React.useCallback(\n+ () => navigation.clearScreens([ComposeThreadRouteName]),\n+ [navigation],\n);\n+\n+ React.useEffect(() => {\n+ if (!chatInputState) {\n+ return undefined;\n}\n- }\n+ chatInputState.registerSendCallback(clearScreens);\n+ return () => chatInputState.unregisterSendCallback(clearScreens);\n+ }, [chatInputState, clearScreens]);\n- render() {\n- const { chatInputState, ...props } = this.props;\nreturn (\n<KeyboardAvoidingView style={styles.keyboardAvoidingView}>\n<ChatNavigator {...props} />\n@@ -155,7 +151,7 @@ class WrappedChatNavigator extends React.PureComponent<WrappedProps> {\n</KeyboardAvoidingView>\n);\n}\n-}\n+hoistNonReactStatics(WrappedChatNavigator, ChatNavigator);\nconst styles = StyleSheet.create({\nkeyboardAvoidingView: {\n@@ -163,11 +159,4 @@ const styles = StyleSheet.create({\n},\n});\n-const ConnectedWrappedChatNavigator = withChatInputState(WrappedChatNavigator);\n-\n-function FinalChatNavigator(props: Props) {\n- return <ConnectedWrappedChatNavigator {...props} />;\n-}\n-hoistNonReactStatics(FinalChatNavigator, ChatNavigator);\n-\n-export default FinalChatNavigator;\n+export default WrappedChatNavigator;\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] ChatInputState.unregisterSendCallback
129,187
01.04.2020 15:14:35
14,400
893f3ef934cbcbf040f84c2fb839b8708cfdd8bf
[native] Don't bother with registerChatScreen for ComposeThread
[ { "change_type": "MODIFY", "old_path": "native/chat/compose-thread.react.js", "new_path": "native/chat/compose-thread.react.js", "diff": "@@ -52,7 +52,6 @@ import UserList from '../components/user-list.react';\nimport ThreadList from '../components/thread-list.react';\nimport LinkButton from '../components/link-button.react';\nimport { MessageListRouteName } from '../navigation/route-names';\n-import { registerChatScreen } from './chat-screen-registry';\nimport ThreadVisibility from '../components/thread-visibility.react';\nimport {\ntype Colors,\n@@ -162,20 +161,14 @@ class ComposeThread extends React.PureComponent<Props, State> {\ncreateThreadPressed = false;\ncomponentDidMount() {\n- registerChatScreen(this.props.navigation.state.key, this);\nsetOnPressCreateThread(this.onPressCreateThread);\nthis.searchUsers('');\n}\ncomponentWillUnmount() {\n- registerChatScreen(this.props.navigation.state.key, null);\nsetOnPressCreateThread(null);\n}\n- get canReset() {\n- return false;\n- }\n-\nuserSearchResultsSelector = createSelector(\n(propsAndState: PropsAndState) => propsAndState.usernameInputText,\n(propsAndState: PropsAndState) => propsAndState.otherUserInfos,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Don't bother with registerChatScreen for ComposeThread