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 | 06.11.2018 10:14:18 | 18,000 | 2e96b00700cde7e3ee767e50857368cbd228cf9f | [native] Only update badge count while connected
Otherwise we may be overriding a recently updated badge count (from a notif) with a stale value from Redux. | [
{
"change_type": "MODIFY",
"old_path": "native/app.react.js",
"new_path": "native/app.react.js",
"diff": "@@ -19,6 +19,10 @@ import {\nnotifPermissionAlertInfoPropType,\n} from './push/alerts';\nimport type { RawMessageInfo } from 'lib/types/message-types';\n+import {\n+ type ConnectionInfo,\n+ connectionInfoPropType,\n+} from 'lib/types/socket-types';\nimport React from 'react';\nimport { Provider } from 'react-redux';\n@@ -112,6 +116,7 @@ type Props = {\nrawThreadInfos: {[id: string]: RawThreadInfo},\nnotifPermissionAlertInfo: NotifPermissionAlertInfo,\nupdatesCurrentAsOf: number,\n+ connection: ConnectionInfo,\n// Redux dispatch functions\ndispatch: NativeDispatch,\ndispatchActionPayload: DispatchActionPayload,\n@@ -134,6 +139,7 @@ class AppWithNavigationState extends React.PureComponent<Props> {\nrawThreadInfos: PropTypes.objectOf(rawThreadInfoPropType).isRequired,\nnotifPermissionAlertInfo: notifPermissionAlertInfoPropType.isRequired,\nupdatesCurrentAsOf: PropTypes.number.isRequired,\n+ connection: connectionInfoPropType.isRequired,\ndispatch: PropTypes.func.isRequired,\ndispatchActionPayload: PropTypes.func.isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\n@@ -319,7 +325,11 @@ class AppWithNavigationState extends React.PureComponent<Props> {\nAppWithNavigationState.clearNotifsOfThread(nextProps);\n}\n- if (nextProps.unreadCount !== this.props.unreadCount) {\n+ if (\n+ nextProps.connection.status === \"connected\" &&\n+ (this.props.connection.status !== \"connected\" ||\n+ nextProps.unreadCount !== this.props.unreadCount)\n+ ) {\nAppWithNavigationState.updateBadgeCount(nextProps.unreadCount);\n}\n@@ -672,6 +682,7 @@ const ConnectedAppWithNavigationState = connect(\nrawThreadInfos: state.threadStore.threadInfos,\nnotifPermissionAlertInfo: state.notifPermissionAlertInfo,\nupdatesCurrentAsOf: state.updatesCurrentAsOf,\n+ connection: state.connection,\n};\n},\n{ setDeviceToken },\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Only update badge count while connected
Otherwise we may be overriding a recently updated badge count (from a notif) with a stale value from Redux. |
129,187 | 06.11.2018 10:46:44 | 18,000 | 1fc6ea6e40c8356bf6b6dfb65995215c77d78e79 | Fix accidental double-state-check behavior
And also set up state check to occur once every three minutes at max. | [
{
"change_type": "MODIFY",
"old_path": "lib/types/session-types.js",
"new_path": "lib/types/session-types.js",
"diff": "@@ -11,10 +11,10 @@ import type { CalendarQuery } from './entry-types';\nimport PropTypes from 'prop-types';\nexport const cookieLifetime = 30*24*60*60*1000; // in milliseconds\n-//export const sessionCheckFrequency = 3*60*60*1000; // in milliseconds\n-export const sessionCheckFrequency = 0; // in milliseconds\n+// Interval the server waits after a state check before starting a new one\n+export const sessionCheckFrequency = 3*60*1000; // in milliseconds\n// How long the server debounces after activity before initiating a state check\n-export const stateCheckInactivityActivationInterval = 3000; // in milliseconds\n+export const stateCheckInactivityActivationInterval = 3*1000; // in milliseconds\n// On native, we specify the cookie directly in the request and response body.\n// We do this because:\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/socket/socket.js",
"new_path": "server/src/socket/socket.js",
"diff": "@@ -754,12 +754,13 @@ class Socket {\nviewer.sessionLastValidated + sessionCheckFrequency - Date.now();\nif (timeUntilStateCheck <= 0) {\nthis.initiateStateCheck();\n- }\n+ } else {\nthis.stateCheckTimeoutID = setTimeout(\nthis.initiateStateCheck,\ntimeUntilStateCheck,\n);\n}\n+ }\ninitiateStateCheck = async () => {\nthis.setStateCheckConditions({ stateCheckOngoing: true });\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | Fix accidental double-state-check behavior
And also set up state check to occur once every three minutes at max. |
129,187 | 06.11.2018 11:25:45 | 18,000 | 7f008e5864858ad59eab51197d77783e872cd363 | State check mechanism for extraneous threads/entries on client
This provides the server a way to tell the client to delete threads or entries it isn't seeing on its end. | [
{
"change_type": "MODIFY",
"old_path": "lib/reducers/entry-reducer.js",
"new_path": "lib/reducers/entry-reducer.js",
"diff": "@@ -689,19 +689,34 @@ function reduceEntryInfos(\nconst checkStateRequest = action.payload.serverRequests.find(\ncandidate => candidate.type === serverRequestTypes.CHECK_STATE,\n);\n- if (\n- !checkStateRequest ||\n- !checkStateRequest.stateChanges ||\n- !checkStateRequest.stateChanges.rawEntryInfos\n- ) {\n+ if (!checkStateRequest || !checkStateRequest.stateChanges) {\nreturn entryStore;\n}\n- const { rawEntryInfos } = checkStateRequest.stateChanges;\n- const [ updatedEntryInfos, updatedDaysToEntries ] = mergeNewEntryInfos(\n- entryInfos,\n+ const { rawEntryInfos, deleteEntryIDs } = checkStateRequest.stateChanges;\n+ if (!rawEntryInfos && !deleteEntryIDs) {\n+ return entryStore;\n+ }\n+\n+ let updatedEntryInfos = { ...entryInfos };\n+ if (deleteEntryIDs) {\n+ for (let deleteEntryID of deleteEntryIDs) {\n+ delete updatedEntryInfos[deleteEntryID];\n+ }\n+ }\n+\n+ let updatedDaysToEntries;\n+ if (rawEntryInfos) {\n+ [ updatedEntryInfos, updatedDaysToEntries ] = mergeNewEntryInfos(\n+ updatedEntryInfos,\nrawEntryInfos,\nnewThreadInfos,\n);\n+ } else {\n+ updatedDaysToEntries = daysToEntriesFromEntryInfos(\n+ values(updatedEntryInfos),\n+ );\n+ }\n+\nconst newInconsistencies = findInconsistencies(\nentryInfos,\naction,\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/reducers/thread-reducer.js",
"new_path": "lib/reducers/thread-reducer.js",
"diff": "@@ -291,18 +291,26 @@ export default function reduceThreadInfos(\nconst checkStateRequest = action.payload.serverRequests.find(\ncandidate => candidate.type === serverRequestTypes.CHECK_STATE,\n);\n- if (\n- !checkStateRequest ||\n- !checkStateRequest.stateChanges ||\n- !checkStateRequest.stateChanges.rawThreadInfos\n- ) {\n+ if (!checkStateRequest || !checkStateRequest.stateChanges) {\nreturn state;\n}\n- const { rawThreadInfos } = checkStateRequest.stateChanges;\n+ const { rawThreadInfos, deleteThreadIDs } = checkStateRequest.stateChanges;\n+ if (!rawThreadInfos && !deleteThreadIDs) {\n+ return state;\n+ }\n+\nconst newThreadInfos = { ...state.threadInfos };\n+ if (rawThreadInfos) {\nfor (let rawThreadInfo of rawThreadInfos) {\nnewThreadInfos[rawThreadInfo.id] = rawThreadInfo;\n}\n+ }\n+ if (deleteThreadIDs) {\n+ for (let deleteThreadID of deleteThreadIDs) {\n+ delete newThreadInfos[deleteThreadID];\n+ }\n+ }\n+\nconst newInconsistencies = findInconsistencies(\nstate.threadInfos,\naction,\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/selectors/socket-selectors.js",
"new_path": "lib/selectors/socket-selectors.js",
"diff": "@@ -71,6 +71,10 @@ const getClientResponsesSelector = createSelector(\nplatformDetails: getConfig().platformDetails,\n});\n} else if (serverRequest.type === serverRequestTypes.CHECK_STATE) {\n+ const filteredEntryInfos = filterRawEntryInfosByCalendarQuery(\n+ serverEntryInfosObject(values(entryInfos)),\n+ calendarQuery(),\n+ );\nconst hashResults = {};\nfor (let key in serverRequest.hashesToCheck) {\nconst expectedHashValue = serverRequest.hashesToCheck[key];\n@@ -78,10 +82,6 @@ const getClientResponsesSelector = createSelector(\nif (key === \"threadInfos\") {\nhashValue = hash(threadInfos);\n} else if (key === \"entryInfos\") {\n- const filteredEntryInfos = filterRawEntryInfosByCalendarQuery(\n- serverEntryInfosObject(values(entryInfos)),\n- calendarQuery(),\n- );\nhashValue = hash(filteredEntryInfos);\n} else if (key === \"currentUserInfo\") {\nhashValue = hash(currentUserInfo);\n@@ -90,7 +90,7 @@ const getClientResponsesSelector = createSelector(\nhashValue = hash(threadInfos[threadID]);\n} else if (key.startsWith(\"entryInfo|\")) {\nconst [ ignore, entryID ] = key.split('|');\n- let rawEntryInfo = entryInfos[entryID];\n+ let rawEntryInfo = filteredEntryInfos[entryID];\nif (rawEntryInfo) {\nrawEntryInfo = serverEntryInfo(rawEntryInfo);\n}\n@@ -98,6 +98,27 @@ const getClientResponsesSelector = createSelector(\n}\nhashResults[key] = expectedHashValue === hashValue;\n}\n+\n+ const { failUnmentioned } = serverRequest;\n+ if (failUnmentioned && failUnmentioned.threadInfos) {\n+ for (let threadID in threadInfos) {\n+ const key = `threadInfo|${threadID}`;\n+ const hashResult = hashResults[key];\n+ if (hashResult === null || hashResult === undefined) {\n+ hashResults[key] = false;\n+ }\n+ }\n+ }\n+ if (failUnmentioned && failUnmentioned.entryInfos) {\n+ for (let entryID in filteredEntryInfos) {\n+ const key = `entryInfo|${entryID}`;\n+ const hashResult = hashResults[key];\n+ if (hashResult === null || hashResult === undefined) {\n+ hashResults[key] = false;\n+ }\n+ }\n+ }\n+\nclientResponses.push({\ntype: serverRequestTypes.CHECK_STATE,\nhashResults,\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/types/request-types.js",
"new_path": "lib/types/request-types.js",
"diff": "@@ -110,11 +110,17 @@ export type EntryInconsistencyClientResponse = {|\nexport type CheckStateServerRequest = {|\ntype: 6,\nhashesToCheck: {[key: string]: number},\n+ failUnmentioned?: $Shape<{|\n+ threadInfos: bool,\n+ entryInfos: bool,\n+ |}>,\nstateChanges?: $Shape<{|\nrawThreadInfos: RawThreadInfo[],\nrawEntryInfos: RawEntryInfo[],\ncurrentUserInfo: CurrentUserInfo,\nuserInfos: AccountUserInfo[],\n+ deleteThreadIDs: string[],\n+ deleteEntryIDs: string[],\n|}>,\n|};\ntype CheckStateClientResponse = {|\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/responders/ping-responders.js",
"new_path": "server/src/responders/ping-responders.js",
"diff": "@@ -636,7 +636,7 @@ async function checkState(\n}\nconst fetchedData = await promiseAll(fetchPromises);\n- const hashesToCheck = {}, stateChanges = {};\n+ const hashesToCheck = {}, failUnmentioned = {}, stateChanges = {};\nfor (let key of invalidKeys) {\nif (key === \"threadInfos\") {\n// Instead of returning all threadInfos, we want to narrow down and figure\n@@ -645,6 +645,7 @@ async function checkState(\nfor (let threadID in threadInfos) {\nhashesToCheck[`threadInfo|${threadID}`] = hash(threadInfos[threadID]);\n}\n+ failUnmentioned.threadInfos = true;\n} else if (key === \"entryInfos\") {\n// Instead of returning all entryInfos, we want to narrow down and figure\n// out which entryInfos don't match first\n@@ -656,23 +657,25 @@ async function checkState(\ninvariant(entryID, \"should be set\");\nhashesToCheck[`entryInfo|${entryID}`] = hash(entryInfo);\n}\n+ failUnmentioned.entryInfos = true;\n} else if (key === \"currentUserInfo\") {\nstateChanges.currentUserInfo = fetchedData.currentUserInfo;\n} else if (key.startsWith(\"threadInfo|\")) {\n- if (!stateChanges.rawThreadInfos) {\n- stateChanges.rawThreadInfos = [];\n- }\nconst [ ignore, threadID ] = key.split('|');\nconst { threadInfos } = fetchedData.threadsResult;\nconst threadInfo = threadInfos[threadID];\nif (!threadInfo) {\n+ if (!stateChanges.deleteThreadIDs) {\n+ stateChanges.deleteThreadIDs = [];\n+ }\n+ stateChanges.deleteThreadIDs.push(threadID);\ncontinue;\n}\n+ if (!stateChanges.rawThreadInfos) {\n+ stateChanges.rawThreadInfos = [];\n+ }\nstateChanges.rawThreadInfos.push(threadInfo);\n} else if (key.startsWith(\"entryInfo|\")) {\n- if (!stateChanges.rawEntryInfos) {\n- stateChanges.rawEntryInfos = [];\n- }\nconst [ ignore, entryID ] = key.split('|');\nconst rawEntryInfos = fetchedData.entriesResult\n? fetchedData.entriesResult.rawEntryInfos\n@@ -681,8 +684,15 @@ async function checkState(\ncandidate => candidate.id === entryID,\n);\nif (!entryInfo) {\n+ if (!stateChanges.deleteEntryIDs) {\n+ stateChanges.deleteEntryIDs = [];\n+ }\n+ stateChanges.deleteEntryIDs.push(entryID);\ncontinue;\n}\n+ if (!stateChanges.rawEntryInfos) {\n+ stateChanges.rawEntryInfos = [];\n+ }\nstateChanges.rawEntryInfos.push(entryInfo);\n}\n}\n@@ -736,6 +746,7 @@ async function checkState(\nconst checkStateRequest = {\ntype: serverRequestTypes.CHECK_STATE,\nhashesToCheck,\n+ failUnmentioned,\nstateChanges,\n};\nif (Object.keys(hashesToCheck).length === 0) {\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | State check mechanism for extraneous threads/entries on client
This provides the server a way to tell the client to delete threads or entries it isn't seeing on its end. |
129,187 | 06.11.2018 14:34:20 | 18,000 | ca36c6b207e2fc57a51cd487a4d86cbaa10df0fb | CalendarQueryHandler
Handles non-user-initiated `UPDATE_CALENDAR_QUERY` calls. | [
{
"change_type": "MODIFY",
"old_path": "lib/selectors/nav-selectors.js",
"new_path": "lib/selectors/nav-selectors.js",
"diff": "@@ -23,10 +23,24 @@ import {\nnonThreadCalendarFiltersSelector,\n} from './calendar-filter-selectors';\n+function timeUntilCalendarRangeExpiration(\n+ lastUserInteractionCalendar: number,\n+): ?number {\n+ const inactivityLimit = getConfig().calendarRangeInactivityLimit;\n+ if (inactivityLimit === null || inactivityLimit === undefined) {\n+ return null;\n+ }\n+ return lastUserInteractionCalendar + inactivityLimit - Date.now();\n+}\n+\nfunction calendarRangeExpired(lastUserInteractionCalendar: number): bool {\n- const calendarRangeInactivityLimit = getConfig().calendarRangeInactivityLimit;\n- return !!calendarRangeInactivityLimit &&\n- (Date.now() - lastUserInteractionCalendar) > calendarRangeInactivityLimit;\n+ const timeUntil = timeUntilCalendarRangeExpiration(\n+ lastUserInteractionCalendar,\n+ );\n+ if (timeUntil === null || timeUntil === undefined) {\n+ return false;\n+ }\n+ return timeUntil <= 0;\n}\nfunction currentStartDate(\n@@ -134,6 +148,7 @@ const nonThreadCalendarQuery = createSelector(\n);\nexport {\n+ timeUntilCalendarRangeExpiration,\ndefaultCalendarQuery,\ncurrentCalendarQuery,\nthreadSearchIndex,\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "lib/socket/calendar-query-handler.react.js",
"diff": "+// @flow\n+\n+import {\n+ type ConnectionInfo,\n+ connectionInfoPropType,\n+} from '../types/socket-types';\n+import type { BaseAppState } from '../types/redux-types';\n+import {\n+ type CalendarQuery,\n+ calendarQueryPropType,\n+ type CalendarQueryUpdateResult,\n+ type CalendarQueryUpdateStartingPayload,\n+} from '../types/entry-types';\n+import type { DispatchActionPromise } from '../utils/action-utils';\n+\n+import * as React from 'react';\n+import PropTypes from 'prop-types';\n+import _isEqual from 'lodash/fp/isEqual';\n+\n+import { connect } from '../utils/redux-utils';\n+import {\n+ updateCalendarQueryActionTypes,\n+ updateCalendarQuery,\n+} from '../actions/entry-actions';\n+import {\n+ currentCalendarQuery,\n+ timeUntilCalendarRangeExpiration,\n+} from '../selectors/nav-selectors';\n+import { getConfig } from '../utils/config';\n+\n+type Props = {|\n+ // Redux state\n+ connection: ConnectionInfo,\n+ currentCalendarQuery: () => CalendarQuery,\n+ actualizedCalendarQuery: CalendarQuery,\n+ lastUserInteractionCalendar: number,\n+ // Redux dispatch functions\n+ dispatchActionPromise: DispatchActionPromise,\n+ // async functions that hit server APIs\n+ updateCalendarQuery: (\n+ calendarQuery: CalendarQuery,\n+ reduxAlreadyUpdated?: bool,\n+ ) => Promise<CalendarQueryUpdateResult>,\n+|};\n+class CalendarQueryHandler extends React.PureComponent<Props> {\n+\n+ static propTypes = {\n+ connection: connectionInfoPropType.isRequired,\n+ currentCalendarQuery: PropTypes.func.isRequired,\n+ actualizedCalendarQuery: calendarQueryPropType.isRequired,\n+ lastUserInteractionCalendar: PropTypes.number.isRequired,\n+ dispatchActionPromise: PropTypes.func.isRequired,\n+ updateCalendarQuery: PropTypes.func.isRequired,\n+ };\n+ expirationTimeoutID: ?TimeoutID;\n+\n+ componentDidMount() {\n+ if (this.props.connection.status !== \"connected\") {\n+ return;\n+ }\n+ const justUpdated = this.possiblyUpdateCalendarQuery();\n+ this.setExpirationTimeout(justUpdated);\n+ }\n+\n+ componentWillUnmount() {\n+ this.clearExpirationTimeout();\n+ }\n+\n+ componentDidUpdate(prevProps: Props) {\n+ if (this.props.connection.status !== \"connected\") {\n+ this.clearExpirationTimeout();\n+ return;\n+ }\n+ let justUpdated = false;\n+ if (\n+ prevProps.connection.status !== \"connected\" ||\n+ this.props.currentCalendarQuery !== prevProps.currentCalendarQuery\n+ ) {\n+ justUpdated = this.possiblyUpdateCalendarQuery();\n+ }\n+ if (\n+ prevProps.connection.status !== \"connected\" ||\n+ this.props.lastUserInteractionCalendar !==\n+ prevProps.lastUserInteractionCalendar\n+ ) {\n+ this.setExpirationTimeout(justUpdated);\n+ }\n+ }\n+\n+ render() {\n+ return null;\n+ }\n+\n+ clearExpirationTimeout() {\n+ if (this.expirationTimeoutID) {\n+ clearTimeout(this.expirationTimeoutID);\n+ this.expirationTimeoutID = null;\n+ }\n+ }\n+\n+ setExpirationTimeout(justUpdated: bool) {\n+ this.clearExpirationTimeout();\n+ const timeUntilExpiration =\n+ timeUntilCalendarRangeExpiration(this.props.lastUserInteractionCalendar);\n+ if (timeUntilExpiration === null || timeUntilExpiration === undefined) {\n+ return;\n+ }\n+ if (timeUntilExpiration <= 0) {\n+ if (!justUpdated) {\n+ this.possiblyUpdateCalendarQuery();\n+ }\n+ } else {\n+ this.expirationTimeoutID = setTimeout(\n+ this.possiblyUpdateCalendarQuery,\n+ timeUntilExpiration,\n+ );\n+ }\n+ }\n+\n+ possiblyUpdateCalendarQuery = () => {\n+ if (this.props.connection.status !== \"connected\") {\n+ return false;\n+ }\n+ const calendarQuery = this.props.currentCalendarQuery();\n+ if (!_isEqual(calendarQuery)(this.props.actualizedCalendarQuery)) {\n+ this.props.dispatchActionPromise(\n+ updateCalendarQueryActionTypes,\n+ this.props.updateCalendarQuery(calendarQuery, true),\n+ undefined,\n+ ({ calendarQuery }: CalendarQueryUpdateStartingPayload),\n+ );\n+ return true;\n+ }\n+ return false;\n+ }\n+\n+}\n+\n+\n+export default connect(\n+ (state: BaseAppState<*>) => ({\n+ connection: state.connection,\n+ currentCalendarQuery: currentCalendarQuery(state),\n+ actualizedCalendarQuery: state.entryStore.actualizedCalendarQuery,\n+ lastUserInteractionCalendar: state.entryStore.lastUserInteractionCalendar\n+ }),\n+ { updateCalendarQuery },\n+)(CalendarQueryHandler);\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/socket/socket.react.js",
"new_path": "lib/socket/socket.react.js",
"diff": "@@ -59,6 +59,7 @@ import ActivityHandler from './activity-handler.react';\nimport RequestResponseHandler from './request-response-handler.react';\nimport UpdateHandler from './update-handler.react';\nimport MessageHandler from './message-handler.react';\n+import CalendarQueryHandler from './calendar-query-handler.react';\nimport { logOutActionTypes } from '../actions/user-actions';\ntype Props = {|\n@@ -285,6 +286,7 @@ class Socket extends React.PureComponent<Props, State> {\naddListener={this.addListener}\nremoveListener={this.removeListener}\n/>\n+ <CalendarQueryHandler />\n</React.Fragment>\n);\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "web/app.react.js",
"new_path": "web/app.react.js",
"diff": "import type { LoadingStatus } from 'lib/types/loading-types';\nimport { type AppState, type NavInfo, navInfoPropType } from './redux-setup';\n-import type {\n- DispatchActionPayload,\n- DispatchActionPromise,\n-} from 'lib/utils/action-utils';\n+import type { DispatchActionPayload } from 'lib/utils/action-utils';\nimport { type VerifyField, verifyField } from 'lib/types/verify-types';\n-import {\n- type CalendarQuery,\n- type CalendarQueryUpdateResult,\n- calendarQueryPropType,\n- type CalendarQueryUpdateStartingPayload,\n-} from 'lib/types/entry-types';\nimport * as React from 'react';\nimport invariant from 'invariant';\n@@ -26,11 +17,9 @@ import classNames from 'classnames';\nimport fontawesome from '@fortawesome/fontawesome';\nimport { getDate } from 'lib/utils/date-utils';\n-import { currentCalendarQuery } from 'lib/selectors/nav-selectors';\nimport {\nfetchEntriesActionTypes,\nupdateCalendarQueryActionTypes,\n- updateCalendarQuery,\n} from 'lib/actions/entry-actions';\nimport {\ncreateLoadingStatusSelector,\n@@ -38,9 +27,6 @@ import {\n} from 'lib/selectors/loading-selectors';\nimport { connect } from 'lib/utils/redux-utils';\nimport { registerConfig } from 'lib/utils/config';\n-import {\n- includeDeletedSelector,\n-} from 'lib/selectors/calendar-filter-selectors';\nimport {\nmostRecentReadThreadSelector,\nunreadCount,\n@@ -90,22 +76,13 @@ type Props = {\nnavInfo: NavInfo,\nverifyField: ?VerifyField,\nentriesLoadingStatus: LoadingStatus,\n- currentCalendarQuery: () => CalendarQuery,\nloggedIn: bool,\n- includeDeleted: bool,\nmostRecentReadThread: ?string,\nactiveThreadCurrentlyUnread: bool,\nviewerID: ?string,\nunreadCount: number,\n- actualizedCalendarQuery: CalendarQuery,\n// Redux dispatch functions\ndispatchActionPayload: DispatchActionPayload,\n- dispatchActionPromise: DispatchActionPromise,\n- // async functions that hit server APIs\n- updateCalendarQuery: (\n- calendarQuery: CalendarQuery,\n- reduxAlreadyUpdated?: bool,\n- ) => Promise<CalendarQueryUpdateResult>,\n};\ntype State = {|\ncurrentModal: ?React.Node,\n@@ -119,27 +96,16 @@ class App extends React.PureComponent<Props, State> {\nnavInfo: navInfoPropType.isRequired,\nverifyField: PropTypes.number,\nentriesLoadingStatus: PropTypes.string.isRequired,\n- currentCalendarQuery: PropTypes.func.isRequired,\nloggedIn: PropTypes.bool.isRequired,\n- includeDeleted: PropTypes.bool.isRequired,\nmostRecentReadThread: PropTypes.string,\nactiveThreadCurrentlyUnread: PropTypes.bool.isRequired,\nviewerID: PropTypes.string,\nunreadCount: PropTypes.number.isRequired,\n- actualizedCalendarQuery: calendarQueryPropType.isRequired,\ndispatchActionPayload: PropTypes.func.isRequired,\n- dispatchActionPromise: PropTypes.func.isRequired,\n- updateCalendarQuery: PropTypes.func.isRequired,\n};\nstate = {\ncurrentModal: null,\n};\n- actualizedCalendarQuery: CalendarQuery;\n-\n- constructor(props: Props) {\n- super(props);\n- this.actualizedCalendarQuery = props.actualizedCalendarQuery;\n- }\ncomponentDidMount() {\nif (this.props.navInfo.verify) {\n@@ -209,12 +175,6 @@ class App extends React.PureComponent<Props, State> {\n}\ncomponentWillReceiveProps(nextProps: Props) {\n- if (\n- nextProps.actualizedCalendarQuery !== this.props.actualizedCalendarQuery\n- ) {\n- this.actualizedCalendarQuery = nextProps.actualizedCalendarQuery;\n- }\n-\nif (nextProps.loggedIn) {\nif (nextProps.location.pathname !== this.props.location.pathname) {\nconst newNavInfo = navInfoFromURL(\n@@ -233,20 +193,6 @@ class App extends React.PureComponent<Props, State> {\nhistory.push(newURL);\n}\n}\n-\n- const calendarQuery = nextProps.currentCalendarQuery();\n- if (\n- !_isEqual(calendarQuery)(this.actualizedCalendarQuery) &&\n- !_isEqual(calendarQuery)(nextProps.actualizedCalendarQuery)\n- ) {\n- this.actualizedCalendarQuery = calendarQuery;\n- nextProps.dispatchActionPromise(\n- updateCalendarQueryActionTypes,\n- nextProps.updateCalendarQuery(calendarQuery, true),\n- undefined,\n- ({ calendarQuery }: CalendarQueryUpdateStartingPayload),\n- );\n- }\n}\nconst justLoggedIn = nextProps.loggedIn && !this.props.loggedIn;\n@@ -415,17 +361,15 @@ export default connect(\nfetchEntriesLoadingStatusSelector(state),\nupdateCalendarQueryLoadingStatusSelector(state),\n),\n- currentCalendarQuery: currentCalendarQuery(state),\nloggedIn: !!(state.currentUserInfo &&\n!state.currentUserInfo.anonymous && true),\n- includeDeleted: includeDeletedSelector(state),\nmostRecentReadThread: mostRecentReadThreadSelector(state),\nactiveThreadCurrentlyUnread: !activeChatThreadID ||\nstate.threadStore.threadInfos[activeChatThreadID].currentUser.unread,\nviewerID: state.currentUserInfo && state.currentUserInfo.id,\nunreadCount: unreadCount(state),\n- actualizedCalendarQuery: state.entryStore.actualizedCalendarQuery,\n};\n},\n- { updateCalendarQuery },\n+ null,\n+ true,\n)(App);\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | CalendarQueryHandler
Handles non-user-initiated `UPDATE_CALENDAR_QUERY` calls. |
129,187 | 07.11.2018 10:48:55 | 18,000 | 8895268ec92f48d6203299b087db0054b974ad2d | Get logInExtraInfo directly from store in resolveInvalidatedCookie | [
{
"change_type": "MODIFY",
"old_path": "lib/socket/socket.react.js",
"new_path": "lib/socket/socket.react.js",
"diff": "@@ -37,7 +37,7 @@ import type {\nDispatchActionPayload,\nDispatchActionPromise,\n} from '../utils/action-utils';\n-import type { LogInExtraInfo, LogOutResult } from '../types/account-types';\n+import type { LogOutResult } from '../types/account-types';\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\n@@ -72,7 +72,6 @@ type Props = {|\nsessionIdentification: SessionIdentification,\ncookie: ?string,\nurlPrefix: string,\n- logInExtraInfo: () => LogInExtraInfo,\nconnection: ConnectionInfo,\n// Redux dispatch functions\ndispatch: Dispatch,\n@@ -95,7 +94,6 @@ class Socket extends React.PureComponent<Props, State> {\nsessionIdentification: sessionIdentificationPropType.isRequired,\ncookie: PropTypes.string,\nurlPrefix: PropTypes.string.isRequired,\n- logInExtraInfo: PropTypes.func.isRequired,\nconnection: connectionInfoPropType.isRequired,\ndispatch: PropTypes.func.isRequired,\ndispatchActionPayload: PropTypes.func.isRequired,\n@@ -367,7 +365,6 @@ class Socket extends React.PureComponent<Props, State> {\ncookie,\nthis.props.urlPrefix,\nsocketAuthErrorResolutionAttempt,\n- this.props.logInExtraInfo,\n);\nif (!recoverySessionChange && sessionChange) {\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/utils/action-utils.js",
"new_path": "lib/utils/action-utils.js",
"diff": "@@ -14,7 +14,6 @@ import type {\nLogInActionSource,\nLogInStartingPayload,\nLogInResult,\n- LogInExtraInfo,\n} from '../types/account-types';\nimport type { Endpoint } from '../types/endpoints';\nimport type { ClientSessionChange } from '../types/session-types';\n@@ -178,7 +177,6 @@ async function fetchNewCookieFromNativeCredentials(\ncookie: ?string,\nurlPrefix: string,\nsource: LogInActionSource,\n- logInExtraInfo: () => LogInExtraInfo,\n): Promise<?ClientSessionChange> {\nconst resolveInvalidatedCookie = getConfig().resolveInvalidatedCookie;\nif (!resolveInvalidatedCookie) {\n@@ -237,7 +235,6 @@ async function fetchNewCookieFromNativeCredentials(\nawait resolveInvalidatedCookie(\nboundFetchJSON,\ndispatchRecoveryAttempt,\n- logInExtraInfo,\n);\nreturn newSessionChange;\n}\n@@ -249,7 +246,6 @@ function bindCookieAndUtilsIntoFetchJSON(\ncookie: ?string,\nurlPrefix: string,\nsessionID: ?string,\n- logInExtraInfo: () => LogInExtraInfo,\nloggedIn: bool,\n): FetchJSON {\nconst boundSetNewSession = setNewSession.bind(null, dispatch);\n@@ -277,7 +273,6 @@ function bindCookieAndUtilsIntoFetchJSON(\nnewAnonymousCookie,\nurlPrefix,\ncookieInvalidationResolutionAttempt,\n- logInExtraInfo,\n);\ncurrentlyWaitingForNewCookie = false;\n@@ -290,7 +285,6 @@ function bindCookieAndUtilsIntoFetchJSON(\nnewSessionChange.cookie,\nurlPrefix,\nnewSessionChange.sessionID,\n- logInExtraInfo,\nloggedIn,\n)\n: null;\n@@ -343,7 +337,6 @@ type BindServerCallsParams = {\ncookie: ?string,\nurlPrefix: string,\nsessionID: ?string,\n- logInExtraInfo: () => LogInExtraInfo,\nloggedIn: bool,\n};\n@@ -361,14 +354,12 @@ const baseCreateBoundServerCallsSelector = (actionFunc: ActionFunc) => {\n(state: BindServerCallsParams) => state.cookie,\n(state: BindServerCallsParams) => state.urlPrefix,\n(state: BindServerCallsParams) => state.sessionID,\n- (state: BindServerCallsParams) => state.logInExtraInfo,\n(state: BindServerCallsParams) => state.loggedIn,\n(\ndispatch: Dispatch,\ncookie: ?string,\nurlPrefix: string,\nsessionID: ?string,\n- logInExtraInfo: () => LogInExtraInfo,\nloggedIn: bool,\n) => {\nconst boundFetchJSON = bindCookieAndUtilsIntoFetchJSON(\n@@ -376,7 +367,6 @@ const baseCreateBoundServerCallsSelector = (actionFunc: ActionFunc) => {\ncookie,\nurlPrefix,\nsessionID,\n- logInExtraInfo,\nloggedIn,\n);\nreturn (...rest: $FlowFixMe) => actionFunc(boundFetchJSON, ...rest);\n@@ -394,7 +384,6 @@ function bindServerCalls(serverCalls: ServerCalls) {\ncookie: ?string,\nurlPrefix: string,\nsessionID: ?string,\n- logInExtraInfo: () => LogInExtraInfo,\ncurrentUserInfoLoggedIn: bool,\n},\ndispatchProps: Object,\n@@ -406,7 +395,6 @@ function bindServerCalls(serverCalls: ServerCalls) {\ncookie,\nurlPrefix,\nsessionID,\n- logInExtraInfo,\ncurrentUserInfoLoggedIn: loggedIn,\n} = stateProps;\nconst boundServerCalls = _mapValues(\n@@ -416,7 +404,6 @@ function bindServerCalls(serverCalls: ServerCalls) {\ncookie,\nurlPrefix,\nsessionID,\n- logInExtraInfo,\nloggedIn,\n}),\n)(serverCalls);\n@@ -438,7 +425,6 @@ export {\nsetNewSessionActionType,\nincludeDispatchActionProps,\nfetchNewCookieFromNativeCredentials,\n- createBoundServerCallsSelector,\nbindServerCalls,\nregisterActiveWebSocket,\n};\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/utils/config.js",
"new_path": "lib/utils/config.js",
"diff": "import type { FetchJSON } from './fetch-json';\nimport type { DispatchRecoveryAttempt } from './action-utils';\nimport type { PlatformDetails } from '../types/device-types';\n-import type { LogInExtraInfo } from '../types/account-types';\nimport invariant from 'invariant';\n@@ -11,7 +10,6 @@ export type Config = {\nresolveInvalidatedCookie: ?((\nfetchJSON: FetchJSON,\ndispatchRecoveryAttempt: DispatchRecoveryAttempt,\n- logInExtraInfo: () => LogInExtraInfo,\n) => Promise<void>),\nsetCookieOnRequest: bool,\nsetSessionIDOnRequest: bool,\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/utils/redux-utils.js",
"new_path": "lib/utils/redux-utils.js",
"diff": "import type { ServerCalls } from './action-utils';\nimport type { AppState } from '../types/redux-types';\n-import type { LogInExtraInfo } from '../types/account-types';\nimport { connect as reactReduxConnect } from 'react-redux';\nimport invariant from 'invariant';\n@@ -11,7 +10,6 @@ import {\nincludeDispatchActionProps,\nbindServerCalls,\n} from './action-utils';\n-import { logInExtraInfoSelector } from '../selectors/account-selectors';\nfunction connect<S: AppState, OP: Object, SP: Object>(\ninputMapStateToProps: ?((state: S, ownProps: OP) => SP),\n@@ -27,14 +25,12 @@ function connect<S: AppState, OP: Object, SP: Object>(\ncookie: ?string,\nurlPrefix: string,\nsessionID: ?string,\n- logInExtraInfo: () => LogInExtraInfo,\ncurrentUserInfoLoggedIn: bool,\n} => ({\n...mapStateToProps(state, ownProps),\ncookie: state.cookie,\nurlPrefix: state.urlPrefix,\nsessionID: state.sessionID,\n- logInExtraInfo: logInExtraInfoSelector(state),\ncurrentUserInfoLoggedIn:\n!!(state.currentUserInfo && !state.currentUserInfo.anonymous && true),\n});\n@@ -44,7 +40,6 @@ function connect<S: AppState, OP: Object, SP: Object>(\ncookie: ?string,\nurlPrefix: string,\nsessionID: ?string,\n- logInExtraInfo: () => LogInExtraInfo,\ncurrentUserInfoLoggedIn: bool,\n} => ({\n// $FlowFixMe\n@@ -52,7 +47,6 @@ function connect<S: AppState, OP: Object, SP: Object>(\ncookie: state.cookie,\nurlPrefix: state.urlPrefix,\nsessionID: state.sessionID,\n- logInExtraInfo: logInExtraInfoSelector(state),\ncurrentUserInfoLoggedIn:\n!!(state.currentUserInfo && !state.currentUserInfo.anonymous && true),\n});\n@@ -63,13 +57,11 @@ function connect<S: AppState, OP: Object, SP: Object>(\ncookie: ?string,\nurlPrefix: string,\nsessionID: ?string,\n- logInExtraInfo: () => LogInExtraInfo,\ncurrentUserInfoLoggedIn: bool,\n} => ({\ncookie: state.cookie,\nurlPrefix: state.urlPrefix,\nsessionID: state.sessionID,\n- logInExtraInfo: logInExtraInfoSelector(state),\ncurrentUserInfoLoggedIn:\n!!(state.currentUserInfo && !state.currentUserInfo.anonymous && true),\n});\n"
},
{
"change_type": "MODIFY",
"old_path": "native/account/logged-out-modal.react.js",
"new_path": "native/account/logged-out-modal.react.js",
"diff": "@@ -42,7 +42,6 @@ import {\n} from 'lib/actions/user-actions';\nimport sleep from 'lib/utils/sleep';\nimport { connect } from 'lib/utils/redux-utils';\n-import { logInExtraInfoSelector } from 'lib/selectors/account-selectors';\nimport {\nwindowHeight,\n@@ -84,7 +83,6 @@ type Props = {\nurlPrefix: string,\nloggedIn: bool,\nisForeground: bool,\n- logInExtraInfo: () => LogInExtraInfo,\n// Redux dispatch functions\ndispatch: Dispatch,\ndispatchActionPayload: DispatchActionPayload,\n@@ -114,7 +112,6 @@ class InnerLoggedOutModal extends React.PureComponent<Props, State> {\nurlPrefix: PropTypes.string.isRequired,\nloggedIn: PropTypes.bool.isRequired,\nisForeground: PropTypes.bool.isRequired,\n- logInExtraInfo: PropTypes.func.isRequired,\ndispatch: PropTypes.func.isRequired,\ndispatchActionPayload: PropTypes.func.isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\n@@ -296,7 +293,6 @@ class InnerLoggedOutModal extends React.PureComponent<Props, State> {\ncookie,\nurlPrefix,\nappStartNativeCredentialsAutoLogIn,\n- nextProps.logInExtraInfo,\n);\nif (!sessionChange) {\nshowPrompt();\n@@ -321,7 +317,6 @@ class InnerLoggedOutModal extends React.PureComponent<Props, State> {\ncookie,\nurlPrefix,\nappStartReduxLoggedInButInvalidCookie,\n- nextProps.logInExtraInfo,\n);\nconst newCookie = sessionChange ? sessionChange.cookie : null;\nif (newCookie && newCookie.startsWith(\"user=\")) {\n@@ -824,7 +819,6 @@ const LoggedOutModal = connect(\nloggedIn: !!(state.currentUserInfo &&\n!state.currentUserInfo.anonymous && true),\nisForeground: isForegroundSelector(state),\n- logInExtraInfo: logInExtraInfoSelector(state),\n}),\nnull,\ntrue,\n"
},
{
"change_type": "MODIFY",
"old_path": "native/account/native-credentials.js",
"new_path": "native/account/native-credentials.js",
"diff": "import type { FetchJSON } from 'lib/utils/fetch-json';\nimport type { DispatchRecoveryAttempt } from 'lib/utils/action-utils';\n-import type { LogInExtraInfo } from 'lib/types/account-types';\nimport { Platform } from 'react-native';\nimport {\n@@ -15,6 +14,9 @@ import {\nimport URL from 'url-parse';\nimport { logInActionTypes, logIn } from 'lib/actions/user-actions';\n+import { logInExtraInfoSelector } from 'lib/selectors/account-selectors';\n+\n+import { store } from '../redux-setup';\ntype Credentials = {|\nusername: string,\n@@ -218,11 +220,10 @@ async function deleteNativeCredentialsFor(username: string) {\nasync function resolveInvalidatedCookie(\nfetchJSON: FetchJSON,\ndispatchRecoveryAttempt: DispatchRecoveryAttempt,\n- logInExtraInfo: () => LogInExtraInfo,\n) {\nconst keychainCredentials = await fetchNativeKeychainCredentials();\nif (keychainCredentials) {\n- const extraInfo = logInExtraInfo();\n+ const extraInfo = logInExtraInfoSelector(store.getState())();\nconst { calendarQuery } = extraInfo;\nconst newCookie = await dispatchRecoveryAttempt(\nlogInActionTypes,\n@@ -242,7 +243,7 @@ async function resolveInvalidatedCookie(\n}\nconst sharedWebCredentials = getNativeSharedWebCredentials();\nif (sharedWebCredentials) {\n- const extraInfo = logInExtraInfo();\n+ const extraInfo = logInExtraInfoSelector(store.getState())();\nconst { calendarQuery } = extraInfo;\nawait dispatchRecoveryAttempt(\nlogInActionTypes,\n"
},
{
"change_type": "MODIFY",
"old_path": "native/socket.react.js",
"new_path": "native/socket.react.js",
"diff": "@@ -7,7 +7,6 @@ import {\nqueuedClientResponsesSelector,\nsessionStateFuncSelector,\n} from 'lib/selectors/socket-selectors';\n-import { logInExtraInfoSelector } from 'lib/selectors/account-selectors';\nimport { logOut } from 'lib/actions/user-actions';\nimport Socket from 'lib/socket/socket.react';\n@@ -35,7 +34,6 @@ export default connect(\nsessionIdentification: sessionIdentificationSelector(state),\ncookie: state.cookie,\nurlPrefix: state.urlPrefix,\n- logInExtraInfo: logInExtraInfoSelector(state),\nconnection: state.connection,\n};\n},\n"
},
{
"change_type": "MODIFY",
"old_path": "web/socket.react.js",
"new_path": "web/socket.react.js",
"diff": "@@ -7,7 +7,6 @@ import {\nqueuedClientResponsesSelector,\nsessionStateFuncSelector,\n} from 'lib/selectors/socket-selectors';\n-import { logInExtraInfoSelector } from 'lib/selectors/account-selectors';\nimport { logOut } from 'lib/actions/user-actions';\nimport Socket from 'lib/socket/socket.react';\n@@ -32,7 +31,6 @@ export default connect(\nsessionIdentification: sessionIdentificationSelector(state),\ncookie: state.cookie,\nurlPrefix: state.urlPrefix,\n- logInExtraInfo: logInExtraInfoSelector(state),\nconnection: state.connection,\n};\n},\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | Get logInExtraInfo directly from store in resolveInvalidatedCookie |
129,187 | 07.11.2018 12:58:24 | 18,000 | d32e1d1d30a7d732dc35f95dfc1327cc92d776c6 | RequestResponseHandler passes currentCalendarQuery to PROCESS_SERVER_REQUESTS | [
{
"change_type": "MODIFY",
"old_path": "lib/socket/request-response-handler.react.js",
"new_path": "lib/socket/request-response-handler.react.js",
"diff": "@@ -17,6 +17,7 @@ import {\ntype ServerRequest,\nclientResponsePropType,\n} from '../types/request-types';\n+import type { CalendarQuery } from '../types/entry-types';\nimport type { DispatchActionPayload } from '../utils/action-utils';\nimport type { AppState } from '../types/redux-types';\n@@ -40,6 +41,7 @@ type Props = {|\ngetClientResponses: (\nactiveServerRequests: $ReadOnlyArray<ServerRequest>,\n) => $ReadOnlyArray<ClientResponse>,\n+ currentCalendarQuery: () => CalendarQuery,\n// Redux state\nconnection: ConnectionInfo,\nqueuedClientResponses: $ReadOnlyArray<ClientResponse>,\n@@ -54,6 +56,7 @@ class RequestResponseHandler extends React.PureComponent<Props> {\naddListener: PropTypes.func.isRequired,\nremoveListener: PropTypes.func.isRequired,\ngetClientResponses: PropTypes.func.isRequired,\n+ currentCalendarQuery: PropTypes.func.isRequired,\nconnection: connectionInfoPropType.isRequired,\nqueuedClientResponses: PropTypes.arrayOf(clientResponsePropType).isRequired,\ndispatchActionPayload: PropTypes.func.isRequired,\n@@ -99,9 +102,10 @@ class RequestResponseHandler extends React.PureComponent<Props> {\nif (serverRequests.length === 0) {\nreturn;\n}\n+ const calendarQuery = this.props.currentCalendarQuery();\nthis.props.dispatchActionPayload(\nprocessServerRequestsActionType,\n- { serverRequests },\n+ { serverRequests, calendarQuery },\n);\nif (this.props.inflightRequests) {\nconst clientResponses = this.props.getClientResponses(serverRequests);\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/socket/socket.react.js",
"new_path": "lib/socket/socket.react.js",
"diff": "@@ -39,6 +39,7 @@ import type {\nDispatchActionPromise,\n} from '../utils/action-utils';\nimport type { LogOutResult } from '../types/account-types';\n+import type { CalendarQuery } from '../types/entry-types';\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\n@@ -77,6 +78,7 @@ type Props = {|\ncookie: ?string,\nurlPrefix: string,\nconnection: ConnectionInfo,\n+ currentCalendarQuery: () => CalendarQuery,\n// Redux dispatch functions\ndispatch: Dispatch,\ndispatchActionPayload: DispatchActionPayload,\n@@ -100,6 +102,7 @@ class Socket extends React.PureComponent<Props, State> {\ncookie: PropTypes.string,\nurlPrefix: PropTypes.string.isRequired,\nconnection: connectionInfoPropType.isRequired,\n+ currentCalendarQuery: PropTypes.func.isRequired,\ndispatch: PropTypes.func.isRequired,\ndispatchActionPayload: PropTypes.func.isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\n@@ -280,6 +283,7 @@ class Socket extends React.PureComponent<Props, State> {\naddListener={this.addListener}\nremoveListener={this.removeListener}\ngetClientResponses={this.props.getClientResponses}\n+ currentCalendarQuery={this.props.currentCalendarQuery}\n/>\n<UpdateHandler\nsendMessage={this.sendMessageWithoutID}\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/types/request-types.js",
"new_path": "lib/types/request-types.js",
"diff": "@@ -211,4 +211,5 @@ export type ClearDeliveredClientResponsesPayload = {|\nexport const processServerRequestsActionType = \"PROCESS_SERVER_REQUESTS\";\nexport type ProcessServerRequestsPayload = {|\nserverRequests: $ReadOnlyArray<ServerRequest>,\n+ calendarQuery: CalendarQuery,\n|};\n"
},
{
"change_type": "MODIFY",
"old_path": "native/socket.react.js",
"new_path": "native/socket.react.js",
"diff": "@@ -16,6 +16,7 @@ import {\nimport {\nactiveThreadSelector,\nappLoggedInSelector,\n+ nativeCalendarQuery,\n} from './selectors/nav-selectors';\nexport default connect(\n@@ -35,6 +36,7 @@ export default connect(\ncookie: state.cookie,\nurlPrefix: state.urlPrefix,\nconnection: state.connection,\n+ currentCalendarQuery: nativeCalendarQuery(state),\n};\n},\n{ logOut },\n"
},
{
"change_type": "MODIFY",
"old_path": "web/socket.react.js",
"new_path": "web/socket.react.js",
"diff": "@@ -13,7 +13,10 @@ import {\nwebGetClientResponsesSelector,\nwebSessionStateFuncSelector,\n} from './selectors/socket-selectors';\n-import { activeThreadSelector } from './selectors/nav-selectors';\n+import {\n+ activeThreadSelector,\n+ webCalendarQuery,\n+} from './selectors/nav-selectors';\nexport default connect(\n(state: AppState) => {\n@@ -32,6 +35,7 @@ export default connect(\ncookie: state.cookie,\nurlPrefix: state.urlPrefix,\nconnection: state.connection,\n+ currentCalendarQuery: webCalendarQuery(state),\n};\n},\n{ logOut },\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | RequestResponseHandler passes currentCalendarQuery to PROCESS_SERVER_REQUESTS |
129,187 | 07.11.2018 13:09:10 | 18,000 | 5cd7cfb816c44a5354add5c23fe5a93e4cacc910 | Move defaultCalendarQuery to entry-types
And remove the duplicate. | [
{
"change_type": "MODIFY",
"old_path": "lib/selectors/nav-selectors.js",
"new_path": "lib/selectors/nav-selectors.js",
"diff": "@@ -5,10 +5,7 @@ import type { BaseNavInfo } from '../types/nav-types';\nimport type { RawThreadInfo } from '../types/thread-types';\nimport type { CalendarQuery } from '../types/entry-types';\nimport type { UserInfo } from '../types/user-types';\n-import {\n- type CalendarFilter,\n- defaultCalendarFilters,\n-} from '../types/filter-types';\n+import type { CalendarFilter } from '../types/filter-types';\nimport { createSelector } from 'reselect';\nimport _some from 'lodash/fp/some';\n@@ -59,12 +56,6 @@ function currentEndDate(\nreturn fifteenDaysLater();\n}\n-const defaultCalendarQuery = () => ({\n- startDate: fifteenDaysEarlier().valueOf(),\n- endDate: fifteenDaysLater().valueOf(),\n- filters: defaultCalendarFilters,\n-});\n-\nconst currentCalendarQuery = createSelector(\n(state: BaseAppState<*>) => state.entryStore.lastUserInteractionCalendar,\n(state: BaseAppState<*>) => state.navInfo,\n@@ -136,7 +127,6 @@ const threadSearchIndex = createSelector(\nexport {\ntimeUntilCalendarRangeExpiration,\n- defaultCalendarQuery,\ncurrentCalendarQuery,\nthreadSearchIndex,\n};\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/shared/entry-utils.js",
"new_path": "lib/shared/entry-utils.js",
"diff": "@@ -7,10 +7,7 @@ import type {\n} from '../types/entry-types';\nimport type { UserInfo } from '../types/user-types';\nimport type { RawThreadInfo } from '../types/thread-types';\n-import {\n- calendarThreadFilterTypes,\n- defaultCalendarFilters,\n-} from '../types/filter-types';\n+import { calendarThreadFilterTypes } from '../types/filter-types';\nimport invariant from 'invariant';\nimport _isEqual from 'lodash/fp/isEqual';\n@@ -19,8 +16,6 @@ import {\ndateString,\ngetDate,\ndateFromString,\n- fifteenDaysEarlier,\n- fifteenDaysLater,\n} from '../utils/date-utils';\nimport {\nfilteredThreadIDs,\n@@ -124,14 +119,6 @@ function filterRawEntryInfosByCalendarQuery(\nreturn filtered ? filteredRawEntryInfos : rawEntryInfos;\n}\n-function defaultCalendarQuery(): CalendarQuery {\n- return {\n- startDate: fifteenDaysEarlier().valueOf(),\n- endDate: fifteenDaysLater().valueOf(),\n- filters: defaultCalendarFilters,\n- };\n-}\n-\nfunction usersInRawEntryInfos(\nentryInfos: $ReadOnlyArray<RawEntryInfo>,\n): string[] {\n@@ -269,7 +256,6 @@ export {\nrawEntryInfoWithinActiveRange,\nrawEntryInfoWithinCalendarQuery,\nfilterRawEntryInfosByCalendarQuery,\n- defaultCalendarQuery,\nusersInRawEntryInfos,\ncalendarQueryDifference,\nserverEntryInfo,\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/types/entry-types.js",
"new_path": "lib/types/entry-types.js",
"diff": "import type { RawMessageInfo } from './message-types';\nimport type { UserInfo, AccountUserInfo } from './user-types';\n-import { type CalendarFilter, calendarFilterPropType } from './filter-types';\n+import {\n+ type CalendarFilter,\n+ calendarFilterPropType,\n+ defaultCalendarFilters,\n+} from './filter-types';\nimport type { CreateUpdatesResponse } from './update-types';\nimport type { EntryInconsistencyClientResponse } from './request-types';\nimport PropTypes from 'prop-types';\n+import { fifteenDaysEarlier, fifteenDaysLater } from '../utils/date-utils';\n+\nexport type RawEntryInfo = {|\nid?: string, // null if local copy without ID yet\nlocalID?: string, // for optimistic creations\n@@ -74,6 +80,12 @@ export type CalendarQuery = {|\nfilters: $ReadOnlyArray<CalendarFilter>,\n|};\n+export const defaultCalendarQuery = () => ({\n+ startDate: fifteenDaysEarlier().valueOf(),\n+ endDate: fifteenDaysLater().valueOf(),\n+ filters: defaultCalendarFilters,\n+});\n+\nexport const calendarQueryPropType = PropTypes.shape({\nstartDate: PropTypes.string.isRequired,\nendDate: PropTypes.string.isRequired,\n"
},
{
"change_type": "MODIFY",
"old_path": "native/redux-setup.js",
"new_path": "native/redux-setup.js",
"diff": "// @flow\nimport type { ThreadStore } from 'lib/types/thread-types';\n-import type { EntryStore } from 'lib/types/entry-types';\n+import { type EntryStore, defaultCalendarQuery } 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@@ -45,7 +45,6 @@ import {\nsaveMessagesActionType,\n} from 'lib/actions/message-actions';\nimport { reduxLoggerMiddleware } from 'lib/utils/redux-logger';\n-import { defaultCalendarQuery } from 'lib/selectors/nav-selectors';\nimport { activeThreadSelector } from './selectors/nav-selectors';\nimport {\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/creators/update-creator.js",
"new_path": "server/src/creators/update-creator.js",
"diff": "@@ -14,10 +14,11 @@ import {\ndefaultNumberPerThread,\ntype FetchMessageInfosResult,\n} from 'lib/types/message-types';\n-import type {\n- RawEntryInfo,\n- FetchEntryInfosResponse,\n- CalendarQuery,\n+import {\n+ type RawEntryInfo,\n+ type FetchEntryInfosResponse,\n+ type CalendarQuery,\n+ defaultCalendarQuery,\n} from 'lib/types/entry-types';\nimport { type UpdateTarget, redisMessageTypes } from 'lib/types/redis-types';\n@@ -26,10 +27,7 @@ import _uniq from 'lodash/fp/uniq';\nimport _intersection from 'lodash/fp/intersection';\nimport { promiseAll } from 'lib/utils/promises';\n-import {\n- defaultCalendarQuery,\n- usersInRawEntryInfos,\n-} from 'lib/shared/entry-utils';\n+import { usersInRawEntryInfos } from 'lib/shared/entry-utils';\nimport { usersInThreadInfo } from 'lib/shared/thread-utils';\nimport { usersInMessageInfos } from 'lib/shared/message-utils';\nimport {\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/updaters/entry-updaters.js",
"new_path": "server/src/updaters/entry-updaters.js",
"diff": "// @flow\n-import type {\n- SaveEntryRequest,\n- SaveEntryResponse,\n- RawEntryInfo,\n- CalendarQuery,\n+import {\n+ type SaveEntryRequest,\n+ type SaveEntryResponse,\n+ type RawEntryInfo,\n+ type CalendarQuery,\n+ defaultCalendarQuery,\n} from 'lib/types/entry-types';\nimport type { Viewer } from '../session/viewer';\nimport { updateTypes, type CreateUpdatesResponse } from 'lib/types/update-types';\n@@ -18,7 +19,6 @@ import { messageTypes } from 'lib/types/message-types';\nimport { dateString } from 'lib/utils/date-utils';\nimport {\nrawEntryInfoWithinCalendarQuery,\n- defaultCalendarQuery,\ncalendarQueryDifference,\n} from 'lib/shared/entry-utils';\nimport { values } from 'lib/utils/objects';\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | Move defaultCalendarQuery to entry-types
And remove the duplicate. |
129,187 | 07.11.2018 13:39:38 | 18,000 | 9a18b8449124d4974d3c89ebfa4956318ff5bfd9 | [lib] Include calendarQuery in REGISTER_SUCCESS | [
{
"change_type": "MODIFY",
"old_path": "lib/actions/user-actions.js",
"new_path": "lib/actions/user-actions.js",
"diff": "@@ -77,6 +77,7 @@ async function register(\nrawMessageInfos: response.rawMessageInfos,\nthreadInfos: response.cookieChange.threadInfos,\nuserInfos: response.cookieChange.userInfos,\n+ calendarQuery: registerInfo.calendarQuery,\n};\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/types/account-types.js",
"new_path": "lib/types/account-types.js",
"diff": "@@ -67,6 +67,7 @@ export type RegisterResult = {|\nrawMessageInfos: $ReadOnlyArray<RawMessageInfo>,\nthreadInfos: {[id: string]: RawThreadInfo},\nuserInfos: $ReadOnlyArray<UserInfo>,\n+ calendarQuery: CalendarQuery,\n|};\nexport type DeleteAccountRequest = {|\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [lib] Include calendarQuery in REGISTER_SUCCESS |
129,187 | 07.11.2018 13:44:54 | 18,000 | ceaf662d20618ede9c0ca2b9b612c38679cc78f2 | [lib] Always include CalendarQuery in UPDATE_CALENDAR_QUERY_SUCCESS | [
{
"change_type": "MODIFY",
"old_path": "lib/actions/entry-actions.js",
"new_path": "lib/actions/entry-actions.js",
"diff": "@@ -52,11 +52,12 @@ async function updateCalendarQuery(\n): Promise<CalendarQueryUpdateResult> {\nconst response = await fetchJSON('update_calendar_query', calendarQuery);\nconst { rawEntryInfos, userInfos } = response;\n- if (reduxAlreadyUpdated) {\n- return { rawEntryInfos, userInfos };\n- } else {\n- return { rawEntryInfos, userInfos, calendarQuery };\n- }\n+ return {\n+ rawEntryInfos,\n+ userInfos,\n+ calendarQuery,\n+ calendarQueryAlreadyUpdated: reduxAlreadyUpdated,\n+ };\n}\nconst createLocalEntryActionType = \"CREATE_LOCAL_ENTRY\";\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/reducers/entry-reducer.js",
"new_path": "lib/reducers/entry-reducer.js",
"diff": "@@ -283,9 +283,10 @@ function reduceEntryInfos(\ninconsistencyResponses,\n};\n} else if (action.type === updateCalendarQueryActionTypes.success) {\n- const newActualizedCalendarQuery = action.payload.calendarQuery\n- ? action.payload.calendarQuery\n- : actualizedCalendarQuery;\n+ const newActualizedCalendarQuery =\n+ action.payload.calendarQueryAlreadyUpdated\n+ ? actualizedCalendarQuery\n+ : action.payload.calendarQuery;\nconst newLastUserInteractionCalendar = action.payload.calendarQuery\n? Date.now()\n: lastUserInteractionCalendar;\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/reducers/nav-reducer.js",
"new_path": "lib/reducers/nav-reducer.js",
"diff": "@@ -23,13 +23,18 @@ export default function reduceBaseNavInfo<T: BaseNavInfo>(\nconst { startDate, endDate } = action.payload.calendarQuery;\nreturn { ...state, startDate, endDate };\n} else if (\n- (action.type === updateCalendarQueryActionTypes.started ||\n- action.type === updateCalendarQueryActionTypes.success) &&\n+ action.type === updateCalendarQueryActionTypes.started &&\naction.payload &&\naction.payload.calendarQuery\n) {\nconst { startDate, endDate } = action.payload.calendarQuery;\nreturn { ...state, startDate, endDate };\n+ } else if (\n+ action.type === updateCalendarQueryActionTypes.success &&\n+ !action.payload.calendarQueryAlreadyUpdated\n+ ) {\n+ const { startDate, endDate } = action.payload.calendarQuery;\n+ return { ...state, startDate, endDate };\n}\nreturn state;\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/types/entry-types.js",
"new_path": "lib/types/entry-types.js",
"diff": "@@ -212,5 +212,6 @@ export type CalendarQueryUpdateStartingPayload = {|\nexport type CalendarQueryUpdateResult = {|\nrawEntryInfos: $ReadOnlyArray<RawEntryInfo>,\nuserInfos: $ReadOnlyArray<AccountUserInfo>,\n- calendarQuery?: CalendarQuery,\n+ calendarQuery: CalendarQuery,\n+ calendarQueryAlreadyUpdated: bool,\n|};\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [lib] Always include CalendarQuery in UPDATE_CALENDAR_QUERY_SUCCESS |
129,187 | 07.11.2018 13:51:52 | 18,000 | 950e09d96d927e55ce14e98469780cac13b6a875 | [lib] Include CalendarQuery in STATE_SYNC payloads | [
{
"change_type": "MODIFY",
"old_path": "lib/socket/socket.react.js",
"new_path": "lib/socket/socket.react.js",
"diff": "@@ -532,7 +532,7 @@ class Socket extends React.PureComponent<Props, State> {\nconst { sessionID, type, ...actionPayload } = stateSyncMessage.payload;\nthis.props.dispatchActionPayload(\nfullStateSyncActionType,\n- actionPayload,\n+ { ...actionPayload, calendarQuery: sessionState.calendarQuery },\n);\nif (sessionID !== null && sessionID !== undefined) {\nthis.props.dispatchActionPayload(\n@@ -547,7 +547,7 @@ class Socket extends React.PureComponent<Props, State> {\nconst { type, ...actionPayload } = stateSyncMessage.payload;\nthis.props.dispatchActionPayload(\nincrementalStateSyncActionType,\n- actionPayload,\n+ { ...actionPayload, calendarQuery: sessionState.calendarQuery },\n);\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/types/socket-types.js",
"new_path": "lib/types/socket-types.js",
"diff": "@@ -13,7 +13,7 @@ import type {\nCurrentUserInfo,\nLoggedOutUserInfo,\n} from './user-types';\n-import type { RawEntryInfo } from './entry-types';\n+import type { RawEntryInfo, CalendarQuery } from './entry-types';\nimport {\ntype ActivityUpdate,\ntype UpdateActivityResult,\n@@ -122,7 +122,8 @@ export const stateSyncPayloadTypes = Object.freeze({\nFULL: 0,\nINCREMENTAL: 1,\n});\n-export type StateSyncFullActionPayload = {|\n+\n+export type FullStateSync = {|\nmessagesResult: MessagesResponse,\nthreadInfos: {[id: string]: RawThreadInfo},\ncurrentUserInfo: CurrentUserInfo,\n@@ -130,24 +131,34 @@ export type StateSyncFullActionPayload = {|\nuserInfos: $ReadOnlyArray<UserInfo>,\nupdatesCurrentAsOf: number,\n|};\n+export type StateSyncFullActionPayload = {|\n+ ...FullStateSync,\n+ calendarQuery: CalendarQuery,\n+|};\nexport const fullStateSyncActionType = \"FULL_STATE_SYNC\";\nexport type StateSyncFullSocketPayload = {|\n- ...StateSyncFullActionPayload,\n+ ...FullStateSync,\ntype: 0,\n// Included iff client is using sessionIdentifierTypes.BODY_SESSION_ID\nsessionID?: string,\n|};\n-export type StateSyncIncrementalActionPayload = {|\n+\n+export type IncrementalStateSync = {|\nmessagesResult: MessagesResponse,\nupdatesResult: UpdatesResult,\ndeltaEntryInfos: $ReadOnlyArray<RawEntryInfo>,\nuserInfos: $ReadOnlyArray<UserInfo>,\n|};\n+export type StateSyncIncrementalActionPayload = {|\n+ ...IncrementalStateSync,\n+ calendarQuery: CalendarQuery,\n+|};\nexport const incrementalStateSyncActionType = \"INCREMENTAL_STATE_SYNC\";\ntype StateSyncIncrementalSocketPayload = {|\ntype: 1,\n- ...StateSyncIncrementalActionPayload,\n+ ...IncrementalStateSync,\n|};\n+\nexport type StateSyncSocketPayload =\n| StateSyncFullSocketPayload\n| StateSyncIncrementalSocketPayload;\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [lib] Include CalendarQuery in STATE_SYNC payloads |
129,187 | 07.11.2018 14:02:34 | 18,000 | 7ac75b8143ef0e7f7f3333c9218dd91d558c25f1 | Move actualizedCalendarQuery to ConnectionInfo | [
{
"change_type": "MODIFY",
"old_path": "lib/reducers/connection-reducer.js",
"new_path": "lib/reducers/connection-reducer.js",
"diff": "@@ -7,13 +7,20 @@ import {\nqueueActivityUpdatesActionType,\nactivityUpdateSuccessActionType,\nactivityUpdateFailedActionType,\n+ fullStateSyncActionType,\n+ incrementalStateSyncActionType,\n} from '../types/socket-types';\n+import { defaultCalendarQuery } from '../types/entry-types';\nimport { setNewSessionActionType } from '../utils/action-utils';\nimport {\nlogOutActionTypes,\ndeleteAccountActionTypes,\n+ logInActionTypes,\n+ resetPasswordActionTypes,\n+ registerActionTypes,\n} from '../actions/user-actions';\n+import { updateCalendarQueryActionTypes } from '../actions/entry-actions';\nexport default function reduceConnectionInfo(\nstate: ConnectionInfo,\n@@ -61,7 +68,29 @@ export default function reduceConnectionInfo(\n(action.type === setNewSessionActionType &&\naction.payload.sessionChange.cookieInvalidated)\n) {\n- return { ...state, queuedActivityUpdates: [] };\n+ return {\n+ ...state,\n+ queuedActivityUpdates: [],\n+ actualizedCalendarQuery: defaultCalendarQuery(),\n+ };\n+ } else if (\n+ action.type === logInActionTypes.success ||\n+ action.type === resetPasswordActionTypes.success\n+ ) {\n+ return {\n+ ...state,\n+ actualizedCalendarQuery: action.payload.calendarResult.calendarQuery,\n+ };\n+ } else if (\n+ action.type === registerActionTypes.success ||\n+ action.type === updateCalendarQueryActionTypes.success ||\n+ action.type === fullStateSyncActionType ||\n+ action.type === incrementalStateSyncActionType\n+ ) {\n+ return {\n+ ...state,\n+ actualizedCalendarQuery: action.payload.calendarQuery,\n+ };\n}\nreturn state;\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/reducers/entry-reducer.js",
"new_path": "lib/reducers/entry-reducer.js",
"diff": "@@ -57,7 +57,6 @@ import {\ndeleteAccountActionTypes,\nlogInActionTypes,\nresetPasswordActionTypes,\n- registerActionTypes,\n} from '../actions/user-actions';\nimport {\ndeleteThreadActionTypes,\n@@ -177,7 +176,6 @@ function reduceEntryInfos(\nconst {\nentryInfos,\ndaysToEntries,\n- actualizedCalendarQuery,\nlastUserInteractionCalendar,\ninconsistencyResponses,\n} = entryStore;\n@@ -200,7 +198,6 @@ function reduceEntryInfos(\nreturn {\nentryInfos,\ndaysToEntries,\n- actualizedCalendarQuery,\nlastUserInteractionCalendar: newLastUserInteractionCalendar,\ninconsistencyResponses,\n};\n@@ -212,7 +209,6 @@ function reduceEntryInfos(\nreturn {\nentryInfos: newEntryInfos,\ndaysToEntries: newDaysToEntries,\n- actualizedCalendarQuery,\nlastUserInteractionCalendar: newLastUserInteractionCalendar,\ninconsistencyResponses,\n};\n@@ -233,7 +229,6 @@ function reduceEntryInfos(\nreturn {\nentryInfos,\ndaysToEntries,\n- actualizedCalendarQuery,\nlastUserInteractionCalendar: newLastUserInteractionCalendar,\ninconsistencyResponses,\n};\n@@ -241,7 +236,6 @@ function reduceEntryInfos(\nreturn {\nentryInfos: newEntryInfos,\ndaysToEntries: newDaysToEntries,\n- actualizedCalendarQuery,\nlastUserInteractionCalendar: newLastUserInteractionCalendar,\ninconsistencyResponses,\n};\n@@ -254,7 +248,6 @@ function reduceEntryInfos(\nreturn {\nentryInfos: updatedEntryInfos,\ndaysToEntries: updatedDaysToEntries,\n- actualizedCalendarQuery,\nlastUserInteractionCalendar,\ninconsistencyResponses,\n};\n@@ -266,27 +259,10 @@ function reduceEntryInfos(\nreturn {\nentryInfos,\ndaysToEntries,\n- actualizedCalendarQuery: action.payload.calendarQuery,\nlastUserInteractionCalendar: Date.now(),\ninconsistencyResponses,\n};\n- } else if (\n- action.type === logInActionTypes.started ||\n- action.type === resetPasswordActionTypes.started ||\n- action.type === registerActionTypes.started\n- ) {\n- return {\n- entryInfos,\n- daysToEntries,\n- actualizedCalendarQuery: action.payload.calendarQuery,\n- lastUserInteractionCalendar,\n- inconsistencyResponses,\n- };\n} else if (action.type === updateCalendarQueryActionTypes.success) {\n- const newActualizedCalendarQuery =\n- action.payload.calendarQueryAlreadyUpdated\n- ? actualizedCalendarQuery\n- : action.payload.calendarQuery;\nconst newLastUserInteractionCalendar = action.payload.calendarQuery\n? Date.now()\n: lastUserInteractionCalendar;\n@@ -298,7 +274,6 @@ function reduceEntryInfos(\nreturn {\nentryInfos: updatedEntryInfos,\ndaysToEntries: updatedDaysToEntries,\n- actualizedCalendarQuery: newActualizedCalendarQuery,\nlastUserInteractionCalendar: newLastUserInteractionCalendar,\ninconsistencyResponses,\n};\n@@ -319,7 +294,6 @@ function reduceEntryInfos(\nreturn {\nentryInfos: newEntryInfos,\ndaysToEntries: newDaysToEntries,\n- actualizedCalendarQuery,\nlastUserInteractionCalendar: Date.now(),\ninconsistencyResponses,\n};\n@@ -379,7 +353,6 @@ function reduceEntryInfos(\nreturn {\nentryInfos: updatedEntryInfos,\ndaysToEntries: newDaysToEntries,\n- actualizedCalendarQuery,\nlastUserInteractionCalendar: Date.now(),\ninconsistencyResponses: [\n...inconsistencyResponses,\n@@ -423,7 +396,6 @@ function reduceEntryInfos(\nreturn {\nentryInfos: updatedEntryInfos,\ndaysToEntries,\n- actualizedCalendarQuery,\nlastUserInteractionCalendar: Date.now(),\ninconsistencyResponses: [\n...inconsistencyResponses,\n@@ -449,7 +421,6 @@ function reduceEntryInfos(\nreturn {\nentryInfos: newEntryInfos,\ndaysToEntries,\n- actualizedCalendarQuery,\nlastUserInteractionCalendar,\ninconsistencyResponses,\n};\n@@ -469,7 +440,6 @@ function reduceEntryInfos(\nreturn {\nentryInfos: newEntryInfos,\ndaysToEntries,\n- actualizedCalendarQuery,\nlastUserInteractionCalendar: Date.now(),\ninconsistencyResponses,\n};\n@@ -494,7 +464,6 @@ function reduceEntryInfos(\nreturn {\nentryInfos,\ndaysToEntries,\n- actualizedCalendarQuery,\nlastUserInteractionCalendar,\ninconsistencyResponses: [\n...inconsistencyResponses,\n@@ -522,7 +491,6 @@ function reduceEntryInfos(\nreturn {\nentryInfos: newEntryInfos,\ndaysToEntries,\n- actualizedCalendarQuery,\nlastUserInteractionCalendar,\ninconsistencyResponses,\n};\n@@ -554,7 +522,6 @@ function reduceEntryInfos(\nreturn {\nentryInfos: updatedEntryInfos,\ndaysToEntries,\n- actualizedCalendarQuery,\nlastUserInteractionCalendar: Date.now(),\ninconsistencyResponses: [\n...inconsistencyResponses,\n@@ -576,7 +543,6 @@ function reduceEntryInfos(\nreturn {\nentryInfos: updatedEntryInfos,\ndaysToEntries: updatedDaysToEntries,\n- actualizedCalendarQuery,\nlastUserInteractionCalendar,\ninconsistencyResponses,\n};\n@@ -594,7 +560,6 @@ function reduceEntryInfos(\nreturn {\nentryInfos: updatedEntryInfos,\ndaysToEntries: updatedDaysToEntries,\n- actualizedCalendarQuery,\nlastUserInteractionCalendar,\ninconsistencyResponses,\n};\n@@ -611,7 +576,6 @@ function reduceEntryInfos(\nreturn {\nentryInfos: updatedEntryInfos,\ndaysToEntries: updatedDaysToEntries,\n- actualizedCalendarQuery,\nlastUserInteractionCalendar,\ninconsistencyResponses,\n};\n@@ -624,7 +588,6 @@ function reduceEntryInfos(\nreturn {\nentryInfos: updatedEntryInfos,\ndaysToEntries: updatedDaysToEntries,\n- actualizedCalendarQuery,\nlastUserInteractionCalendar,\ninconsistencyResponses,\n};\n@@ -647,7 +610,6 @@ function reduceEntryInfos(\nreturn {\nentryInfos: newEntryInfos,\ndaysToEntries: newDaysToEntries,\n- actualizedCalendarQuery,\nlastUserInteractionCalendar,\ninconsistencyResponses,\n};\n@@ -682,7 +644,6 @@ function reduceEntryInfos(\nreturn {\nentryInfos,\ndaysToEntries,\n- actualizedCalendarQuery,\nlastUserInteractionCalendar,\ninconsistencyResponses: updatedResponses,\n};\n@@ -723,12 +684,11 @@ function reduceEntryInfos(\naction,\nentryInfos,\nupdatedEntryInfos,\n- actualizedCalendarQuery,\n+ action.payload.calendarQuery,\n);\nreturn {\nentryInfos: updatedEntryInfos,\ndaysToEntries: updatedDaysToEntries,\n- actualizedCalendarQuery,\nlastUserInteractionCalendar,\ninconsistencyResponses: [\n...inconsistencyResponses,\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/reducers/nav-reducer.js",
"new_path": "lib/reducers/nav-reducer.js",
"diff": "import type { BaseAction } from '../types/redux-types';\nimport type { BaseNavInfo } from '../types/nav-types';\n+import {\n+ fullStateSyncActionType,\n+ incrementalStateSyncActionType,\n+} from '../types/socket-types';\nimport { dateFromString } from '../utils/date-utils';\nimport { updateCalendarQueryActionTypes } from '../actions/entry-actions';\n@@ -18,7 +22,9 @@ export default function reduceBaseNavInfo<T: BaseNavInfo>(\nif (\naction.type === logInActionTypes.started ||\naction.type === resetPasswordActionTypes.started ||\n- action.type === registerActionTypes.started\n+ action.type === registerActionTypes.started ||\n+ action.type === fullStateSyncActionType ||\n+ action.type === incrementalStateSyncActionType\n) {\nconst { startDate, endDate } = action.payload.calendarQuery;\nreturn { ...state, startDate, endDate };\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/socket/calendar-query-handler.react.js",
"new_path": "lib/socket/calendar-query-handler.react.js",
"diff": "@@ -32,7 +32,6 @@ type Props = {|\n// Redux state\nconnection: ConnectionInfo,\ncurrentCalendarQuery: () => CalendarQuery,\n- actualizedCalendarQuery: CalendarQuery,\nlastUserInteractionCalendar: number,\n// Redux dispatch functions\ndispatchActionPromise: DispatchActionPromise,\n@@ -47,7 +46,6 @@ class CalendarQueryHandler extends React.PureComponent<Props> {\nstatic propTypes = {\nconnection: connectionInfoPropType.isRequired,\ncurrentCalendarQuery: PropTypes.func.isRequired,\n- actualizedCalendarQuery: calendarQueryPropType.isRequired,\nlastUserInteractionCalendar: PropTypes.number.isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\nupdateCalendarQuery: PropTypes.func.isRequired,\n@@ -122,7 +120,8 @@ class CalendarQueryHandler extends React.PureComponent<Props> {\nreturn false;\n}\nconst calendarQuery = this.props.currentCalendarQuery();\n- if (!_isEqual(calendarQuery)(this.props.actualizedCalendarQuery)) {\n+ const { actualizedCalendarQuery } = this.props.connection;\n+ if (!_isEqual(calendarQuery)(actualizedCalendarQuery)) {\nthis.props.dispatchActionPromise(\nupdateCalendarQueryActionTypes,\nthis.props.updateCalendarQuery(calendarQuery, true),\n@@ -141,7 +140,6 @@ export default connect(\n(state: BaseAppState<*>) => ({\nconnection: state.connection,\ncurrentCalendarQuery: currentCalendarQuery(state),\n- actualizedCalendarQuery: state.entryStore.actualizedCalendarQuery,\nlastUserInteractionCalendar: state.entryStore.lastUserInteractionCalendar\n}),\n{ updateCalendarQuery },\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/types/entry-types.js",
"new_path": "lib/types/entry-types.js",
"diff": "@@ -69,7 +69,6 @@ export const entryInfoPropType = PropTypes.shape({\nexport type EntryStore = {|\nentryInfos: {[id: string]: RawEntryInfo},\ndaysToEntries: {[day: string]: string[]},\n- actualizedCalendarQuery: CalendarQuery,\nlastUserInteractionCalendar: number,\ninconsistencyResponses: $ReadOnlyArray<EntryInconsistencyClientResponse>,\n|};\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/types/socket-types.js",
"new_path": "lib/types/socket-types.js",
"diff": "@@ -13,7 +13,11 @@ import type {\nCurrentUserInfo,\nLoggedOutUserInfo,\n} from './user-types';\n-import type { RawEntryInfo, CalendarQuery } from './entry-types';\n+import {\n+ type RawEntryInfo,\n+ type CalendarQuery,\n+ defaultCalendarQuery,\n+} from './entry-types';\nimport {\ntype ActivityUpdate,\ntype UpdateActivityResult,\n@@ -231,6 +235,7 @@ export type ConnectionStatus =\nexport type ConnectionInfo = {|\nstatus: ConnectionStatus,\nqueuedActivityUpdates: $ReadOnlyArray<ActivityUpdate>,\n+ actualizedCalendarQuery: CalendarQuery,\n|};\nexport const connectionInfoPropType = PropTypes.shape({\nstatus: PropTypes.oneOf([\n@@ -243,10 +248,11 @@ export const connectionInfoPropType = PropTypes.shape({\n]).isRequired,\nqueuedActivityUpdates: PropTypes.arrayOf(activityUpdatePropType).isRequired,\n});\n-export const defaultConnectionInfo = {\n+export const defaultConnectionInfo = () => ({\nstatus: \"connecting\",\nqueuedActivityUpdates: [],\n-};\n+ actualizedCalendarQuery: defaultCalendarQuery(),\n+});\nexport const updateConnectionStatusActionType = \"UPDATE_CONNECTION_STATUS\";\nexport type UpdateConnectionStatusPayload = {|\nstatus: ConnectionStatus,\n"
},
{
"change_type": "MODIFY",
"old_path": "native/persist.js",
"new_path": "native/persist.js",
"diff": "@@ -77,9 +77,13 @@ const migrations = {\n...state,\npingTimestamps: undefined,\nactiveServerRequests: undefined,\n- connection: defaultConnectionInfo,\n+ connection: defaultConnectionInfo(),\nwatchedThreadIDs: [],\nforeground: true,\n+ entryStore: {\n+ ...state.entryStore,\n+ actualizedCalendarQuery: undefined,\n+ },\n}),\n};\n"
},
{
"change_type": "MODIFY",
"old_path": "native/redux-setup.js",
"new_path": "native/redux-setup.js",
"diff": "// @flow\nimport type { ThreadStore } from 'lib/types/thread-types';\n-import { type EntryStore, defaultCalendarQuery } from 'lib/types/entry-types';\n+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@@ -116,7 +116,6 @@ const defaultState = ({\nentryStore: {\nentryInfos: {},\ndaysToEntries: {},\n- actualizedCalendarQuery: defaultCalendarQuery(),\nlastUserInteractionCalendar: 0,\ninconsistencyResponses: [],\n},\n@@ -141,7 +140,7 @@ const defaultState = ({\nthreadIDsToNotifIDs: {},\nnotifPermissionAlertInfo: defaultNotifPermissionAlertInfo,\nmessageSentFromRoute: [],\n- connection: defaultConnectionInfo,\n+ connection: defaultConnectionInfo(),\nwatchedThreadIDs: [],\nforeground: true,\n_persist: null,\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/responders/website-responders.js",
"new_path": "server/src/responders/website-responders.js",
"diff": "@@ -132,7 +132,6 @@ async function websiteResponder(viewer: Viewer, url: string): Promise<string> {\nentryStore: {\nentryInfos: _keyBy('id')(rawEntryInfos),\ndaysToEntries: daysToEntriesFromEntryInfos(rawEntryInfos),\n- actualizedCalendarQuery: calendarQuery,\nlastUserInteractionCalendar: initialTime,\ninconsistencyResponses: [],\n},\n@@ -154,7 +153,7 @@ async function websiteResponder(viewer: Viewer, url: string): Promise<string> {\nurlPrefix: \"\",\nwindowDimensions: { width: 0, height: 0 },\nbaseHref: baseDomain + baseURL,\n- connection: defaultConnectionInfo,\n+ connection: defaultConnectionInfo(),\nwatchedThreadIDs: [],\nforeground: true,\n}: AppState),\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | Move actualizedCalendarQuery to ConnectionInfo |
129,187 | 07.11.2018 14:32:27 | 18,000 | ebee0bef59a62b8903061b58454c84be20fff383 | Update CalendarQueryHandler logic to use actualizedCalendarQuery | [
{
"change_type": "MODIFY",
"old_path": "lib/socket/calendar-query-handler.react.js",
"new_path": "lib/socket/calendar-query-handler.react.js",
"diff": "@@ -22,16 +22,13 @@ import {\nupdateCalendarQueryActionTypes,\nupdateCalendarQuery,\n} from '../actions/entry-actions';\n-import {\n- currentCalendarQuery,\n- timeUntilCalendarRangeExpiration,\n-} from '../selectors/nav-selectors';\n+import { timeUntilCalendarRangeExpiration } from '../selectors/nav-selectors';\nimport { getConfig } from '../utils/config';\ntype Props = {|\n+ currentCalendarQuery: () => CalendarQuery,\n// Redux state\nconnection: ConnectionInfo,\n- currentCalendarQuery: () => CalendarQuery,\nlastUserInteractionCalendar: number,\n// Redux dispatch functions\ndispatchActionPromise: DispatchActionPromise,\n@@ -50,14 +47,20 @@ class CalendarQueryHandler extends React.PureComponent<Props> {\ndispatchActionPromise: PropTypes.func.isRequired,\nupdateCalendarQuery: PropTypes.func.isRequired,\n};\n+ serverCalendarQuery: CalendarQuery;\nexpirationTimeoutID: ?TimeoutID;\n+ constructor(props: Props) {\n+ super(props);\n+ this.serverCalendarQuery = this.props.connection.actualizedCalendarQuery;\n+ }\n+\ncomponentDidMount() {\nif (this.props.connection.status !== \"connected\") {\nreturn;\n}\n- const justUpdated = this.possiblyUpdateCalendarQuery();\n- this.setExpirationTimeout(justUpdated);\n+ this.setExpirationTimeout();\n+ this.possiblyUpdateCalendarQuery();\n}\ncomponentWillUnmount() {\n@@ -65,23 +68,39 @@ class CalendarQueryHandler extends React.PureComponent<Props> {\n}\ncomponentDidUpdate(prevProps: Props) {\n+ const { actualizedCalendarQuery } = this.props.connection;\nif (this.props.connection.status !== \"connected\") {\nthis.clearExpirationTimeout();\n+ if (!_isEqual(this.serverCalendarQuery)(actualizedCalendarQuery)) {\n+ this.serverCalendarQuery = actualizedCalendarQuery;\n+ }\nreturn;\n}\n- let justUpdated = false;\n+\nif (\n- prevProps.connection.status !== \"connected\" ||\n- this.props.currentCalendarQuery !== prevProps.currentCalendarQuery\n+ !_isEqual(this.serverCalendarQuery)(actualizedCalendarQuery) &&\n+ _isEqual(this.props.currentCalendarQuery())(actualizedCalendarQuery)\n) {\n- justUpdated = this.possiblyUpdateCalendarQuery();\n+ this.serverCalendarQuery = actualizedCalendarQuery;\n}\n+\n+ let expired = false;\nif (\nprevProps.connection.status !== \"connected\" ||\nthis.props.lastUserInteractionCalendar !==\nprevProps.lastUserInteractionCalendar\n) {\n- this.setExpirationTimeout(justUpdated);\n+ expired = this.setExpirationTimeout();\n+ }\n+\n+ const shouldUpdate = (\n+ expired ||\n+ prevProps.connection.status !== \"connected\" ||\n+ this.props.currentCalendarQuery !== prevProps.currentCalendarQuery\n+ ) && this.shouldUpdateCalendarQuery;\n+\n+ if (shouldUpdate) {\n+ this.updateCalendarQuery();\n}\n}\n@@ -96,41 +115,47 @@ class CalendarQueryHandler extends React.PureComponent<Props> {\n}\n}\n- setExpirationTimeout(justUpdated: bool) {\n+ setExpirationTimeout() {\nthis.clearExpirationTimeout();\nconst timeUntilExpiration =\ntimeUntilCalendarRangeExpiration(this.props.lastUserInteractionCalendar);\nif (timeUntilExpiration === null || timeUntilExpiration === undefined) {\n- return;\n+ return false;\n}\nif (timeUntilExpiration <= 0) {\n- if (!justUpdated) {\n- this.possiblyUpdateCalendarQuery();\n- }\n+ return true;\n} else {\nthis.expirationTimeoutID = setTimeout(\nthis.possiblyUpdateCalendarQuery,\ntimeUntilExpiration,\n);\n}\n+ return false;\n}\n- possiblyUpdateCalendarQuery = () => {\n+ get shouldUpdateCalendarQuery() {\nif (this.props.connection.status !== \"connected\") {\nreturn false;\n}\nconst calendarQuery = this.props.currentCalendarQuery();\n- const { actualizedCalendarQuery } = this.props.connection;\n- if (!_isEqual(calendarQuery)(actualizedCalendarQuery)) {\n+ return !_isEqual(calendarQuery)(this.serverCalendarQuery);\n+ }\n+\n+ updateCalendarQuery() {\n+ const calendarQuery = this.props.currentCalendarQuery();\n+ this.serverCalendarQuery = calendarQuery;\nthis.props.dispatchActionPromise(\nupdateCalendarQueryActionTypes,\nthis.props.updateCalendarQuery(calendarQuery, true),\nundefined,\n({ calendarQuery }: CalendarQueryUpdateStartingPayload),\n);\n- return true;\n}\n- return false;\n+\n+ possiblyUpdateCalendarQuery = () => {\n+ if (this.shouldUpdateCalendarQuery) {\n+ this.updateCalendarQuery();\n+ }\n}\n}\n@@ -139,7 +164,6 @@ class CalendarQueryHandler extends React.PureComponent<Props> {\nexport default connect(\n(state: BaseAppState<*>) => ({\nconnection: state.connection,\n- currentCalendarQuery: currentCalendarQuery(state),\nlastUserInteractionCalendar: state.entryStore.lastUserInteractionCalendar\n}),\n{ updateCalendarQuery },\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/socket/socket.react.js",
"new_path": "lib/socket/socket.react.js",
"diff": "@@ -294,7 +294,9 @@ class Socket extends React.PureComponent<Props, State> {\naddListener={this.addListener}\nremoveListener={this.removeListener}\n/>\n- <CalendarQueryHandler />\n+ <CalendarQueryHandler\n+ currentCalendarQuery={this.props.currentCalendarQuery}\n+ />\n</React.Fragment>\n);\n}\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | Update CalendarQueryHandler logic to use actualizedCalendarQuery |
129,187 | 07.11.2018 14:41:31 | 18,000 | ecbec4aca86b21fc9c6133f88ff7434ad51643a0 | Move invalidation recovery to its own file to avoid require cycle | [
{
"change_type": "MODIFY",
"old_path": "native/account/native-credentials.js",
"new_path": "native/account/native-credentials.js",
"diff": "// @flow\n-import type { FetchJSON } from 'lib/utils/fetch-json';\n-import type { DispatchRecoveryAttempt } from 'lib/utils/action-utils';\n-\nimport { Platform } from 'react-native';\nimport {\ngetInternetCredentials,\n@@ -13,11 +10,6 @@ import {\n} from 'react-native-keychain';\nimport URL from 'url-parse';\n-import { logInActionTypes, logIn } from 'lib/actions/user-actions';\n-\n-import { store } from '../redux-setup';\n-import { nativeLogInExtraInfoSelector } from '../selectors/account-selectors';\n-\ntype Credentials = {|\nusername: string,\npassword: string,\n@@ -217,53 +209,10 @@ async function deleteNativeCredentialsFor(username: string) {\n]);\n}\n-async function resolveInvalidatedCookie(\n- fetchJSON: FetchJSON,\n- dispatchRecoveryAttempt: DispatchRecoveryAttempt,\n-) {\n- const keychainCredentials = await fetchNativeKeychainCredentials();\n- if (keychainCredentials) {\n- const extraInfo = nativeLogInExtraInfoSelector(store.getState())();\n- const { calendarQuery } = extraInfo;\n- const newCookie = await dispatchRecoveryAttempt(\n- logInActionTypes,\n- logIn(\n- fetchJSON,\n- {\n- usernameOrEmail: keychainCredentials.username,\n- password: keychainCredentials.password,\n- ...extraInfo,\n- },\n- ),\n- { calendarQuery },\n- );\n- if (newCookie) {\n- return;\n- }\n- }\n- const sharedWebCredentials = getNativeSharedWebCredentials();\n- if (sharedWebCredentials) {\n- const extraInfo = nativeLogInExtraInfoSelector(store.getState())();\n- const { calendarQuery } = extraInfo;\n- await dispatchRecoveryAttempt(\n- logInActionTypes,\n- logIn(\n- fetchJSON,\n- {\n- usernameOrEmail: sharedWebCredentials.username,\n- password: sharedWebCredentials.password,\n- ...extraInfo,\n- },\n- ),\n- { calendarQuery },\n- );\n- }\n-}\n-\nexport {\n+ fetchNativeKeychainCredentials,\nfetchNativeCredentials,\ngetNativeSharedWebCredentials,\nsetNativeCredentials,\ndeleteNativeCredentialsFor,\n- resolveInvalidatedCookie,\n};\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "native/account/resolve-invalidated-cookie.js",
"diff": "+// @flow\n+\n+import type { FetchJSON } from 'lib/utils/fetch-json';\n+import type { DispatchRecoveryAttempt } from 'lib/utils/action-utils';\n+\n+import { logInActionTypes, logIn } from 'lib/actions/user-actions';\n+\n+import {\n+ fetchNativeKeychainCredentials,\n+ getNativeSharedWebCredentials,\n+} from './native-credentials';\n+import { nativeLogInExtraInfoSelector } from '../selectors/account-selectors';\n+import { store } from '../redux-setup';\n+\n+async function resolveInvalidatedCookie(\n+ fetchJSON: FetchJSON,\n+ dispatchRecoveryAttempt: DispatchRecoveryAttempt,\n+) {\n+ const keychainCredentials = await fetchNativeKeychainCredentials();\n+ if (keychainCredentials) {\n+ const extraInfo = nativeLogInExtraInfoSelector(store.getState())();\n+ const { calendarQuery } = extraInfo;\n+ const newCookie = await dispatchRecoveryAttempt(\n+ logInActionTypes,\n+ logIn(\n+ fetchJSON,\n+ {\n+ usernameOrEmail: keychainCredentials.username,\n+ password: keychainCredentials.password,\n+ ...extraInfo,\n+ },\n+ ),\n+ { calendarQuery },\n+ );\n+ if (newCookie) {\n+ return;\n+ }\n+ }\n+ const sharedWebCredentials = getNativeSharedWebCredentials();\n+ if (sharedWebCredentials) {\n+ const extraInfo = nativeLogInExtraInfoSelector(store.getState())();\n+ const { calendarQuery } = extraInfo;\n+ await dispatchRecoveryAttempt(\n+ logInActionTypes,\n+ logIn(\n+ fetchJSON,\n+ {\n+ usernameOrEmail: sharedWebCredentials.username,\n+ password: sharedWebCredentials.password,\n+ ...extraInfo,\n+ },\n+ ),\n+ { calendarQuery },\n+ );\n+ }\n+}\n+\n+export {\n+ resolveInvalidatedCookie,\n+};\n"
},
{
"change_type": "MODIFY",
"old_path": "native/app.react.js",
"new_path": "native/app.react.js",
"diff": "@@ -69,7 +69,7 @@ import {\nclearAndroidNotificationActionType,\n} from './navigation/action-types';\nimport { store, appBecameInactive } from './redux-setup';\n-import { resolveInvalidatedCookie } from './account/native-credentials';\n+import { resolveInvalidatedCookie } from './account/resolve-invalidated-cookie';\nimport ConnectedStatusBar from './connected-status-bar.react';\nimport {\nactiveThreadSelector,\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | Move invalidation recovery to its own file to avoid require cycle |
129,187 | 07.11.2018 17:57:55 | 18,000 | ab369a55e238bddceb521570c3619b1ddb78cbae | [native] Consider calendarActive if ThreadPicker is active | [
{
"change_type": "MODIFY",
"old_path": "native/selectors/account-selectors.js",
"new_path": "native/selectors/account-selectors.js",
"diff": "@@ -7,10 +7,8 @@ import { createSelector } from 'reselect';\nimport { logInExtraInfoSelector } from 'lib/selectors/account-selectors';\n-import { createActiveTabSelector } from './nav-selectors';\n-import { CalendarRouteName } from '../navigation/route-names';\n+import { calendarActiveSelector } from './nav-selectors';\n-const calendarActiveSelector = createActiveTabSelector(CalendarRouteName);\nconst nativeLogInExtraInfoSelector = createSelector(\nlogInExtraInfoSelector,\ncalendarActiveSelector,\n"
},
{
"change_type": "MODIFY",
"old_path": "native/selectors/nav-selectors.js",
"new_path": "native/selectors/nav-selectors.js",
"diff": "@@ -20,6 +20,7 @@ import {\nMessageListRouteName,\nChatRouteName,\nCalendarRouteName,\n+ ThreadPickerModalRouteName,\naccountModals,\n} from '../navigation/route-names';\nimport {\n@@ -99,7 +100,16 @@ const appCanRespondToBackButtonSelector = createSelector(\n},\n);\n-const calendarActiveSelector = createActiveTabSelector(CalendarRouteName);\n+const calendarTabActiveSelector = createActiveTabSelector(CalendarRouteName);\n+const threadPickerActiveSelector =\n+ createIsForegroundSelector(ThreadPickerModalRouteName);\n+const calendarActiveSelector = createSelector(\n+ calendarTabActiveSelector,\n+ threadPickerActiveSelector,\n+ (calendarTabActive: bool, threadPickerActive: bool) =>\n+ calendarTabActive || threadPickerActive,\n+);\n+\nconst nativeCalendarQuery = createSelector(\ncurrentCalendarQuery,\ncalendarActiveSelector,\n@@ -134,6 +144,7 @@ export {\ncreateActiveTabSelector,\nactiveThreadSelector,\nappCanRespondToBackButtonSelector,\n+ calendarActiveSelector,\nnativeCalendarQuery,\nnonThreadCalendarQuery,\n};\n"
},
{
"change_type": "MODIFY",
"old_path": "native/selectors/socket-selectors.js",
"new_path": "native/selectors/socket-selectors.js",
"diff": "@@ -15,8 +15,7 @@ import {\nsessionStateFuncSelector,\n} from 'lib/selectors/socket-selectors';\n-import { createActiveTabSelector } from './nav-selectors';\n-import { CalendarRouteName } from '../navigation/route-names';\n+import { calendarActiveSelector } from './nav-selectors';\nconst openSocketSelector = createSelector(\n(state: AppState) => state.urlPrefix,\n@@ -34,8 +33,6 @@ const sessionIdentificationSelector = createSelector(\n(cookie: ?string): SessionIdentification => ({ cookie }),\n);\n-const calendarActiveSelector = createActiveTabSelector(CalendarRouteName);\n-\nconst nativeGetClientResponsesSelector = createSelector(\ngetClientResponsesSelector,\ncalendarActiveSelector,\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Consider calendarActive if ThreadPicker is active |
129,187 | 07.11.2018 18:01:37 | 18,000 | 1e21db0de1bc254d19950a7cc86197886b705d67 | [lib] Different error messages for each place inflightRequests can be falsey | [
{
"change_type": "MODIFY",
"old_path": "lib/socket/activity-handler.react.js",
"new_path": "lib/socket/activity-handler.react.js",
"diff": "@@ -102,7 +102,10 @@ class ActivityHandler extends React.PureComponent<Props> {\nactivityUpdates: $ReadOnlyArray<ActivityUpdate>\n): Promise<ActivityUpdateResponseServerSocketMessage> {\nconst { inflightRequests } = this.props;\n- invariant(inflightRequests, \"inflightRequests should exist\");\n+ invariant(\n+ inflightRequests,\n+ \"inflightRequests falsey inside sendActivityUpdates\",\n+ );\nconst messageID = this.props.sendMessage({\ntype: clientSocketMessageTypes.ACTIVITY_UPDATES,\npayload: { activityUpdates },\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/socket/request-response-handler.react.js",
"new_path": "lib/socket/request-response-handler.react.js",
"diff": "@@ -127,7 +127,10 @@ class RequestResponseHandler extends React.PureComponent<Props> {\nclientResponses: $ReadOnlyArray<ClientResponse>,\n): Promise<RequestsServerSocketMessage> {\nconst { inflightRequests } = this.props;\n- invariant(inflightRequests, \"inflightRequests should exist\");\n+ invariant(\n+ inflightRequests,\n+ \"inflightRequests falsey inside sendClientResponses\",\n+ );\nconst messageID = this.props.sendMessage({\ntype: clientSocketMessageTypes.RESPONSES,\npayload: { clientResponses },\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/socket/socket.react.js",
"new_path": "lib/socket/socket.react.js",
"diff": "@@ -350,7 +350,10 @@ class Socket extends React.PureComponent<Props, State> {\n// so we can reset the ping timeout.\nthis.resetPing();\n- invariant(this.state.inflightRequests, \"inflightRequests should exist\");\n+ invariant(\n+ this.state.inflightRequests,\n+ \"inflightRequests falsey inside receiveMessage\",\n+ );\nthis.state.inflightRequests.resolveRequestsForMessage(message);\nconst { status } = this.props.connection;\nif (status === \"disconnecting\" || status === \"forcedDisconnecting\") {\n@@ -457,7 +460,10 @@ class Socket extends React.PureComponent<Props, State> {\nasync sendInitialMessage() {\nconst { inflightRequests } = this.state;\n- invariant(inflightRequests, \"inflightRequests should exist\");\n+ invariant(\n+ inflightRequests,\n+ \"inflightRequests falsey inside sendInitialMessage\",\n+ );\nconst messageID = this.nextClientMessageID++;\nconst promises = {};\n@@ -627,7 +633,10 @@ class Socket extends React.PureComponent<Props, State> {\ntype: clientSocketMessageTypes.PING,\n});\ntry {\n- invariant(this.state.inflightRequests, \"inflightRequests should exist\");\n+ invariant(\n+ this.state.inflightRequests,\n+ \"inflightRequests falsey inside sendPing\",\n+ );\nawait this.state.inflightRequests.fetchResponse(\nmessageID,\nserverSocketMessageTypes.PONG,\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [lib] Different error messages for each place inflightRequests can be falsey |
129,187 | 07.11.2018 18:19:29 | 18,000 | 63f5bc97464dd4f88771525304ad3585580823b9 | [server] Fix comparison guarding sessionUpdate of calendarQuery
Should be an equality check, not a subset check. | [
{
"change_type": "MODIFY",
"old_path": "server/src/updaters/entry-updaters.js",
"new_path": "server/src/updaters/entry-updaters.js",
"diff": "@@ -12,6 +12,7 @@ import { updateTypes, type CreateUpdatesResponse } from 'lib/types/update-types'\nimport type { SessionUpdate } from './session-updaters';\nimport invariant from 'invariant';\n+import _isEqual from 'lodash/fp/isEqual';\nimport { ServerError } from 'lib/utils/errors';\nimport { threadPermissions } from 'lib/types/thread-types';\n@@ -265,9 +266,9 @@ function compareNewCalendarQuery(\noldCalendarQuery,\nnewCalendarQuery,\n);\n- const sessionUpdate = difference.length > 0\n- ? { query: newCalendarQuery }\n- : {};\n+ const sessionUpdate = _isEqual(oldCalendarQuery)(newCalendarQuery)\n+ ? {}\n+ : { query: newCalendarQuery };\nreturn { difference, oldCalendarQuery, sessionUpdate };\n}\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [server] Fix comparison guarding sessionUpdate of calendarQuery
Should be an equality check, not a subset check. |
129,187 | 07.11.2018 19:31:19 | 18,000 | 4a6f84f6f391f147eff7927fd7e551ad401ae92e | MESSAGE_STORE_PRUNE action | [
{
"change_type": "MODIFY",
"old_path": "lib/reducers/message-reducer.js",
"new_path": "lib/reducers/message-reducer.js",
"diff": "@@ -10,6 +10,7 @@ import {\nmessageTypes,\ndefaultNumberPerThread,\nprocessMessagesActionType,\n+ messageStorePruneActionType,\n} from '../types/message-types';\nimport type { BaseAction } from '../types/redux-types';\nimport { type RawThreadInfo, threadPermissions } from '../types/thread-types';\n@@ -658,6 +659,29 @@ function reduceMessageStore(\nnewThreadInfos,\naction.type,\n);\n+ } else if (action.type === messageStorePruneActionType) {\n+ const now = Date.now();\n+ const messageIDsToPrune = [];\n+ let newThreads = { ...messageStore.threads };\n+ for (let threadID of action.payload.threadIDs) {\n+ const thread = newThreads[threadID];\n+ if (!thread) {\n+ continue;\n+ }\n+ const removed = thread.messageIDs.splice(defaultNumberPerThread);\n+ for (let messageID of removed) {\n+ messageIDsToPrune.push(messageID);\n+ }\n+ thread.lastPruned = now;\n+ if (removed.length > 0) {\n+ thread.startReached = false;\n+ }\n+ }\n+ return {\n+ messages: _omit(messageIDsToPrune)(messageStore.messages),\n+ threads: newThreads,\n+ currentAsOf: messageStore.currentAsOf,\n+ };\n}\nreturn messageStore;\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/types/message-types.js",
"new_path": "lib/types/message-types.js",
"diff": "@@ -610,3 +610,8 @@ export type MessagesResultWithUserInfos = {|\nuserInfos: $ReadOnlyArray<UserInfo>,\n|};\nexport const processMessagesActionType = \"PROCESS_MESSAGES\";\n+\n+export const messageStorePruneActionType = \"MESSAGE_STORE_PRUNE\";\n+export type MessageStorePrunePayload = {|\n+ threadIDs: $ReadOnlyArray<string>,\n+|};\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/types/redux-types.js",
"new_path": "lib/types/redux-types.js",
"diff": "@@ -41,6 +41,7 @@ import type {\nSendTextMessagePayload,\nSaveMessagesPayload,\nMessagesResultWithUserInfos,\n+ MessageStorePrunePayload,\n} from './message-types';\nimport type { SetSessionPayload } from './session-types';\nimport type { ReportCreationResponse } from './report-types';\n@@ -584,6 +585,9 @@ export type BaseAction =\n|} | {|\ntype: \"PROCESS_MESSAGES\",\npayload: MessagesResultWithUserInfos,\n+ |} | {|\n+ type: \"MESSAGE_STORE_PRUNE\",\n+ payload: MessageStorePrunePayload,\n|};\nexport type ActionPayload\n"
},
{
"change_type": "MODIFY",
"old_path": "native/app.react.js",
"new_path": "native/app.react.js",
"diff": "@@ -86,6 +86,7 @@ import NotificationBody from './push/notification-body.react';\nimport ErrorBoundary from './error-boundary.react';\nimport { persistConfig, codeVersion } from './persist';\nimport { AppRouteName } from './navigation/route-names';\n+import MessageStorePruner from './chat/message-store-pruner.react';\nimport Socket from './socket.react';\nregisterConfig({\n@@ -652,6 +653,7 @@ class AppWithNavigationState extends React.PureComponent<Props> {\nnotificationBodyComponent={NotificationBody}\nref={this.inAppNotificationRef}\n/>\n+ <MessageStorePruner />\n</View>\n);\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "native/chat/message-store-pruner.react.js",
"diff": "+// @flow\n+\n+import type { AppState } from '../redux-setup';\n+import { messageStorePruneActionType } from 'lib/types/message-types';\n+import type { DispatchActionPayload } from 'lib/utils/action-utils';\n+\n+import * as React from 'react';\n+import PropTypes from 'prop-types';\n+\n+import { connect } from 'lib/utils/redux-utils';\n+\n+import {\n+ nextMessagePruneTimeSelector,\n+ pruneThreadIDsSelector,\n+} from '../selectors/message-selectors';\n+\n+type Props = {|\n+ // Redux state\n+ nextMessagePruneTime: ?number,\n+ pruneThreadIDs: () => $ReadOnlyArray<string>,\n+ // Redux dispatch functions\n+ dispatchActionPayload: DispatchActionPayload,\n+|};\n+class MessageStorePruner extends React.PureComponent<Props> {\n+\n+ static propTypes = {\n+ nextMessagePruneTime: PropTypes.number,\n+ pruneThreadIDs: PropTypes.func.isRequired,\n+ dispatchActionPayload: PropTypes.func.isRequired,\n+ };\n+ pruneTimeoutID: ?TimeoutID;\n+\n+ componentDidMount() {\n+ this.setExpirationTimeout();\n+ }\n+\n+ componentWillUnmount() {\n+ this.clearPruneTimeout();\n+ }\n+\n+ componentDidUpdate(prevProps: Props) {\n+ this.setExpirationTimeout();\n+ }\n+\n+ render() {\n+ return null;\n+ }\n+\n+ clearPruneTimeout() {\n+ if (this.pruneTimeoutID) {\n+ clearTimeout(this.pruneTimeoutID);\n+ this.pruneTimeoutID = null;\n+ }\n+ }\n+\n+ setExpirationTimeout() {\n+ this.clearPruneTimeout();\n+ const { nextMessagePruneTime } = this.props;\n+ if (nextMessagePruneTime === null || nextMessagePruneTime === undefined) {\n+ return;\n+ }\n+ const timeUntilExpiration = nextMessagePruneTime - Date.now();\n+ if (timeUntilExpiration <= 0) {\n+ this.dispatchMessageStorePruneAction();\n+ } else {\n+ this.pruneTimeoutID = setTimeout(\n+ this.dispatchMessageStorePruneAction,\n+ timeUntilExpiration,\n+ );\n+ }\n+ return false;\n+ }\n+\n+ dispatchMessageStorePruneAction = () => {\n+ const threadIDs = this.props.pruneThreadIDs();\n+ if (threadIDs.length === 0) {\n+ return;\n+ }\n+ this.props.dispatchActionPayload(\n+ messageStorePruneActionType,\n+ { threadIDs },\n+ );\n+ }\n+\n+}\n+\n+export default connect(\n+ (state: AppState) => ({\n+ nextMessagePruneTime: nextMessagePruneTimeSelector(state),\n+ pruneThreadIDs: pruneThreadIDsSelector(state),\n+ }),\n+ null,\n+ true,\n+)(MessageStorePruner);\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "native/selectors/message-selectors.js",
"diff": "+// @flow\n+\n+import type { AppState } from '../redux-setup';\n+import type { ThreadMessageInfo } from 'lib/types/message-types';\n+\n+import { createSelector } from 'reselect';\n+\n+import { activeThreadSelector } from './nav-selectors';\n+\n+const msInHour = 60 * 60 * 1000;\n+\n+const nextMessagePruneTimeSelector = createSelector(\n+ (state: AppState) => state.messageStore.threads,\n+ (threadMessageInfos: {[id: string]: ThreadMessageInfo}): ?number => {\n+ const now = Date.now();\n+ let nextTime;\n+ for (let threadID in threadMessageInfos) {\n+ const threadMessageInfo = threadMessageInfos[threadID];\n+ const threadPruneTime = Math.max(\n+ threadMessageInfo.lastNavigatedTo + msInHour,\n+ threadMessageInfo.lastPruned + msInHour * 6,\n+ );\n+ if (nextTime === undefined || threadPruneTime < nextTime) {\n+ nextTime = threadPruneTime;\n+ }\n+ }\n+ return nextTime;\n+ },\n+);\n+\n+const pruneThreadIDsSelector = createSelector(\n+ (state: AppState) => state.messageStore.threads,\n+ activeThreadSelector,\n+ (\n+ threadMessageInfos: {[id: string]: ThreadMessageInfo},\n+ activeThread: ?string,\n+ ) => (): $ReadOnlyArray<string> => {\n+ const now = Date.now();\n+ const threadIDsToPrune = [];\n+ for (let threadID in threadMessageInfos) {\n+ if (threadID === activeThread) {\n+ continue;\n+ }\n+ const threadMessageInfo = threadMessageInfos[threadID];\n+ if (\n+ threadMessageInfo.lastNavigatedTo + msInHour < now &&\n+ threadMessageInfo.lastPruned + msInHour * 6 < now\n+ ) {\n+ threadIDsToPrune.push(threadID);\n+ }\n+ }\n+ return threadIDsToPrune;\n+ },\n+);\n+\n+export {\n+ nextMessagePruneTimeSelector,\n+ pruneThreadIDsSelector,\n+};\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | MESSAGE_STORE_PRUNE action |
129,187 | 07.11.2018 20:00:51 | 18,000 | daee700479e7747a643cb42a0ba0d6411b50b5aa | [server] Early exit in updateUnreadStatus if no updates | [
{
"change_type": "MODIFY",
"old_path": "server/src/creators/message-creator.js",
"new_path": "server/src/creators/message-creator.js",
"diff": "@@ -295,6 +295,9 @@ async function postMessageSend(\nasync function updateUnreadStatus(\nsetUnreadPairs: $ReadOnlyArray<{| userID: string, threadID: string |}>,\n) {\n+ if (setUnreadPairs.length === 0) {\n+ return;\n+ }\nconst updateConditions = setUnreadPairs.map(\npair => SQL`(user = ${pair.userID} AND thread = ${pair.threadID})`,\n);\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [server] Early exit in updateUnreadStatus if no updates |
129,187 | 07.11.2018 20:39:58 | 18,000 | 0aed939208f1778b50023b21ae763ffe7a0b7e59 | [lib] Call serverEntryInfosObject before generating entry inconsistencies | [
{
"change_type": "MODIFY",
"old_path": "lib/reducers/entry-reducer.js",
"new_path": "lib/reducers/entry-reducer.js",
"diff": "@@ -71,6 +71,7 @@ import {\nentryID,\nrawEntryInfoWithinCalendarQuery,\nfilterRawEntryInfosByCalendarQuery,\n+ serverEntryInfosObject,\n} from '../shared/entry-utils';\nimport { threadInFilterList } from '../shared/thread-utils';\nimport { getConfig } from '../utils/config';\n@@ -735,11 +736,11 @@ function findInconsistencies(\ncalendarQuery: CalendarQuery,\n): EntryInconsistencyClientResponse[] {\nconst filteredPollResult = filterRawEntryInfosByCalendarQuery(\n- oldResult,\n+ serverEntryInfosObject(values(oldResult)),\ncalendarQuery,\n);\nconst filteredPushResult = filterRawEntryInfosByCalendarQuery(\n- newResult,\n+ serverEntryInfosObject(values(newResult)),\ncalendarQuery,\n);\nif (_isEqual(filteredPollResult)(filteredPushResult)) {\n@@ -762,8 +763,8 @@ function findInconsistencies(\nbeforeAction,\naction: sanitizeAction(action),\ncalendarQuery,\n- pollResult: oldResult,\n- pushResult: newResult,\n+ pollResult: filteredPollResult,\n+ pushResult: filteredPushResult,\nlastActionTypes: reduxLogger.interestingActionTypes,\ntime: Date.now(),\n}];\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [lib] Call serverEntryInfosObject before generating entry inconsistencies |
129,187 | 07.11.2018 20:26:29 | 18,000 | b4c48f0152dd224c3f109421ea4248f1f3bfa025 | codeVersion -> 23 | [
{
"change_type": "MODIFY",
"old_path": "lib/facts/version.json",
"new_path": "lib/facts/version.json",
"diff": "{\n- \"currentCodeVersion\": 22\n+ \"currentCodeVersion\": 23\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "native/android/app/build.gradle",
"new_path": "native/android/app/build.gradle",
"diff": "@@ -109,8 +109,8 @@ android {\napplicationId \"org.squadcal\"\nminSdkVersion rootProject.ext.minSdkVersion\ntargetSdkVersion rootProject.ext.targetSdkVersion\n- versionCode 22\n- versionName \"0.0.22\"\n+ versionCode 23\n+ versionName \"0.0.23\"\nndk {\nabiFilters \"armeabi-v7a\", \"x86\"\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "native/ios/SquadCal/Info.plist",
"new_path": "native/ios/SquadCal/Info.plist",
"diff": "<key>CFBundlePackageType</key>\n<string>APPL</string>\n<key>CFBundleShortVersionString</key>\n- <string>0.0.22</string>\n+ <string>0.0.23</string>\n<key>CFBundleSignature</key>\n<string>????</string>\n<key>CFBundleVersion</key>\n- <string>22</string>\n+ <string>23</string>\n<key>LSApplicationQueriesSchemes</key>\n<array>\n<string>org-appextension-feature-password-management</string>\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | codeVersion -> 23 |
129,187 | 08.11.2018 08:16:47 | 18,000 | 25535eab3f85d84cd42807df6b68c7d4167c195a | [lib] Avoid clearing initial platform details ClientResponse
We know this doesn't come from `queuedClientResponses` so there's no point trying to clear it from the queue. | [
{
"change_type": "MODIFY",
"old_path": "lib/socket/socket.react.js",
"new_path": "lib/socket/socket.react.js",
"diff": "@@ -115,7 +115,7 @@ class Socket extends React.PureComponent<Props, State> {\nnextClientMessageID = 0;\nlisteners: Set<SocketListener> = new Set();\npingTimeoutID: ?TimeoutID\n- initialPlatformDetailsSent = false;\n+ initialPlatformDetailsSent = getConfig().platformDetails === \"web\";\nreopenConnectionAfterClosing = false;\nopenSocket(newStatus: ConnectionStatus) {\n@@ -467,23 +467,22 @@ class Socket extends React.PureComponent<Props, State> {\nconst messageID = this.nextClientMessageID++;\nconst promises = {};\n- const nonActivityClientResponses = [ ...this.props.queuedClientResponses ];\n+ const { queuedClientResponses } = this.props;\n+ const clientResponses = [ ...queuedClientResponses ];\nif (!this.initialPlatformDetailsSent) {\nthis.initialPlatformDetailsSent = true;\n- nonActivityClientResponses.push({\n+ clientResponses.push({\ntype: serverRequestTypes.PLATFORM_DETAILS,\nplatformDetails: getConfig().platformDetails,\n});\n}\n-\n- if (nonActivityClientResponses.length > 0) {\n+ if (clientResponses.length > 0) {\npromises.serverRequestMessage = inflightRequests.fetchResponse(\nmessageID,\nserverSocketMessageTypes.REQUESTS,\n);\n}\n- const clientResponses = [ ...nonActivityClientResponses];\nconst { queuedActivityUpdates } = this.props.connection;\nif (queuedActivityUpdates.length > 0) {\nclientResponses.push({\n@@ -520,10 +519,10 @@ class Socket extends React.PureComponent<Props, State> {\nserverRequestMessage,\n} = await promiseAll(promises);\n- if (serverRequestMessage) {\n+ if (serverRequestMessage && queuedClientResponses.length > 0) {\nthis.props.dispatchActionPayload(\nclearDeliveredClientResponsesActionType,\n- { clientResponses: nonActivityClientResponses },\n+ { clientResponses: queuedClientResponses },\n);\n}\nif (activityUpdateMessage) {\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [lib] Avoid clearing initial platform details ClientResponse
We know this doesn't come from `queuedClientResponses` so there's no point trying to clear it from the queue. |
129,187 | 08.11.2018 10:15:18 | 18,000 | 589066d0c8e79d42b77fd2d28f42c4d03d10feeb | Fix platform-specific use of defaultCalendarQuery and defaultConnectionInfo | [
{
"change_type": "MODIFY",
"old_path": "lib/reducers/connection-reducer.js",
"new_path": "lib/reducers/connection-reducer.js",
"diff": "@@ -21,6 +21,7 @@ import {\nregisterActionTypes,\n} from '../actions/user-actions';\nimport { updateCalendarQueryActionTypes } from '../actions/entry-actions';\n+import { getConfig } from '../utils/config';\nexport default function reduceConnectionInfo(\nstate: ConnectionInfo,\n@@ -71,7 +72,9 @@ export default function reduceConnectionInfo(\nreturn {\n...state,\nqueuedActivityUpdates: [],\n- actualizedCalendarQuery: defaultCalendarQuery(),\n+ actualizedCalendarQuery: defaultCalendarQuery(\n+ getConfig().platformDetails.platform,\n+ ),\n};\n} else if (\naction.type === logInActionTypes.success ||\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/types/entry-types.js",
"new_path": "lib/types/entry-types.js",
"diff": "@@ -9,10 +9,12 @@ import {\n} from './filter-types';\nimport type { CreateUpdatesResponse } from './update-types';\nimport type { EntryInconsistencyClientResponse } from './request-types';\n+import type { Platform } from './device-types';\nimport PropTypes from 'prop-types';\nimport { fifteenDaysEarlier, fifteenDaysLater } from '../utils/date-utils';\n+import { thisMonthDates } from '../utils/date-utils';\nexport type RawEntryInfo = {|\nid?: string, // null if local copy without ID yet\n@@ -79,11 +81,20 @@ export type CalendarQuery = {|\nfilters: $ReadOnlyArray<CalendarFilter>,\n|};\n-export const defaultCalendarQuery = () => ({\n+export const defaultCalendarQuery = (platform: ?Platform) => {\n+ if (platform === \"web\") {\n+ return {\n+ ...thisMonthDates(),\n+ filters: defaultCalendarFilters,\n+ };\n+ } else {\n+ return {\nstartDate: fifteenDaysEarlier().valueOf(),\nendDate: fifteenDaysLater().valueOf(),\nfilters: defaultCalendarFilters,\n-});\n+ };\n+ }\n+};\nexport const calendarQueryPropType = PropTypes.shape({\nstartDate: PropTypes.string.isRequired,\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/types/socket-types.js",
"new_path": "lib/types/socket-types.js",
"diff": "@@ -23,6 +23,7 @@ import {\ntype UpdateActivityResult,\nactivityUpdatePropType,\n} from './activity-types';\n+import type { Platform } from './device-types';\nimport invariant from 'invariant';\nimport PropTypes from 'prop-types';\n@@ -248,10 +249,10 @@ export const connectionInfoPropType = PropTypes.shape({\n]).isRequired,\nqueuedActivityUpdates: PropTypes.arrayOf(activityUpdatePropType).isRequired,\n});\n-export const defaultConnectionInfo = () => ({\n+export const defaultConnectionInfo = (platform: Platform) => ({\nstatus: \"connecting\",\nqueuedActivityUpdates: [],\n- actualizedCalendarQuery: defaultCalendarQuery(),\n+ actualizedCalendarQuery: defaultCalendarQuery(platform),\n});\nexport const updateConnectionStatusActionType = \"UPDATE_CONNECTION_STATUS\";\nexport type UpdateConnectionStatusPayload = {|\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/utils/date-utils.js",
"new_path": "lib/utils/date-utils.js",
"diff": "@@ -106,6 +106,15 @@ function longAbsoluteDate(timestamp: number) {\n}\n}\n+function thisMonthDates(): {| startDate: string, endDate: string |} {\n+ const year = (new Date()).getFullYear();\n+ const month = (new Date()).getMonth() + 1;\n+ return {\n+ startDate: startDateForYearAndMonth(year, month),\n+ endDate: endDateForYearAndMonth(year, month),\n+ };\n+}\n+\nexport {\ngetDate,\npadMonthOrDay,\n@@ -118,4 +127,5 @@ export {\ndateFromString,\nshortAbsoluteDate,\nlongAbsoluteDate,\n+ thisMonthDates,\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "native/persist.js",
"new_path": "native/persist.js",
"diff": "@@ -10,6 +10,7 @@ import invariant from 'invariant';\nimport { nativeCalendarQuery } from './selectors/nav-selectors';\nimport version from 'lib/facts/version';\n+import { getConfig } from 'lib/utils/config';\nimport { defaultNotifPermissionAlertInfo } from './push/alerts';\n@@ -77,7 +78,7 @@ const migrations = {\n...state,\npingTimestamps: undefined,\nactiveServerRequests: undefined,\n- connection: defaultConnectionInfo(),\n+ connection: defaultConnectionInfo(getConfig().platformDetails.platform),\nwatchedThreadIDs: [],\nforeground: true,\nentryStore: {\n"
},
{
"change_type": "MODIFY",
"old_path": "native/redux-setup.js",
"new_path": "native/redux-setup.js",
"diff": "@@ -45,6 +45,7 @@ import {\nsaveMessagesActionType,\n} from 'lib/actions/message-actions';\nimport { reduxLoggerMiddleware } from 'lib/utils/redux-logger';\n+import { getConfig } from 'lib/utils/config';\nimport { activeThreadSelector } from './selectors/nav-selectors';\nimport {\n@@ -140,7 +141,7 @@ const defaultState = ({\nthreadIDsToNotifIDs: {},\nnotifPermissionAlertInfo: defaultNotifPermissionAlertInfo,\nmessageSentFromRoute: [],\n- connection: defaultConnectionInfo(),\n+ connection: defaultConnectionInfo(getConfig().platformDetails.platform),\nwatchedThreadIDs: [],\nforeground: true,\n_persist: null,\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/creators/update-creator.js",
"new_path": "server/src/creators/update-creator.js",
"diff": "@@ -381,7 +381,7 @@ async function fetchUpdateInfosWithRawUpdateInfos(\n// the corresponding UpdateInfos anyways, so no reason to be worried.\ncalendarQuery = viewerInfo.viewer.calendarQuery;\n} else if (!calendarQuery) {\n- calendarQuery = defaultCalendarQuery();\n+ calendarQuery = defaultCalendarQuery(viewerInfo.viewer.platform);\n}\nif (threadIDsNeedingDetailedFetch.size > 0) {\nconst threadSelectionCriteria = { threadCursors: {} };\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/responders/website-responders.js",
"new_path": "server/src/responders/website-responders.js",
"diff": "@@ -153,7 +153,10 @@ async function websiteResponder(viewer: Viewer, url: string): Promise<string> {\nurlPrefix: \"\",\nwindowDimensions: { width: 0, height: 0 },\nbaseHref: baseDomain + baseURL,\n- connection: defaultConnectionInfo(),\n+ connection: {\n+ ...defaultConnectionInfo(\"web\"),\n+ actualizedCalendarQuery: calendarQuery,\n+ },\nwatchedThreadIDs: [],\nforeground: true,\n}: AppState),\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/updaters/entry-updaters.js",
"new_path": "server/src/updaters/entry-updaters.js",
"diff": "@@ -211,7 +211,7 @@ async function createUpdateDatasForChangedEntryInfo(\n// the corresponding UpdateInfos anyways, so no reason to be worried.\ncalendarQuery = viewer.calendarQuery;\n} else {\n- calendarQuery = defaultCalendarQuery();\n+ calendarQuery = defaultCalendarQuery(viewer.platform);\n}\nlet replaced = null;\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | Fix platform-specific use of defaultCalendarQuery and defaultConnectionInfo |
129,187 | 08.11.2018 10:20:35 | 18,000 | 3ee309c5be35ba2578698764f3471c1f71ad871b | [lib] Add sort to daysToEntriesFromEntryInfos
Otherwise web gets reordered after first incremental state sync, since the server's order doesn't match the browser's for some reason. | [
{
"change_type": "MODIFY",
"old_path": "lib/reducers/entry-reducer.js",
"new_path": "lib/reducers/entry-reducer.js",
"diff": "@@ -36,6 +36,7 @@ import _mapKeys from 'lodash/fp/mapKeys';\nimport _groupBy from 'lodash/fp/groupBy';\nimport _isEqual from 'lodash/fp/isEqual';\nimport _isEmpty from 'lodash/fp/isEmpty';\n+import _sortBy from 'lodash/fp/sortBy';\nimport invariant from 'invariant';\nimport { dateString } from '../utils/date-utils';\n@@ -81,6 +82,7 @@ import { sanitizeAction } from '../utils/sanitization';\nfunction daysToEntriesFromEntryInfos(entryInfos: $ReadOnlyArray<RawEntryInfo>) {\nreturn _flow(\n+ _sortBy(['id', 'localID']),\n_groupBy(\n(entryInfo: RawEntryInfo) =>\ndateString(entryInfo.year, entryInfo.month, entryInfo.day),\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [lib] Add sort to daysToEntriesFromEntryInfos
Otherwise web gets reordered after first incremental state sync, since the server's order doesn't match the browser's for some reason. |
129,187 | 09.11.2018 20:34:40 | 18,000 | 1490829a268b3bb298f053a78a37a03280b0f8d2 | [lib] APIRequestHandler | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "lib/socket/api-request-handler.react.js",
"diff": "+// @flow\n+\n+import {\n+ clientSocketMessageTypes,\n+ serverSocketMessageTypes,\n+ type ClientSocketMessageWithoutID,\n+ type ConnectionInfo,\n+ connectionInfoPropType,\n+} from '../types/socket-types';\n+import type { APIRequest } from '../types/endpoints';\n+import type { BaseAppState } from '../types/redux-types';\n+\n+import * as React from 'react';\n+import PropTypes from 'prop-types';\n+import invariant from 'invariant';\n+\n+import { connect } from '../utils/redux-utils';\n+import { registerActiveSocket } from '../utils/action-utils';\n+import { InflightRequests, SocketOffline } from './inflight-requests';\n+\n+type Props = {|\n+ inflightRequests: ?InflightRequests,\n+ sendMessage: (message: ClientSocketMessageWithoutID) => number,\n+ // Redux state\n+ connection: ConnectionInfo,\n+|};\n+class APIRequestHandler extends React.PureComponent<Props> {\n+\n+ static propTypes = {\n+ inflightRequests: PropTypes.object,\n+ sendMessage: PropTypes.func.isRequired,\n+ connection: connectionInfoPropType.isRequired,\n+ };\n+\n+ static isConnected(props: Props) {\n+ const { inflightRequests, connection } = props;\n+ return inflightRequests && connection.status === \"connected\";\n+ }\n+\n+ get registeredResponseFetcher() {\n+ return APIRequestHandler.isConnected(this.props)\n+ ? this.fetchResponse\n+ : null;\n+ }\n+\n+ componentDidMount() {\n+ registerActiveSocket(this.registeredResponseFetcher);\n+ }\n+\n+ componentWillUnmount() {\n+ registerActiveSocket(null);\n+ }\n+\n+ componentDidUpdate(prevProps: Props) {\n+ const isConnected = APIRequestHandler.isConnected(this.props);\n+ const wasConnected = APIRequestHandler.isConnected(prevProps);\n+ if (isConnected !== wasConnected) {\n+ registerActiveSocket(this.registeredResponseFetcher);\n+ }\n+ }\n+\n+ render() {\n+ return null;\n+ }\n+\n+ fetchResponse = async (request: APIRequest): Promise<Object> => {\n+ if (!APIRequestHandler.isConnected(this.props)) {\n+ throw new SocketOffline(\"socket_offline\");\n+ }\n+ const { inflightRequests } = this.props;\n+ invariant(\n+ inflightRequests,\n+ \"inflightRequests falsey inside fetchResponse\",\n+ );\n+ const messageID = this.props.sendMessage({\n+ type: clientSocketMessageTypes.API_REQUEST,\n+ payload: request,\n+ });\n+ const response = await inflightRequests.fetchResponse(\n+ messageID,\n+ serverSocketMessageTypes.API_RESPONSE,\n+ );\n+ return response.payload;\n+ }\n+\n+}\n+\n+export default connect((state: BaseAppState<*>) => ({\n+ connection: state.connection,\n+}))(APIRequestHandler);\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/socket/inflight-requests.js",
"new_path": "lib/socket/inflight-requests.js",
"diff": "@@ -6,6 +6,7 @@ import {\ntype RequestsServerSocketMessage,\ntype ActivityUpdateResponseServerSocketMessage,\ntype PongServerSocketMessage,\n+ type APIResponseServerSocketMessage,\ntype ServerSocketMessageType,\nserverSocketMessageTypes,\n} from '../types/socket-types';\n@@ -21,6 +22,7 @@ type ValidResponseMessageMap = {\nb: RequestsServerSocketMessage,\nc: ActivityUpdateResponseServerSocketMessage,\nd: PongServerSocketMessage,\n+ e: APIResponseServerSocketMessage,\n};\ntype BaseInflightRequest<Response: ServerSocketMessage> = {|\nexpectedResponseType: $PropertyType<Response, 'type'>,\n@@ -36,6 +38,8 @@ type InflightRequestMap = $ObjMap<\ntype ValidResponseMessage = $Values<ValidResponseMessageMap>;\ntype InflightRequest = $Values<InflightRequestMap>;\n+class SocketOffline extends ExtendableError { }\n+\nclass SocketTimeout extends ExtendableError {\nexpectedResponseType: ServerSocketMessageType;\nconstructor(expectedType: ServerSocketMessageType) {\n@@ -95,6 +99,13 @@ class InflightRequests {\nreject,\nmessageID,\n};\n+ } else if (expectedType === serverSocketMessageTypes.API_RESPONSE) {\n+ inflightRequest = {\n+ expectedResponseType: serverSocketMessageTypes.API_RESPONSE,\n+ resolve,\n+ reject,\n+ messageID,\n+ };\n}\n});\ninvariant(\n@@ -160,6 +171,12 @@ class InflightRequests {\ninflightRequest.expectedResponseType === serverSocketMessageTypes.PONG\n) {\ninflightRequest.resolve(message);\n+ } else if (\n+ message.type === serverSocketMessageTypes.API_RESPONSE &&\n+ inflightRequest.expectedResponseType ===\n+ serverSocketMessageTypes.API_RESPONSE\n+ ) {\n+ inflightRequest.resolve(message);\n}\n}\n}\n@@ -184,6 +201,7 @@ class InflightRequests {\n}\nexport {\n+ SocketOffline,\nSocketTimeout,\nInflightRequests,\n};\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/socket/socket.react.js",
"new_path": "lib/socket/socket.react.js",
"diff": "@@ -29,6 +29,7 @@ import {\ntype ActivityUpdatesClientSocketMessage,\ntype PingClientSocketMessage,\ntype AckUpdatesClientSocketMessage,\n+ type APIRequestClientSocketMessage,\ntype ClientSocketMessageWithoutID,\ntype SocketListener,\ntype ConnectionStatus,\n@@ -48,7 +49,6 @@ import _debounce from 'lodash/debounce';\nimport { getConfig } from '../utils/config';\nimport {\n- registerActiveWebSocket,\nsetNewSessionActionType,\nfetchNewCookieFromNativeCredentials,\n} from '../utils/action-utils';\n@@ -168,7 +168,6 @@ class Socket extends React.PureComponent<Props, State> {\n}\nmarkSocketInitialized() {\n- registerActiveWebSocket(this.socket);\nthis.props.dispatchActionPayload(\nupdateConnectionStatusActionType,\n{ status: \"connected\" },\n@@ -184,7 +183,6 @@ class Socket extends React.PureComponent<Props, State> {\nthis.reopenConnectionAfterClosing = false;\nreturn;\n}\n- registerActiveWebSocket(null);\nthis.stopPing();\nthis.props.dispatchActionPayload(\nupdateConnectionStatusActionType,\n@@ -194,7 +192,6 @@ class Socket extends React.PureComponent<Props, State> {\n}\nforceCloseSocket() {\n- registerActiveWebSocket(null);\nthis.stopPing();\nconst { status } = this.props.connection;\nif (status !== \"forcedDisconnecting\" && status !== \"disconnected\") {\n@@ -211,7 +208,6 @@ class Socket extends React.PureComponent<Props, State> {\nif (inflightRequests && !inflightRequests.allRequestsResolved) {\nreturn;\n}\n- registerActiveWebSocket(null);\nif (this.socket && this.socket.readyState < 2) {\n// If it's not closing already, close it\nthis.socket.close();\n@@ -318,6 +314,8 @@ class Socket extends React.PureComponent<Props, State> {\nthis.sendMessage(({ ...message, id }: PingClientSocketMessage));\n} else if (message.type === clientSocketMessageTypes.ACK_UPDATES) {\nthis.sendMessage(({ ...message, id }: AckUpdatesClientSocketMessage));\n+ } else if (message.type === clientSocketMessageTypes.API_REQUEST) {\n+ this.sendMessage(({ ...message, id }: APIRequestClientSocketMessage));\n}\nreturn id;\n}\n@@ -414,13 +412,6 @@ class Socket extends React.PureComponent<Props, State> {\nconst { status } = this.props.connection;\nthis.socket = null;\nthis.stopPing();\n- if (\n- status !== \"disconnecting\" &&\n- status !== \"forcedDisconnecting\" &&\n- status !== \"disconnected\"\n- ) {\n- registerActiveWebSocket(null);\n- }\nif (this.state.inflightRequests) {\nthis.state.inflightRequests.rejectAll(new Error(\"socket closed\"));\nthis.setState({ inflightRequests: null });\n@@ -434,7 +425,6 @@ class Socket extends React.PureComponent<Props, State> {\n}\nhandleTimeout() {\n- registerActiveWebSocket(null);\nthis.setState({ inflightRequests: null });\nconst { status } = this.props.connection;\nif (this.socket && this.socket.readyState < 2) {\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/types/endpoints.js",
"new_path": "lib/types/endpoints.js",
"diff": "// @flow\n+export type APIRequest = {|\n+ endpoint: Endpoint,\n+ input: Object,\n+|};\n+export type SocketAPIHandler = (request: APIRequest) => Promise<Object>;\n+\nexport const endpoint = Object.freeze({\nUPDATE_ACTIVITY: 'update_activity',\nUPDATE_USER_SUBSCRIPTION: 'update_user_subscription',\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/types/socket-types.js",
"new_path": "lib/types/socket-types.js",
"diff": "@@ -24,6 +24,7 @@ import {\nactivityUpdatePropType,\n} from './activity-types';\nimport type { Platform } from './device-types';\n+import type { APIRequest } from './endpoints';\nimport invariant from 'invariant';\nimport PropTypes from 'prop-types';\n@@ -35,6 +36,7 @@ export const clientSocketMessageTypes = Object.freeze({\nACTIVITY_UPDATES: 2,\nPING: 3,\nACK_UPDATES: 4,\n+ API_REQUEST: 5,\n});\nexport type ClientSocketMessageType = $Values<typeof clientSocketMessageTypes>;\nexport function assertClientSocketMessageType(\n@@ -45,7 +47,8 @@ export function assertClientSocketMessageType(\nourClientSocketMessageType === 1 ||\nourClientSocketMessageType === 2 ||\nourClientSocketMessageType === 3 ||\n- ourClientSocketMessageType === 4,\n+ ourClientSocketMessageType === 4 ||\n+ ourClientSocketMessageType === 5,\n\"number is not ClientSocketMessageType enum\",\n);\nreturn ourClientSocketMessageType;\n@@ -85,12 +88,18 @@ export type AckUpdatesClientSocketMessage = {|\ncurrentAsOf: number,\n|},\n|};\n+export type APIRequestClientSocketMessage = {|\n+ type: 5,\n+ id: number,\n+ payload: APIRequest,\n+|};\nexport type ClientSocketMessage =\n| InitialClientSocketMessage\n| ResponsesClientSocketMessage\n| ActivityUpdatesClientSocketMessage\n| PingClientSocketMessage\n- | AckUpdatesClientSocketMessage;\n+ | AckUpdatesClientSocketMessage\n+ | APIRequestClientSocketMessage;\nexport type ClientSocketMessageWithoutID =\n$Diff<ClientSocketMessage, { id: number }>;\n@@ -104,6 +113,7 @@ export const serverSocketMessageTypes = Object.freeze({\nPONG: 5,\nUPDATES: 6,\nMESSAGES: 7,\n+ API_RESPONSE: 8,\n});\nexport type ServerSocketMessageType = $Values<typeof serverSocketMessageTypes>;\nexport function assertServerSocketMessageType(\n@@ -117,7 +127,8 @@ export function assertServerSocketMessageType(\nourServerSocketMessageType === 4 ||\nourServerSocketMessageType === 5 ||\nourServerSocketMessageType === 6 ||\n- ourServerSocketMessageType === 7,\n+ ourServerSocketMessageType === 7 ||\n+ ourServerSocketMessageType === 8,\n\"number is not ServerSocketMessageType enum\",\n);\nreturn ourServerSocketMessageType;\n@@ -214,6 +225,10 @@ export type MessagesServerSocketMessage = {|\ntype: 7,\npayload: MessagesResultWithUserInfos,\n|};\n+export type APIResponseServerSocketMessage = {|\n+ type: 8,\n+ payload: Object,\n+|};\nexport type ServerSocketMessage =\n| StateSyncServerSocketMessage\n| RequestsServerSocketMessage\n@@ -222,7 +237,8 @@ export type ServerSocketMessage =\n| ActivityUpdateResponseServerSocketMessage\n| PongServerSocketMessage\n| UpdatesServerSocketMessage\n- | MessagesServerSocketMessage;\n+ | MessagesServerSocketMessage\n+ | APIResponseServerSocketMessage;\nexport type SocketListener = (message: ServerSocketMessage) => void;\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/utils/action-utils.js",
"new_path": "lib/utils/action-utils.js",
"diff": "@@ -15,7 +15,7 @@ import type {\nLogInStartingPayload,\nLogInResult,\n} from '../types/account-types';\n-import type { Endpoint } from '../types/endpoints';\n+import type { Endpoint, SocketAPIHandler } from '../types/endpoints';\nimport type { ClientSessionChange } from '../types/session-types';\nimport invariant from 'invariant';\n@@ -416,9 +416,9 @@ function bindServerCalls(serverCalls: ServerCalls) {\n};\n}\n-let webSocket = null;\n-function registerActiveWebSocket(passedWebSocket: ?WebSocket) {\n- webSocket = passedWebSocket;\n+let socketAPIHandler: ?SocketAPIHandler = null;\n+function registerActiveSocket(passedSocketAPIHandler: ?SocketAPIHandler) {\n+ socketAPIHandler = passedSocketAPIHandler;\n}\nexport {\n@@ -426,5 +426,5 @@ export {\nincludeDispatchActionProps,\nfetchNewCookieFromNativeCredentials,\nbindServerCalls,\n- registerActiveWebSocket,\n+ registerActiveSocket,\n};\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [lib] APIRequestHandler |
129,187 | 10.11.2018 12:05:24 | 18,000 | 76bd4b472fcb818987073d64e6b8d470a9cc29d4 | [lib] Hook fetchJSON up to SocketAPIHandler | [
{
"change_type": "MODIFY",
"old_path": "lib/types/endpoints.js",
"new_path": "lib/types/endpoints.js",
"diff": "@@ -6,7 +6,27 @@ export type APIRequest = {|\n|};\nexport type SocketAPIHandler = (request: APIRequest) => Promise<Object>;\n-export const endpoint = Object.freeze({\n+// Endpoints that can cause session changes should occur over HTTP, since the\n+// socket code does not currently support changing sessions. In the future they\n+// could be made to work for native, but cookie changes on web require HTTP\n+// since websockets aren't able to Set-Cookie.\n+export type Endpoint =\n+ | SessionChangingEndpoint\n+ | SocketSafeEndpoint;\n+\n+// Note that technically any endpoint can cause a sessionChange, and in that\n+// case the server will close the socket with a specific error code, and the\n+// client will proceed via HTTP.\n+export const sessionChangingEndpoints = Object.freeze({\n+ LOG_OUT: 'log_out',\n+ DELETE_ACCOUNT: 'delete_account',\n+ CREATE_ACCOUNT: 'create_account',\n+ LOG_IN: 'log_in',\n+ UPDATE_PASSWORD: 'update_password',\n+});\n+type SessionChangingEndpoint = $Values<typeof sessionChangingEndpoints>;\n+\n+export const socketSafeEndpoints = Object.freeze({\nUPDATE_ACTIVITY: 'update_activity',\nUPDATE_USER_SUBSCRIPTION: 'update_user_subscription',\nUPDATE_DEVICE_TOKEN: 'update_device_token',\n@@ -31,15 +51,15 @@ export const endpoint = Object.freeze({\nFETCH_MESSAGES: 'fetch_messages',\nJOIN_THREAD: 'join_thread',\nPING: 'ping',\n- LOG_OUT: 'log_out',\n- DELETE_ACCOUNT: 'delete_account',\n- CREATE_ACCOUNT: 'create_account',\n- LOG_IN: 'log_in',\n- UPDATE_PASSWORD: 'update_password',\nCREATE_ERROR_REPORT: 'create_error_report',\nFETCH_ERROR_REPORT_INFOS: 'fetch_error_report_infos',\nREQUEST_ACCESS: 'request_access',\nCREATE_REPORT: 'create_report',\nUPDATE_CALENDAR_QUERY: 'update_calendar_query',\n});\n-export type Endpoint = $Values<typeof endpoint>;\n+type SocketSafeEndpoint = $Values<typeof socketSafeEndpoints>;\n+\n+const socketSafeEndpointSet = new Set(Object.values(socketSafeEndpoints));\n+export function endpointIsSocketSafe(endpoint: Endpoint): bool {\n+ return socketSafeEndpointSet.has(endpoint);\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/utils/action-utils.js",
"new_path": "lib/utils/action-utils.js",
"diff": "@@ -17,6 +17,7 @@ import type {\n} from '../types/account-types';\nimport type { Endpoint, SocketAPIHandler } from '../types/endpoints';\nimport type { ClientSessionChange } from '../types/session-types';\n+import type { ConnectionStatus } from '../types/socket-types';\nimport invariant from 'invariant';\nimport _mapValues from 'lodash/fp/mapValues';\n@@ -204,6 +205,8 @@ async function fetchNewCookieFromNativeCredentials(\n(sessionChange: ClientSessionChange) => new Promise(r => r(null)),\nurlPrefix,\nnull,\n+ \"disconnected\",\n+ null,\nendpoint,\ndata,\noptions,\n@@ -241,13 +244,15 @@ async function fetchNewCookieFromNativeCredentials(\n// Third param is optional and gets called with newCookie if we get a new cookie\n// Necessary to propagate cookie in cookieInvalidationRecovery below\n-function bindCookieAndUtilsIntoFetchJSON(\n- dispatch: Dispatch,\n- cookie: ?string,\n- urlPrefix: string,\n- sessionID: ?string,\n- loggedIn: bool,\n-): FetchJSON {\n+function bindCookieAndUtilsIntoFetchJSON(params: BindServerCallsParams): FetchJSON {\n+ const {\n+ dispatch,\n+ cookie,\n+ urlPrefix,\n+ sessionID,\n+ loggedIn,\n+ connectionStatus,\n+ } = params;\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@@ -255,11 +260,11 @@ function bindCookieAndUtilsIntoFetchJSON(\nif (!getConfig().resolveInvalidatedCookie) {\n// If there is no resolveInvalidatedCookie function, just let the caller\n// fetchJSON instance continue\n- return new Promise(r => r(null));\n+ return Promise.resolve(null);\n}\nif (!currentlyWaitingForNewCookie) {\n// Our cookie seems to be valid\n- return new Promise(r => r(null));\n+ return Promise.resolve(null);\n}\n// Wait to run until we get our new cookie\nreturn new Promise(r => fetchJSONCallsWaitingForNewCookie.push(r));\n@@ -280,13 +285,11 @@ function bindCookieAndUtilsIntoFetchJSON(\nfetchJSONCallsWaitingForNewCookie = [];\nconst newFetchJSON = newSessionChange\n- ? bindCookieAndUtilsIntoFetchJSON(\n- dispatch,\n- newSessionChange.cookie,\n- urlPrefix,\n- newSessionChange.sessionID,\n- loggedIn,\n- )\n+ ? bindCookieAndUtilsIntoFetchJSON({\n+ ...params,\n+ cookie: newSessionChange.cookie,\n+ sessionID: newSessionChange.sessionID,\n+ })\n: null;\nfor (const func of currentWaitingCalls) {\nfunc(newFetchJSON);\n@@ -300,12 +303,12 @@ function bindCookieAndUtilsIntoFetchJSON(\nif (!getConfig().resolveInvalidatedCookie) {\n// If there is no resolveInvalidatedCookie function, just let the caller\n// fetchJSON instance continue\n- return new Promise(r => r(null));\n+ return Promise.resolve(null);\n}\nif (!loggedIn) {\n// We don't want to attempt any use native credentials of a logged out\n// user to log-in after a cookieInvalidation while logged out\n- return new Promise(r => r(null));\n+ return Promise.resolve(null);\n}\nif (currentlyWaitingForNewCookie) {\nreturn new Promise(r => fetchJSONCallsWaitingForNewCookie.push(r));\n@@ -325,6 +328,8 @@ function bindCookieAndUtilsIntoFetchJSON(\ncookieInvalidationRecovery,\nurlPrefix,\nsessionID,\n+ connectionStatus,\n+ socketAPIHandler,\nendpoint,\ndata,\noptions,\n@@ -332,13 +337,14 @@ function bindCookieAndUtilsIntoFetchJSON(\n}\ntype ActionFunc = (fetchJSON: FetchJSON, ...rest: $FlowFixMe) => Promise<*>;\n-type BindServerCallsParams = {\n+type BindServerCallsParams = {|\ndispatch: Dispatch,\ncookie: ?string,\nurlPrefix: string,\nsessionID: ?string,\nloggedIn: bool,\n-};\n+ connectionStatus: ConnectionStatus,\n+|};\n// All server calls needs to include some information from the Redux state\n// (namely, the cookie). This information is used deep in the server call,\n@@ -355,20 +361,23 @@ const baseCreateBoundServerCallsSelector = (actionFunc: ActionFunc) => {\n(state: BindServerCallsParams) => state.urlPrefix,\n(state: BindServerCallsParams) => state.sessionID,\n(state: BindServerCallsParams) => state.loggedIn,\n+ (state: BindServerCallsParams) => state.connectionStatus,\n(\ndispatch: Dispatch,\ncookie: ?string,\nurlPrefix: string,\nsessionID: ?string,\nloggedIn: bool,\n+ connectionStatus: ConnectionStatus,\n) => {\n- const boundFetchJSON = bindCookieAndUtilsIntoFetchJSON(\n+ const boundFetchJSON = bindCookieAndUtilsIntoFetchJSON({\ndispatch,\ncookie,\nurlPrefix,\nsessionID,\nloggedIn,\n- );\n+ connectionStatus,\n+ });\nreturn (...rest: $FlowFixMe) => actionFunc(boundFetchJSON, ...rest);\n},\n);\n@@ -385,6 +394,7 @@ function bindServerCalls(serverCalls: ServerCalls) {\nurlPrefix: string,\nsessionID: ?string,\ncurrentUserInfoLoggedIn: bool,\n+ connectionStatus: ConnectionStatus,\n},\ndispatchProps: Object,\nownProps: {[propName: string]: mixed},\n@@ -396,6 +406,7 @@ function bindServerCalls(serverCalls: ServerCalls) {\nurlPrefix,\nsessionID,\ncurrentUserInfoLoggedIn: loggedIn,\n+ connectionStatus,\n} = stateProps;\nconst boundServerCalls = _mapValues(\n(serverCall: (fetchJSON: FetchJSON, ...rest: any) => Promise<any>) =>\n@@ -405,6 +416,7 @@ function bindServerCalls(serverCalls: ServerCalls) {\nurlPrefix,\nsessionID,\nloggedIn,\n+ connectionStatus,\n}),\n)(serverCalls);\nreturn {\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/utils/fetch-json.js",
"new_path": "lib/utils/fetch-json.js",
"diff": "// @flow\n-import type { Endpoint } from '../types/endpoints';\n+import {\n+ type Endpoint,\n+ type SocketAPIHandler,\n+ endpointIsSocketSafe,\n+} from '../types/endpoints';\nimport type {\nServerSessionChange,\nClientSessionChange,\n} from '../types/session-types';\n+import type { ConnectionStatus } from '../types/socket-types';\nimport invariant from 'invariant';\nimport _map from 'lodash/fp/map';\n@@ -15,6 +20,7 @@ import _cloneDeep from 'lodash/fp/cloneDeep';\nimport { ServerError, FetchTimeout } from './errors';\nimport { getConfig } from './config';\nimport sleep from './sleep';\n+import { SocketOffline, SocketTimeout } from '../socket/inflight-requests';\n// You'll notice that this is not the type of the fetchJSON function below. This\n// is because the first several parameters to that functon get bound in by the\n@@ -51,6 +57,8 @@ async function fetchJSON(\n(sessionChange: ClientSessionChange) => Promise<?FetchJSON>,\nurlPrefix: string,\nsessionID: ?string,\n+ connectionStatus: ConnectionStatus,\n+ socketAPIHandler: ?SocketAPIHandler,\nendpoint: Endpoint,\ninput: {[key: string]: mixed},\noptions?: ?FetchJSONOptions,\n@@ -60,6 +68,25 @@ async function fetchJSON(\nreturn await possibleReplacement(endpoint, input, options);\n}\n+ if (\n+ endpointIsSocketSafe(endpoint) &&\n+ connectionStatus === \"connected\" &&\n+ socketAPIHandler\n+ ) {\n+ try {\n+ return await socketAPIHandler({ endpoint, input });\n+ } catch (e) {\n+ // In the case where a socket error occurred, we'll try to proceed via a\n+ // HTTP request. If it was a ServerError or something client-local, we\n+ // will rethrow the exception.\n+ if (e instanceof SocketOffline) {\n+ } else if (e instanceof SocketTimeout) {\n+ } else {\n+ throw e;\n+ }\n+ }\n+ }\n+\nconst mergedData: RequestData = { input };\nif (getConfig().setCookieOnRequest) {\n// We make sure that if setCookieOnRequest is true, we never set cookie to\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/utils/redux-utils.js",
"new_path": "lib/utils/redux-utils.js",
"diff": "import type { ServerCalls } from './action-utils';\nimport type { AppState } from '../types/redux-types';\n+import type { ConnectionStatus } from '../types/socket-types';\nimport { connect as reactReduxConnect } from 'react-redux';\nimport invariant from 'invariant';\n@@ -26,6 +27,7 @@ function connect<S: AppState, OP: Object, SP: Object>(\nurlPrefix: string,\nsessionID: ?string,\ncurrentUserInfoLoggedIn: bool,\n+ connectionStatus: ConnectionStatus,\n} => ({\n...mapStateToProps(state, ownProps),\ncookie: state.cookie,\n@@ -33,6 +35,7 @@ function connect<S: AppState, OP: Object, SP: Object>(\nsessionID: state.sessionID,\ncurrentUserInfoLoggedIn:\n!!(state.currentUserInfo && !state.currentUserInfo.anonymous && true),\n+ connectionStatus: state.connection.status,\n});\n} else if (serverCallExists && mapStateToProps) {\nmapState = (state: S): {\n@@ -41,6 +44,7 @@ function connect<S: AppState, OP: Object, SP: Object>(\nurlPrefix: string,\nsessionID: ?string,\ncurrentUserInfoLoggedIn: bool,\n+ connectionStatus: ConnectionStatus,\n} => ({\n// $FlowFixMe\n...mapStateToProps(state),\n@@ -49,6 +53,7 @@ function connect<S: AppState, OP: Object, SP: Object>(\nsessionID: state.sessionID,\ncurrentUserInfoLoggedIn:\n!!(state.currentUserInfo && !state.currentUserInfo.anonymous && true),\n+ connectionStatus: state.connection.status,\n});\n} else if (mapStateToProps) {\nmapState = mapStateToProps;\n@@ -58,12 +63,14 @@ function connect<S: AppState, OP: Object, SP: Object>(\nurlPrefix: string,\nsessionID: ?string,\ncurrentUserInfoLoggedIn: bool,\n+ connectionStatus: ConnectionStatus,\n} => ({\ncookie: state.cookie,\nurlPrefix: state.urlPrefix,\nsessionID: state.sessionID,\ncurrentUserInfoLoggedIn:\n!!(state.currentUserInfo && !state.currentUserInfo.anonymous && true),\n+ connectionStatus: state.connection.status,\n});\n}\nconst dispatchIncluded = includeDispatch === true\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [lib] Hook fetchJSON up to SocketAPIHandler |
129,187 | 10.11.2018 18:29:41 | 18,000 | b199007f8e853567386989ff71cb925a14fe1073 | Server support for API requests via socket | [
{
"change_type": "MODIFY",
"old_path": "lib/types/socket-types.js",
"new_path": "lib/types/socket-types.js",
"diff": "@@ -227,6 +227,7 @@ export type MessagesServerSocketMessage = {|\n|};\nexport type APIResponseServerSocketMessage = {|\ntype: 8,\n+ responseTo: number,\npayload: Object,\n|};\nexport type ServerSocketMessage =\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "server/src/endpoints.js",
"diff": "+// @flow\n+\n+import type { JSONResponder } from './responders/handlers';\n+import type { Endpoint } from 'lib/types/endpoints';\n+\n+import {\n+ textMessageCreationResponder,\n+ messageFetchResponder,\n+} from './responders/message-responders';\n+import { updateActivityResponder } from './responders/activity-responders';\n+import { deviceTokenUpdateResponder } from './responders/device-responders';\n+import {\n+ userSubscriptionUpdateResponder,\n+ accountUpdateResponder,\n+ sendVerificationEmailResponder,\n+ sendPasswordResetEmailResponder,\n+ logOutResponder,\n+ accountDeletionResponder,\n+ accountCreationResponder,\n+ logInResponder,\n+ passwordUpdateResponder,\n+ requestAccessResponder,\n+} from './responders/user-responders';\n+import { userSearchResponder } from './responders/search-responders';\n+import {\n+ entryFetchResponder,\n+ entryRevisionFetchResponder,\n+ entryCreationResponder,\n+ entryUpdateResponder,\n+ entryDeletionResponder,\n+ entryRestorationResponder,\n+ calendarQueryUpdateResponder,\n+} from './responders/entry-responders';\n+import {\n+ codeVerificationResponder,\n+} from './responders/verification-responders';\n+import {\n+ threadDeletionResponder,\n+ roleUpdateResponder,\n+ memberRemovalResponder,\n+ threadLeaveResponder,\n+ threadUpdateResponder,\n+ threadCreationResponder,\n+ threadJoinResponder,\n+} from './responders/thread-responders';\n+import { pingResponder } from './responders/ping-responders';\n+import {\n+ reportCreationResponder,\n+ errorReportFetchInfosResponder,\n+} from './responders/report-responders';\n+\n+const jsonEndpoints: {[id: Endpoint]: JSONResponder} = {\n+ 'update_activity': updateActivityResponder,\n+ 'update_user_subscription': userSubscriptionUpdateResponder,\n+ 'update_device_token': deviceTokenUpdateResponder,\n+ 'update_account': accountUpdateResponder,\n+ 'send_verification_email': sendVerificationEmailResponder,\n+ 'search_users': userSearchResponder,\n+ 'send_password_reset_email': sendPasswordResetEmailResponder,\n+ 'create_text_message': textMessageCreationResponder,\n+ 'fetch_entries': entryFetchResponder,\n+ 'fetch_entry_revisions': entryRevisionFetchResponder,\n+ 'verify_code': codeVerificationResponder,\n+ 'delete_thread': threadDeletionResponder,\n+ 'create_entry': entryCreationResponder,\n+ 'update_entry': entryUpdateResponder,\n+ 'delete_entry': entryDeletionResponder,\n+ 'restore_entry': entryRestorationResponder,\n+ 'update_role': roleUpdateResponder,\n+ 'remove_members': memberRemovalResponder,\n+ 'leave_thread': threadLeaveResponder,\n+ 'update_thread': threadUpdateResponder,\n+ 'create_thread': threadCreationResponder,\n+ 'fetch_messages': messageFetchResponder,\n+ 'join_thread': threadJoinResponder,\n+ 'ping': pingResponder,\n+ 'log_out': logOutResponder,\n+ 'delete_account': accountDeletionResponder,\n+ 'create_account': accountCreationResponder,\n+ 'log_in': logInResponder,\n+ 'update_password': passwordUpdateResponder,\n+ 'create_error_report': reportCreationResponder,\n+ 'create_report': reportCreationResponder,\n+ 'fetch_error_report_infos': errorReportFetchInfosResponder,\n+ 'request_access': requestAccessResponder,\n+ 'update_calendar_query': calendarQueryUpdateResponder,\n+};\n+\n+export {\n+ jsonEndpoints,\n+};\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/server.js",
"new_path": "server/src/server.js",
"diff": "// @flow\n-import type { JSONResponder } from './responders/handlers';\n-import type { Endpoint } from 'lib/types/endpoints';\n-\nimport express from 'express';\nimport cookieParser from 'cookie-parser';\nimport cluster from 'cluster';\n@@ -14,96 +11,15 @@ import {\ndownloadHandler,\nhtmlHandler,\n} from './responders/handlers';\n-import {\n- textMessageCreationResponder,\n- messageFetchResponder,\n-} from './responders/message-responders';\n-import { updateActivityResponder } from './responders/activity-responders';\n-import { deviceTokenUpdateResponder } from './responders/device-responders';\n-import {\n- userSubscriptionUpdateResponder,\n- accountUpdateResponder,\n- sendVerificationEmailResponder,\n- sendPasswordResetEmailResponder,\n- logOutResponder,\n- accountDeletionResponder,\n- accountCreationResponder,\n- logInResponder,\n- passwordUpdateResponder,\n- requestAccessResponder,\n-} from './responders/user-responders';\n-import { userSearchResponder } from './responders/search-responders';\n-import {\n- entryFetchResponder,\n- entryRevisionFetchResponder,\n- entryCreationResponder,\n- entryUpdateResponder,\n- entryDeletionResponder,\n- entryRestorationResponder,\n- calendarQueryUpdateResponder,\n-} from './responders/entry-responders';\n-import {\n- codeVerificationResponder,\n-} from './responders/verification-responders';\n-import {\n- threadDeletionResponder,\n- roleUpdateResponder,\n- memberRemovalResponder,\n- threadLeaveResponder,\n- threadUpdateResponder,\n- threadCreationResponder,\n- threadJoinResponder,\n-} from './responders/thread-responders';\n-import { pingResponder } from './responders/ping-responders';\n-import { websiteResponder } from './responders/website-responders';\n-import {\n- reportCreationResponder,\n- errorReportFetchInfosResponder,\n- errorReportDownloadHandler,\n-} from './responders/report-responders';\nimport { onConnection } from './socket/socket';\nimport urlFacts from '../facts/url';\nimport './cron';\n+import { jsonEndpoints } from './endpoints';\n+import { websiteResponder } from './responders/website-responders';\n+import { errorReportDownloadHandler } from './responders/report-responders';\nconst { baseRoutePath } = urlFacts;\n-const jsonEndpoints: {[id: Endpoint]: JSONResponder} = {\n- 'update_activity': updateActivityResponder,\n- 'update_user_subscription': userSubscriptionUpdateResponder,\n- 'update_device_token': deviceTokenUpdateResponder,\n- 'update_account': accountUpdateResponder,\n- 'send_verification_email': sendVerificationEmailResponder,\n- 'search_users': userSearchResponder,\n- 'send_password_reset_email': sendPasswordResetEmailResponder,\n- 'create_text_message': textMessageCreationResponder,\n- 'fetch_entries': entryFetchResponder,\n- 'fetch_entry_revisions': entryRevisionFetchResponder,\n- 'verify_code': codeVerificationResponder,\n- 'delete_thread': threadDeletionResponder,\n- 'create_entry': entryCreationResponder,\n- 'update_entry': entryUpdateResponder,\n- 'delete_entry': entryDeletionResponder,\n- 'restore_entry': entryRestorationResponder,\n- 'update_role': roleUpdateResponder,\n- 'remove_members': memberRemovalResponder,\n- 'leave_thread': threadLeaveResponder,\n- 'update_thread': threadUpdateResponder,\n- 'create_thread': threadCreationResponder,\n- 'fetch_messages': messageFetchResponder,\n- 'join_thread': threadJoinResponder,\n- 'ping': pingResponder,\n- 'log_out': logOutResponder,\n- 'delete_account': accountDeletionResponder,\n- 'create_account': accountCreationResponder,\n- 'log_in': logInResponder,\n- 'update_password': passwordUpdateResponder,\n- 'create_error_report': reportCreationResponder,\n- 'create_report': reportCreationResponder,\n- 'fetch_error_report_infos': errorReportFetchInfosResponder,\n- 'request_access': requestAccessResponder,\n- 'update_calendar_query': calendarQueryUpdateResponder,\n-};\n-\nif (cluster.isMaster) {\nconst cpuCount = os.cpus().length;\nfor (let i = 0; i < cpuCount; i++) {\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/socket/socket.js",
"new_path": "server/src/socket/socket.js",
"diff": "@@ -13,6 +13,7 @@ import {\ntype AuthErrorServerSocketMessage,\ntype PingClientSocketMessage,\ntype AckUpdatesClientSocketMessage,\n+ type APIRequestClientSocketMessage,\nclientSocketMessageTypes,\nstateSyncPayloadTypes,\nserverSocketMessageTypes,\n@@ -25,6 +26,7 @@ import {\nimport { defaultNumberPerThread } from 'lib/types/message-types';\nimport { serverRequestTypes } from 'lib/types/request-types';\nimport { redisMessageTypes, type RedisMessage } from 'lib/types/redis-types';\n+import { endpointIsSocketSafe } from 'lib/types/endpoints';\nimport t from 'tcomb';\nimport invariant from 'invariant';\n@@ -82,6 +84,7 @@ import {\nimport { focusedTableRefreshFrequency } from '../shared/focused-times';\nimport { RedisSubscriber } from './redis';\nimport { fetchUpdateInfosWithRawUpdateInfos } from '../creators/update-creator';\n+import { jsonEndpoints } from '../endpoints';\nconst clientSocketMessageInputValidator = t.union([\ntShape({\n@@ -141,6 +144,17 @@ const clientSocketMessageInputValidator = t.union([\ncurrentAsOf: t.Number,\n}),\n}),\n+ tShape({\n+ type: t.irreducible(\n+ 'clientSocketMessageTypes.API_REQUEST',\n+ x => x === clientSocketMessageTypes.API_REQUEST,\n+ ),\n+ id: t.Number,\n+ payload: tShape({\n+ endpoint: t.String,\n+ input: t.Object,\n+ }),\n+ }),\n]);\nfunction onConnection(ws: WebSocket, req: $Request) {\n@@ -370,6 +384,9 @@ class Socket {\n} else if (message.type === clientSocketMessageTypes.ACK_UPDATES) {\nthis.markActivityOccurred();\nreturn await this.handleAckUpdatesClientSocketMessage(message);\n+ } else if (message.type === clientSocketMessageTypes.API_REQUEST) {\n+ this.markActivityOccurred();\n+ return await this.handleAPIRequestClientSocketMessage(message);\n}\nreturn [];\n}\n@@ -615,6 +632,23 @@ class Socket {\nreturn [];\n}\n+ async handleAPIRequestClientSocketMessage(\n+ message: APIRequestClientSocketMessage,\n+ ): Promise<ServerSocketMessage[]> {\n+ if (!endpointIsSocketSafe(message.payload.endpoint)) {\n+ throw new ServerError('endpoint_unsafe_for_socket');\n+ }\n+ const { viewer } = this;\n+ invariant(viewer, \"should be set\");\n+ const responder = jsonEndpoints[message.payload.endpoint];\n+ const response = await responder(viewer, message.payload.input);\n+ return [{\n+ type: serverSocketMessageTypes.API_RESPONSE,\n+ responseTo: message.id,\n+ payload: response,\n+ }];\n+ }\n+\nonRedisMessage = async (message: RedisMessage) => {\ntry {\nawait this.processRedisMessage(message);\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/utils/validation-utils.js",
"new_path": "server/src/utils/validation-utils.js",
"diff": "@@ -51,7 +51,9 @@ const tPassword = t.refinement(t.String, (password: string) => password);\nconst tCookie = tRegex(/^(user|anonymous)=[0-9]+:[0-9a-f]+$/);\nasync function validateInput(viewer: Viewer, inputValidator: *, input: *) {\n+ if (!viewer.isSocket) {\nawait checkClientSupported(viewer, inputValidator, input);\n+ }\ncheckInputValidator(inputValidator, input);\n}\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | Server support for API requests via socket |
129,187 | 12.11.2018 11:27:10 | 18,000 | 6f0bdf5a79bd3943ee28a0b34686f239158b7221 | [lib] endpointIsSocketOnly | [
{
"change_type": "MODIFY",
"old_path": "lib/types/endpoints.js",
"new_path": "lib/types/endpoints.js",
"diff": "@@ -12,6 +12,7 @@ export type SocketAPIHandler = (request: APIRequest) => Promise<Object>;\n// since websockets aren't able to Set-Cookie.\nexport type Endpoint =\n| SessionChangingEndpoint\n+ | SocketOnlyEndpoint\n| SocketSafeEndpoint;\n// Note that technically any endpoint can cause a sessionChange, and in that\n@@ -26,8 +27,13 @@ export const sessionChangingEndpoints = Object.freeze({\n});\ntype SessionChangingEndpoint = $Values<typeof sessionChangingEndpoints>;\n-export const socketSafeEndpoints = Object.freeze({\n+export const socketOnlyEndpoints = Object.freeze({\nUPDATE_ACTIVITY: 'update_activity',\n+ UPDATE_CALENDAR_QUERY: 'update_calendar_query',\n+});\n+type SocketOnlyEndpoint = $Values<typeof socketOnlyEndpoints>;\n+\n+export const socketSafeEndpoints = Object.freeze({\nUPDATE_USER_SUBSCRIPTION: 'update_user_subscription',\nUPDATE_DEVICE_TOKEN: 'update_device_token',\nUPDATE_ACCOUNT: 'update_account',\n@@ -55,11 +61,18 @@ export const socketSafeEndpoints = Object.freeze({\nFETCH_ERROR_REPORT_INFOS: 'fetch_error_report_infos',\nREQUEST_ACCESS: 'request_access',\nCREATE_REPORT: 'create_report',\n- UPDATE_CALENDAR_QUERY: 'update_calendar_query',\n});\ntype SocketSafeEndpoint = $Values<typeof socketSafeEndpoints>;\n-const socketSafeEndpointSet = new Set(Object.values(socketSafeEndpoints));\n+const socketSafeEndpointSet = new Set([\n+ ...Object.values(socketSafeEndpoints),\n+ ...Object.values(socketOnlyEndpoints),\n+]);\nexport function endpointIsSocketSafe(endpoint: Endpoint): bool {\nreturn socketSafeEndpointSet.has(endpoint);\n}\n+\n+const socketOnlyEndpointSet = new Set(Object.values(socketOnlyEndpoints));\n+export function endpointIsSocketOnly(endpoint: Endpoint): bool {\n+ return socketOnlyEndpointSet.has(endpoint);\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/utils/action-utils.js",
"new_path": "lib/utils/action-utils.js",
"diff": "@@ -49,10 +49,10 @@ function wrapActionPromise<\n>(\nactionTypes: ActionTypes<AT, BT, CT>,\npromise: Promise<BP>,\n- loadingOptions?: ?LoadingOptions,\n- startingPayload?: ?AP,\n+ loadingOptions: ?LoadingOptions,\n+ startingPayload: ?AP,\n): PromisedAction {\n- const loadingInfo = {\n+ const loadingInfo: LoadingInfo = {\nfetchIndex: nextPromiseIndex++,\ntrackMultipleRequests:\n!!(loadingOptions && loadingOptions.trackMultipleRequests),\n@@ -64,12 +64,12 @@ function wrapActionPromise<\nconst startAction = startingPayload\n? {\ntype: (actionTypes.started: AT),\n- loadingInfo: (loadingInfo: LoadingInfo),\n+ loadingInfo,\npayload: (startingPayload: AP),\n}\n: {\ntype: (actionTypes.started: AT),\n- loadingInfo: (loadingInfo: LoadingInfo),\n+ loadingInfo,\n};\ndispatch(startAction);\ntry {\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/utils/fetch-json.js",
"new_path": "lib/utils/fetch-json.js",
"diff": "@@ -4,6 +4,7 @@ import {\ntype Endpoint,\ntype SocketAPIHandler,\nendpointIsSocketSafe,\n+ endpointIsSocketOnly,\n} from '../types/endpoints';\nimport type {\nServerSessionChange,\n@@ -76,16 +77,18 @@ async function fetchJSON(\ntry {\nreturn await socketAPIHandler({ endpoint, input });\n} catch (e) {\n- // In the case where a socket error occurred, we'll try to proceed via a\n- // HTTP request. If it was a ServerError or something client-local, we\n- // will rethrow the exception.\n- if (e instanceof SocketOffline) {\n+ if (endpointIsSocketOnly(endpoint)) {\n+ throw e;\n+ } else if (e instanceof SocketOffline) {\n} else if (e instanceof SocketTimeout) {\n} else {\nthrow e;\n}\n}\n}\n+ if (endpointIsSocketOnly(endpoint)) {\n+ throw new SocketOffline(\"socket_offline\");\n+ }\nconst mergedData: RequestData = { input };\nif (getConfig().setCookieOnRequest) {\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [lib] endpointIsSocketOnly |
129,187 | 12.11.2018 13:45:22 | 18,000 | e1cf531c371b0d40a455c39ad5005b5fe5a68b4c | [native] Move registerConfig to separate file
And avoid using it in defining default Redux state due to require cycle. | [
{
"change_type": "MODIFY",
"old_path": "native/app.react.js",
"new_path": "native/app.react.js",
"diff": "@@ -45,7 +45,6 @@ import InAppNotification from 'react-native-in-app-notification';\nimport FCM, { FCMEvent } from 'react-native-fcm';\nimport SplashScreen from 'react-native-splash-screen';\n-import { registerConfig } from 'lib/utils/config';\nimport { connect } from 'lib/utils/redux-utils';\nimport {\nsetDeviceTokenActionTypes,\n@@ -69,7 +68,6 @@ import {\nclearAndroidNotificationActionType,\n} from './navigation/action-types';\nimport { store, appBecameInactive } from './redux-setup';\n-import { resolveInvalidatedCookie } from './account/resolve-invalidated-cookie';\nimport ConnectedStatusBar from './connected-status-bar.react';\nimport {\nactiveThreadSelector,\n@@ -84,23 +82,10 @@ import {\n} from './push/android';\nimport NotificationBody from './push/notification-body.react';\nimport ErrorBoundary from './error-boundary.react';\n-import { persistConfig, codeVersion } from './persist';\nimport { AppRouteName } from './navigation/route-names';\nimport MessageStorePruner from './chat/message-store-pruner.react';\nimport Socket from './socket.react';\n-registerConfig({\n- resolveInvalidatedCookie,\n- setCookieOnRequest: true,\n- setSessionIDOnRequest: false,\n- calendarRangeInactivityLimit: 15 * 60 * 1000,\n- platformDetails: {\n- platform: Platform.OS,\n- codeVersion,\n- stateVersion: persistConfig.version,\n- },\n-});\n-\nconst msInDay = 24 * 60 * 60 * 1000;\nconst ReduxifiedRootNavigator = reduxifyNavigator(RootNavigator, \"root\");\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "native/config.js",
"diff": "+// @flow\n+\n+import { Platform } from 'react-native';\n+\n+import { registerConfig } from 'lib/utils/config';\n+\n+import { resolveInvalidatedCookie } from './account/resolve-invalidated-cookie';\n+import { persistConfig, codeVersion } from './persist';\n+\n+registerConfig({\n+ resolveInvalidatedCookie,\n+ setCookieOnRequest: true,\n+ setSessionIDOnRequest: false,\n+ calendarRangeInactivityLimit: 15 * 60 * 1000,\n+ platformDetails: {\n+ platform: Platform.OS,\n+ codeVersion,\n+ stateVersion: persistConfig.version,\n+ },\n+});\n"
},
{
"change_type": "MODIFY",
"old_path": "native/index.js",
"new_path": "native/index.js",
"diff": "// @flow\nimport './reactotron';\n+import './config';\nimport './app.react';\n"
},
{
"change_type": "MODIFY",
"old_path": "native/persist.js",
"new_path": "native/persist.js",
"diff": "@@ -7,10 +7,10 @@ import { defaultConnectionInfo } from 'lib/types/socket-types';\nimport storage from 'redux-persist/lib/storage';\nimport { createMigrate } from 'redux-persist';\nimport invariant from 'invariant';\n+import { Platform } from 'react-native';\nimport { nativeCalendarQuery } from './selectors/nav-selectors';\nimport version from 'lib/facts/version';\n-import { getConfig } from 'lib/utils/config';\nimport { defaultNotifPermissionAlertInfo } from './push/alerts';\n@@ -78,7 +78,7 @@ const migrations = {\n...state,\npingTimestamps: undefined,\nactiveServerRequests: undefined,\n- connection: defaultConnectionInfo(getConfig().platformDetails.platform),\n+ connection: defaultConnectionInfo(Platform.OS),\nwatchedThreadIDs: [],\nforeground: true,\nentryStore: {\n"
},
{
"change_type": "MODIFY",
"old_path": "native/redux-setup.js",
"new_path": "native/redux-setup.js",
"diff": "@@ -36,7 +36,7 @@ import { NavigationActions, StackActions } from 'react-navigation';\nimport {\ncreateReactNavigationReduxMiddleware,\n} from 'react-navigation-redux-helpers';\n-import { AppState as NativeAppState } from 'react-native';\n+import { AppState as NativeAppState, Platform } from 'react-native';\nimport baseReducer from 'lib/reducers/master-reducer';\nimport { notificationPressActionType } from 'lib/shared/notif-utils';\n@@ -141,7 +141,7 @@ const defaultState = ({\nthreadIDsToNotifIDs: {},\nnotifPermissionAlertInfo: defaultNotifPermissionAlertInfo,\nmessageSentFromRoute: [],\n- connection: defaultConnectionInfo(getConfig().platformDetails.platform),\n+ connection: defaultConnectionInfo(Platform.OS),\nwatchedThreadIDs: [],\nforeground: true,\n_persist: null,\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Move registerConfig to separate file
And avoid using it in defining default Redux state due to require cycle. |
129,187 | 12.11.2018 13:47:35 | 18,000 | 5999c064bf17fd252b875b1a98f54a4e6b0b73fc | [lib] Use DispatchActionPromise for activity updates | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "lib/actions/activity-actions.js",
"diff": "+// @flow\n+\n+import type { FetchJSON } from '../utils/fetch-json';\n+import type {\n+ ActivityUpdate,\n+ ActivityUpdateSuccessPayload,\n+} from '../types/activity-types';\n+\n+const updateActivityActionTypes = Object.freeze({\n+ started: \"UPDATE_ACTIVITY_STARTED\",\n+ success: \"UPDATE_ACTIVITY_SUCCESS\",\n+ failed: \"UPDATE_ACTIVITY_FAILED\",\n+});\n+async function updateActivity(\n+ fetchJSON: FetchJSON,\n+ activityUpdates: $ReadOnlyArray<ActivityUpdate>,\n+): Promise<ActivityUpdateSuccessPayload> {\n+ const response = await fetchJSON(\n+ 'update_activity',\n+ { updates: activityUpdates },\n+ );\n+ return {\n+ activityUpdates,\n+ result: {\n+ unfocusedToUnread: response.unfocusedToUnread,\n+ },\n+ };\n+}\n+\n+export {\n+ updateActivityActionTypes,\n+ updateActivity,\n+};\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/reducers/connection-reducer.js",
"new_path": "lib/reducers/connection-reducer.js",
"diff": "@@ -4,13 +4,11 @@ import type { BaseAction } from '../types/redux-types';\nimport {\ntype ConnectionInfo,\nupdateConnectionStatusActionType,\n- queueActivityUpdatesActionType,\n- activityUpdateSuccessActionType,\n- activityUpdateFailedActionType,\nfullStateSyncActionType,\nincrementalStateSyncActionType,\n} from '../types/socket-types';\nimport { defaultCalendarQuery } from '../types/entry-types';\n+import { queueActivityUpdatesActionType } from '../types/activity-types';\nimport { setNewSessionActionType } from '../utils/action-utils';\nimport {\n@@ -21,6 +19,7 @@ import {\nregisterActionTypes,\n} from '../actions/user-actions';\nimport { updateCalendarQueryActionTypes } from '../actions/entry-actions';\n+import { updateActivityActionTypes } from '../actions/activity-actions';\nimport { getConfig } from '../utils/config';\nexport default function reduceConnectionInfo(\n@@ -53,8 +52,8 @@ export default function reduceConnectionInfo(\n],\n};\n} else if (\n- action.type === activityUpdateSuccessActionType ||\n- action.type === activityUpdateFailedActionType\n+ action.type === updateActivityActionTypes.success ||\n+ action.type === updateActivityActionTypes.failed\n) {\nconst { payload } = action;\nreturn {\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/reducers/thread-reducer.js",
"new_path": "lib/reducers/thread-reducer.js",
"diff": "@@ -16,8 +16,8 @@ import {\nimport {\nfullStateSyncActionType,\nincrementalStateSyncActionType,\n- activityUpdateSuccessActionType,\n} from '../types/socket-types';\n+import { updateActivityActionTypes } from '../actions/activity-actions';\nimport invariant from 'invariant';\nimport _isEqual from 'lodash/fp/isEqual';\n@@ -324,7 +324,7 @@ export default function reduceThreadInfos(\n...newInconsistencies,\n],\n};\n- } else if (action.type === activityUpdateSuccessActionType) {\n+ } else if (action.type === updateActivityActionTypes.success) {\nconst newThreadInfos = { ...state.threadInfos };\nfor (let setToUnread of action.payload.result.unfocusedToUnread) {\nconst threadInfo = newThreadInfos[setToUnread];\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/socket/activity-handler.react.js",
"new_path": "lib/socket/activity-handler.react.js",
"diff": "// @flow\nimport {\n- type ActivityUpdateResponseServerSocketMessage,\n- clientSocketMessageTypes,\n- serverSocketMessageTypes,\n- queueActivityUpdatesActionType,\n- activityUpdateSuccessActionType,\n- activityUpdateFailedActionType,\n- type ClientSocketMessageWithoutID,\ntype ConnectionInfo,\nconnectionInfoPropType,\n} from '../types/socket-types';\n-import type { ActivityUpdate } from '../types/activity-types';\n-import type { DispatchActionPayload } from '../utils/action-utils';\n+import {\n+ type ActivityUpdate,\n+ type ActivityUpdateSuccessPayload,\n+ queueActivityUpdatesActionType,\n+} from '../types/activity-types';\n+import type {\n+ DispatchActionPayload,\n+ DispatchActionPromise,\n+} from '../utils/action-utils';\nimport type { BaseAppState } from '../types/redux-types';\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\n-import invariant from 'invariant';\nimport { connect } from '../utils/redux-utils';\n-import { InflightRequests, SocketTimeout } from './inflight-requests';\n-import { ServerError } from '../utils/errors';\n+import {\n+ updateActivityActionTypes,\n+ updateActivity,\n+} from '../actions/activity-actions';\ntype Props = {|\nactiveThread: ?string,\n- inflightRequests: ?InflightRequests,\n- sendMessage: (message: ClientSocketMessageWithoutID) => number,\n// Redux state\nconnection: ConnectionInfo,\nactiveThreadLatestMessage: ?string,\n// Redux dispatch functions\ndispatchActionPayload: DispatchActionPayload,\n+ dispatchActionPromise: DispatchActionPromise,\n+ // async functions that hit server APIs\n+ updateActivity: (\n+ activityUpdates: $ReadOnlyArray<ActivityUpdate>,\n+ ) => Promise<ActivityUpdateSuccessPayload>,\n|};\nclass ActivityHandler extends React.PureComponent<Props> {\nstatic propTypes = {\nactiveThread: PropTypes.string,\n- inflightRequests: PropTypes.object,\n- sendMessage: PropTypes.func.isRequired,\nconnection: connectionInfoPropType.isRequired,\nactiveThreadLatestMessage: PropTypes.string,\ndispatchActionPayload: PropTypes.func.isRequired,\n+ dispatchActionPromise: PropTypes.func.isRequired,\n};\ncomponentDidUpdate(prevProps: Props) {\n@@ -69,18 +72,17 @@ class ActivityHandler extends React.PureComponent<Props> {\n);\n}\n- const { inflightRequests, connection } = this.props;\n- if (!inflightRequests || connection.status !== \"connected\") {\n+ if (this.props.connection.status !== \"connected\") {\nreturn;\n}\nif (prevProps.connection.status !== \"connected\") {\nconst { queuedActivityUpdates } = this.props.connection;\n- this.sendAndHandleActivityUpdates(\n+ this.sendActivityUpdates(\n[ ...queuedActivityUpdates, ...activityUpdates ],\n);\n} else {\n- this.sendAndHandleActivityUpdates(activityUpdates);\n+ this.sendActivityUpdates(activityUpdates);\n}\n}\n@@ -88,75 +90,18 @@ class ActivityHandler extends React.PureComponent<Props> {\nreturn null;\n}\n- sendAndHandleActivityUpdates(\n+ sendActivityUpdates(\nactivityUpdates: $ReadOnlyArray<ActivityUpdate>,\n) {\nif (activityUpdates.length === 0) {\nreturn;\n}\n- const promise = this.sendActivityUpdates(activityUpdates);\n- this.handleActivityUpdates(promise, activityUpdates);\n- }\n-\n- sendActivityUpdates(\n- activityUpdates: $ReadOnlyArray<ActivityUpdate>\n- ): Promise<ActivityUpdateResponseServerSocketMessage> {\n- const { inflightRequests } = this.props;\n- invariant(\n- inflightRequests,\n- \"inflightRequests falsey inside sendActivityUpdates\",\n- );\n- const messageID = this.props.sendMessage({\n- type: clientSocketMessageTypes.ACTIVITY_UPDATES,\n- payload: { activityUpdates },\n- });\n- return inflightRequests.fetchResponse(\n- messageID,\n- serverSocketMessageTypes.ACTIVITY_UPDATE_RESPONSE,\n+ this.props.dispatchActionPromise(\n+ updateActivityActionTypes,\n+ this.props.updateActivity(activityUpdates),\n);\n}\n- async handleActivityUpdates(\n- promise: Promise<ActivityUpdateResponseServerSocketMessage>,\n- activityUpdates: $ReadOnlyArray<ActivityUpdate>,\n- retriesLeft: number = 1,\n- ): Promise<void> {\n- try {\n- const response = await promise;\n- this.props.dispatchActionPayload(\n- activityUpdateSuccessActionType,\n- { activityUpdates, result: response.payload },\n- );\n- } catch (e) {\n- console.log(e);\n- if (\n- e instanceof SocketTimeout ||\n- this.props.connection.status !== \"connected\" ||\n- !this.props.inflightRequests\n- ) {\n- // This indicates that the socket will be closed. Do nothing, since when\n- // it will reopen it will send all the queued activity updates again.\n- } else if (\n- retriesLeft === 0 ||\n- (e instanceof ServerError && e.message !== \"unknown_error\")\n- ) {\n- // We're giving up on these activity updates, as they seem to cause the\n- // server to error...\n- this.props.dispatchActionPayload(\n- activityUpdateFailedActionType,\n- { activityUpdates },\n- );\n- } else {\n- const newPromise = this.sendActivityUpdates(activityUpdates);\n- await this.handleActivityUpdates(\n- newPromise,\n- activityUpdates,\n- retriesLeft - 1,\n- );\n- }\n- }\n- }\n-\n}\nexport default connect(\n@@ -170,6 +115,5 @@ export default connect(\n: null,\n};\n},\n- null,\n- true,\n+ { updateActivity },\n)(ActivityHandler);\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/socket/socket.react.js",
"new_path": "lib/socket/socket.react.js",
"diff": "@@ -23,7 +23,6 @@ import {\nupdateConnectionStatusActionType,\nconnectionInfoPropType,\ntype ConnectionInfo,\n- activityUpdateSuccessActionType,\ntype InitialClientSocketMessage,\ntype ResponsesClientSocketMessage,\ntype ActivityUpdatesClientSocketMessage,\n@@ -63,6 +62,7 @@ import UpdateHandler from './update-handler.react';\nimport MessageHandler from './message-handler.react';\nimport CalendarQueryHandler from './calendar-query-handler.react';\nimport { logOutActionTypes } from '../actions/user-actions';\n+import { updateActivityActionTypes } from '../actions/activity-actions';\ntype Props = {|\n// Redux state\n@@ -268,11 +268,7 @@ class Socket extends React.PureComponent<Props, State> {\nrender() {\nreturn (\n<React.Fragment>\n- <ActivityHandler\n- activeThread={this.props.activeThread}\n- inflightRequests={this.state.inflightRequests}\n- sendMessage={this.sendMessageWithoutID}\n- />\n+ <ActivityHandler activeThread={this.props.activeThread} />\n<RequestResponseHandler\ninflightRequests={this.state.inflightRequests}\nsendMessage={this.sendMessageWithoutID}\n@@ -517,7 +513,7 @@ class Socket extends React.PureComponent<Props, State> {\n}\nif (activityUpdateMessage) {\nthis.props.dispatchActionPayload(\n- activityUpdateSuccessActionType,\n+ updateActivityActionTypes.success,\n{\nactivityUpdates: queuedActivityUpdates,\nresult: activityUpdateMessage.payload,\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/types/activity-types.js",
"new_path": "lib/types/activity-types.js",
"diff": "@@ -25,3 +25,16 @@ export type UpdateActivityRequest = {|\nexport type UpdateActivityResult = {|\nunfocusedToUnread: string[],\n|};\n+\n+export type ActivityUpdateSuccessPayload = {|\n+ activityUpdates: $ReadOnlyArray<ActivityUpdate>,\n+ result: UpdateActivityResult,\n+|};\n+export type ActivityUpdateErrorExtras = {\n+ activityUpdates: $ReadOnlyArray<ActivityUpdate>,\n+};\n+\n+export const queueActivityUpdatesActionType = \"QUEUE_ACTIVITY_UPDATES\";\n+export type QueueActivityUpdatesPayload = {|\n+ activityUpdates: $ReadOnlyArray<ActivityUpdate>,\n+|};\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/types/redux-types.js",
"new_path": "lib/types/redux-types.js",
"diff": "@@ -60,11 +60,13 @@ import type {\nStateSyncFullActionPayload,\nStateSyncIncrementalActionPayload,\nUpdateConnectionStatusPayload,\n- QueueActivityUpdatesPayload,\n- ActivityUpdateSuccessPayload,\n- ActivityUpdateFailedPayload,\n} from '../types/socket-types';\nimport type { UpdatesResultWithUserInfos } from '../types/update-types';\n+import type {\n+ ActivityUpdateSuccessPayload,\n+ ActivityUpdateErrorExtras,\n+ QueueActivityUpdatesPayload,\n+} from '../types/activity-types';\nexport type BaseAppState<NavInfo: BaseNavInfo> = {\nnavInfo: NavInfo,\n@@ -469,6 +471,19 @@ export type BaseAction =\nkey: string,\ndraft: string,\n},\n+ |} | {|\n+ type: \"UPDATE_ACTIVITY_STARTED\",\n+ payload?: void,\n+ loadingInfo: LoadingInfo,\n+ |} | {|\n+ type: \"UPDATE_ACTIVITY_FAILED\",\n+ error: true,\n+ payload: Error & ActivityUpdateErrorExtras,\n+ loadingInfo: LoadingInfo,\n+ |} | {|\n+ type: \"UPDATE_ACTIVITY_SUCCESS\",\n+ payload: ActivityUpdateSuccessPayload,\n+ loadingInfo: LoadingInfo,\n|} | {|\ntype: \"SET_DEVICE_TOKEN_STARTED\",\npayload: string,\n@@ -567,12 +582,6 @@ export type BaseAction =\n|} | {|\ntype: \"QUEUE_ACTIVITY_UPDATES\",\npayload: QueueActivityUpdatesPayload,\n- |} | {|\n- type: \"ACTIVITY_UPDATE_SUCCESS\",\n- payload: ActivityUpdateSuccessPayload,\n- |} | {|\n- type: \"ACTIVITY_UPDATE_FAILED\",\n- payload: ActivityUpdateFailedPayload,\n|} | {|\ntype: \"FOREGROUND\",\npayload?: void,\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/types/socket-types.js",
"new_path": "lib/types/socket-types.js",
"diff": "@@ -275,16 +275,3 @@ export const updateConnectionStatusActionType = \"UPDATE_CONNECTION_STATUS\";\nexport type UpdateConnectionStatusPayload = {|\nstatus: ConnectionStatus,\n|};\n-export const queueActivityUpdatesActionType = \"QUEUE_ACTIVITY_UPDATES\";\n-export type QueueActivityUpdatesPayload = {|\n- activityUpdates: $ReadOnlyArray<ActivityUpdate>,\n-|};\n-export const activityUpdateSuccessActionType = \"ACTIVITY_UPDATE_SUCCESS\";\n-export type ActivityUpdateSuccessPayload = {|\n- activityUpdates: $ReadOnlyArray<ActivityUpdate>,\n- result: UpdateActivityResult,\n-|};\n-export const activityUpdateFailedActionType = \"ACTIVITY_UPDATE_FAILED\";\n-export type ActivityUpdateFailedPayload = {|\n- activityUpdates: $ReadOnlyArray<ActivityUpdate>,\n-|};\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [lib] Use DispatchActionPromise for activity updates |
129,187 | 12.11.2018 14:20:28 | 18,000 | 4d4cef3d919f7a1764303cc8279b54ec682fe3ae | [lib] Don't rehydrate connection status from redux-persist | [
{
"change_type": "MODIFY",
"old_path": "lib/reducers/connection-reducer.js",
"new_path": "lib/reducers/connection-reducer.js",
"diff": "// @flow\n-import type { BaseAction } from '../types/redux-types';\n+import {\n+ type BaseAction,\n+ rehydrateActionType,\n+} from '../types/redux-types';\nimport {\ntype ConnectionInfo,\nupdateConnectionStatusActionType,\n@@ -93,6 +96,14 @@ export default function reduceConnectionInfo(\n...state,\nactualizedCalendarQuery: action.payload.calendarQuery,\n};\n+ } else if (action.type === rehydrateActionType) {\n+ if (!action.payload || !action.payload.connection) {\n+ return state;\n+ }\n+ return {\n+ ...action.payload.connection,\n+ status: \"connecting\",\n+ };\n}\nreturn state;\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/types/redux-types.js",
"new_path": "lib/types/redux-types.js",
"diff": "@@ -614,4 +614,7 @@ export type Dispatch =\n((thunkedAction: ThunkedAction) => void) &\n((action: SuperAction) => bool);\n+// This is lifted from redux-persist/lib/constants.js\n+// I don't want to add redux-persist to the web/server bundles...\n+// import { REHYDRATE } from 'redux-persist';\nexport const rehydrateActionType = \"persist/REHYDRATE\";\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/utils/redux-logger.js",
"new_path": "lib/utils/redux-logger.js",
"diff": "// @flow\n-import type { AppState, BaseAction } from '../types/redux-types';\n+import {\n+ type AppState,\n+ type BaseAction,\n+ rehydrateActionType,\n+} from '../types/redux-types';\nimport { saveDraftActionType } from '../reducers/draft-reducer';\n-// This is lifted from redux-persist/lib/constants.js\n-// I don't want to add redux-persist to the web/server bundles...\n-// import { REHYDRATE } from 'redux-persist';\n-const REHYDRATE = 'persist/REHYDRATE';\nconst uninterestingActionTypes = new Set([ saveDraftActionType ]);\nclass ReduxLogger {\n@@ -33,7 +33,8 @@ class ReduxLogger {\naddAction(action: BaseAction, state: AppState) {\nif (\nthis.lastNActions.length > 0 &&\n- this.lastNActions[this.lastNActions.length - 1].type === REHYDRATE\n+ this.lastNActions[this.lastNActions.length - 1].type\n+ === rehydrateActionType\n) {\n// redux-persist can't handle replaying REHYDRATE\n// https://github.com/rt2zz/redux-persist/issues/743\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [lib] Don't rehydrate connection status from redux-persist |
129,187 | 12.11.2018 14:20:50 | 18,000 | cf8dd8b2f3913844872c6cd85921ad713417b16b | [server] Don't double-save serverRequestTypes.INITIAL_ACTIVITY_UPDATES | [
{
"change_type": "MODIFY",
"old_path": "server/src/responders/ping-responders.js",
"new_path": "server/src/responders/ping-responders.js",
"diff": "@@ -457,13 +457,6 @@ async function processClientResponses(\n}\n}\n- if (activityUpdates.length > 0) {\n- promises.push(activityUpdater(\n- viewer,\n- { updates: activityUpdates },\n- ));\n- }\n-\nlet activityUpdateResult;\nif (activityUpdates.length > 0 || promises.length > 0) {\n[ activityUpdateResult ] = await Promise.all([\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [server] Don't double-save serverRequestTypes.INITIAL_ACTIVITY_UPDATES |
129,187 | 12.11.2018 14:22:11 | 18,000 | a4efa630ab664ce9631ad4da8963ae7d1f4472b1 | [lib] Actually instantiate APIRequestHandler in Socket component | [
{
"change_type": "MODIFY",
"old_path": "lib/socket/socket.react.js",
"new_path": "lib/socket/socket.react.js",
"diff": "@@ -56,6 +56,7 @@ import { ServerError } from '../utils/errors';\nimport { pingFrequency } from '../shared/timeouts';\nimport { promiseAll } from '../utils/promises';\nimport { InflightRequests, SocketTimeout } from './inflight-requests';\n+import APIRequestHandler from './api-request-handler.react';\nimport ActivityHandler from './activity-handler.react';\nimport RequestResponseHandler from './request-response-handler.react';\nimport UpdateHandler from './update-handler.react';\n@@ -268,6 +269,10 @@ class Socket extends React.PureComponent<Props, State> {\nrender() {\nreturn (\n<React.Fragment>\n+ <APIRequestHandler\n+ inflightRequests={this.state.inflightRequests}\n+ sendMessage={this.sendMessageWithoutID}\n+ />\n<ActivityHandler activeThread={this.props.activeThread} />\n<RequestResponseHandler\ninflightRequests={this.state.inflightRequests}\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [lib] Actually instantiate APIRequestHandler in Socket component |
129,187 | 13.11.2018 11:03:40 | 18,000 | 296d7645a5186bfd551d93d9d8a9368c8b3479c4 | Make createUpdates have an explicit updatesForCurrentSession input
This allow us to prevent activity updates from triggering Redis messages that trigger server socket messages about the activity update that get sent to the client. | [
{
"change_type": "MODIFY",
"old_path": "lib/types/redis-types.js",
"new_path": "lib/types/redis-types.js",
"diff": "@@ -19,9 +19,10 @@ type StartSubscriptionRedisMessage = {|\ntype: 0,\ninstanceID: string,\n|};\n-type NewUpdatesRedisMessage = {|\n+export type NewUpdatesRedisMessage = {|\ntype: 1,\nupdates: $ReadOnlyArray<RawUpdateInfo>,\n+ ignoreSession?: string,\n|};\ntype NewMessagesRedisMessage = {|\ntype: 2,\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/creators/update-creator.js",
"new_path": "server/src/creators/update-creator.js",
"diff": "@@ -20,7 +20,11 @@ import {\ntype CalendarQuery,\ndefaultCalendarQuery,\n} from 'lib/types/entry-types';\n-import { type UpdateTarget, redisMessageTypes } from 'lib/types/redis-types';\n+import {\n+ type UpdateTarget,\n+ redisMessageTypes,\n+ type NewUpdatesRedisMessage,\n+} from 'lib/types/redis-types';\nimport invariant from 'invariant';\nimport _uniq from 'lodash/fp/uniq';\n@@ -61,15 +65,31 @@ import {\nimport { channelNameForUpdateTarget, publisher } from '../socket/redis';\nimport { handleAsyncPromise } from '../responders/handlers';\n-export type ViewerInfo =\n- | {| viewer: Viewer |}\n+type UpdatesForCurrentSession =\n+ // This is the default if no Viewer is passed, or if an isSocket Viewer is\n+ // passed in. We will broadcast to all valid sessions via Redis and return\n+ // nothing to the caller, relying on the current session's Redis listener to\n+ // pick up the updates and deliver them asynchronously.\n+ | \"broadcast\"\n+ // This is the default if a non-isSocket Viewer is passed in. We avoid\n+ // broadcasting the update to the current session, and instead return the\n+ // update to the caller, who will handle delivering it to the client.\n+ | \"return\"\n+ // This means we ignore any updates destined for the current session.\n+ // Presumably the caller knows what they are doing and has a different way of\n+ // communicating the relevant information to the client.\n+ | \"ignore\";\n+\n+type ViewerInfo =\n| {|\nviewer: Viewer,\n- calendarQuery: ?CalendarQuery,\n+ calendarQuery?: ?CalendarQuery,\n+ updatesForCurrentSession?: UpdatesForCurrentSession,\n|}\n| {|\nviewer: Viewer,\ncalendarQuery: ?CalendarQuery,\n+ updatesForCurrentSession?: UpdatesForCurrentSession,\nthreadInfos: {[id: string]: RawThreadInfo},\nuserInfos: {[id: string]: AccountUserInfo},\n|};\n@@ -197,6 +217,20 @@ async function createUpdates(\n}\nconst ids = await createIDs(\"updates\", filteredUpdateDatas.length);\n+ let updatesForCurrentSession =\n+ viewerInfo && viewerInfo.updatesForCurrentSession;\n+ if (!updatesForCurrentSession && viewerInfo) {\n+ updatesForCurrentSession = viewerInfo.viewer.isSocket\n+ ? \"broadcast\"\n+ : \"return\";\n+ } else if (!updatesForCurrentSession) {\n+ updatesForCurrentSession = \"broadcast\";\n+ }\n+ const dontBroadcastSession =\n+ updatesForCurrentSession !== \"broadcast\" && viewerInfo\n+ ? viewerInfo.viewer.session\n+ : null;\n+\nconst publishInfos: Map<string, PublishInfo> = new Map();\nconst viewerRawUpdateInfos: RawUpdateInfo[] = [];\nconst insertRows: (?(number | string))[][] = [];\n@@ -233,6 +267,8 @@ async function createUpdates(\n}\nconst rawUpdateInfo = rawUpdateInfoFromUpdateData(updateData, ids[i]);\n+\n+ if (!target || !dontBroadcastSession || target !== dontBroadcastSession) {\nconst updateTarget = target\n? { userID: updateData.userID, sessionID: target }\n: { userID: updateData.userID };\n@@ -243,12 +279,13 @@ async function createUpdates(\npublishInfos.set(channelName, publishInfo);\n}\npublishInfo.rawUpdateInfos.push(rawUpdateInfo);\n+ }\nif (\n+ updatesForCurrentSession === \"return\" &&\nviewerInfo &&\nupdateData.userID === viewerInfo.viewer.id &&\n- (!target || target === viewerInfo.viewer.session) &&\n- !viewerInfo.viewer.isSocket\n+ (!target || target === viewerInfo.viewer.session)\n) {\nviewerRawUpdateInfos.push(rawUpdateInfo);\n}\n@@ -275,7 +312,7 @@ async function createUpdates(\nkey,\ncontent,\nupdateData.time,\n- viewerInfo ? viewerInfo.viewer.session : null,\n+ dontBroadcastSession,\ntarget,\n];\ninsertRows.push(insertRow);\n@@ -311,7 +348,10 @@ async function createUpdates(\n}\nif (publishInfos.size > 0) {\n- handleAsyncPromise(redisPublish(publishInfos.values()));\n+ handleAsyncPromise(redisPublish(\n+ publishInfos.values(),\n+ dontBroadcastSession,\n+ ));\n}\nif (deleteSQLConditions.length > 0) {\n@@ -652,16 +692,20 @@ type PublishInfo = {|\nupdateTarget: UpdateTarget,\nrawUpdateInfos: RawUpdateInfo[],\n|};\n-async function redisPublish(publishInfos: Iterator<PublishInfo>) {\n+async function redisPublish(\n+ publishInfos: Iterator<PublishInfo>,\n+ dontBroadcastSession: ?string,\n+): Promise<void> {\nfor (let publishInfo of publishInfos) {\nconst { updateTarget, rawUpdateInfos } = publishInfo;\n- publisher.sendMessage(\n- updateTarget,\n- {\n+ const redisMessage: NewUpdatesRedisMessage = {\ntype: redisMessageTypes.NEW_UPDATES,\nupdates: rawUpdateInfos,\n- },\n- );\n+ };\n+ if (!updateTarget.sessionID && dontBroadcastSession) {\n+ redisMessage.ignoreSession = dontBroadcastSession;\n+ }\n+ publisher.sendMessage(updateTarget, redisMessage);\n}\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/socket/socket.js",
"new_path": "server/src/socket/socket.js",
"diff": "@@ -663,6 +663,9 @@ class Socket {\n} else if (message.type === redisMessageTypes.NEW_UPDATES) {\nconst { viewer } = this;\ninvariant(viewer, \"should be set\");\n+ if (message.ignoreSession && message.ignoreSession === viewer.session) {\n+ return;\n+ }\nconst rawUpdateInfos = message.updates;\nconst {\nupdateInfos,\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/updaters/activity-updaters.js",
"new_path": "server/src/updaters/activity-updaters.js",
"diff": "@@ -107,7 +107,7 @@ async function activityUpdater(\nthreadID,\nunread: false,\n})),\n- { viewer },\n+ { viewer, updatesForCurrentSession: \"ignore\" },\n));\nconst rescindCondition = SQL`\nn.user = ${viewer.userID} AND n.thread IN (${memberFocusedThreadIDs})\n@@ -237,7 +237,7 @@ async function possiblyResetThreadsToUnread(\nthreadID,\nunread: true,\n})),\n- { viewer },\n+ { viewer, updatesForCurrentSession: \"ignore\" },\n));\nawait Promise.all(promises);\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | Make createUpdates have an explicit updatesForCurrentSession input
This allow us to prevent activity updates from triggering Redis messages that trigger server socket messages about the activity update that get sent to the client. |
129,187 | 13.11.2018 15:12:39 | 18,000 | 2ed31450d3b0554d0163c6f094c3dea2cebdd294 | Get rid of clientSocketMessageTypes.ACTIVITY_UPDATES
Note: this breaks client codeVersion v23, but I only ever deployed that version to my phone. | [
{
"change_type": "MODIFY",
"old_path": "lib/socket/socket.react.js",
"new_path": "lib/socket/socket.react.js",
"diff": "@@ -25,7 +25,6 @@ import {\ntype ConnectionInfo,\ntype InitialClientSocketMessage,\ntype ResponsesClientSocketMessage,\n- type ActivityUpdatesClientSocketMessage,\ntype PingClientSocketMessage,\ntype AckUpdatesClientSocketMessage,\ntype APIRequestClientSocketMessage,\n@@ -267,6 +266,12 @@ class Socket extends React.PureComponent<Props, State> {\n}\nrender() {\n+ // It's important that APIRequestHandler get rendered first here. This is so\n+ // that it is registered with Redux first, so that its componentDidUpdate\n+ // processes before the other Handlers. This allows APIRequestHandler to\n+ // register itself with action-utils before other Handlers call\n+ // dispatchActionPromise in response to the componentDidUpdate triggered by\n+ // the same Redux change (state.connection.status).\nreturn (\n<React.Fragment>\n<APIRequestHandler\n@@ -306,11 +311,6 @@ class Socket extends React.PureComponent<Props, State> {\nthis.sendMessage(({ ...message, id }: InitialClientSocketMessage));\n} else if (message.type === clientSocketMessageTypes.RESPONSES) {\nthis.sendMessage(({ ...message, id }: ResponsesClientSocketMessage));\n- } else if (message.type === clientSocketMessageTypes.ACTIVITY_UPDATES) {\n- this.sendMessage(({\n- ...message,\n- id,\n- }: ActivityUpdatesClientSocketMessage));\n} else if (message.type === clientSocketMessageTypes.PING) {\nthis.sendMessage(({ ...message, id }: PingClientSocketMessage));\n} else if (message.type === clientSocketMessageTypes.ACK_UPDATES) {\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/types/socket-types.js",
"new_path": "lib/types/socket-types.js",
"diff": "@@ -33,7 +33,7 @@ import PropTypes from 'prop-types';\nexport const clientSocketMessageTypes = Object.freeze({\nINITIAL: 0,\nRESPONSES: 1,\n- ACTIVITY_UPDATES: 2,\n+ //ACTIVITY_UPDATES: 2,\nPING: 3,\nACK_UPDATES: 4,\nAPI_REQUEST: 5,\n@@ -45,7 +45,6 @@ export function assertClientSocketMessageType(\ninvariant(\nourClientSocketMessageType === 0 ||\nourClientSocketMessageType === 1 ||\n- ourClientSocketMessageType === 2 ||\nourClientSocketMessageType === 3 ||\nourClientSocketMessageType === 4 ||\nourClientSocketMessageType === 5,\n@@ -70,13 +69,6 @@ export type ResponsesClientSocketMessage = {|\nclientResponses: $ReadOnlyArray<ClientResponse>,\n|},\n|};\n-export type ActivityUpdatesClientSocketMessage = {|\n- type: 2,\n- id: number,\n- payload: {|\n- activityUpdates: $ReadOnlyArray<ActivityUpdate>,\n- |},\n-|};\nexport type PingClientSocketMessage = {|\ntype: 3,\nid: number,\n@@ -96,7 +88,6 @@ export type APIRequestClientSocketMessage = {|\nexport type ClientSocketMessage =\n| InitialClientSocketMessage\n| ResponsesClientSocketMessage\n- | ActivityUpdatesClientSocketMessage\n| PingClientSocketMessage\n| AckUpdatesClientSocketMessage\n| APIRequestClientSocketMessage;\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/socket/socket.js",
"new_path": "server/src/socket/socket.js",
"diff": "@@ -6,7 +6,6 @@ import {\ntype ClientSocketMessage,\ntype InitialClientSocketMessage,\ntype ResponsesClientSocketMessage,\n- type ActivityUpdatesClientSocketMessage,\ntype StateSyncFullSocketPayload,\ntype ServerSocketMessage,\ntype ErrorServerSocketMessage,\n@@ -65,10 +64,7 @@ import {\nimport { fetchThreadInfos } from '../fetchers/thread-fetchers';\nimport { fetchEntryInfos } from '../fetchers/entry-fetchers';\nimport { fetchCurrentUserInfo } from '../fetchers/user-fetchers';\n-import {\n- updateActivityTime,\n- activityUpdater,\n-} from '../updaters/activity-updaters';\n+import { updateActivityTime } from '../updaters/activity-updaters';\nimport {\ndeleteUpdatesBeforeTimeTargettingSession,\n} from '../deleters/update-deleters';\n@@ -117,16 +113,6 @@ const clientSocketMessageInputValidator = t.union([\nclientResponses: t.list(clientResponseInputValidator),\n}),\n}),\n- tShape({\n- type: t.irreducible(\n- 'clientSocketMessageTypes.ACTIVITY_UPDATES',\n- x => x === clientSocketMessageTypes.ACTIVITY_UPDATES,\n- ),\n- id: t.Number,\n- payload: tShape({\n- activityUpdates: activityUpdatesInputValidator,\n- }),\n- }),\ntShape({\ntype: t.irreducible(\n'clientSocketMessageTypes.PING',\n@@ -376,9 +362,6 @@ class Socket {\n} else if (message.type === clientSocketMessageTypes.RESPONSES) {\nthis.markActivityOccurred();\nreturn await this.handleResponsesClientSocketMessage(message);\n- } else if (message.type === clientSocketMessageTypes.ACTIVITY_UPDATES) {\n- this.markActivityOccurred();\n- return await this.handleActivityUpdatesClientSocketMessage(message);\n} else if (message.type === clientSocketMessageTypes.PING) {\nreturn await this.handlePingClientSocketMessage(message);\n} else if (message.type === clientSocketMessageTypes.ACK_UPDATES) {\n@@ -594,22 +577,6 @@ class Socket {\n}];\n}\n- async handleActivityUpdatesClientSocketMessage(\n- message: ActivityUpdatesClientSocketMessage,\n- ): Promise<ServerSocketMessage[]> {\n- const { viewer } = this;\n- invariant(viewer, \"should be set\");\n- const result = await activityUpdater(\n- viewer,\n- { updates: message.payload.activityUpdates },\n- );\n- return [{\n- type: serverSocketMessageTypes.ACTIVITY_UPDATE_RESPONSE,\n- responseTo: message.id,\n- payload: result,\n- }];\n- }\n-\nasync handlePingClientSocketMessage(\nmessage: PingClientSocketMessage,\n): Promise<ServerSocketMessage[]> {\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | Get rid of clientSocketMessageTypes.ACTIVITY_UPDATES
Note: this breaks client codeVersion v23, but I only ever deployed that version to my phone. |
129,187 | 14.11.2018 14:47:09 | 18,000 | f91fd3cbf39e54eb1a9a8980104cff0b4ad35f2a | [lib] Increment currentAsOf timestamps while connected
Always increment these when getting a new update or message, except while disconnected. | [
{
"change_type": "MODIFY",
"old_path": "lib/reducers/master-reducer.js",
"new_path": "lib/reducers/master-reducer.js",
"diff": "import type { BaseAppState, BaseAction } from '../types/redux-types';\nimport type { BaseNavInfo } from '../types/nav-types';\n+import {\n+ fullStateSyncActionType,\n+ incrementalStateSyncActionType,\n+} from '../types/socket-types';\nimport invariant from 'invariant';\n@@ -32,6 +36,34 @@ export default function baseReducer<N: BaseNavInfo, T: BaseAppState<N>>(\n? state.navInfo\n: { ...state.navInfo, ...baseNavInfo };\n+ // Only allow checkpoints to increase if we are connected\n+ // or if the action is a STATE_SYNC\n+ let messageStore = reduceMessageStore(\n+ state.messageStore,\n+ action,\n+ threadInfos,\n+ );\n+ let updatesCurrentAsOf = reduceUpdatesCurrentAsOf(\n+ state.updatesCurrentAsOf,\n+ action,\n+ );\n+ const connection = reduceConnectionInfo(state.connection, action);\n+ if (\n+ connection.status !== \"connected\" &&\n+ action.type !== incrementalStateSyncActionType &&\n+ action.type !== fullStateSyncActionType\n+ ) {\n+ if (messageStore.currentAsOf !== state.messageStore.currentAsOf) {\n+ messageStore = {\n+ ...messageStore,\n+ currentAsOf: state.messageStore.currentAsOf,\n+ };\n+ }\n+ if (updatesCurrentAsOf !== state.updatesCurrentAsOf) {\n+ updatesCurrentAsOf = state.updatesCurrentAsOf;\n+ }\n+ }\n+\nreturn {\n...state,\nnavInfo,\n@@ -46,16 +78,13 @@ export default function baseReducer<N: BaseNavInfo, T: BaseAppState<N>>(\nuserInfos: reduceUserInfos(state.userInfos, action),\nmessageStore: reduceMessageStore(state.messageStore, action, threadInfos),\ndrafts: reduceDrafts(state.drafts, action),\n- updatesCurrentAsOf: reduceUpdatesCurrentAsOf(\n- state.updatesCurrentAsOf,\n- action,\n- ),\n+ updatesCurrentAsOf,\nurlPrefix: reduceURLPrefix(state.urlPrefix, action),\ncalendarFilters: reduceCalendarFilters(\nstate.calendarFilters,\naction,\n),\n- connection: reduceConnectionInfo(state.connection, action),\n+ connection,\nforeground: reduceForeground(state.foreground, action),\n};\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/reducers/message-reducer.js",
"new_path": "lib/reducers/message-reducer.js",
"diff": "@@ -305,7 +305,12 @@ function mergeNewMessages(\n])('desc')(threads[threadID].messageIDs);\n}\n- return { messages, threads, currentAsOf: oldMessageStore.currentAsOf };\n+ const currentAsOf = Math.max(\n+ orderedNewMessageInfos.length > 0 ? orderedNewMessageInfos[0].time : 0,\n+ oldMessageStore.currentAsOf,\n+ );\n+\n+ return { messages, threads, currentAsOf };\n}\nfunction isContiguous(\n@@ -610,6 +615,7 @@ function reduceMessageStore(\nconst newMessageIDs = _uniq(\nmessageStore.threads[threadID].messageIDs.map(replaceMessageKey),\n);\n+ const currentAsOf = Math.max(payload.time, messageStore.currentAsOf);\nreturn {\nmessages: newMessages,\nthreads: {\n@@ -619,7 +625,7 @@ function reduceMessageStore(\nmessageIDs: newMessageIDs,\n},\n},\n- currentAsOf: messageStore.currentAsOf,\n+ currentAsOf,\n};\n} else if (action.type === rehydrateActionType) {\nif (!action.payload || !action.payload.messageStore) {\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [lib] Increment currentAsOf timestamps while connected
Always increment these when getting a new update or message, except while disconnected. |
129,187 | 14.11.2018 17:26:59 | 18,000 | f1d442262309ebe21ec83d1149e4ca7ccf786b2a | [lib] Include activityUpdates in UPDATE_ACTIVITY_FAILED
Forgot to include this... | [
{
"change_type": "MODIFY",
"old_path": "lib/socket/activity-handler.react.js",
"new_path": "lib/socket/activity-handler.react.js",
"diff": "@@ -90,18 +90,25 @@ class ActivityHandler extends React.PureComponent<Props> {\nreturn null;\n}\n- sendActivityUpdates(\n- activityUpdates: $ReadOnlyArray<ActivityUpdate>,\n- ) {\n+ sendActivityUpdates(activityUpdates: $ReadOnlyArray<ActivityUpdate>) {\nif (activityUpdates.length === 0) {\nreturn;\n}\nthis.props.dispatchActionPromise(\nupdateActivityActionTypes,\n- this.props.updateActivity(activityUpdates),\n+ this.updateActivity(activityUpdates),\n);\n}\n+ async updateActivity(activityUpdates: $ReadOnlyArray<ActivityUpdate>) {\n+ try {\n+ return await this.props.updateActivity(activityUpdates);\n+ } catch (e) {\n+ e.activityUpdates = activityUpdates;\n+ throw e;\n+ }\n+ }\n+\n}\nexport default connect(\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [lib] Include activityUpdates in UPDATE_ACTIVITY_FAILED
Forgot to include this... |
129,187 | 14.11.2018 17:35:45 | 18,000 | 5f04a3914a63516f2e97b288a42bd4797468aa1a | Pop down a bar when native is disconnected | [
{
"change_type": "MODIFY",
"old_path": "lib/types/socket-types.js",
"new_path": "lib/types/socket-types.js",
"diff": "@@ -246,15 +246,16 @@ export type ConnectionInfo = {|\nqueuedActivityUpdates: $ReadOnlyArray<ActivityUpdate>,\nactualizedCalendarQuery: CalendarQuery,\n|};\n-export const connectionInfoPropType = PropTypes.shape({\n- status: PropTypes.oneOf([\n+export const connectionStatusPropType = PropTypes.oneOf([\n\"connecting\",\n\"connected\",\n\"reconnecting\",\n\"disconnecting\",\n\"forcedDisconnecting\",\n\"disconnected\",\n- ]).isRequired,\n+]);\n+export const connectionInfoPropType = PropTypes.shape({\n+ status: connectionStatusPropType.isRequired,\nqueuedActivityUpdates: PropTypes.arrayOf(activityUpdatePropType).isRequired,\n});\nexport const defaultConnectionInfo = (platform: Platform) => ({\n"
},
{
"change_type": "MODIFY",
"old_path": "native/calendar/calendar.react.js",
"new_path": "native/calendar/calendar.react.js",
"diff": "@@ -81,6 +81,7 @@ import {\nCalendarRouteName,\nThreadPickerModalRouteName,\n} from '../navigation/route-names';\n+import DisconnectedBar from '../navigation/disconnected-bar.react';\nexport type EntryInfoWithHeight = {|\n...EntryInfo,\n@@ -750,6 +751,7 @@ class InnerCalendar extends React.PureComponent<Props, State> {\n}\nreturn (\n<SafeAreaView forceInset={forceInset} style={styles.container}>\n+ <DisconnectedBar />\n<TextHeightMeasurer\ntextToMeasure={this.state.textToMeasure}\nallHeightsMeasuredCallback={this.allHeightsMeasured}\n"
},
{
"change_type": "MODIFY",
"old_path": "native/chat/chat.react.js",
"new_path": "native/chat/chat.react.js",
"diff": "@@ -24,14 +24,22 @@ import {\nMessageListRouteName,\nChatThreadListRouteName,\n} from '../navigation/route-names';\n+import Header from '../navigation/header.react';\n-const Chat = createStackNavigator({\n- [ChatThreadListRouteName]: { screen: ChatThreadList },\n- [MessageListRouteName]: { screen: MessageList },\n- [ComposeThreadRouteName]: { screen: ComposeThread },\n- [ThreadSettingsRouteName]: { screen: ThreadSettings },\n- [DeleteThreadRouteName]: { screen: DeleteThread },\n-});\n+const Chat = createStackNavigator(\n+ {\n+ [ChatThreadListRouteName]: ChatThreadList,\n+ [MessageListRouteName]: MessageList,\n+ [ComposeThreadRouteName]: ComposeThread,\n+ [ThreadSettingsRouteName]: ThreadSettings,\n+ [DeleteThreadRouteName]: DeleteThread,\n+ },\n+ {\n+ defaultNavigationOptions: {\n+ header: Header,\n+ },\n+ },\n+);\nChat.navigationOptions = ({ navigation }) => ({\ntabBarLabel: Platform.OS === \"android\"\n? ({ tintColor }) => <ChatLabel color={tintColor} />\n"
},
{
"change_type": "MODIFY",
"old_path": "native/more/more.react.js",
"new_path": "native/more/more.react.js",
"diff": "@@ -19,15 +19,23 @@ import {\nBuildInfoRouteName,\nDevToolsRouteName,\n} from '../navigation/route-names';\n+import Header from '../navigation/header.react';\n-const More = createStackNavigator({\n- [MoreScreenRouteName]: { screen: MoreScreen },\n- [EditEmailRouteName]: { screen: EditEmail },\n- [EditPasswordRouteName]: { screen: EditPassword },\n- [DeleteAccountRouteName]: { screen: DeleteAccount },\n- [BuildInfoRouteName]: { screen: BuildInfo },\n- [DevToolsRouteName]: { screen: DevTools },\n-});\n+const More = createStackNavigator(\n+ {\n+ [MoreScreenRouteName]: MoreScreen,\n+ [EditEmailRouteName]: EditEmail,\n+ [EditPasswordRouteName]: EditPassword,\n+ [DeleteAccountRouteName]: DeleteAccount,\n+ [BuildInfoRouteName]: BuildInfo,\n+ [DevToolsRouteName]: DevTools,\n+ },\n+ {\n+ defaultNavigationOptions: {\n+ header: Header,\n+ },\n+ },\n+);\nMore.navigationOptions = ({ navigation }) => ({\ntabBarLabel: 'More',\ntabBarIcon: ({ tintColor }) => (\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "native/navigation/disconnected-bar.react.js",
"diff": "+// @flow\n+\n+import type { AppState } from '../redux-setup';\n+import {\n+ type ConnectionStatus,\n+ connectionStatusPropType,\n+} from 'lib/types/socket-types';\n+\n+import * as React from 'react';\n+import { View, Text, StyleSheet, LayoutAnimation } from 'react-native';\n+\n+import { connect } from 'lib/utils/redux-utils';\n+\n+type Props = {|\n+ connectionStatus: ConnectionStatus,\n+|};\n+type State = {|\n+ disconnected: bool,\n+|};\n+class DisconnectedBar extends React.PureComponent<Props, State> {\n+\n+ static propTypes = {\n+ connectionStatus: connectionStatusPropType.isRequired,\n+ };\n+ state = {\n+ disconnected: false,\n+ };\n+\n+ componentDidUpdate(prevProps: Props, prevState: State) {\n+ const { connectionStatus } = this.props;\n+ const { disconnected } = this.state;\n+ if (connectionStatus !== \"disconnected\") {\n+ if (connectionStatus === \"reconnecting\" && !disconnected) {\n+ this.setState({ disconnected: true });\n+ } else if (connectionStatus !== \"reconnecting\" && disconnected) {\n+ this.setState({ disconnected: false });\n+ }\n+ }\n+\n+ if (this.state.disconnected !== prevState.disconnected) {\n+ LayoutAnimation.easeInEaseOut();\n+ }\n+ }\n+\n+ render() {\n+ const { connectionStatus } = this.props;\n+ const { disconnected } = this.state;\n+\n+ const disconnectedBarStyles = [ styles.disconnectedBar ];\n+ let text;\n+ if (disconnected) {\n+ text = <Text style={styles.disconnectedText}>DISCONNECTED</Text>;\n+ } else {\n+ disconnectedBarStyles.push(styles.hiddenDisconnectedBar);\n+ }\n+\n+ return <View style={disconnectedBarStyles}>{text}</View>;\n+ }\n+\n+}\n+\n+const styles = StyleSheet.create({\n+ disconnectedBar: {\n+ backgroundColor: '#CC0000',\n+ padding: 5,\n+ },\n+ hiddenDisconnectedBar: {\n+ height: 0,\n+ padding: 0,\n+ },\n+ disconnectedText: {\n+ fontSize: 14,\n+ textAlign: 'center',\n+ color: 'white',\n+ },\n+});\n+\n+export default connect((state: AppState) => ({\n+ connectionStatus: state.connection.status,\n+}))(DisconnectedBar);\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "native/navigation/header.react.js",
"diff": "+// @flow\n+\n+import * as React from 'react';\n+import { Header } from 'react-navigation-stack';\n+\n+import DisconnectedBar from './disconnected-bar.react';\n+\n+export default function CustomHeader(props: *) {\n+ return (\n+ <React.Fragment>\n+ <Header {...props} />\n+ <DisconnectedBar />\n+ </React.Fragment>\n+ );\n+}\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | Pop down a bar when native is disconnected |
129,187 | 14.11.2018 18:08:56 | 18,000 | 25c7cec07a1e0dc5f87bc3b857c5c7c73eb9ae69 | [native] Flow libdef for | [
{
"change_type": "RENAME",
"old_path": "native/flow-typed/npm/react-navigation_v2.x.x.js",
"new_path": "native/flow-typed/npm/react-navigation_v3.x.x.js",
"diff": "-// flow-typed signature: 5d7fecbdc3f50450fb6a171350f15910\n-// flow-typed version: 40e6366386/react-navigation_v2.x.x/flow_>=v0.60.x\n-\n// @flow\ndeclare module 'react-navigation' {\n@@ -296,7 +293,7 @@ declare module 'react-navigation' {\ndeclare export type NavigationComponent =\n| NavigationScreenComponent<NavigationRoute, *, *>\n- | NavigationContainer<*, *, *>;\n+ | NavigationNavigator<*, *, *>;\ndeclare interface withOptionalNavigationOptions<Options> {\nnavigationOptions?: NavigationScreenConfig<Options>;\n@@ -320,7 +317,7 @@ declare module 'react-navigation' {\nState: NavigationState,\nOptions: {},\nProps: {}\n- > = React$ComponentType<{\n+ > = React$StatelessFunctionalComponent<{\n...Props,\n...NavigationNavigatorProps<Options, State>,\n}> &\n@@ -399,7 +396,7 @@ declare module 'react-navigation' {\ninitialRouteName?: string,\ninitialRouteParams?: NavigationParams,\npaths?: NavigationPathsConfig,\n- navigationOptions?: NavigationScreenConfig<*>,\n+ defaultNavigationOptions?: NavigationScreenConfig<*>,\ninitialRouteKey?: string,\n|};\n@@ -434,7 +431,7 @@ declare module 'react-navigation' {\ninitialRouteName?: string,\ninitialRouteParams?: NavigationParams,\npaths?: NavigationPathsConfig,\n- navigationOptions?: NavigationScreenConfig<*>,\n+ defaultNavigationOptions?: NavigationScreenConfig<*>,\norder?: Array<string>,\nbackBehavior?: 'none' | 'initialRoute', // defaults to `'none'`\nresetOnBlur?: boolean, // defaults to `true`\n@@ -448,7 +445,7 @@ declare module 'react-navigation' {\ninitialRouteName?: string,\ninitialRouteParams?: NavigationParams,\npaths?: NavigationPathsConfig,\n- navigationOptions?: NavigationScreenConfig<*>,\n+ defaultNavigationOptions?: NavigationScreenConfig<*>,\n// todo: type these as the real route names rather than 'string'\norder?: Array<string>,\n// Does the back button cause the router to switch to the initial tab\n@@ -536,7 +533,7 @@ declare module 'react-navigation' {\neventName: string,\ncallback: NavigationEventCallback\n) => NavigationEventSubscription,\n- getParam: <ParamName>(\n+ getParam: <ParamName: string>(\nparamName: ParamName,\nfallback?: $ElementType<\n$PropertyType<\n@@ -764,6 +761,9 @@ declare module 'react-navigation' {\n* Now we type the actual exported module\n*/\n+ declare export function createAppContainer<S: NavigationState, O: {}>(\n+ Component: NavigationNavigator<S, O, *>\n+ ): NavigationContainer<S, O, *>;\ndeclare export function createNavigationContainer<S: NavigationState, O: {}>(\nComponent: NavigationNavigator<S, O, *>\n): NavigationContainer<S, O, *>;\n@@ -895,11 +895,11 @@ declare module 'react-navigation' {\ndeclare export function StackNavigator(\nrouteConfigMap: NavigationRouteConfigMap,\nstackConfig?: StackNavigatorConfig\n- ): NavigationContainer<*, *, *>;\n+ ): NavigationNavigator<*, *, *>;\ndeclare export function createStackNavigator(\nrouteConfigMap: NavigationRouteConfigMap,\nstackConfig?: StackNavigatorConfig\n- ): NavigationContainer<*, *, *>;\n+ ): NavigationNavigator<*, *, *>;\ndeclare type _TabViewConfig = {|\ntabBarComponent?: React$ElementType,\n@@ -923,31 +923,31 @@ declare module 'react-navigation' {\ndeclare export function TabNavigator(\nrouteConfigs: NavigationRouteConfigMap,\nconfig?: _TabNavigatorConfig\n- ): NavigationContainer<*, *, *>;\n+ ): NavigationNavigator<*, *, *>;\ndeclare export function createTabNavigator(\nrouteConfigs: NavigationRouteConfigMap,\nconfig?: _TabNavigatorConfig\n- ): NavigationContainer<*, *, *>;\n+ ): NavigationNavigator<*, *, *>;\n/* TODO: fix the config for each of these tab navigator types */\ndeclare export function createBottomTabNavigator(\nrouteConfigs: NavigationRouteConfigMap,\nconfig?: _TabNavigatorConfig\n- ): NavigationContainer<*, *, *>;\n+ ): NavigationNavigator<*, *, *>;\ndeclare export function createMaterialTopTabNavigator(\nrouteConfigs: NavigationRouteConfigMap,\nconfig?: _TabNavigatorConfig\n- ): NavigationContainer<*, *, *>;\n+ ): NavigationNavigator<*, *, *>;\ndeclare type _SwitchNavigatorConfig = {|\n...NavigationSwitchRouterConfig,\n|};\ndeclare export function SwitchNavigator(\nrouteConfigs: NavigationRouteConfigMap,\nconfig?: _SwitchNavigatorConfig\n- ): NavigationContainer<*, *, *>;\n+ ): NavigationNavigator<*, *, *>;\ndeclare export function createSwitchNavigator(\nrouteConfigs: NavigationRouteConfigMap,\nconfig?: _SwitchNavigatorConfig\n- ): NavigationContainer<*, *, *>;\n+ ): NavigationNavigator<*, *, *>;\ndeclare type _DrawerViewConfig = {|\ndrawerLockMode?: 'unlocked' | 'locked-closed' | 'locked-open',\n@@ -968,11 +968,11 @@ declare module 'react-navigation' {\ndeclare export function DrawerNavigator(\nrouteConfigs: NavigationRouteConfigMap,\nconfig?: _DrawerNavigatorConfig\n- ): NavigationContainer<*, *, *>;\n+ ): NavigationNavigator<*, *, *>;\ndeclare export function createDrawerNavigator(\nrouteConfigs: NavigationRouteConfigMap,\nconfig?: _DrawerNavigatorConfig\n- ): NavigationContainer<*, *, *>;\n+ ): NavigationNavigator<*, *, *>;\ndeclare export function StackRouter(\nrouteConfigs: NavigationRouteConfigMap,\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Flow libdef for react-navigation@3.0 |
129,187 | 14.11.2018 19:32:11 | 18,000 | c5d4e045a944aec0309d90045082c05905a801c2 | Avoid long timers because RN setTimeout on Android doesn't like them | [
{
"change_type": "MODIFY",
"old_path": "lib/socket/calendar-query-handler.react.js",
"new_path": "lib/socket/calendar-query-handler.react.js",
"diff": "@@ -30,6 +30,7 @@ type Props = {|\n// Redux state\nconnection: ConnectionInfo,\nlastUserInteractionCalendar: number,\n+ foreground: bool,\n// Redux dispatch functions\ndispatchActionPromise: DispatchActionPromise,\n// async functions that hit server APIs\n@@ -44,6 +45,7 @@ class CalendarQueryHandler extends React.PureComponent<Props> {\nconnection: connectionInfoPropType.isRequired,\ncurrentCalendarQuery: PropTypes.func.isRequired,\nlastUserInteractionCalendar: PropTypes.number.isRequired,\n+ foreground: PropTypes.bool.isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\nupdateCalendarQuery: PropTypes.func.isRequired,\n};\n@@ -56,21 +58,14 @@ class CalendarQueryHandler extends React.PureComponent<Props> {\n}\ncomponentDidMount() {\n- if (this.props.connection.status !== \"connected\") {\n- return;\n- }\n- this.setExpirationTimeout();\n+ if (this.props.connection.status === \"connected\") {\nthis.possiblyUpdateCalendarQuery();\n}\n-\n- componentWillUnmount() {\n- this.clearExpirationTimeout();\n}\ncomponentDidUpdate(prevProps: Props) {\nconst { actualizedCalendarQuery } = this.props.connection;\nif (this.props.connection.status !== \"connected\") {\n- this.clearExpirationTimeout();\nif (!_isEqual(this.serverCalendarQuery)(actualizedCalendarQuery)) {\nthis.serverCalendarQuery = actualizedCalendarQuery;\n}\n@@ -84,17 +79,8 @@ class CalendarQueryHandler extends React.PureComponent<Props> {\nthis.serverCalendarQuery = actualizedCalendarQuery;\n}\n- let expired = false;\n- if (\n- prevProps.connection.status !== \"connected\" ||\n- this.props.lastUserInteractionCalendar !==\n- prevProps.lastUserInteractionCalendar\n- ) {\n- expired = this.setExpirationTimeout();\n- }\n-\nconst shouldUpdate = (\n- expired ||\n+ this.isExpired ||\nprevProps.connection.status !== \"connected\" ||\nthis.props.currentCalendarQuery !== prevProps.currentCalendarQuery\n) && this.shouldUpdateCalendarQuery;\n@@ -108,29 +94,12 @@ class CalendarQueryHandler extends React.PureComponent<Props> {\nreturn null;\n}\n- clearExpirationTimeout() {\n- if (this.expirationTimeoutID) {\n- clearTimeout(this.expirationTimeoutID);\n- this.expirationTimeoutID = null;\n- }\n- }\n-\n- setExpirationTimeout() {\n- this.clearExpirationTimeout();\n+ get isExpired() {\nconst timeUntilExpiration =\ntimeUntilCalendarRangeExpiration(this.props.lastUserInteractionCalendar);\n- if (timeUntilExpiration === null || timeUntilExpiration === undefined) {\n- return false;\n- }\n- if (timeUntilExpiration <= 0) {\n- return true;\n- } else {\n- this.expirationTimeoutID = setTimeout(\n- this.possiblyUpdateCalendarQuery,\n- timeUntilExpiration,\n- );\n- }\n- return false;\n+ return timeUntilExpiration !== null &&\n+ timeUntilExpiration !== undefined &&\n+ timeUntilExpiration <= 0;\n}\nget shouldUpdateCalendarQuery() {\n@@ -164,7 +133,9 @@ class CalendarQueryHandler extends React.PureComponent<Props> {\nexport default connect(\n(state: BaseAppState<*>) => ({\nconnection: state.connection,\n- lastUserInteractionCalendar: state.entryStore.lastUserInteractionCalendar\n+ lastUserInteractionCalendar: state.entryStore.lastUserInteractionCalendar,\n+ // We include this so that componentDidUpdate will be called on foreground\n+ foreground: state.foreground,\n}),\n{ updateCalendarQuery },\n)(CalendarQueryHandler);\n"
},
{
"change_type": "MODIFY",
"old_path": "native/chat/message-store-pruner.react.js",
"new_path": "native/chat/message-store-pruner.react.js",
"diff": "@@ -18,6 +18,7 @@ type Props = {|\n// Redux state\nnextMessagePruneTime: ?number,\npruneThreadIDs: () => $ReadOnlyArray<string>,\n+ foreground: bool,\n// Redux dispatch functions\ndispatchActionPayload: DispatchActionPayload,\n|};\n@@ -26,52 +27,19 @@ class MessageStorePruner extends React.PureComponent<Props> {\nstatic propTypes = {\nnextMessagePruneTime: PropTypes.number,\npruneThreadIDs: PropTypes.func.isRequired,\n+ foreground: PropTypes.bool.isRequired,\ndispatchActionPayload: PropTypes.func.isRequired,\n};\n- pruneTimeoutID: ?TimeoutID;\n-\n- componentDidMount() {\n- this.setExpirationTimeout();\n- }\n-\n- componentWillUnmount() {\n- this.clearPruneTimeout();\n- }\ncomponentDidUpdate(prevProps: Props) {\n- this.setExpirationTimeout();\n- }\n-\n- render() {\n- return null;\n- }\n-\n- clearPruneTimeout() {\n- if (this.pruneTimeoutID) {\n- clearTimeout(this.pruneTimeoutID);\n- this.pruneTimeoutID = null;\n- }\n- }\n-\n- setExpirationTimeout() {\n- this.clearPruneTimeout();\nconst { nextMessagePruneTime } = this.props;\nif (nextMessagePruneTime === null || nextMessagePruneTime === undefined) {\nreturn;\n}\nconst timeUntilExpiration = nextMessagePruneTime - Date.now();\n- if (timeUntilExpiration <= 0) {\n- this.dispatchMessageStorePruneAction();\n- } else {\n- this.pruneTimeoutID = setTimeout(\n- this.dispatchMessageStorePruneAction,\n- timeUntilExpiration,\n- );\n- }\n- return false;\n+ if (timeUntilExpiration > 0) {\n+ return;\n}\n-\n- dispatchMessageStorePruneAction = () => {\nconst threadIDs = this.props.pruneThreadIDs();\nif (threadIDs.length === 0) {\nreturn;\n@@ -82,12 +50,18 @@ class MessageStorePruner extends React.PureComponent<Props> {\n);\n}\n+ render() {\n+ return null;\n+ }\n+\n}\nexport default connect(\n(state: AppState) => ({\nnextMessagePruneTime: nextMessagePruneTimeSelector(state),\npruneThreadIDs: pruneThreadIDsSelector(state),\n+ // We include this so that componentDidUpdate will be called on foreground\n+ foreground: state.foreground,\n}),\nnull,\ntrue,\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | Avoid long timers because RN setTimeout on Android doesn't like them |
129,187 | 14.11.2018 18:16:11 | 18,000 | 72a1777bd76e1656410c7d0319a51aee742a7319 | codeVersion -> 24 | [
{
"change_type": "MODIFY",
"old_path": "lib/facts/version.json",
"new_path": "lib/facts/version.json",
"diff": "{\n- \"currentCodeVersion\": 23\n+ \"currentCodeVersion\": 24\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "native/android/app/build.gradle",
"new_path": "native/android/app/build.gradle",
"diff": "@@ -109,8 +109,8 @@ android {\napplicationId \"org.squadcal\"\nminSdkVersion rootProject.ext.minSdkVersion\ntargetSdkVersion rootProject.ext.targetSdkVersion\n- versionCode 23\n- versionName \"0.0.23\"\n+ versionCode 24\n+ versionName \"0.0.24\"\nndk {\nabiFilters \"armeabi-v7a\", \"x86\"\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "native/ios/SquadCal/Info.plist",
"new_path": "native/ios/SquadCal/Info.plist",
"diff": "<key>CFBundlePackageType</key>\n<string>APPL</string>\n<key>CFBundleShortVersionString</key>\n- <string>0.0.23</string>\n+ <string>0.0.24</string>\n<key>CFBundleSignature</key>\n<string>????</string>\n<key>CFBundleVersion</key>\n- <string>23</string>\n+ <string>24</string>\n<key>LSApplicationQueriesSchemes</key>\n<array>\n<string>org-appextension-feature-password-management</string>\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | codeVersion -> 24 |
129,187 | 20.11.2018 19:52:28 | 18,000 | afd0d895611979612a279a75ba4e05975eab313d | [lib] Allow mergeNewMessages to match orphaned localIDs
If a `sendMessage` fails for some reason, we currently have no way to match up its serverID when it gets delivered. This allows us to do that. | [
{
"change_type": "MODIFY",
"old_path": "lib/reducers/message-reducer.js",
"new_path": "lib/reducers/message-reducer.js",
"diff": "@@ -148,30 +148,44 @@ function mergeNewMessages(\nthreadInfos: {[threadID: string]: RawThreadInfo},\nactionType: *,\n): MessageStore {\n+ const localIDsToServerIDs: Map<string, string> = new Map();\nconst orderedNewMessageInfos = _flow(\n_map((messageInfo: RawMessageInfo) => {\n- const inputMessageInfo = messageInfo;\n- invariant(inputMessageInfo.id, \"new messageInfos should have serverID\");\n- const currentMessageInfo = oldMessageStore.messages[inputMessageInfo.id];\n- if (\n- currentMessageInfo &&\n- typeof currentMessageInfo.localID === \"string\"\n- ) {\n- invariant(\n- inputMessageInfo.type === messageTypes.TEXT,\n- \"only MessageType.TEXT has localID\",\n- );\n- // Try to preserve localIDs. This is because we use them as React\n- // keys and changing React keys leads to loss of component state.\n+ const { id: inputID } = messageInfo;\n+ invariant(inputID, \"new messageInfos should have serverID\");\n+ const currentMessageInfo = oldMessageStore.messages[inputID];\n+ if (messageInfo.type === messageTypes.TEXT) {\n+ const { localID: inputLocalID } = messageInfo;\n+ const currentLocalMessageInfo = inputLocalID\n+ ? oldMessageStore.messages[inputLocalID]\n+ : null;\n+ if (currentMessageInfo && currentMessageInfo.localID) {\n+ // If the client already has a RawMessageInfo with this serverID, keep\n+ // any localID associated with the existing one. This is because we\n+ // use localIDs as React keys and changing React keys leads to loss of\n+ // component state.\nmessageInfo = {\n- type: messageTypes.TEXT,\n- id: inputMessageInfo.id,\n+ ...messageInfo,\nlocalID: currentMessageInfo.localID,\n- threadID: inputMessageInfo.threadID,\n- creatorID: inputMessageInfo.creatorID,\n- time: inputMessageInfo.time,\n- text: inputMessageInfo.text,\n};\n+ } else if (currentLocalMessageInfo && currentLocalMessageInfo.localID) {\n+ // If the client has a RawMessageInfo with this localID, but not with\n+ // the serverID, that means the message creation succeeded but the\n+ // sendMessageActionTypes.success never got processed. We set a key in\n+ // localIDsToServerIDs here to fix the messageIDs for the thread too.\n+ invariant(inputLocalID, \"should be set\");\n+ localIDsToServerIDs.set(inputLocalID, inputID);\n+ messageInfo = {\n+ ...messageInfo,\n+ localID: currentLocalMessageInfo.localID,\n+ };\n+ } else {\n+ // If neither the serverID nor the localID from the delivered\n+ // RawMessageInfo exists in the local store, then this message is\n+ // brand new to us. Ignore any localID provided by the server.\n+ const { localID, ...rest } = messageInfo;\n+ messageInfo = { ...rest };\n+ }\n}\nreturn _isEqual(messageInfo)(currentMessageInfo)\n? currentMessageInfo\n@@ -213,7 +227,16 @@ function mergeNewMessages(\nlastPruned,\n};\n}\n- if (!isContiguous(truncate, oldThread.messageIDs, messageIDs)) {\n+ let oldMessageIDsUnchanged = true;\n+ const oldMessageIDs = oldThread.messageIDs.map(oldID => {\n+ const newID = localIDsToServerIDs.get(oldID);\n+ if (newID !== null && newID !== undefined) {\n+ oldMessageIDsUnchanged = false;\n+ return newID;\n+ }\n+ return oldID;\n+ });\n+ if (!isContiguous(truncate, oldMessageIDs, messageIDs)) {\n// If the result set in the payload isn't contiguous with what we have\n// now, that means we need to dump what we have in the state and replace\n// it with the result set. We do this to achieve our two goals for the\n@@ -225,20 +248,23 @@ function mergeNewMessages(\nlastPruned: oldThread.lastPruned,\n};\n}\n- const oldNotInNew = _difference(oldThread.messageIDs)(messageIDs);\n+ const oldNotInNew = _difference(oldMessageIDs)(messageIDs);\nfor (let messageID of oldNotInNew) {\n- oldMessageInfosToCombine.push(oldMessageStore.messages[messageID]);\n+ const oldMessageInfo = oldMessageStore.messages[messageID];\n+ invariant(\n+ oldMessageInfo,\n+ `could not find ${messageID} in messageStore`,\n+ );\n+ oldMessageInfosToCombine.push(oldMessageInfo);\n}\nconst startReached = oldThread.startReached ||\ntruncate === messageTruncationStatus.EXHAUSTIVE;\n- if (_difference(messageIDs)(oldThread.messageIDs).length === 0) {\n- // If we have no new messageIDs in the payload, then the only thing that\n- // might've changed is startReached.\n- if (startReached === oldThread.startReached) {\n+ if (_difference(messageIDs)(oldMessageIDs).length === 0) {\n+ if (startReached === oldThread.startReached && oldMessageIDsUnchanged) {\nreturn oldThread;\n}\nreturn {\n- messageIDs: oldThread.messageIDs,\n+ messageIDs: oldMessageIDs,\nstartReached,\nlastNavigatedTo: oldThread.lastNavigatedTo,\nlastPruned: oldThread.lastPruned,\n@@ -658,13 +684,20 @@ function reduceMessageStore(\ntruncationStatuses[messageInfo.threadID] =\nmessageTruncationStatus.UNCHANGED;\n}\n- return mergeNewMessages(\n+ const newMessageStore = mergeNewMessages(\nmessageStore,\naction.payload.rawMessageInfos,\ntruncationStatuses,\nnewThreadInfos,\naction.type,\n);\n+ return {\n+ messages: newMessageStore.messages,\n+ threads: newMessageStore.threads,\n+ // We avoid bumping currentAsOf because notifs may include a contracted\n+ // RawMessageInfo, so we want to make sure we still fetch it\n+ currentAsOf: messageStore.currentAsOf,\n+ };\n} else if (action.type === messageStorePruneActionType) {\nconst now = Date.now();\nconst messageIDsToPrune = [];\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [lib] Allow mergeNewMessages to match orphaned localIDs
If a `sendMessage` fails for some reason, we currently have no way to match up its serverID when it gets delivered. This allows us to do that. |
129,187 | 20.11.2018 21:15:35 | 18,000 | 56f38ac5f52a712f7f3c823e233e00237b77a108 | Include localID in message creation APIRequest
Message creations should be idempotent now. | [
{
"change_type": "MODIFY",
"old_path": "lib/actions/message-actions.js",
"new_path": "lib/actions/message-actions.js",
"diff": "@@ -64,9 +64,13 @@ const sendMessageActionTypes = Object.freeze({\nasync function sendMessage(\nfetchJSON: FetchJSON,\nthreadID: string,\n+ localID: string,\ntext: string,\n): Promise<SendTextMessageResult> {\n- const response = await fetchJSON('create_text_message', { threadID, text });\n+ const response = await fetchJSON(\n+ 'create_text_message',\n+ { threadID, localID, text },\n+ );\nreturn {\nid: response.newMessageInfo.id,\ntime: response.newMessageInfo.time,\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/reducers/message-reducer.js",
"new_path": "lib/reducers/message-reducer.js",
"diff": "@@ -568,20 +568,31 @@ function reduceMessageStore(\naction.type,\n);\n} else if (action.type === sendMessageActionTypes.started) {\n- const payload = action.payload;\n- invariant(payload.localID, `localID should be set on ${action.type}`);\n+ const { payload } = action;\n+ const { localID, threadID } = payload;\n+ invariant(localID, `localID should be set on ${action.type}`);\n+ if (messageStore.messages[localID]) {\n+ return messageStore;\n+ }\n+ const { messageIDs } = messageStore.threads[threadID];\n+ for (let existingMessageID of messageIDs) {\n+ const existingMessageInfo = messageStore.messages[existingMessageID];\n+ if (existingMessageInfo && existingMessageInfo.localID === localID) {\n+ return messageStore;\n+ }\n+ }\nreturn {\nmessages: {\n...messageStore.messages,\n- [payload.localID]: payload,\n+ [localID]: payload,\n},\nthreads: {\n...messageStore.threads,\n- [payload.threadID]: {\n- ...messageStore.threads[payload.threadID],\n+ [threadID]: {\n+ ...messageStore.threads[threadID],\nmessageIDs: [\n- payload.localID,\n- ...messageStore.threads[payload.threadID].messageIDs,\n+ localID,\n+ ...messageStore.threads[threadID].messageIDs,\n],\n},\n},\n@@ -619,6 +630,7 @@ function reduceMessageStore(\n// serverID message and scrub the localID one\nnewMessages = _omitBy(\n(messageInfo: RawMessageInfo) => messageInfo.type === 0 &&\n+ !messageInfo.id &&\nmessageInfo.localID === payload.localID,\n)(messageStore.messages);\n} else if (messageStore.messages[payload.localID]) {\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/types/message-types.js",
"new_path": "lib/types/message-types.js",
"diff": "@@ -65,8 +65,9 @@ export function assertMessageType(\n// Raw*MessageInfo = used by server, and contained in client's local store\n// *MessageInfo = used by client in UI code\n-type TextMessageData = {|\n+export type TextMessageData = {|\ntype: 0,\n+ localID?: string, // for optimistic creations. included by new clients\nthreadID: string,\ncreatorID: string,\ntime: number,\n@@ -576,6 +577,7 @@ export const defaultNumberPerThread = 20;\nexport type SendTextMessageRequest = {|\nthreadID: string,\n+ localID?: string,\ntext: string,\n|};\nexport type SendTextMessageResponse = {|\n"
},
{
"change_type": "MODIFY",
"old_path": "native/chat/chat-input-bar.react.js",
"new_path": "native/chat/chat-input-bar.react.js",
"diff": "@@ -69,6 +69,7 @@ type Props = {\n// async functions that hit server APIs\nsendMessage: (\nthreadID: string,\n+ localID: string,\ntext: string,\n) => Promise<SendTextMessageResult>,\njoinThread: (request: ClientThreadJoinRequest) => Promise<ThreadJoinPayload>,\n@@ -274,15 +275,16 @@ class ChatInputBar extends React.PureComponent<Props, State> {\nasync sendMessageAction(messageInfo: RawTextMessageInfo) {\ntry {\n- const result = await this.props.sendMessage(\n- messageInfo.threadID,\n- messageInfo.text,\n- );\nconst { localID } = messageInfo;\ninvariant(\nlocalID !== null && localID !== undefined,\n\"localID should be set\",\n);\n+ const result = await this.props.sendMessage(\n+ messageInfo.threadID,\n+ localID,\n+ messageInfo.text,\n+ );\nreturn {\nlocalID,\nserverID: result.id,\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/creators/message-creator.js",
"new_path": "server/src/creators/message-creator.js",
"diff": "@@ -34,6 +34,10 @@ import { handleAsyncPromise } from '../responders/handlers';\nimport { earliestFocusedTimeConsideredCurrent } from '../shared/focused-times';\nimport { fetchOtherSessionsForViewer } from '../fetchers/session-fetchers';\nimport { publisher } from '../socket/redis';\n+import {\n+ creationString,\n+ fetchMessageInfoForLocalID,\n+} from '../fetchers/message-fetchers';\n// Does not do permission checks! (checkThreadPermission)\nasync function createMessages(\n@@ -44,14 +48,36 @@ async function createMessages(\nreturn [];\n}\n- const ids = await createIDs(\"messages\", messageDatas.length);\n+ const messageInfos: RawMessageInfo[] = [];\n+ const newMessageDatas: MessageData[] = [];\n+ const existingMessages = await Promise.all(\n+ messageDatas.map(messageData => fetchMessageInfoForLocalID(\n+ viewer,\n+ messageData.type === messageTypes.TEXT ? messageData.localID : null,\n+ ))\n+ );\n+ for (let i = 0; i < existingMessages.length; i++) {\n+ const existingMessage = existingMessages[i];\n+ if (existingMessage) {\n+ messageInfos.push(existingMessage);\n+ } else {\n+ newMessageDatas.push(messageDatas[i]);\n+ }\n+ }\n+ if (newMessageDatas.length === 0) {\n+ return shimUnsupportedRawMessageInfos(\n+ messageInfos,\n+ viewer.platformDetails,\n+ );\n+ }\n+\n+ const ids = await createIDs(\"messages\", newMessageDatas.length);\nconst subthreadPermissionsToCheck: Set<string> = new Set();\nconst threadsToMessageIndices: Map<string, number[]> = new Map();\nconst messageInsertRows = [];\n- const messageInfos: RawMessageInfo[] = [];\n- for (let i = 0; i < messageDatas.length; i++) {\n- const messageData = messageDatas[i];\n+ for (let i = 0; i < newMessageDatas.length; i++) {\n+ const messageData = newMessageDatas[i];\nconst threadID = messageData.threadID;\nconst creatorID = messageData.creatorID;\n@@ -98,6 +124,11 @@ async function createMessages(\ntext: messageData.text,\n});\n}\n+\n+ const creation = messageData.localID && viewer.hasSessionInfo\n+ ? creationString(viewer, messageData.localID)\n+ : null;\n+\nmessageInsertRows.push([\nids[i],\nthreadID,\n@@ -105,8 +136,8 @@ async function createMessages(\nmessageData.type,\ncontent,\nmessageData.time,\n+ creation,\n]);\n-\nmessageInfos.push(rawMessageInfoFromMessageData(messageData, ids[i]));\n}\n@@ -118,7 +149,7 @@ async function createMessages(\n));\nconst messageInsertQuery = SQL`\n- INSERT INTO messages(id, thread, user, type, content, time)\n+ INSERT INTO messages(id, thread, user, type, content, time, creation)\nVALUES ${messageInsertRows}\n`;\nawait dbQuery(messageInsertQuery);\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/fetchers/message-fetchers.js",
"new_path": "server/src/fetchers/message-fetchers.js",
"diff": "@@ -281,6 +281,8 @@ function rawMessageInfoFromRow(row: Object): ?RawMessageInfo {\n}\n}\n+const visibleExtractString = `$.${threadPermissions.VISIBLE}.value`;\n+\nasync function fetchMessageInfos(\nviewer: Viewer,\ncriteria: ThreadSelectionCriteria,\n@@ -290,7 +292,6 @@ async function fetchMessageInfos(\nconst truncationStatuses = {};\nconst viewerID = viewer.id;\n- const visibleExtractString = `$.${threadPermissions.VISIBLE}.value`;\nconst query = SQL`\nSELECT * FROM (\nSELECT x.id, x.content, x.time, x.type, x.user AS creatorID,\n@@ -461,7 +462,6 @@ async function fetchMessageInfosSince(\n);\nconst viewerID = viewer.id;\n- const visibleExtractString = `$.${threadPermissions.VISIBLE}.value`;\nconst query = SQL`\nSELECT m.id, m.thread AS threadID, m.content, m.time, m.type,\nu.username AS creator, m.user AS creatorID,\n@@ -546,9 +546,42 @@ async function getMessageFetchResultFromRedisMessages(\n};\n}\n+function creationString(viewer: Viewer, localID: string) {\n+ return `${viewer.session}|${localID}`;\n+}\n+\n+async function fetchMessageInfoForLocalID(\n+ viewer: Viewer,\n+ localID: ?string,\n+): Promise<?RawMessageInfo> {\n+ if (!localID || !viewer.hasSessionInfo) {\n+ return null;\n+ }\n+ const creation = creationString(viewer, localID);\n+ const viewerID = viewer.id;\n+ const query = SQL`\n+ SELECT m.id, m.thread AS threadID, m.content, m.time, m.type,\n+ m.user AS creatorID, stm.permissions AS subthread_permissions\n+ FROM messages m\n+ LEFT JOIN memberships mm ON mm.thread = m.thread AND mm.user = ${viewerID}\n+ LEFT JOIN memberships stm ON m.type = ${messageTypes.CREATE_SUB_THREAD}\n+ AND stm.thread = m.content AND stm.user = ${viewerID}\n+ WHERE m.user = ${viewerID} AND m.creation = ${creation} AND\n+ JSON_EXTRACT(mm.permissions, ${visibleExtractString}) IS TRUE\n+ `;\n+\n+ const [ result ] = await dbQuery(query);\n+ if (result.length === 0) {\n+ return null;\n+ }\n+ return rawMessageInfoFromRow(result[0]);\n+}\n+\nexport {\nfetchCollapsableNotifs,\nfetchMessageInfos,\nfetchMessageInfosSince,\ngetMessageFetchResultFromRedisMessages,\n+ creationString,\n+ fetchMessageInfoForLocalID,\n};\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/responders/message-responders.js",
"new_path": "server/src/responders/message-responders.js",
"diff": "@@ -9,6 +9,7 @@ import {\ntype FetchMessageInfosRequest,\ndefaultNumberPerThread,\ntype SendTextMessageResponse,\n+ type TextMessageData,\n} from 'lib/types/message-types';\nimport t from 'tcomb';\n@@ -23,6 +24,7 @@ import { fetchMessageInfos } from '../fetchers/message-fetchers';\nconst sendTextMessageRequestInputValidator = tShape({\nthreadID: t.String,\n+ localID: t.maybe(t.String),\ntext: t.String,\n});\n@@ -33,7 +35,7 @@ async function textMessageCreationResponder(\nconst request: SendTextMessageRequest = input;\nawait validateInput(viewer, sendTextMessageRequestInputValidator, request);\n- const { threadID, text: rawText } = request;\n+ const { threadID, localID, text: rawText } = request;\nconst text = rawText.trim();\nif (!text) {\nthrow new ServerError('invalid_parameters');\n@@ -48,13 +50,16 @@ async function textMessageCreationResponder(\nthrow new ServerError('invalid_parameters');\n}\n- const messageData = {\n+ const messageData: TextMessageData = {\ntype: messageTypes.TEXT,\nthreadID,\ncreatorID: viewer.id,\ntime: Date.now(),\ntext,\n};\n+ if (localID) {\n+ messageData.localID = localID;\n+ }\nconst rawMessageInfos = await createMessages(viewer, [messageData]);\nreturn { newMessageInfo: rawMessageInfos[0] };\n"
},
{
"change_type": "MODIFY",
"old_path": "web/chat/chat-input-bar.react.js",
"new_path": "web/chat/chat-input-bar.react.js",
"diff": "@@ -52,6 +52,7 @@ type Props = {|\n// async functions that hit server APIs\nsendMessage: (\nthreadID: string,\n+ localID: string,\ntext: string,\n) => Promise<SendTextMessageResult>,\njoinThread: (request: ClientThreadJoinRequest) => Promise<ThreadJoinPayload>,\n@@ -233,15 +234,16 @@ class ChatInputBar extends React.PureComponent<Props, State> {\nasync sendMessageAction(messageInfo: RawTextMessageInfo) {\ntry {\n- const result = await this.props.sendMessage(\n- messageInfo.threadID,\n- messageInfo.text,\n- );\nconst { localID } = messageInfo;\ninvariant(\nlocalID !== null && localID !== undefined,\n\"localID should be set\",\n);\n+ const result = await this.props.sendMessage(\n+ messageInfo.threadID,\n+ localID,\n+ messageInfo.text,\n+ );\nreturn {\nlocalID,\nserverID: result.id,\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | Include localID in message creation APIRequest
Message creations should be idempotent now. |
129,187 | 20.11.2018 21:46:14 | 18,000 | acfc93adc2364dfcd91e057e89c3037701ff2bd3 | [server] Move creationString function to separate file | [
{
"change_type": "MODIFY",
"old_path": "server/src/creators/message-creator.js",
"new_path": "server/src/creators/message-creator.js",
"diff": "@@ -34,10 +34,8 @@ import { handleAsyncPromise } from '../responders/handlers';\nimport { earliestFocusedTimeConsideredCurrent } from '../shared/focused-times';\nimport { fetchOtherSessionsForViewer } from '../fetchers/session-fetchers';\nimport { publisher } from '../socket/redis';\n-import {\n- creationString,\n- fetchMessageInfoForLocalID,\n-} from '../fetchers/message-fetchers';\n+import { fetchMessageInfoForLocalID } from '../fetchers/message-fetchers';\n+import { creationString } from '../utils/idempotent';\n// Does not do permission checks! (checkThreadPermission)\nasync function createMessages(\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/fetchers/message-fetchers.js",
"new_path": "server/src/fetchers/message-fetchers.js",
"diff": "@@ -27,6 +27,7 @@ import { ServerError } from 'lib/utils/errors';\nimport { dbQuery, SQL, mergeOrConditions } from '../database';\nimport { fetchUserInfos } from './user-fetchers';\n+import { creationString } from '../utils/idempotent';\nexport type CollapsableNotifInfo = {|\ncollapseKey: ?string,\n@@ -546,10 +547,6 @@ async function getMessageFetchResultFromRedisMessages(\n};\n}\n-function creationString(viewer: Viewer, localID: string) {\n- return `${viewer.session}|${localID}`;\n-}\n-\nasync function fetchMessageInfoForLocalID(\nviewer: Viewer,\nlocalID: ?string,\n@@ -582,6 +579,5 @@ export {\nfetchMessageInfos,\nfetchMessageInfosSince,\ngetMessageFetchResultFromRedisMessages,\n- creationString,\nfetchMessageInfoForLocalID,\n};\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "server/src/utils/idempotent.js",
"diff": "+// @flow\n+\n+import type { Viewer } from '../session/viewer';\n+\n+function creationString(viewer: Viewer, localID: string) {\n+ return `${viewer.session}|${localID}`;\n+}\n+\n+export {\n+ creationString,\n+};\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [server] Move creationString function to separate file |
129,187 | 20.11.2018 22:19:16 | 18,000 | 16037289002620af86dc8c36718aa012d216e3ef | [server] Don't use reporter Viewer to create squadbot report messages | [
{
"change_type": "MODIFY",
"old_path": "server/src/creators/message-creator.js",
"new_path": "server/src/creators/message-creator.js",
"diff": "@@ -355,7 +355,7 @@ async function redisPublish(\nmessageInfosPerUser: {[userID: string]: $ReadOnlyArray<RawMessageInfo>},\n) {\nfor (let userID in messageInfosPerUser) {\n- if (userID === viewer.userID) {\n+ if (userID === viewer.userID && viewer.hasSessionInfo) {\ncontinue;\n}\nconst messageInfos = messageInfosPerUser[userID];\n@@ -368,7 +368,7 @@ async function redisPublish(\n);\n}\nconst viewerMessageInfos = messageInfosPerUser[viewer.userID];\n- if (!viewerMessageInfos) {\n+ if (!viewerMessageInfos || !viewer.hasSessionInfo) {\nreturn;\n}\nconst sessionIDs = await fetchOtherSessionsForViewer(viewer);\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/creators/report-creator.js",
"new_path": "server/src/creators/report-creator.js",
"diff": "@@ -21,6 +21,7 @@ import { fetchUsername } from '../fetchers/user-fetchers';\nimport urlFacts from '../../facts/url';\nimport createMessages from './message-creator';\nimport { handleAsyncPromise } from '../responders/handlers';\n+import { createBotViewer } from '../session/bots';\nconst { baseDomain, basePath, https } = urlFacts;\nconst { squadbot } = bots;\n@@ -77,7 +78,7 @@ async function sendSquadbotMessage(\n}\nconst time = Date.now();\nawait createMessages(\n- viewer,\n+ createBotViewer(squadbot.userID),\n[{\ntype: messageTypes.TEXT,\nthreadID: squadbot.ashoatThreadID,\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [server] Don't use reporter Viewer to create squadbot report messages |
129,187 | 20.11.2018 22:20:58 | 18,000 | 949c549731b56ee529cf102da0e063274e84cac5 | [server] Use updatesForCurrentSession "return" for entry updates
Otherwise we generate inconsistency reports while using sockets. | [
{
"change_type": "MODIFY",
"old_path": "server/src/updaters/entry-updaters.js",
"new_path": "server/src/updaters/entry-updaters.js",
"diff": "@@ -241,7 +241,7 @@ async function createUpdateDatasForChangedEntryInfo(\n}));\nconst { userInfos, ...updatesResult } = await createUpdates(\nupdateDatas,\n- { viewer, calendarQuery },\n+ { viewer, calendarQuery, updatesForCurrentSession: \"return\" },\n);\nreturn {\n...updatesResult,\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [server] Use updatesForCurrentSession "return" for entry updates
Otherwise we generate inconsistency reports while using sockets. |
129,187 | 20.11.2018 20:45:47 | 28,800 | bdc484151a206c8a3589e6dd068c97bde1f912f1 | Include localID in entry creation APIRequest
Entry creations should be idempotent now. | [
{
"change_type": "MODIFY",
"old_path": "lib/actions/entry-actions.js",
"new_path": "lib/actions/entry-actions.js",
"diff": "@@ -6,7 +6,7 @@ import type {\nSaveEntryInfo,\nSaveEntryResult,\nCreateEntryInfo,\n- SaveEntryPayload,\n+ CreateEntryPayload,\nDeleteEntryInfo,\nDeleteEntryPayload,\nRestoreEntryInfo,\n@@ -89,13 +89,14 @@ const createEntryActionTypes = Object.freeze({\nasync function createEntry(\nfetchJSON: FetchJSON,\nrequest: CreateEntryInfo,\n-): Promise<SaveEntryPayload> {\n+): Promise<CreateEntryPayload> {\nconst result = await fetchJSON('create_entry', request);\nreturn {\nentryID: result.entryID,\ntext: request.text,\nnewMessageInfos: result.newMessageInfos,\nthreadID: request.threadID,\n+ localID: request.localID,\nupdatesResult: result.updatesResult,\ncalendarQuery: request.calendarQuery,\n};\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/reducers/entry-reducer.js",
"new_path": "lib/reducers/entry-reducer.js",
"diff": "@@ -309,7 +309,8 @@ function reduceEntryInfos(\n// entry, and this probably won't happen often, so for now we can just\n// keep the serverID entry.\nrekeyedEntryInfos = _omitBy(\n- (candidate: RawEntryInfo) => candidate.localID === localID,\n+ (candidate: RawEntryInfo) => !candidate.id &&\n+ candidate.localID === localID,\n)(entryInfos);\n} else if (entryInfos[localID]) {\nrekeyedEntryInfos = _mapKeys(\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/types/entry-types.js",
"new_path": "lib/types/entry-types.js",
"diff": "@@ -140,6 +140,7 @@ export type CreateEntryInfo = {|\ntimestamp: number,\ndate: string,\nthreadID: string,\n+ localID: string,\ncalendarQuery: CalendarQuery,\n|};\n@@ -148,6 +149,7 @@ export type CreateEntryRequest = {|\ntimestamp: number,\ndate: string,\nthreadID: string,\n+ localID?: string,\ncalendarQuery?: CalendarQuery,\n|};\n"
},
{
"change_type": "MODIFY",
"old_path": "native/calendar/entry.react.js",
"new_path": "native/calendar/entry.react.js",
"diff": "@@ -6,7 +6,7 @@ import {\ntype CreateEntryInfo,\ntype SaveEntryInfo,\ntype SaveEntryResult,\n- type SaveEntryPayload,\n+ type CreateEntryPayload,\ntype DeleteEntryInfo,\ntype DeleteEntryPayload,\ntype CalendarQuery,\n@@ -93,7 +93,7 @@ type Props = {\ndispatchActionPayload: DispatchActionPayload,\ndispatchActionPromise: DispatchActionPromise,\n// async functions that hit server APIs\n- createEntry: (info: CreateEntryInfo) => Promise<SaveEntryPayload>,\n+ createEntry: (info: CreateEntryInfo) => Promise<CreateEntryPayload>,\nsaveEntry: (info: SaveEntryInfo) => Promise<SaveEntryResult>,\ndeleteEntry: (info: DeleteEntryInfo) => Promise<DeleteEntryPayload>,\n};\n@@ -494,6 +494,7 @@ class InternalEntry extends React.Component<Props, State> {\nthis.props.entryInfo.day,\n),\nthreadID: this.props.entryInfo.threadID,\n+ localID,\ncalendarQuery: this.props.calendarQuery(),\n});\nif (curSaveAttempt + 1 === this.nextSaveAttemptIndex) {\n@@ -508,7 +509,7 @@ class InternalEntry extends React.Component<Props, State> {\nthis.needsDeleteAfterCreation = false;\nthis.dispatchDelete(response.entryID);\n}\n- return { ...response, localID };\n+ return response;\n} catch(e) {\nif (curSaveAttempt + 1 === this.nextSaveAttemptIndex) {\nthis.guardedSetState({ loadingStatus: \"error\" });\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/creators/entry-creator.js",
"new_path": "server/src/creators/entry-creator.js",
"diff": "@@ -8,8 +8,11 @@ import type { Viewer } from '../session/viewer';\nimport { messageTypes } from 'lib/types/message-types';\nimport { threadPermissions } from 'lib/types/thread-types';\n+import invariant from 'invariant';\n+\nimport { ServerError } from 'lib/utils/errors';\nimport { dateFromString } from 'lib/utils/date-utils'\n+import { values } from 'lib/utils/objects';\nimport { dbQuery, SQL } from '../database';\nimport fetchOrCreateDayID from '../creators/day-creator';\n@@ -19,6 +22,10 @@ import { checkThreadPermission } from '../fetchers/thread-fetchers';\nimport {\ncreateUpdateDatasForChangedEntryInfo,\n} from '../updaters/entry-updaters';\n+import { fetchEntryInfoForLocalID } from '../fetchers/entry-fetchers';\n+import { fetchMessageInfoForEntryCreation } from '../fetchers/message-fetchers';\n+import { fetchUpdateInfoForEntryCreation } from '../fetchers/update-fetchers';\n+import { creationString } from '../utils/idempotent';\nasync function createEntry(\nviewer: Viewer,\n@@ -36,6 +43,27 @@ async function createEntry(\nthrow new ServerError('invalid_credentials');\n}\n+ const existingEntryInfo = await fetchEntryInfoForLocalID(\n+ viewer,\n+ request.localID,\n+ );\n+ if (existingEntryInfo) {\n+ const { id: entryID, threadID } = existingEntryInfo;\n+ invariant(entryID, \"should be set\");\n+ const [ rawMessageInfo, fetchUpdatesResult ] = await Promise.all([\n+ fetchMessageInfoForEntryCreation(viewer, entryID, threadID),\n+ fetchUpdateInfoForEntryCreation(viewer, entryID),\n+ ]);\n+ return {\n+ entryID,\n+ newMessageInfos: rawMessageInfo ? [ rawMessageInfo ] : [],\n+ updatesResult: {\n+ viewerUpdates: fetchUpdatesResult.updateInfos,\n+ userInfos: values(fetchUpdatesResult.userInfos),\n+ },\n+ };\n+ }\n+\nconst [\ndayID,\n[ entryID ],\n@@ -49,6 +77,9 @@ async function createEntry(\ncreateIDs(\"revisions\", 1),\n]);\n+ const creation = request.localID && viewer.hasSessionInfo\n+ ? creationString(viewer, request.localID)\n+ : null;\nconst viewerID = viewer.userID;\nconst entryRow = [\nentryID,\n@@ -58,6 +89,7 @@ async function createEntry(\nrequest.timestamp,\nrequest.timestamp,\n0,\n+ creation,\n];\nconst revisionRow = [\nrevisionID,\n@@ -71,7 +103,7 @@ async function createEntry(\n];\nconst entryInsertQuery = SQL`\nINSERT INTO entries(id, day, text, creator, creation_time, last_update,\n- deleted)\n+ deleted, creation)\nVALUES ${[entryRow]}\n`;\nconst revisionInsertQuery = SQL`\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/fetchers/entry-fetchers.js",
"new_path": "server/src/fetchers/entry-fetchers.js",
"diff": "@@ -33,6 +33,7 @@ import {\nmergeAndConditions,\nmergeOrConditions,\n} from '../database';\n+import { creationString } from '../utils/idempotent';\nasync function fetchEntryInfo(\nviewer: Viewer,\n@@ -45,6 +46,20 @@ async function fetchEntryInfo(\nreturn results[0];\n}\n+function rawEntryInfoFromRow(row: Object): RawEntryInfo {\n+ return {\n+ id: row.id.toString(),\n+ threadID: row.threadID.toString(),\n+ text: row.text,\n+ year: row.year,\n+ month: row.month,\n+ day: row.day,\n+ creationTime: row.creationTime,\n+ creatorID: row.creatorID.toString(),\n+ deleted: !!row.deleted,\n+ };\n+}\n+\nconst visPermissionExtractString = `$.${threadPermissions.VISIBLE}.value`;\nasync function fetchEntryInfosByID(\nviewer: Viewer,\n@@ -65,17 +80,7 @@ async function fetchEntryInfosByID(\nJSON_EXTRACT(m.permissions, ${visPermissionExtractString}) IS TRUE\n`;\nconst [ result ] = await dbQuery(query);\n- return result.map(row => ({\n- id: row.id.toString(),\n- threadID: row.threadID.toString(),\n- text: row.text,\n- year: row.year,\n- month: row.month,\n- day: row.day,\n- creationTime: row.creationTime,\n- creatorID: row.creatorID.toString(),\n- deleted: !!row.deleted,\n- }));\n+ return result.map(rawEntryInfoFromRow);\n}\nfunction sqlConditionForCalendarQuery(\n@@ -133,19 +138,9 @@ async function fetchEntryInfos(\nconst rawEntryInfos = [];\nconst userInfos = {};\nfor (let row of result) {\n- const creatorID = row.creatorID.toString();\n- rawEntryInfos.push({\n- id: row.id.toString(),\n- threadID: row.threadID.toString(),\n- text: row.text,\n- year: row.year,\n- month: row.month,\n- day: row.day,\n- creationTime: row.creationTime,\n- creatorID,\n- deleted: !!row.deleted,\n- });\n+ rawEntryInfos.push(rawEntryInfoFromRow(row));\nif (row.creator) {\n+ const creatorID = row.creatorID.toString();\nuserInfos[creatorID] = {\nid: creatorID,\nusername: row.creator,\n@@ -252,6 +247,33 @@ async function fetchEntriesForSession(\nreturn { rawEntryInfos: filteredRawEntryInfos, userInfos: filteredUserInfos };\n}\n+async function fetchEntryInfoForLocalID(\n+ viewer: Viewer,\n+ localID: ?string,\n+): Promise<?RawEntryInfo> {\n+ if (!localID || !viewer.hasSessionInfo) {\n+ return null;\n+ }\n+ const creation = creationString(viewer, localID);\n+ const viewerID = viewer.id;\n+ const query = SQL`\n+ SELECT DAY(d.date) AS day, MONTH(d.date) AS month, YEAR(d.date) AS year,\n+ e.id, e.text, e.creation_time AS creationTime, d.thread AS threadID,\n+ e.deleted, e.creator AS creatorID\n+ FROM entries e\n+ LEFT JOIN days d ON d.id = e.day\n+ LEFT JOIN memberships m ON m.thread = d.thread AND m.user = ${viewerID}\n+ WHERE e.creator = ${viewerID} AND e.creation = ${creation} AND\n+ JSON_EXTRACT(m.permissions, ${visPermissionExtractString}) IS TRUE\n+ `;\n+\n+ const [ result ] = await dbQuery(query);\n+ if (result.length === 0) {\n+ return null;\n+ }\n+ return rawEntryInfoFromRow(result[0]);\n+}\n+\nexport {\nfetchEntryInfo,\nfetchEntryInfosByID,\n@@ -259,4 +281,5 @@ export {\ncheckThreadPermissionForEntry,\nfetchEntryRevisionInfo,\nfetchEntriesForSession,\n+ fetchEntryInfoForLocalID,\n};\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/fetchers/message-fetchers.js",
"new_path": "server/src/fetchers/message-fetchers.js",
"diff": "@@ -574,10 +574,36 @@ async function fetchMessageInfoForLocalID(\nreturn rawMessageInfoFromRow(result[0]);\n}\n+const entryIDExtractString = \"$.entryID\";\n+async function fetchMessageInfoForEntryCreation(\n+ viewer: Viewer,\n+ entryID: string,\n+ threadID: string,\n+): Promise<?RawMessageInfo> {\n+ const viewerID = viewer.id;\n+ const query = SQL`\n+ SELECT m.id, m.thread AS threadID, m.content, m.time, m.type,\n+ m.user AS creatorID\n+ FROM messages m\n+ LEFT JOIN memberships mm ON mm.thread = m.thread AND mm.user = ${viewerID}\n+ WHERE m.user = ${viewerID} AND m.thread = ${threadID} AND\n+ m.type = ${messageTypes.CREATE_ENTRY} AND\n+ JSON_EXTRACT(m.content, ${entryIDExtractString}) = ${entryID} AND\n+ JSON_EXTRACT(mm.permissions, ${visibleExtractString}) IS TRUE\n+ `;\n+\n+ const [ result ] = await dbQuery(query);\n+ if (result.length === 0) {\n+ return null;\n+ }\n+ return rawMessageInfoFromRow(result[0]);\n+}\n+\nexport {\nfetchCollapsableNotifs,\nfetchMessageInfos,\nfetchMessageInfosSince,\ngetMessageFetchResultFromRedisMessages,\nfetchMessageInfoForLocalID,\n+ fetchMessageInfoForEntryCreation,\n};\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/fetchers/update-fetchers.js",
"new_path": "server/src/fetchers/update-fetchers.js",
"diff": "@@ -117,6 +117,38 @@ function rawUpdateInfoFromRow(row: Object): RawUpdateInfo {\ninvariant(false, `unrecognized updateType ${type}`);\n}\n+const entryIDExtractString = \"$.entryID\";\n+async function fetchUpdateInfoForEntryCreation(\n+ viewer: Viewer,\n+ entryID: string,\n+): Promise<FetchUpdatesResult> {\n+ if (!viewer.loggedIn) {\n+ throw new ServerError('not_logged_in');\n+ }\n+\n+ const query = SQL`\n+ SELECT id, type, content, time\n+ FROM updates\n+ WHERE user = ${viewer.id} AND\n+ type = ${updateTypes.UPDATE_ENTRY} AND\n+ JSON_EXTRACT(content, ${entryIDExtractString}) = ${entryID}\n+ ORDER BY time DESC\n+ LIMIT 1\n+ `;\n+ const [ result ] = await dbQuery(query);\n+\n+ const rawUpdateInfos = [];\n+ for (let row of result) {\n+ rawUpdateInfos.push(rawUpdateInfoFromRow(row));\n+ }\n+\n+ return await fetchUpdateInfosWithRawUpdateInfos(\n+ rawUpdateInfos,\n+ { viewer },\n+ );\n+}\n+\nexport {\nfetchUpdateInfos,\n+ fetchUpdateInfoForEntryCreation,\n};\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/responders/entry-responders.js",
"new_path": "server/src/responders/entry-responders.js",
"diff": "@@ -144,6 +144,7 @@ const createEntryRequestInputValidator = tShape({\ntimestamp: t.Number,\ndate: tDate,\nthreadID: t.String,\n+ localID: t.maybe(t.String),\ncalendarQuery: t.maybe(newEntryQueryInputValidator),\n});\n"
},
{
"change_type": "MODIFY",
"old_path": "web/calendar/entry.react.js",
"new_path": "web/calendar/entry.react.js",
"diff": "@@ -6,7 +6,7 @@ import {\ntype CreateEntryInfo,\ntype SaveEntryInfo,\ntype SaveEntryResult,\n- type SaveEntryPayload,\n+ type CreateEntryPayload,\ntype DeleteEntryInfo,\ntype DeleteEntryPayload,\ntype CalendarQuery,\n@@ -64,7 +64,7 @@ type Props = {\ndispatchActionPayload: DispatchActionPayload,\ndispatchActionPromise: DispatchActionPromise,\n// async functions that hit server APIs\n- createEntry: (info: CreateEntryInfo) => Promise<SaveEntryPayload>,\n+ createEntry: (info: CreateEntryInfo) => Promise<CreateEntryPayload>,\nsaveEntry: (info: SaveEntryInfo) => Promise<SaveEntryResult>,\ndeleteEntry: (info: DeleteEntryInfo) => Promise<DeleteEntryPayload>,\n};\n@@ -310,6 +310,7 @@ class Entry extends React.PureComponent<Props, State> {\nthis.props.entryInfo.day,\n),\nthreadID: this.props.entryInfo.threadID,\n+ localID,\ncalendarQuery: this.props.calendarQuery(),\n});\nif (curSaveAttempt + 1 === this.nextSaveAttemptIndex) {\n@@ -324,7 +325,7 @@ class Entry extends React.PureComponent<Props, State> {\nthis.needsDeleteAfterCreation = false;\nthis.delete(response.entryID, false);\n}\n- return { ...response, localID };\n+ return response;\n} catch(e) {\nif (curSaveAttempt + 1 === this.nextSaveAttemptIndex) {\nthis.guardedSetState({ loadingStatus: \"error\" });\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | Include localID in entry creation APIRequest
Entry creations should be idempotent now. |
129,187 | 20.11.2018 22:31:44 | 28,800 | c7003d98407fb9ae2b51cd676895cf5d4973e5dc | Include localIDs in message fetch for state sync
This allows client to dedup in the case of a missed response. | [
{
"change_type": "MODIFY",
"old_path": "lib/shared/message-utils.js",
"new_path": "lib/shared/message-utils.js",
"diff": "@@ -427,70 +427,19 @@ function rawMessageInfoFromMessageData(\nid: string,\n): RawMessageInfo {\nif (messageData.type === messageTypes.TEXT) {\n- return {\n- type: messageTypes.TEXT,\n- id,\n- threadID: messageData.threadID,\n- creatorID: messageData.creatorID,\n- time: messageData.time,\n- text: messageData.text,\n- };\n+ return { ...messageData, id };\n} else if (messageData.type === messageTypes.CREATE_THREAD) {\n- return {\n- type: messageTypes.CREATE_THREAD,\n- id,\n- threadID: messageData.threadID,\n- creatorID: messageData.creatorID,\n- time: messageData.time,\n- initialThreadState: messageData.initialThreadState,\n- };\n+ return { ...messageData, id };\n} else if (messageData.type === messageTypes.ADD_MEMBERS) {\n- return {\n- type: messageTypes.ADD_MEMBERS,\n- id,\n- threadID: messageData.threadID,\n- creatorID: messageData.creatorID,\n- time: messageData.time,\n- addedUserIDs: messageData.addedUserIDs,\n- };\n+ return { ...messageData, id };\n} else if (messageData.type === messageTypes.CREATE_SUB_THREAD) {\n- return {\n- type: messageTypes.CREATE_SUB_THREAD,\n- id,\n- threadID: messageData.threadID,\n- creatorID: messageData.creatorID,\n- time: messageData.time,\n- childThreadID: messageData.childThreadID,\n- };\n+ return { ...messageData, id };\n} else if (messageData.type === messageTypes.CHANGE_SETTINGS) {\n- return {\n- type: messageTypes.CHANGE_SETTINGS,\n- id,\n- threadID: messageData.threadID,\n- creatorID: messageData.creatorID,\n- time: messageData.time,\n- field: messageData.field,\n- value: messageData.value,\n- };\n+ return { ...messageData, id };\n} else if (messageData.type === messageTypes.REMOVE_MEMBERS) {\n- return {\n- type: messageTypes.REMOVE_MEMBERS,\n- id,\n- threadID: messageData.threadID,\n- creatorID: messageData.creatorID,\n- time: messageData.time,\n- removedUserIDs: messageData.removedUserIDs,\n- };\n+ return { ...messageData, id };\n} else if (messageData.type === messageTypes.CHANGE_ROLE) {\n- return {\n- type: messageTypes.CHANGE_ROLE,\n- id,\n- threadID: messageData.threadID,\n- creatorID: messageData.creatorID,\n- time: messageData.time,\n- userIDs: messageData.userIDs,\n- newRole: messageData.newRole,\n- };\n+ return { ...messageData, id };\n} else if (messageData.type === messageTypes.LEAVE_THREAD) {\nreturn {\ntype: messageTypes.LEAVE_THREAD,\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/types/message-types.js",
"new_path": "lib/types/message-types.js",
"diff": "@@ -189,7 +189,6 @@ export type MessageData =\nexport type RawTextMessageInfo = {|\n...TextMessageData,\nid?: string, // null if local copy without ID yet\n- localID?: string, // for optimistic creations\n|};\ntype RawRobotextMessageInfo = {|\n...CreateThreadMessageData,\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/fetchers/message-fetchers.js",
"new_path": "server/src/fetchers/message-fetchers.js",
"diff": "@@ -11,6 +11,7 @@ import {\nmessageTruncationStatus,\ntype MessageTruncationStatuses,\ntype FetchMessageInfosResult,\n+ type RawTextMessageInfo,\n} from 'lib/types/message-types';\nimport { threadPermissions } from 'lib/types/thread-types';\nimport type { Viewer } from '../session/viewer';\n@@ -27,7 +28,7 @@ import { ServerError } from 'lib/utils/errors';\nimport { dbQuery, SQL, mergeOrConditions } from '../database';\nimport { fetchUserInfos } from './user-fetchers';\n-import { creationString } from '../utils/idempotent';\n+import { creationString, localIDFromCreationString } from '../utils/idempotent';\nexport type CollapsableNotifInfo = {|\ncollapseKey: ?string,\n@@ -133,10 +134,13 @@ async function fetchCollapsableNotifs(\nreturn { usersToCollapsableNotifInfo, userInfos };\n}\n-function rawMessageInfoFromRow(row: Object): ?RawMessageInfo {\n+function rawMessageInfoFromRow(\n+ row: Object,\n+ viewer?: Viewer,\n+): ?RawMessageInfo {\nconst type = assertMessageType(row.type);\nif (type === messageTypes.TEXT) {\n- return {\n+ const rawTextMessageInfo: RawTextMessageInfo = {\ntype: messageTypes.TEXT,\nid: row.id.toString(),\nthreadID: row.threadID.toString(),\n@@ -144,6 +148,11 @@ function rawMessageInfoFromRow(row: Object): ?RawMessageInfo {\ncreatorID: row.creatorID.toString(),\ntext: row.content,\n};\n+ const localID = localIDFromCreationString(viewer, row.creation);\n+ if (localID) {\n+ rawTextMessageInfo.localID = localID;\n+ }\n+ return rawTextMessageInfo;\n} else if (type === messageTypes.CREATE_THREAD) {\nconst dbInitialThreadState = JSON.parse(row.content);\n// For legacy clients before the rename\n@@ -296,13 +305,13 @@ async function fetchMessageInfos(\nconst query = SQL`\nSELECT * FROM (\nSELECT x.id, x.content, x.time, x.type, x.user AS creatorID,\n- u.username AS creator, x.subthread_permissions,\n+ x.creation, u.username AS creator, x.subthread_permissions,\n@num := if(@thread = x.thread, @num + 1, 1) AS number,\n@thread := x.thread AS threadID\nFROM (SELECT @num := 0, @thread := '') init\nJOIN (\nSELECT m.id, m.thread, m.user, m.content, m.time, m.type,\n- stm.permissions AS subthread_permissions\n+ m.creation, stm.permissions AS subthread_permissions\nFROM messages m\nLEFT JOIN memberships mm\nON mm.thread = m.thread AND mm.user = ${viewerID}\n@@ -329,7 +338,7 @@ async function fetchMessageInfos(\nid: creatorID,\nusername: row.creator,\n};\n- const rawMessageInfo = rawMessageInfoFromRow(row);\n+ const rawMessageInfo = rawMessageInfoFromRow(row, viewer);\nif (rawMessageInfo) {\nrawMessageInfos.push(rawMessageInfo);\n}\n@@ -465,7 +474,7 @@ async function fetchMessageInfosSince(\nconst viewerID = viewer.id;\nconst query = SQL`\nSELECT m.id, m.thread AS threadID, m.content, m.time, m.type,\n- u.username AS creator, m.user AS creatorID,\n+ m.creation, u.username AS creator, m.user AS creatorID,\nstm.permissions AS subthread_permissions\nFROM messages m\nLEFT JOIN memberships mm ON mm.thread = m.thread AND mm.user = ${viewerID}\n@@ -504,7 +513,7 @@ async function fetchMessageInfosSince(\nid: creatorID,\nusername: row.creator,\n};\n- const rawMessageInfo = rawMessageInfoFromRow(row);\n+ const rawMessageInfo = rawMessageInfoFromRow(row, viewer);\nif (rawMessageInfo) {\nrawMessageInfos.push(rawMessageInfo);\n}\n@@ -557,7 +566,7 @@ async function fetchMessageInfoForLocalID(\nconst creation = creationString(viewer, localID);\nconst viewerID = viewer.id;\nconst query = SQL`\n- SELECT m.id, m.thread AS threadID, m.content, m.time, m.type,\n+ SELECT m.id, m.thread AS threadID, m.content, m.time, m.type, m.creation,\nm.user AS creatorID, stm.permissions AS subthread_permissions\nFROM messages m\nLEFT JOIN memberships mm ON mm.thread = m.thread AND mm.user = ${viewerID}\n@@ -571,7 +580,7 @@ async function fetchMessageInfoForLocalID(\nif (result.length === 0) {\nreturn null;\n}\n- return rawMessageInfoFromRow(result[0]);\n+ return rawMessageInfoFromRow(result[0], viewer);\n}\nconst entryIDExtractString = \"$.entryID\";\n@@ -582,7 +591,7 @@ async function fetchMessageInfoForEntryCreation(\n): Promise<?RawMessageInfo> {\nconst viewerID = viewer.id;\nconst query = SQL`\n- SELECT m.id, m.thread AS threadID, m.content, m.time, m.type,\n+ SELECT m.id, m.thread AS threadID, m.content, m.time, m.type, m.creation,\nm.user AS creatorID\nFROM messages m\nLEFT JOIN memberships mm ON mm.thread = m.thread AND mm.user = ${viewerID}\n@@ -596,7 +605,7 @@ async function fetchMessageInfoForEntryCreation(\nif (result.length === 0) {\nreturn null;\n}\n- return rawMessageInfoFromRow(result[0]);\n+ return rawMessageInfoFromRow(result[0], viewer);\n}\nexport {\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/utils/idempotent.js",
"new_path": "server/src/utils/idempotent.js",
"diff": "@@ -6,6 +6,15 @@ function creationString(viewer: Viewer, localID: string) {\nreturn `${viewer.session}|${localID}`;\n}\n+function localIDFromCreationString(viewer: ?Viewer, creationString: ?string) {\n+ if (!creationString || !viewer || !viewer.hasSessionInfo) {\n+ return null;\n+ }\n+ const [ session, localID ] = creationString.split('|');\n+ return session === viewer.session ? localID : null;\n+}\n+\nexport {\ncreationString,\n+ localIDFromCreationString,\n};\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | Include localIDs in message fetch for state sync
This allows client to dedup in the case of a missed response. |
129,187 | 20.11.2018 23:37:08 | 28,800 | 5cb62e8375a5ba979b31ca218acf7e0a8b21f96a | [server] Make thread deletion idempotent | [
{
"change_type": "MODIFY",
"old_path": "server/src/creators/update-creator.js",
"new_path": "server/src/creators/update-creator.js",
"diff": "@@ -80,7 +80,7 @@ type UpdatesForCurrentSession =\n// communicating the relevant information to the client.\n| \"ignore\";\n-type ViewerInfo =\n+export type ViewerInfo =\n| {|\nviewer: Viewer,\ncalendarQuery?: ?CalendarQuery,\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/deleters/thread-deleters.js",
"new_path": "server/src/deleters/thread-deleters.js",
"diff": "@@ -11,15 +11,17 @@ import bcrypt from 'twin-bcrypt';\nimport { ServerError } from 'lib/utils/errors';\nimport { threadPermissions } from 'lib/types/thread-types';\n+import { permissionLookup } from 'lib/permissions/thread-permissions';\nimport { dbQuery, SQL } from '../database';\nimport {\n- checkThreadPermission,\n+ fetchThreadPermissionsBlob,\nfetchThreadInfos,\nfetchServerThreadInfos,\n} from '../fetchers/thread-fetchers';\nimport { rescindPushNotifs } from '../push/rescind';\nimport { createUpdates } from '../creators/update-creator';\n+import { fetchUpdateInfoForThreadDeletion } from '../fetchers/update-fetchers';\nasync function deleteThread(\nviewer: Viewer,\n@@ -28,20 +30,40 @@ async function deleteThread(\nif (!viewer.loggedIn) {\nthrow new ServerError('not_logged_in');\n}\n+ const { threadID } = threadDeletionRequest;\nconst [\n- hasPermission,\n+ permissionsBlob,\n[ hashResult ],\n{ threadInfos: serverThreadInfos },\n] = await Promise.all([\n- checkThreadPermission(\n- viewer,\n- threadDeletionRequest.threadID,\n- threadPermissions.DELETE_THREAD,\n- ),\n+ fetchThreadPermissionsBlob(viewer, threadID),\ndbQuery(SQL`SELECT hash FROM users WHERE id = ${viewer.userID}`),\n- fetchServerThreadInfos(SQL`t.id = ${threadDeletionRequest.threadID}`),\n+ fetchServerThreadInfos(SQL`t.id = ${threadID}`),\n]);\n+\n+ if (!permissionsBlob) {\n+ // This should only occur if the first request goes through but the client\n+ // never receives the response\n+ const [\n+ { threadInfos },\n+ { updateInfos },\n+ ] = await Promise.all([\n+ fetchThreadInfos(viewer),\n+ fetchUpdateInfoForThreadDeletion(viewer, threadID),\n+ ]);\n+ return {\n+ threadInfos,\n+ updatesResult: {\n+ newUpdates: updateInfos,\n+ },\n+ };\n+ }\n+\n+ const hasPermission = permissionLookup(\n+ permissionsBlob,\n+ threadPermissions.DELETE_THREAD,\n+ );\nif (!hasPermission) {\nthrow new ServerError('invalid_credentials');\n}\n@@ -54,8 +76,8 @@ async function deleteThread(\n}\nawait rescindPushNotifs(\n- SQL`n.thread = ${threadDeletionRequest.threadID}`,\n- SQL`IF(m.thread = ${threadDeletionRequest.threadID}, NULL, 1)`,\n+ SQL`n.thread = ${threadID}`,\n+ SQL`IF(m.thread = ${threadID}, NULL, 1)`,\n);\n// TODO: if org, delete all descendant threads as well. make sure to warn user\n@@ -79,10 +101,10 @@ async function deleteThread(\nLEFT JOIN focused f ON f.thread = t.id\nLEFT JOIN notifications n ON n.thread = t.id\nLEFT JOIN ids ino ON ino.id = n.id\n- WHERE t.id = ${threadDeletionRequest.threadID}\n+ WHERE t.id = ${threadID}\n`;\n- const serverThreadInfo = serverThreadInfos[threadDeletionRequest.threadID];\n+ const serverThreadInfo = serverThreadInfos[threadID];\nconst time = Date.now();\nconst updateDatas = [];\nfor (let memberInfo of serverThreadInfo.members) {\n@@ -90,7 +112,7 @@ async function deleteThread(\ntype: updateTypes.DELETE_THREAD,\nuserID: memberInfo.id,\ntime,\n- threadID: threadDeletionRequest.threadID,\n+ threadID,\n});\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/fetchers/update-fetchers.js",
"new_path": "server/src/fetchers/update-fetchers.js",
"diff": "@@ -7,26 +7,38 @@ import {\n} from 'lib/types/update-types';\nimport type { CalendarQuery } from 'lib/types/entry-types';\nimport type { Viewer } from '../session/viewer';\n+import type { ViewerInfo } from '../creators/update-creator';\nimport invariant from 'invariant';\nimport { ServerError } from 'lib/utils/errors';\n-import { dbQuery, SQL } from '../database';\n+import { dbQuery, SQL, SQLStatement } from '../database';\nimport {\ntype FetchUpdatesResult,\nfetchUpdateInfosWithRawUpdateInfos,\n} from '../creators/update-creator';\n-async function fetchUpdateInfos(\n- viewer: Viewer,\n- currentAsOf: number,\n- calendarQuery: CalendarQuery,\n+async function fetchUpdateInfosWithQuery(\n+ viewerInfo: ViewerInfo,\n+ query: SQLStatement,\n): Promise<FetchUpdatesResult> {\n- if (!viewer.loggedIn) {\n+ if (!viewerInfo.viewer.loggedIn) {\nthrow new ServerError('not_logged_in');\n}\n+ const [ result ] = await dbQuery(query);\n+ const rawUpdateInfos = [];\n+ for (let row of result) {\n+ rawUpdateInfos.push(rawUpdateInfoFromRow(row));\n+ }\n+ return await fetchUpdateInfosWithRawUpdateInfos(rawUpdateInfos, viewerInfo);\n+}\n+function fetchUpdateInfos(\n+ viewer: Viewer,\n+ currentAsOf: number,\n+ calendarQuery: CalendarQuery,\n+): Promise<FetchUpdatesResult> {\nconst query = SQL`\nSELECT id, type, content, time\nFROM updates\n@@ -35,16 +47,9 @@ async function fetchUpdateInfos(\nAND (target IS NULL OR target = ${viewer.session})\nORDER BY time ASC\n`;\n- const [ result ] = await dbQuery(query);\n-\n- const rawUpdateInfos = [];\n- for (let row of result) {\n- rawUpdateInfos.push(rawUpdateInfoFromRow(row));\n- }\n-\n- return await fetchUpdateInfosWithRawUpdateInfos(\n- rawUpdateInfos,\n+ return fetchUpdateInfosWithQuery(\n{ viewer, calendarQuery },\n+ query,\n);\n}\n@@ -118,14 +123,10 @@ function rawUpdateInfoFromRow(row: Object): RawUpdateInfo {\n}\nconst entryIDExtractString = \"$.entryID\";\n-async function fetchUpdateInfoForEntryCreation(\n+function fetchUpdateInfoForEntryCreation(\nviewer: Viewer,\nentryID: string,\n): Promise<FetchUpdatesResult> {\n- if (!viewer.loggedIn) {\n- throw new ServerError('not_logged_in');\n- }\n-\nconst query = SQL`\nSELECT id, type, content, time\nFROM updates\n@@ -135,20 +136,28 @@ async function fetchUpdateInfoForEntryCreation(\nORDER BY time DESC\nLIMIT 1\n`;\n- const [ result ] = await dbQuery(query);\n-\n- const rawUpdateInfos = [];\n- for (let row of result) {\n- rawUpdateInfos.push(rawUpdateInfoFromRow(row));\n+ return fetchUpdateInfosWithQuery({ viewer }, query);\n}\n- return await fetchUpdateInfosWithRawUpdateInfos(\n- rawUpdateInfos,\n- { viewer },\n- );\n+const threadIDExtractString = \"$.threadID\";\n+function fetchUpdateInfoForThreadDeletion(\n+ viewer: Viewer,\n+ threadID: string,\n+): Promise<FetchUpdatesResult> {\n+ const query = SQL`\n+ SELECT id, type, content, time\n+ FROM updates\n+ WHERE user = ${viewer.id} AND\n+ type = ${updateTypes.DELETE_THREAD} AND\n+ JSON_EXTRACT(content, ${threadIDExtractString}) = ${threadID}\n+ ORDER BY time DESC\n+ LIMIT 1\n+ `;\n+ return fetchUpdateInfosWithQuery({ viewer }, query);\n}\nexport {\nfetchUpdateInfos,\nfetchUpdateInfoForEntryCreation,\n+ fetchUpdateInfoForThreadDeletion,\n};\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [server] Make thread deletion idempotent |
129,187 | 21.11.2018 00:06:22 | 28,800 | 434abef584b532a199f239425d8a3e9ed6b90e32 | [server] Make entry deletion and restoration idempotent | [
{
"change_type": "MODIFY",
"old_path": "server/src/creators/entry-creator.js",
"new_path": "server/src/creators/entry-creator.js",
"diff": "@@ -23,8 +23,8 @@ import {\ncreateUpdateDatasForChangedEntryInfo,\n} from '../updaters/entry-updaters';\nimport { fetchEntryInfoForLocalID } from '../fetchers/entry-fetchers';\n-import { fetchMessageInfoForEntryCreation } from '../fetchers/message-fetchers';\n-import { fetchUpdateInfoForEntryCreation } from '../fetchers/update-fetchers';\n+import { fetchMessageInfoForEntryAction } from '../fetchers/message-fetchers';\n+import { fetchUpdateInfoForEntryUpdate } from '../fetchers/update-fetchers';\nimport { creationString } from '../utils/idempotent';\nasync function createEntry(\n@@ -51,8 +51,13 @@ async function createEntry(\nconst { id: entryID, threadID } = existingEntryInfo;\ninvariant(entryID, \"should be set\");\nconst [ rawMessageInfo, fetchUpdatesResult ] = await Promise.all([\n- fetchMessageInfoForEntryCreation(viewer, entryID, threadID),\n- fetchUpdateInfoForEntryCreation(viewer, entryID),\n+ fetchMessageInfoForEntryAction(\n+ viewer,\n+ messageTypes.CREATE_ENTRY,\n+ entryID,\n+ threadID,\n+ ),\n+ fetchUpdateInfoForEntryUpdate(viewer, entryID),\n]);\nreturn {\nentryID,\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/deleters/entry-deleters.js",
"new_path": "server/src/deleters/entry-deleters.js",
"diff": "@@ -13,6 +13,7 @@ import type {\nimport { ServerError } from 'lib/utils/errors';\nimport { dateString } from 'lib/utils/date-utils';\n+import { values } from 'lib/utils/objects';\nimport { dbQuery, SQL } from '../database';\nimport { checkThreadPermissionForEntry } from '../fetchers/entry-fetchers';\n@@ -21,6 +22,8 @@ import createMessages from '../creators/message-creator';\nimport {\ncreateUpdateDatasForChangedEntryInfo,\n} from '../updaters/entry-updaters';\n+import { fetchMessageInfoForEntryAction } from '../fetchers/message-fetchers';\n+import { fetchUpdateInfoForEntryUpdate } from '../fetchers/update-fetchers';\nconst lastRevisionQuery = (entryID: string) =>\n(SQL`\n@@ -57,8 +60,25 @@ async function deleteEntry(\nthrow new ServerError('unknown_error');\n}\nconst lastRevisionRow = lastRevisionResult[0];\n+ const threadID = lastRevisionRow.thread.toString();\nif (lastRevisionRow.deleted) {\n- throw new ServerError('entry_deleted');\n+ const [ rawMessageInfo, fetchUpdatesResult ] = await Promise.all([\n+ fetchMessageInfoForEntryAction(\n+ viewer,\n+ messageTypes.DELETE_ENTRY,\n+ request.entryID,\n+ threadID,\n+ ),\n+ fetchUpdateInfoForEntryUpdate(viewer, request.entryID),\n+ ]);\n+ return {\n+ threadID,\n+ newMessageInfos: rawMessageInfo ? [ rawMessageInfo ] : [],\n+ updatesResult: {\n+ viewerUpdates: fetchUpdatesResult.updateInfos,\n+ userInfos: values(fetchUpdatesResult.userInfos),\n+ },\n+ };\n}\nconst text = lastRevisionRow.text;\n@@ -96,7 +116,6 @@ async function deleteEntry(\nVALUES ${[revisionRow]}\n`));\n- const threadID = lastRevisionRow.thread.toString();\nconst messageData = {\ntype: messageTypes.DELETE_ENTRY,\nthreadID,\n@@ -159,11 +178,38 @@ async function restoreEntry(\nthrow new ServerError('unknown_error');\n}\nconst lastRevisionRow = lastRevisionResult[0];\n- if (!lastRevisionRow.deleted) {\n- throw new ServerError('entry_not_deleted');\n+ const oldEntryInfo = {\n+ id: request.entryID,\n+ threadID: lastRevisionRow.thread.toString(),\n+ text: lastRevisionRow.text,\n+ year: lastRevisionRow.year,\n+ month: lastRevisionRow.month,\n+ day: lastRevisionRow.day,\n+ creationTime: lastRevisionRow.creation_time,\n+ creatorID: lastRevisionRow.creator.toString(),\n+ deleted: !!lastRevisionRow.deleted,\n+ };\n+\n+ if (!oldEntryInfo.deleted) {\n+ const [ rawMessageInfo, fetchUpdatesResult ] = await Promise.all([\n+ fetchMessageInfoForEntryAction(\n+ viewer,\n+ messageTypes.RESTORE_ENTRY,\n+ request.entryID,\n+ oldEntryInfo.threadID,\n+ ),\n+ fetchUpdateInfoForEntryUpdate(viewer, request.entryID),\n+ ]);\n+ return {\n+ entryInfo: oldEntryInfo,\n+ newMessageInfos: rawMessageInfo ? [ rawMessageInfo ] : [],\n+ updatesResult: {\n+ viewerUpdates: fetchUpdatesResult.updateInfos,\n+ userInfos: values(fetchUpdatesResult.userInfos),\n+ },\n+ };\n}\n- const text = lastRevisionRow.text;\nconst viewerID = viewer.userID;\nconst dbPromises = [];\ndbPromises.push(dbQuery(SQL`\n@@ -174,7 +220,7 @@ async function restoreEntry(\nrevisionID,\nrequest.entryID,\nviewerID,\n- text,\n+ oldEntryInfo.text,\nrequest.timestamp,\nviewer.session,\nrequest.timestamp,\n@@ -186,27 +232,14 @@ async function restoreEntry(\nVALUES ${[revisionRow]}\n`));\n- const threadID = lastRevisionRow.thread.toString();\nconst messageData = {\ntype: messageTypes.RESTORE_ENTRY,\n- threadID,\n+ threadID: oldEntryInfo.threadID,\ncreatorID: viewerID,\ntime: Date.now(),\nentryID: request.entryID.toString(),\ndate: dateString(lastRevisionRow.date),\n- text,\n- };\n-\n- const oldEntryInfo = {\n- id: request.entryID,\n- threadID,\n- text,\n- year: lastRevisionRow.year,\n- month: lastRevisionRow.month,\n- day: lastRevisionRow.day,\n- creationTime: lastRevisionRow.creation_time,\n- creatorID: lastRevisionRow.creator.toString(),\n- deleted: true,\n+ text: oldEntryInfo.text,\n};\nconst newEntryInfo = {\n...oldEntryInfo,\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/fetchers/message-fetchers.js",
"new_path": "server/src/fetchers/message-fetchers.js",
"diff": "@@ -5,6 +5,7 @@ import type { UserInfos } from 'lib/types/user-types';\nimport {\ntype RawMessageInfo,\nmessageTypes,\n+ type MessageType,\nassertMessageType,\ntype ThreadSelectionCriteria,\ntype MessageTruncationStatus,\n@@ -584,8 +585,9 @@ async function fetchMessageInfoForLocalID(\n}\nconst entryIDExtractString = \"$.entryID\";\n-async function fetchMessageInfoForEntryCreation(\n+async function fetchMessageInfoForEntryAction(\nviewer: Viewer,\n+ messageType: MessageType,\nentryID: string,\nthreadID: string,\n): Promise<?RawMessageInfo> {\n@@ -596,7 +598,7 @@ async function fetchMessageInfoForEntryCreation(\nFROM messages m\nLEFT JOIN memberships mm ON mm.thread = m.thread AND mm.user = ${viewerID}\nWHERE m.user = ${viewerID} AND m.thread = ${threadID} AND\n- m.type = ${messageTypes.CREATE_ENTRY} AND\n+ m.type = ${messageType} AND\nJSON_EXTRACT(m.content, ${entryIDExtractString}) = ${entryID} AND\nJSON_EXTRACT(mm.permissions, ${visibleExtractString}) IS TRUE\n`;\n@@ -614,5 +616,5 @@ export {\nfetchMessageInfosSince,\ngetMessageFetchResultFromRedisMessages,\nfetchMessageInfoForLocalID,\n- fetchMessageInfoForEntryCreation,\n+ fetchMessageInfoForEntryAction,\n};\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/fetchers/update-fetchers.js",
"new_path": "server/src/fetchers/update-fetchers.js",
"diff": "@@ -123,7 +123,7 @@ function rawUpdateInfoFromRow(row: Object): RawUpdateInfo {\n}\nconst entryIDExtractString = \"$.entryID\";\n-function fetchUpdateInfoForEntryCreation(\n+function fetchUpdateInfoForEntryUpdate(\nviewer: Viewer,\nentryID: string,\n): Promise<FetchUpdatesResult> {\n@@ -158,6 +158,6 @@ function fetchUpdateInfoForThreadDeletion(\nexport {\nfetchUpdateInfos,\n- fetchUpdateInfoForEntryCreation,\n+ fetchUpdateInfoForEntryUpdate,\nfetchUpdateInfoForThreadDeletion,\n};\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [server] Make entry deletion and restoration idempotent |
129,187 | 21.11.2018 16:44:41 | 28,800 | 4f7845b65fb1f31acb91762f86bc502f47c7a1fd | [lib] Don't crash if persisted store nonexistant | [
{
"change_type": "MODIFY",
"old_path": "lib/selectors/local-id-selectors.js",
"new_path": "lib/selectors/local-id-selectors.js",
"diff": "@@ -16,6 +16,7 @@ function numberFromLocalID(localID: string) {\nfunction highestLocalIDSelector(state: BaseAppState<*>): number {\nlet highestLocalIDFound = -1;\n+ if (state && state.messageStore) {\nfor (let messageKey in state.messageStore.messages) {\nconst messageInfo = state.messageStore.messages[messageKey];\nif (messageInfo.type !== messageTypes.TEXT) {\n@@ -30,7 +31,9 @@ function highestLocalIDSelector(state: BaseAppState<*>): number {\nhighestLocalIDFound = thisLocalID;\n}\n}\n+ }\n+ if (state && state.entryStore) {\nfor (let entryKey in state.entryStore.entryInfos) {\nconst localID = state.entryStore.entryInfos[entryKey].localID;\nif (!localID) {\n@@ -41,6 +44,7 @@ function highestLocalIDSelector(state: BaseAppState<*>): number {\nhighestLocalIDFound = thisLocalID;\n}\n}\n+ }\nreturn highestLocalIDFound;\n}\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [lib] Don't crash if persisted store nonexistant |
129,187 | 21.11.2018 16:45:28 | 28,800 | c93c14fe4654492f9fcd29a1a1e14bf47b5f4674 | [lib] Fix timeout connection close behavior | [
{
"change_type": "MODIFY",
"old_path": "lib/socket/socket.react.js",
"new_path": "lib/socket/socket.react.js",
"diff": "@@ -114,7 +114,7 @@ class Socket extends React.PureComponent<Props, State> {\nsocket: ?WebSocket;\nnextClientMessageID = 0;\nlisteners: Set<SocketListener> = new Set();\n- pingTimeoutID: ?TimeoutID\n+ pingTimeoutID: ?TimeoutID;\ninitialPlatformDetailsSent = getConfig().platformDetails === \"web\";\nreopenConnectionAfterClosing = false;\n@@ -160,7 +160,7 @@ class Socket extends React.PureComponent<Props, State> {\ninflightRequests: new InflightRequests(\n() => {\nif (this.socket === socket) {\n- this.handleTimeout();\n+ this.finishClosingSocket();\n}\n},\n),\n@@ -425,30 +425,6 @@ class Socket extends React.PureComponent<Props, State> {\n}\n}\n- handleTimeout() {\n- this.setState({ inflightRequests: null });\n- const { status } = this.props.connection;\n- if (this.socket && this.socket.readyState < 2) {\n- // We just call close, onClose will handle the rest\n- this.socket.close();\n- if (status !== \"disconnecting\") {\n- this.props.dispatchActionPayload(\n- updateConnectionStatusActionType,\n- { status: \"disconnecting\" },\n- );\n- }\n- } else {\n- this.socket = null;\n- this.stopPing();\n- if (status !== \"disconnected\") {\n- this.props.dispatchActionPayload(\n- updateConnectionStatusActionType,\n- { status: \"disconnected\" },\n- );\n- }\n- }\n- }\n-\nasync sendInitialMessage() {\nconst { inflightRequests } = this.state;\ninvariant(\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [lib] Fix timeout connection close behavior |
129,187 | 22.11.2018 17:53:56 | 28,800 | 9ecbc028cc26c8807bd492199424a3a042b8170f | Track late responses in Redux
This is so we can show the "disconnected" bar a bit earlier. | [
{
"change_type": "MODIFY",
"old_path": "lib/reducers/connection-reducer.js",
"new_path": "lib/reducers/connection-reducer.js",
"diff": "@@ -9,6 +9,7 @@ import {\nupdateConnectionStatusActionType,\nfullStateSyncActionType,\nincrementalStateSyncActionType,\n+ setLateResponseActionType,\n} from '../types/socket-types';\nimport { defaultCalendarQuery } from '../types/entry-types';\nimport { queueActivityUpdatesActionType } from '../types/activity-types';\n@@ -30,7 +31,7 @@ export default function reduceConnectionInfo(\naction: BaseAction,\n): ConnectionInfo {\nif (action.type === updateConnectionStatusActionType) {\n- return { ...state, status: action.payload.status };\n+ return { ...state, status: action.payload.status, lateResponses: [] };\n} else if (action.type === queueActivityUpdatesActionType) {\nconst { activityUpdates } = action.payload;\nreturn {\n@@ -103,7 +104,17 @@ export default function reduceConnectionInfo(\nreturn {\n...action.payload.connection,\nstatus: \"connecting\",\n+ lateResponses: [],\n};\n+ } else if (action.type === setLateResponseActionType) {\n+ const { messageID, isLate } = action.payload;\n+ const lateResponsesSet = new Set(state.lateResponses);\n+ if (isLate) {\n+ lateResponsesSet.add(messageID);\n+ } else {\n+ lateResponsesSet.delete(messageID);\n+ }\n+ return { ...state, lateResponses: [...lateResponsesSet] };\n}\nreturn state;\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/socket/inflight-requests.js",
"new_path": "lib/socket/inflight-requests.js",
"diff": "@@ -14,7 +14,10 @@ import {\nimport invariant from 'invariant';\nimport { ServerError, ExtendableError } from '../utils/errors';\n-import { clientRequestSocketTimeout } from '../shared/timeouts';\n+import {\n+ clientRequestVisualTimeout,\n+ clientRequestSocketTimeout,\n+} from '../shared/timeouts';\nimport sleep from '../utils/sleep';\ntype ValidResponseMessageMap = {\n@@ -38,6 +41,9 @@ type InflightRequestMap = $ObjMap<\ntype ValidResponseMessage = $Values<ValidResponseMessageMap>;\ntype InflightRequest = $Values<InflightRequestMap>;\n+const remainingTimeAfterVisualTimeout =\n+ clientRequestSocketTimeout - clientRequestVisualTimeout;\n+\nclass SocketOffline extends ExtendableError { }\nclass SocketTimeout extends ExtendableError {\n@@ -47,18 +53,19 @@ class SocketTimeout extends ExtendableError {\nthis.expectedResponseType = expectedType;\n}\n}\n-async function timeout(expectedType: ServerSocketMessageType) {\n- await sleep(clientRequestSocketTimeout);\n- throw new SocketTimeout(expectedType);\n-}\n-\n+type Callbacks = {|\n+ timeout: () => void,\n+ setLateResponse: (messageID: number, isLate: bool) => void,\n+|};\nclass InflightRequests {\ndata: InflightRequest[] = [];\ntimeoutCallback: () => void;\n+ setLateResponse: (messageID: number, isLate: bool) => void;\n- constructor(timeoutCallback: () => void) {\n- this.timeoutCallback = timeoutCallback;\n+ constructor(callbacks: Callbacks) {\n+ this.timeoutCallback = callbacks.timeout;\n+ this.setLateResponse = callbacks.setLateResponse;\n}\nasync fetchResponse<M: ValidResponseMessage>(\n@@ -113,11 +120,21 @@ class InflightRequests {\n`${expectedType} is an invalid server response type`,\n);\nthis.data.push(inflightRequest);\n+\n+ // We create this object so we can pass it by reference to the timeout\n+ // function below. That function will avoid setting this request as late if\n+ // the response has already arrived.\n+ const requestResult = { success: false, lateResponse: false };\n+\ntry {\nconst response = await Promise.race([\nresponsePromise,\n- timeout(expectedType),\n+ this.timeout(messageID, expectedType, requestResult),\n]);\n+ requestResult.success = true;\n+ if (requestResult.lateResponse) {\n+ this.setLateResponse(messageID, false);\n+ }\nthis.clearRequest(inflightRequest);\nreturn response;\n} catch (e) {\n@@ -130,6 +147,24 @@ class InflightRequests {\n}\n}\n+ async timeout(\n+ messageID: number,\n+ expectedType: ServerSocketMessageType,\n+ requestResult: {| success: bool, lateResponse: bool |},\n+ ) {\n+ await sleep(clientRequestVisualTimeout);\n+ if (requestResult.success) {\n+ // We're just doing this to bail out. If requestResult.success, we can\n+ // conclude that responsePromise already won the race. Returning here\n+ // gives Flow errors since Flow is worried response will be undefined.\n+ throw new Error();\n+ }\n+ requestResult.lateResponse = true;\n+ this.setLateResponse(messageID, true);\n+ await sleep(remainingTimeAfterVisualTimeout);\n+ throw new SocketTimeout(expectedType);\n+ }\n+\nclearRequest(requestToClear: InflightRequest) {\nthis.data = this.data.filter(request => request !== requestToClear);\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/socket/socket.react.js",
"new_path": "lib/socket/socket.react.js",
"diff": "@@ -31,6 +31,7 @@ import {\ntype ClientSocketMessageWithoutID,\ntype SocketListener,\ntype ConnectionStatus,\n+ setLateResponseActionType,\n} from '../types/socket-types';\nimport type { Dispatch } from '../types/redux-types';\nimport type {\n@@ -157,13 +158,14 @@ class Socket extends React.PureComponent<Props, State> {\n};\nthis.socket = socket;\nthis.setState({\n- inflightRequests: new InflightRequests(\n- () => {\n+ inflightRequests: new InflightRequests({\n+ timeout: () => {\nif (this.socket === socket) {\nthis.finishClosingSocket();\n}\n},\n- ),\n+ setLateResponse: this.setLateResponse,\n+ }),\n});\n}\n@@ -612,6 +614,13 @@ class Socket extends React.PureComponent<Props, State> {\n}\n}\n+ setLateResponse = (messageID: number, isLate: bool) => {\n+ this.props.dispatchActionPayload(\n+ setLateResponseActionType,\n+ { messageID, isLate },\n+ );\n+ }\n+\n}\nexport default Socket;\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/types/redux-types.js",
"new_path": "lib/types/redux-types.js",
"diff": "@@ -60,6 +60,7 @@ import type {\nStateSyncFullActionPayload,\nStateSyncIncrementalActionPayload,\nUpdateConnectionStatusPayload,\n+ SetLateResponsePayload,\n} from '../types/socket-types';\nimport type { UpdatesResultWithUserInfos } from '../types/update-types';\nimport type {\n@@ -598,6 +599,9 @@ export type BaseAction =\n|} | {|\ntype: \"MESSAGE_STORE_PRUNE\",\npayload: MessageStorePrunePayload,\n+ |} | {|\n+ type: \"SET_LATE_RESPONSE\",\n+ payload: SetLateResponsePayload,\n|};\nexport type ActionPayload\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/types/socket-types.js",
"new_path": "lib/types/socket-types.js",
"diff": "@@ -17,6 +17,7 @@ import {\ntype RawEntryInfo,\ntype CalendarQuery,\ndefaultCalendarQuery,\n+ calendarQueryPropType,\n} from './entry-types';\nimport {\ntype ActivityUpdate,\n@@ -245,6 +246,7 @@ export type ConnectionInfo = {|\nstatus: ConnectionStatus,\nqueuedActivityUpdates: $ReadOnlyArray<ActivityUpdate>,\nactualizedCalendarQuery: CalendarQuery,\n+ lateResponses: $ReadOnlyArray<number>,\n|};\nexport const connectionStatusPropType = PropTypes.oneOf([\n\"connecting\",\n@@ -257,13 +259,22 @@ export const connectionStatusPropType = PropTypes.oneOf([\nexport const connectionInfoPropType = PropTypes.shape({\nstatus: connectionStatusPropType.isRequired,\nqueuedActivityUpdates: PropTypes.arrayOf(activityUpdatePropType).isRequired,\n+ actualizedCalendarQuery: calendarQueryPropType.isRequired,\n+ lateResponses: PropTypes.arrayOf(PropTypes.number).isRequired,\n});\nexport const defaultConnectionInfo = (platform: Platform) => ({\nstatus: \"connecting\",\nqueuedActivityUpdates: [],\nactualizedCalendarQuery: defaultCalendarQuery(platform),\n+ lateResponses: [],\n});\nexport const updateConnectionStatusActionType = \"UPDATE_CONNECTION_STATUS\";\nexport type UpdateConnectionStatusPayload = {|\nstatus: ConnectionStatus,\n|};\n+\n+export const setLateResponseActionType = \"SET_LATE_RESPONSE\";\n+export type SetLateResponsePayload = {|\n+ messageID: number,\n+ isLate: bool,\n+|};\n"
},
{
"change_type": "MODIFY",
"old_path": "native/navigation/disconnected-bar.react.js",
"new_path": "native/navigation/disconnected-bar.react.js",
"diff": "@@ -8,11 +8,13 @@ import {\nimport * as React from 'react';\nimport { View, Text, StyleSheet, LayoutAnimation } from 'react-native';\n+import PropTypes from 'prop-types';\nimport { connect } from 'lib/utils/redux-utils';\ntype Props = {|\nconnectionStatus: ConnectionStatus,\n+ someRequestIsLate: bool,\n|};\ntype State = {|\ndisconnected: bool,\n@@ -21,20 +23,25 @@ class DisconnectedBar extends React.PureComponent<Props, State> {\nstatic propTypes = {\nconnectionStatus: connectionStatusPropType.isRequired,\n+ someRequestIsLate: PropTypes.bool.isRequired,\n};\nstate = {\ndisconnected: false,\n};\ncomponentDidUpdate(prevProps: Props, prevState: State) {\n- const { connectionStatus } = this.props;\n- const { disconnected } = this.state;\n- if (connectionStatus !== \"disconnected\") {\n- if (connectionStatus === \"reconnecting\" && !disconnected) {\n- this.setState({ disconnected: true });\n- } else if (connectionStatus !== \"reconnecting\" && disconnected) {\n- this.setState({ disconnected: false });\n+ const { connectionStatus, someRequestIsLate } = this.props;\n+\n+ let newDisconnected;\n+ if (someRequestIsLate) {\n+ newDisconnected = true;\n+ } else if (connectionStatus !== \"disconnected\") {\n+ newDisconnected = connectionStatus === \"reconnecting\";\n}\n+\n+ const { disconnected } = this.state;\n+ if (newDisconnected !== undefined && newDisconnected !== disconnected) {\n+ this.setState({ disconnected: newDisconnected });\n}\nif (this.state.disconnected !== prevState.disconnected) {\n@@ -77,4 +84,5 @@ const styles = StyleSheet.create({\nexport default connect((state: AppState) => ({\nconnectionStatus: state.connection.status,\n+ someRequestIsLate: state.connection.lateResponses.length !== 0,\n}))(DisconnectedBar);\n"
},
{
"change_type": "MODIFY",
"old_path": "native/persist.js",
"new_path": "native/persist.js",
"diff": "@@ -90,6 +90,10 @@ const migrations = {\n[9]: (state: AppState) => ({\n...state,\nnextLocalID: highestLocalIDSelector(state),\n+ connection: {\n+ ...state.connection,\n+ lateResponses: [],\n+ },\n}),\n};\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | Track late responses in Redux
This is so we can show the "disconnected" bar a bit earlier. |
129,187 | 22.11.2018 23:11:37 | 28,800 | cf5ca8efb65862f017f87dff37f3a6ea956b9ee8 | [native] Use NetInfo to preemptively identify when network is down | [
{
"change_type": "MODIFY",
"old_path": "native/android/app/src/main/AndroidManifest.xml",
"new_path": "native/android/app/src/main/AndroidManifest.xml",
"diff": "<uses-permission android:name=\"android.permission.RECEIVE_BOOT_COMPLETED\" />\n<uses-permission android:name=\"android.permission.VIBRATE\" />\n<uses-permission android:name=\"android.permission.READ_PHONE_STATE\" tools:node=\"remove\" />\n+ <uses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\" />\n<application\nandroid:name=\".MainApplication\"\n"
},
{
"change_type": "MODIFY",
"old_path": "native/navigation/disconnected-bar.react.js",
"new_path": "native/navigation/disconnected-bar.react.js",
"diff": "@@ -7,7 +7,7 @@ import {\n} from 'lib/types/socket-types';\nimport * as React from 'react';\n-import { View, Text, StyleSheet, LayoutAnimation } from 'react-native';\n+import { View, Text, StyleSheet, LayoutAnimation, NetInfo } from 'react-native';\nimport PropTypes from 'prop-types';\nimport { connect } from 'lib/utils/redux-utils';\n@@ -28,12 +28,35 @@ class DisconnectedBar extends React.PureComponent<Props, State> {\nstate = {\ndisconnected: false,\n};\n+ networkActive = true;\n+\n+ componentDidMount() {\n+ NetInfo.addEventListener(\n+ 'connectionChange',\n+ this.handleConnectionChange,\n+ );\n+ NetInfo.getConnectionInfo().then(this.handleConnectionChange);\n+ }\n+\n+ componentWillUnmount() {\n+ NetInfo.removeEventListener(\n+ 'connectionChange',\n+ this.handleConnectionChange,\n+ );\n+ }\n+\n+ handleConnectionChange = connectionInfo => {\n+ this.networkActive = connectionInfo.type !== \"none\";\n+ if (!this.networkActive && !this.state.disconnected) {\n+ this.setState({ disconnected: true });\n+ }\n+ }\ncomponentDidUpdate(prevProps: Props, prevState: State) {\nconst { connectionStatus, someRequestIsLate } = this.props;\nlet newDisconnected;\n- if (someRequestIsLate) {\n+ if (!this.networkActive || someRequestIsLate) {\nnewDisconnected = true;\n} else if (connectionStatus !== \"disconnected\") {\nnewDisconnected = connectionStatus === \"reconnecting\";\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Use NetInfo to preemptively identify when network is down |
129,187 | 23.11.2018 15:50:44 | 28,800 | 75cab8a73944756b098436e1bcb65b10268f1108 | [server] Fix up server delivery result format
And avoid duplicate notification row writes. | [
{
"change_type": "MODIFY",
"old_path": "server/src/push/rescind.js",
"new_path": "server/src/push/rescind.js",
"diff": "@@ -26,7 +26,12 @@ async function rescindPushNotifs(\nconst promises = [];\nconst rescindedIDs = [];\nfor (let row of fetchResult) {\n- if (row.delivery.iosID) {\n+ const deliveries = Array.isArray(row.delivery)\n+ ? row.delivery\n+ : [ row.delivery ];\n+ for (let delivery of row.delivery) {\n+ if (row.delivery.iosID && row.delivery.iosDeviceTokens) {\n+ // Old iOS\nconst notification = prepareIOSNotification(\nrow.delivery.iosID,\nrow.unread_count,\n@@ -35,8 +40,8 @@ async function rescindPushNotifs(\nnotification,\nrow.delivery.iosDeviceTokens,\n));\n- }\n- if (row.delivery.androidID) {\n+ } else if (row.delivery.androidID) {\n+ // Old Android\nconst notification = prepareAndroidNotification(\nrow.collapse_key ? row.collapse_key : row.id.toString(),\nrow.unread_count,\n@@ -46,10 +51,8 @@ async function rescindPushNotifs(\nrow.delivery.androidDeviceTokens,\nnull,\n));\n- }\n- if (Array.isArray(row.delivery)) {\n- for (let delivery of row.delivery) {\n- if (delivery.deviceType === \"ios\") {\n+ } else if (delivery.deviceType === \"ios\") {\n+ // New iOS\nconst { iosID, deviceTokens } = delivery;\nconst notification = prepareIOSNotification(\niosID,\n@@ -60,6 +63,7 @@ async function rescindPushNotifs(\ndeviceTokens,\n));\n} else if (delivery.deviceType === \"android\") {\n+ // New Android\nconst { deviceTokens } = delivery;\nconst notification = prepareAndroidNotification(\nrow.collapse_key ? row.collapse_key : row.id.toString(),\n@@ -72,7 +76,6 @@ async function rescindPushNotifs(\n));\n}\n}\n- }\nrescindedIDs.push(row.id);\n}\nif (rescindedIDs.length > 0) {\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/push/send.js",
"new_path": "server/src/push/send.js",
"diff": "@@ -50,6 +50,15 @@ type PushUserInfo = {|\ndevices: Device[],\nmessageInfos: RawMessageInfo[],\n|};\n+type Delivery = IOSDelivery | AndroidDelivery | {| collapsedInto: string |};\n+type NotificationRow = {|\n+ dbID: string,\n+ userID: string,\n+ threadID: string,\n+ messageID: string,\n+ collapseKey: ?string,\n+ deliveries: Delivery[];\n+|};\nexport type PushInfo = { [userID: string]: PushUserInfo };\nasync function sendPushNotifs(pushInfo: PushInfo) {\n@@ -68,7 +77,7 @@ async function sendPushNotifs(pushInfo: PushInfo) {\n]);\nconst deliveryPromises = [];\n- const notifications = [];\n+ const notifications: Map<string, NotificationRow> = new Map();\nfor (let userID in usersToCollapsableNotifInfo) {\nconst threadInfos = _flow(\n_mapValues(\n@@ -187,15 +196,16 @@ async function sendPushNotifs(pushInfo: PushInfo) {\nfor (let newMessageInfo of remainingNewMessageInfos) {\nconst newDBID = dbIDs.shift();\ninvariant(newDBID, \"should have sufficient DB IDs\");\n- notifications.push([\n- newDBID,\n+ const messageID = newMessageInfo.id;\n+ invariant(messageID, \"RawMessageInfo.id should be set on server\");\n+ notifications.set(newDBID, {\n+ dbID: newDBID,\nuserID,\n- newMessageInfo.threadID,\n- newMessageInfo.id,\n- notifInfo.collapseKey,\n- JSON.stringify({ collapsedInto: dbID }),\n- 0,\n- ]);\n+ threadID: newMessageInfo.threadID,\n+ messageID,\n+ collapseKey: notifInfo.collapseKey,\n+ deliveries: [ { collapsedInto: dbID } ],\n+ });\n}\n}\n}\n@@ -213,16 +223,21 @@ async function sendPushNotifs(pushInfo: PushInfo) {\nconst allInvalidTokens = [];\nfor (let deliveryResult of deliveryResults) {\nconst { info, delivery, invalidTokens } = deliveryResult;\n- const { dbID, userID, threadID, messageID, collapseKey } = info;\n- notifications.push([\n+ const { dbID, userID } = info;\n+ const curNotifRow = notifications.get(dbID);\n+ if (curNotifRow) {\n+ curNotifRow.deliveries.push(delivery);\n+ } else {\n+ const { threadID, messageID, collapseKey } = info;\n+ notifications.set(dbID, {\ndbID,\nuserID,\nthreadID,\nmessageID,\ncollapseKey,\n- JSON.stringify(delivery),\n- 0,\n- ]);\n+ deliveries: [ delivery ],\n+ });\n+ }\nif (invalidTokens) {\nallInvalidTokens.push({\nuserID,\n@@ -231,15 +246,28 @@ async function sendPushNotifs(pushInfo: PushInfo) {\n}\n}\n+ const notificationRows = [];\n+ for (let notification of notifications.values()) {\n+ notificationRows.push([\n+ notification.dbID,\n+ notification.userID,\n+ notification.threadID,\n+ notification.messageID,\n+ notification.collapseKey,\n+ JSON.stringify(notification.deliveries),\n+ 0,\n+ ]);\n+ }\n+\nconst dbPromises = [];\nif (allInvalidTokens.length > 0) {\ndbPromises.push(removeInvalidTokens(allInvalidTokens));\n}\n- if (notifications.length > 0) {\n+ if (notificationRows.length > 0) {\nconst query = SQL`\nINSERT INTO notifications\n(id, user, thread, message, collapse_key, delivery, rescinded)\n- VALUES ${notifications}\n+ VALUES ${notificationRows}\n`;\ndbPromises.push(dbQuery(query));\n}\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [server] Fix up server delivery result format
And avoid duplicate notification row writes. |
129,187 | 23.11.2018 16:02:04 | 28,800 | f2700b7fcd4f17832131f1ae37b78d907327f1b5 | [native] Fix up DisconnectedBar to use NetInfo.isConnected
And don't count "connecting" as a change in connection status. | [
{
"change_type": "MODIFY",
"old_path": "native/navigation/disconnected-bar.react.js",
"new_path": "native/navigation/disconnected-bar.react.js",
"diff": "@@ -31,35 +31,35 @@ class DisconnectedBar extends React.PureComponent<Props, State> {\nnetworkActive = true;\ncomponentDidMount() {\n- NetInfo.addEventListener(\n+ NetInfo.isConnected.addEventListener(\n'connectionChange',\nthis.handleConnectionChange,\n);\n- NetInfo.getConnectionInfo().then(this.handleConnectionChange);\n+ NetInfo.isConnected.fetch().then(this.handleConnectionChange);\n}\ncomponentWillUnmount() {\n- NetInfo.removeEventListener(\n+ NetInfo.isConnected.removeEventListener(\n'connectionChange',\nthis.handleConnectionChange,\n);\n}\n- handleConnectionChange = connectionInfo => {\n- this.networkActive = connectionInfo.type !== \"none\";\n+ handleConnectionChange = isConnected => {\n+ this.networkActive = isConnected;\nif (!this.networkActive && !this.state.disconnected) {\nthis.setState({ disconnected: true });\n}\n}\ncomponentDidUpdate(prevProps: Props, prevState: State) {\n- const { connectionStatus, someRequestIsLate } = this.props;\n+ const { connectionStatus: status, someRequestIsLate } = this.props;\nlet newDisconnected;\nif (!this.networkActive || someRequestIsLate) {\nnewDisconnected = true;\n- } else if (connectionStatus !== \"disconnected\") {\n- newDisconnected = connectionStatus === \"reconnecting\";\n+ } else if (status !== \"disconnected\" && status !== \"connecting\") {\n+ newDisconnected = status === \"reconnecting\";\n}\nconst { disconnected } = this.state;\n@@ -67,7 +67,7 @@ class DisconnectedBar extends React.PureComponent<Props, State> {\nthis.setState({ disconnected: newDisconnected });\n}\n- if (this.state.disconnected !== prevState.disconnected) {\n+ if (disconnected !== prevState.disconnected) {\nLayoutAnimation.easeInEaseOut();\n}\n}\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Fix up DisconnectedBar to use NetInfo.isConnected
And don't count "connecting" as a change in connection status. |
129,187 | 23.11.2018 16:40:41 | 28,800 | 99933771315b09c414e3bdc57832844f865280cb | [native] Wrap entire Chat StackNavigator with KeyboardAvoidingView | [
{
"change_type": "MODIFY",
"old_path": "native/chat/chat-thread-list.react.js",
"new_path": "native/chat/chat-thread-list.react.js",
"diff": "@@ -36,7 +36,6 @@ import {\nComposeThreadRouteName,\nMessageListRouteName,\n} from '../navigation/route-names';\n-import KeyboardAvoidingView from '../components/keyboard-avoiding-view.react';\nconst floatingActions = [{\ntext: 'Compose',\n@@ -236,8 +235,8 @@ class InnerChatThreadList extends React.PureComponent<Props, State> {\n/>\n);\n}\n- const content = (\n- <React.Fragment>\n+ return (\n+ <View style={styles.container}>\n<FlatList\ndata={this.state.listData}\nrenderItem={this.renderItem}\n@@ -249,12 +248,7 @@ class InnerChatThreadList extends React.PureComponent<Props, State> {\nstyle={styles.flatList}\n/>\n{floatingAction}\n- </React.Fragment>\n- );\n- return (\n- <KeyboardAvoidingView style={styles.container}>\n- {content}\n- </KeyboardAvoidingView>\n+ </View>\n);\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "native/chat/chat.react.js",
"new_path": "native/chat/chat.react.js",
"diff": "@@ -6,8 +6,9 @@ import type {\n} from 'react-navigation';\nimport React from 'react';\n-import { Platform } from 'react-native';\n+import { Platform, StyleSheet } from 'react-native';\nimport { createStackNavigator } from 'react-navigation';\n+import hoistNonReactStatics from 'hoist-non-react-statics';\nimport ChatThreadList from './chat-thread-list.react';\nimport MessageList from './message-list.react';\n@@ -25,6 +26,7 @@ import {\nChatThreadListRouteName,\n} from '../navigation/route-names';\nimport Header from '../navigation/header.react';\n+import KeyboardAvoidingView from '../components/keyboard-avoiding-view.react';\nconst Chat = createStackNavigator(\n{\n@@ -68,4 +70,17 @@ Chat.navigationOptions = ({ navigation }) => ({\n},\n});\n-export default Chat;\n+const styles = StyleSheet.create({\n+ keyboardAvoidingView: {\n+ flex: 1,\n+ },\n+});\n+\n+const KeyboardAvoidingChat = (props: *) => (\n+ <KeyboardAvoidingView style={styles.keyboardAvoidingView}>\n+ <Chat {...props} />\n+ </KeyboardAvoidingView>\n+);\n+hoistNonReactStatics(KeyboardAvoidingChat, Chat);\n+\n+export default KeyboardAvoidingChat;\n"
},
{
"change_type": "MODIFY",
"old_path": "native/chat/compose-thread.react.js",
"new_path": "native/chat/compose-thread.react.js",
"diff": "@@ -62,7 +62,6 @@ import LinkButton from '../components/link-button.react';\nimport { MessageListRouteName } from '../navigation/route-names';\nimport { registerChatScreen } from './chat-screen-registry';\nimport ThreadVisibility from '../components/thread-visibility.react';\n-import KeyboardAvoidingView from '../components/keyboard-avoiding-view.react';\nconst tagInputProps = {\nplaceholder: \"username\",\n@@ -314,8 +313,8 @@ class InnerComposeThread extends React.PureComponent<Props, State> {\n...tagInputProps,\nonSubmitEditing: this.onPressCreateThread,\n};\n- const content = (\n- <React.Fragment>\n+ return (\n+ <View style={styles.container}>\n{parentThreadRow}\n<View style={styles.userSelectionRow}>\n<Text style={styles.tagInputLabel}>To: </Text>\n@@ -339,12 +338,7 @@ class InnerComposeThread extends React.PureComponent<Props, State> {\n/>\n</View>\n{existingThreadsSection}\n- </React.Fragment>\n- );\n- return (\n- <KeyboardAvoidingView style={styles.container}>\n- {content}\n- </KeyboardAvoidingView>\n+ </View>\n);\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "native/chat/message-list.react.js",
"new_path": "native/chat/message-list.react.js",
"diff": "@@ -56,7 +56,6 @@ import ListLoadingIndicator from '../list-loading-indicator.react';\nimport MessageListHeaderTitle from './message-list-header-title.react';\nimport { registerChatScreen } from './chat-screen-registry';\nimport ThreadSettingsButton from './thread-settings-button.react';\n-import KeyboardAvoidingView from '../components/keyboard-avoiding-view.react';\ntype NavProp =\n& {\n@@ -455,7 +454,7 @@ class InnerMessageList extends React.PureComponent<Props, State> {\nconst inputBar = <ChatInputBar threadInfo={threadInfo} />;\nreturn (\n- <KeyboardAvoidingView style={styles.container}>\n+ <View style={styles.container}>\n<TextHeightMeasurer\ntextToMeasure={this.state.textToMeasure}\nallHeightsMeasuredCallback={this.allHeightsMeasured}\n@@ -464,7 +463,7 @@ class InnerMessageList extends React.PureComponent<Props, State> {\n{flatList}\n</View>\n{inputBar}\n- </KeyboardAvoidingView>\n+ </View>\n);\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "native/package.json",
"new_path": "native/package.json",
"diff": "\"color\": \"^2.0.0\",\n\"find-root\": \"^1.1.0\",\n\"fs-extra\": \"^6.0.1\",\n+ \"hoist-non-react-statics\": \"^3.1.0\",\n\"invariant\": \"^2.2.2\",\n\"lib\": \"0.0.1\",\n\"lodash\": \"^4.17.5\",\n"
},
{
"change_type": "MODIFY",
"old_path": "yarn.lock",
"new_path": "yarn.lock",
"diff": "@@ -5236,7 +5236,7 @@ hoist-non-react-statics@^2.3.1, hoist-non-react-statics@^2.5.0:\nresolved \"https://registry.yarnpkg.com/hoist-non-react-statics/-/hoist-non-react-statics-2.5.5.tgz#c5903cf409c0dfd908f388e619d86b9c1174cb47\"\nintegrity sha512-rqcy4pJo55FTTLWt+bU8ukscqHeE/e9KWvsOW2b/a3afxQZhwkQdT1rPPCJ0rYXdj4vNcasY8zHTH+jF/qStxw==\n-hoist-non-react-statics@^3.0.0, hoist-non-react-statics@^3.0.1:\n+hoist-non-react-statics@^3.0.0, hoist-non-react-statics@^3.0.1, hoist-non-react-statics@^3.1.0:\nversion \"3.1.0\"\nresolved \"https://registry.yarnpkg.com/hoist-non-react-statics/-/hoist-non-react-statics-3.1.0.tgz#42414ccdfff019cd2168168be998c7b3bd5245c0\"\nintegrity sha512-MYcYuROh7SBM69xHGqXEwQqDux34s9tz+sCnxJmN18kgWh6JFdTw/5YdZtqsOdZJXddE/wUpCzfEdDrJj8p0Iw==\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Wrap entire Chat StackNavigator with KeyboardAvoidingView |
129,187 | 23.11.2018 16:45:13 | 28,800 | 51b01807ff1ef721d2b320099a89363473113a0b | [native] Get rid of keyboardVerticalOffset prop in KeyboardAvoidingView | [
{
"change_type": "MODIFY",
"old_path": "native/calendar/calendar.react.js",
"new_path": "native/calendar/calendar.react.js",
"diff": "@@ -757,10 +757,7 @@ class InnerCalendar extends React.PureComponent<Props, State> {\nallHeightsMeasuredCallback={this.allHeightsMeasured}\nstyle={[entryStyles.entry, entryStyles.text]}\n/>\n- <KeyboardAvoidingView\n- style={styles.keyboardAvoidingView}\n- keyboardVerticalOffset={0}\n- >\n+ <KeyboardAvoidingView style={styles.keyboardAvoidingView}>\n{loadingIndicator}\n{flatList}\n<CalendarInputBar\n"
},
{
"change_type": "MODIFY",
"old_path": "native/components/keyboard-avoiding-view.react.js",
"new_path": "native/components/keyboard-avoiding-view.react.js",
"diff": "@@ -37,7 +37,6 @@ type KeyboardChangeEvent = {\ntype Props = {|\nchildren?: React.Node,\nstyle?: ViewStyle,\n- keyboardVerticalOffset: number,\n|};\ntype State = {|\nbottom: number,\n@@ -47,10 +46,6 @@ class KeyboardAvoidingView extends React.PureComponent<Props, State> {\nstatic propTypes = {\nchildren: PropTypes.node,\nstyle: ViewPropTypes.style,\n- keyboardVerticalOffset: PropTypes.number.isRequired,\n- };\n- static defaultProps = {\n- keyboardVerticalOffset: 0,\n};\nstate = {\nbottom: 0,\n@@ -64,12 +59,9 @@ class KeyboardAvoidingView extends React.PureComponent<Props, State> {\nif (!frame || !keyboardFrame) {\nreturn 0;\n}\n-\n- const keyboardY = keyboardFrame.screenY - this.props.keyboardVerticalOffset;\n-\n// Calculate the displacement needed for the view such that it\n// no longer overlaps with the keyboard\n- return Math.max(frame.y + frame.height - keyboardY, 0);\n+ return Math.max(frame.y + frame.height - keyboardFrame.screenY, 0);\n}\nonKeyboardChange = (event: ?KeyboardChangeEvent) => {\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Get rid of keyboardVerticalOffset prop in KeyboardAvoidingView |
129,187 | 23.11.2018 17:15:48 | 28,800 | 73f3cdd4e763a8b7b5843e296824a7837f82e784 | [native] Don't persist foreground status in Redux | [
{
"change_type": "MODIFY",
"old_path": "native/persist.js",
"new_path": "native/persist.js",
"diff": "@@ -16,8 +16,8 @@ import { nativeCalendarQuery } from './selectors/nav-selectors';\nimport { defaultNotifPermissionAlertInfo } from './push/alerts';\nconst blacklist = __DEV__\n- ? [ 'loadingStatuses' ]\n- : [ 'loadingStatuses', 'navInfo' ];\n+ ? [ 'loadingStatuses', 'foreground' ]\n+ : [ 'loadingStatuses', 'foreground', 'navInfo' ];\nconst migrations = {\n[1]: (state: AppState) => ({\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Don't persist foreground status in Redux |
129,187 | 25.11.2018 17:01:56 | 28,800 | 87898f34738f36538b24018aed25b1b14adb0c19 | [native] Update logic for detecting disconnected status
Make sure a reconnect clears `DisconnectedBar`, since we can't trust `NetInfo` to always report when the network comes back online.
We still have some edge cases that only seem to happen in iOS Simulator, but otherwise hopefully we're done with detecting disconnect for the time being... | [
{
"change_type": "MODIFY",
"old_path": "native/navigation/disconnected-bar.react.js",
"new_path": "native/navigation/disconnected-bar.react.js",
"diff": "@@ -56,10 +56,17 @@ class DisconnectedBar extends React.PureComponent<Props, State> {\nconst { connectionStatus: status, someRequestIsLate } = this.props;\nlet newDisconnected;\n- if (!this.networkActive || someRequestIsLate) {\n+ if (status === \"connected\" && prevProps.connectionStatus !== \"connected\") {\n+ // Sometimes NetInfo misses the network coming back online for some\n+ // reason. But if the socket reconnects, the network must be up\n+ this.networkActive = true;\n+ newDisconnected = false;\n+ } else if (!this.networkActive || someRequestIsLate) {\nnewDisconnected = true;\n- } else if (status !== \"disconnected\" && status !== \"connecting\") {\n- newDisconnected = status === \"reconnecting\";\n+ } else if (status === \"reconnecting\" || status === \"forcedDisconnecting\") {\n+ newDisconnected = true;\n+ } else if (status === \"connected\") {\n+ newDisconnected = false;\n}\nconst { disconnected } = this.state;\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Update logic for detecting disconnected status
Make sure a reconnect clears `DisconnectedBar`, since we can't trust `NetInfo` to always report when the network comes back online.
We still have some edge cases that only seem to happen in iOS Simulator, but otherwise hopefully we're done with detecting disconnect for the time being... |
129,187 | 25.11.2018 17:11:48 | 28,800 | a348856b67e80c39c9db2e1acb829600314866a5 | codeVersion -> 25 | [
{
"change_type": "MODIFY",
"old_path": "lib/facts/version.json",
"new_path": "lib/facts/version.json",
"diff": "{\n- \"currentCodeVersion\": 24\n+ \"currentCodeVersion\": 25\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "native/android/app/build.gradle",
"new_path": "native/android/app/build.gradle",
"diff": "@@ -109,8 +109,8 @@ android {\napplicationId \"org.squadcal\"\nminSdkVersion rootProject.ext.minSdkVersion\ntargetSdkVersion rootProject.ext.targetSdkVersion\n- versionCode 24\n- versionName \"0.0.24\"\n+ versionCode 25\n+ versionName \"0.0.25\"\nndk {\nabiFilters \"armeabi-v7a\", \"x86\"\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "native/ios/SquadCal/Info.plist",
"new_path": "native/ios/SquadCal/Info.plist",
"diff": "<key>CFBundlePackageType</key>\n<string>APPL</string>\n<key>CFBundleShortVersionString</key>\n- <string>0.0.24</string>\n+ <string>0.0.25</string>\n<key>CFBundleSignature</key>\n<string>????</string>\n<key>CFBundleVersion</key>\n- <string>24</string>\n+ <string>25</string>\n<key>LSApplicationQueriesSchemes</key>\n<array>\n<string>org-appextension-feature-password-management</string>\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | codeVersion -> 25 |
129,187 | 26.11.2018 13:23:26 | 28,800 | 652a75262b6b06b39e2c77d0219390aecd3e047a | Extract DisconnectedBar visibility logic so it's shared
Determined in `DisconnectedBarVisibilityHandler`, set in Redux, and consumed by `DisconnectedBar`. | [
{
"change_type": "MODIFY",
"old_path": "lib/reducers/connection-reducer.js",
"new_path": "lib/reducers/connection-reducer.js",
"diff": "@@ -10,6 +10,7 @@ import {\nfullStateSyncActionType,\nincrementalStateSyncActionType,\nsetLateResponseActionType,\n+ updateDisconnectedBarActionType,\n} from '../types/socket-types';\nimport { defaultCalendarQuery } from '../types/entry-types';\nimport { queueActivityUpdatesActionType } from '../types/activity-types';\n@@ -105,6 +106,7 @@ export default function reduceConnectionInfo(\n...action.payload.connection,\nstatus: \"connecting\",\nlateResponses: [],\n+ showDisconnectedBar: false,\n};\n} else if (action.type === setLateResponseActionType) {\nconst { messageID, isLate } = action.payload;\n@@ -115,6 +117,8 @@ export default function reduceConnectionInfo(\nlateResponsesSet.delete(messageID);\n}\nreturn { ...state, lateResponses: [...lateResponsesSet] };\n+ } else if (action.type === updateDisconnectedBarActionType) {\n+ return { ...state, showDisconnectedBar: action.payload.visible };\n}\nreturn state;\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/types/redux-types.js",
"new_path": "lib/types/redux-types.js",
"diff": "@@ -61,6 +61,7 @@ import type {\nStateSyncIncrementalActionPayload,\nUpdateConnectionStatusPayload,\nSetLateResponsePayload,\n+ UpdateDisconnectedBarPayload,\n} from '../types/socket-types';\nimport type { UpdatesResultWithUserInfos } from '../types/update-types';\nimport type {\n@@ -602,6 +603,9 @@ export type BaseAction =\n|} | {|\ntype: \"SET_LATE_RESPONSE\",\npayload: SetLateResponsePayload,\n+ |} | {|\n+ type: \"UPDATE_DISCONNECTED_BAR\",\n+ payload: UpdateDisconnectedBarPayload,\n|};\nexport type ActionPayload\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/types/socket-types.js",
"new_path": "lib/types/socket-types.js",
"diff": "@@ -247,6 +247,7 @@ export type ConnectionInfo = {|\nqueuedActivityUpdates: $ReadOnlyArray<ActivityUpdate>,\nactualizedCalendarQuery: CalendarQuery,\nlateResponses: $ReadOnlyArray<number>,\n+ showDisconnectedBar: bool,\n|};\nexport const connectionStatusPropType = PropTypes.oneOf([\n\"connecting\",\n@@ -261,12 +262,14 @@ export const connectionInfoPropType = PropTypes.shape({\nqueuedActivityUpdates: PropTypes.arrayOf(activityUpdatePropType).isRequired,\nactualizedCalendarQuery: calendarQueryPropType.isRequired,\nlateResponses: PropTypes.arrayOf(PropTypes.number).isRequired,\n+ showDisconnectedBar: PropTypes.bool.isRequired,\n});\nexport const defaultConnectionInfo = (platform: Platform) => ({\nstatus: \"connecting\",\nqueuedActivityUpdates: [],\nactualizedCalendarQuery: defaultCalendarQuery(platform),\nlateResponses: [],\n+ showDisconnectedBar: false,\n});\nexport const updateConnectionStatusActionType = \"UPDATE_CONNECTION_STATUS\";\nexport type UpdateConnectionStatusPayload = {|\n@@ -278,3 +281,6 @@ export type SetLateResponsePayload = {|\nmessageID: number,\nisLate: bool,\n|};\n+\n+export const updateDisconnectedBarActionType = \"UPDATE_DISCONNECTED_BAR\";\n+export type UpdateDisconnectedBarPayload = {| visible: bool |};\n"
},
{
"change_type": "MODIFY",
"old_path": "native/app.react.js",
"new_path": "native/app.react.js",
"diff": "@@ -84,6 +84,8 @@ import NotificationBody from './push/notification-body.react';\nimport ErrorBoundary from './error-boundary.react';\nimport { AppRouteName } from './navigation/route-names';\nimport MessageStorePruner from './chat/message-store-pruner.react';\n+import DisconnectedBarVisibilityHandler\n+ from './navigation/disconnected-bar-visibility-handler.react';\nimport Socket from './socket.react';\nconst msInDay = 24 * 60 * 60 * 1000;\n@@ -639,6 +641,7 @@ class AppWithNavigationState extends React.PureComponent<Props> {\nref={this.inAppNotificationRef}\n/>\n<MessageStorePruner />\n+ <DisconnectedBarVisibilityHandler />\n</View>\n);\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "native/navigation/disconnected-bar-visibility-handler.react.js",
"diff": "+// @flow\n+\n+import {\n+ type ConnectionStatus,\n+ connectionStatusPropType,\n+ updateDisconnectedBarActionType,\n+} from 'lib/types/socket-types';\n+import type { DispatchActionPayload } from 'lib/utils/action-utils';\n+import type { AppState } from '../redux-setup';\n+\n+import * as React from 'react';\n+import PropTypes from 'prop-types';\n+import { NetInfo } from 'react-native';\n+\n+import { connect } from 'lib/utils/redux-utils';\n+\n+type Props = {|\n+ // Redux state\n+ showDisconnectedBar: bool,\n+ connectionStatus: ConnectionStatus,\n+ someRequestIsLate: bool,\n+ // Redux dispatch functions\n+ dispatchActionPayload: DispatchActionPayload,\n+|};\n+class DisconnectedBarVisibilityHandler extends React.PureComponent<Props> {\n+\n+ static propTypes = {\n+ showDisconnectedBar: PropTypes.bool.isRequired,\n+ connectionStatus: connectionStatusPropType.isRequired,\n+ someRequestIsLate: PropTypes.bool.isRequired,\n+ dispatchActionPayload: PropTypes.func.isRequired,\n+ };\n+ networkActive = true;\n+\n+ get disconnected() {\n+ return this.props.showDisconnectedBar;\n+ }\n+\n+ setDisconnected(disconnected: bool) {\n+ if (this.disconnected === disconnected) {\n+ return;\n+ }\n+ this.props.dispatchActionPayload(\n+ updateDisconnectedBarActionType,\n+ { visible: disconnected },\n+ );\n+ }\n+\n+ componentDidMount() {\n+ NetInfo.isConnected.addEventListener(\n+ 'connectionChange',\n+ this.handleConnectionChange,\n+ );\n+ NetInfo.isConnected.fetch().then(this.handleConnectionChange);\n+ }\n+\n+ componentWillUnmount() {\n+ NetInfo.isConnected.removeEventListener(\n+ 'connectionChange',\n+ this.handleConnectionChange,\n+ );\n+ }\n+\n+ handleConnectionChange = isConnected => {\n+ this.networkActive = isConnected;\n+ if (!this.networkActive) {\n+ this.setDisconnected(true);\n+ }\n+ }\n+\n+ componentDidUpdate(prevProps: Props) {\n+ const { connectionStatus: status, someRequestIsLate } = this.props;\n+ if (status === \"connected\" && prevProps.connectionStatus !== \"connected\") {\n+ // Sometimes NetInfo misses the network coming back online for some\n+ // reason. But if the socket reconnects, the network must be up\n+ this.networkActive = true;\n+ this.setDisconnected(false);\n+ } else if (!this.networkActive || someRequestIsLate) {\n+ this.setDisconnected(true);\n+ } else if (status === \"reconnecting\" || status === \"forcedDisconnecting\") {\n+ this.setDisconnected(true);\n+ } else if (status === \"connected\") {\n+ this.setDisconnected(false);\n+ }\n+ }\n+\n+ render() {\n+ return null;\n+ }\n+\n+}\n+\n+export default connect(\n+ (state: AppState) => ({\n+ showDisconnectedBar: state.connection.showDisconnectedBar,\n+ connectionStatus: state.connection.status,\n+ someRequestIsLate: state.connection.lateResponses.length !== 0,\n+ }),\n+ null,\n+ true,\n+)(DisconnectedBarVisibilityHandler);\n"
},
{
"change_type": "MODIFY",
"old_path": "native/navigation/disconnected-bar.react.js",
"new_path": "native/navigation/disconnected-bar.react.js",
"diff": "// @flow\nimport type { AppState } from '../redux-setup';\n-import {\n- type ConnectionStatus,\n- connectionStatusPropType,\n-} from 'lib/types/socket-types';\nimport * as React from 'react';\n-import { View, Text, StyleSheet, LayoutAnimation, NetInfo } from 'react-native';\n+import { View, Text, StyleSheet, LayoutAnimation } from 'react-native';\nimport PropTypes from 'prop-types';\nimport { connect } from 'lib/utils/redux-utils';\ntype Props = {|\n- connectionStatus: ConnectionStatus,\n- someRequestIsLate: bool,\n+ visible: bool,\n|};\n-type State = {|\n- disconnected: bool,\n-|};\n-class DisconnectedBar extends React.PureComponent<Props, State> {\n+class DisconnectedBar extends React.PureComponent<Props> {\nstatic propTypes = {\n- connectionStatus: connectionStatusPropType.isRequired,\n- someRequestIsLate: PropTypes.bool.isRequired,\n- };\n- state = {\n- disconnected: false,\n+ visible: PropTypes.bool.isRequired,\n};\n- networkActive = true;\n-\n- componentDidMount() {\n- NetInfo.isConnected.addEventListener(\n- 'connectionChange',\n- this.handleConnectionChange,\n- );\n- NetInfo.isConnected.fetch().then(this.handleConnectionChange);\n- }\n-\n- componentWillUnmount() {\n- NetInfo.isConnected.removeEventListener(\n- 'connectionChange',\n- this.handleConnectionChange,\n- );\n- }\n-\n- handleConnectionChange = isConnected => {\n- this.networkActive = isConnected;\n- if (!this.networkActive && !this.state.disconnected) {\n- this.setState({ disconnected: true });\n- }\n- }\n-\n- componentDidUpdate(prevProps: Props, prevState: State) {\n- const { connectionStatus: status, someRequestIsLate } = this.props;\n-\n- let newDisconnected;\n- if (status === \"connected\" && prevProps.connectionStatus !== \"connected\") {\n- // Sometimes NetInfo misses the network coming back online for some\n- // reason. But if the socket reconnects, the network must be up\n- this.networkActive = true;\n- newDisconnected = false;\n- } else if (!this.networkActive || someRequestIsLate) {\n- newDisconnected = true;\n- } else if (status === \"reconnecting\" || status === \"forcedDisconnecting\") {\n- newDisconnected = true;\n- } else if (status === \"connected\") {\n- newDisconnected = false;\n- }\n- const { disconnected } = this.state;\n- if (newDisconnected !== undefined && newDisconnected !== disconnected) {\n- this.setState({ disconnected: newDisconnected });\n- }\n-\n- if (disconnected !== prevState.disconnected) {\n+ componentDidUpdate(prevProps: Props) {\n+ if (this.props.visible !== prevProps.visible) {\nLayoutAnimation.easeInEaseOut();\n}\n}\nrender() {\n- const { connectionStatus } = this.props;\n- const { disconnected } = this.state;\n-\nconst disconnectedBarStyles = [ styles.disconnectedBar ];\nlet text;\n- if (disconnected) {\n+ if (this.props.visible) {\ntext = <Text style={styles.disconnectedText}>DISCONNECTED</Text>;\n} else {\ndisconnectedBarStyles.push(styles.hiddenDisconnectedBar);\n}\n-\nreturn <View style={disconnectedBarStyles}>{text}</View>;\n}\n@@ -113,6 +53,5 @@ const styles = StyleSheet.create({\n});\nexport default connect((state: AppState) => ({\n- connectionStatus: state.connection.status,\n- someRequestIsLate: state.connection.lateResponses.length !== 0,\n+ visible: state.connection.showDisconnectedBar,\n}))(DisconnectedBar);\n"
},
{
"change_type": "MODIFY",
"old_path": "native/persist.js",
"new_path": "native/persist.js",
"diff": "@@ -95,6 +95,20 @@ const migrations = {\nlateResponses: [],\n},\n}),\n+ [9]: (state: AppState) => ({\n+ ...state,\n+ connection: {\n+ ...state.connection,\n+ lateResponses: [],\n+ },\n+ }),\n+ [10]: (state: AppState) => ({\n+ ...state,\n+ connection: {\n+ ...state.connection,\n+ showDisconnectedBar: false,\n+ },\n+ }),\n};\nconst persistConfig = {\n@@ -102,7 +116,7 @@ const persistConfig = {\nstorage,\nblacklist,\ndebug: __DEV__,\n- version: 9,\n+ version: 10,\nmigrate: createMigrate(migrations, { debug: __DEV__ }),\n};\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | Extract DisconnectedBar visibility logic so it's shared
Determined in `DisconnectedBarVisibilityHandler`, set in Redux, and consumed by `DisconnectedBar`. |
129,187 | 26.11.2018 15:00:43 | 28,800 | d7a61e5bce26b0b2f76d6f339fb5ea46f7f3d0a5 | Introducing LocalMessageInfo
Will track messages that failed to send. This commit also makes it so those messages don't just disappear anymore. | [
{
"change_type": "MODIFY",
"old_path": "lib/reducers/message-reducer.js",
"new_path": "lib/reducers/message-reducer.js",
"diff": "import {\ntype RawMessageInfo,\ntype ThreadMessageInfo,\n+ type LocalMessageInfo,\ntype MessageStore,\ntype MessageTruncationStatus,\ntype MessagesResponse,\n@@ -134,7 +135,7 @@ function freshMessageStore(\nlastPruned,\n};\n}\n- return { messages, threads, currentAsOf };\n+ return { messages, threads, local: {}, currentAsOf };\n}\n// oldMessageStore is from the old state\n@@ -170,7 +171,8 @@ function mergeNewMessages(\n// If the client has a RawMessageInfo with this localID, but not with\n// the serverID, that means the message creation succeeded but the\n// sendMessageActionTypes.success never got processed. We set a key in\n- // localIDsToServerIDs here to fix the messageIDs for the thread too.\n+ // localIDsToServerIDs here to fix the messageIDs for the rest of the\n+ // MessageStore too.\ninvariant(inputLocalID, \"should be set\");\nlocalIDsToServerIDs.set(inputLocalID, inputID);\nmessageInfo = {\n@@ -179,7 +181,7 @@ function mergeNewMessages(\n};\n} else {\n// If neither the serverID nor the localID from the delivered\n- // RawMessageInfo exists in the local store, then this message is\n+ // RawMessageInfo exists in the client store, then this message is\n// brand new to us. Ignore any localID provided by the server.\nconst { localID, ...rest } = messageInfo;\nmessageInfo = { ...rest };\n@@ -199,6 +201,7 @@ function mergeNewMessages(\nconst mustResortThreadMessageIDs = [];\nconst lastPruned = Date.now();\nconst watchedIDs = threadWatcher.getWatchedIDs();\n+ const local = {};\nconst threads = _flow(\n_pickBy(\n(messageIDs: string[], threadID: string) =>\n@@ -254,6 +257,10 @@ function mergeNewMessages(\n`could not find ${messageID} in messageStore`,\n);\noldMessageInfosToCombine.push(oldMessageInfo);\n+ const localInfo = oldMessageStore.local[messageID];\n+ if (localInfo) {\n+ local[messageID] = localInfo;\n+ }\n}\nconst startReached = oldThread.startReached ||\ntruncate === messageTruncationStatus.EXHAUSTIVE;\n@@ -301,6 +308,10 @@ function mergeNewMessages(\nif (messageInfo) {\noldMessageInfosToCombine.push(messageInfo);\n}\n+ const localInfo = oldMessageStore.local[messageID];\n+ if (localInfo) {\n+ local[messageID] = localInfo;\n+ }\n}\n}\n@@ -334,7 +345,7 @@ function mergeNewMessages(\noldMessageStore.currentAsOf,\n);\n- return { messages, threads, currentAsOf };\n+ return { messages, threads, local, currentAsOf };\n}\nfunction isContiguous(\n@@ -371,6 +382,7 @@ function filterByNewThreadInfos(\nreturn {\nmessages: _omit(messageIDsToRemove)(messageStore.messages),\nthreads: _pick(Object.keys(watchedThreadInfos))(messageStore.threads),\n+ local: _omit(messageIDsToRemove)(messageStore.local),\ncurrentAsOf: messageStore.currentAsOf,\n};\n}\n@@ -412,6 +424,7 @@ function reduceMessageStore(\nreturn {\nmessages: newMessageStore.messages,\nthreads: newMessageStore.threads,\n+ local: newMessageStore.local,\ncurrentAsOf: messagesResult.currentAsOf,\n};\n} else if (action.type === processUpdatesActionType) {\n@@ -449,6 +462,7 @@ function reduceMessageStore(\nreturn {\nmessages: newMessageStore.messages,\nthreads: newMessageStore.threads,\n+ local: newMessageStore.local,\ncurrentAsOf: messageStore.currentAsOf,\n};\n} else if (\n@@ -466,6 +480,7 @@ function reduceMessageStore(\nreturn {\nmessages: newMessageStore.messages,\nthreads: newMessageStore.threads,\n+ local: newMessageStore.local,\ncurrentAsOf: messagesResult.currentAsOf,\n};\n} else if (\n@@ -596,25 +611,17 @@ function reduceMessageStore(\n],\n},\n},\n+ local: messageStore.local,\ncurrentAsOf: messageStore.currentAsOf,\n};\n} else if (action.type === sendMessageActionTypes.failed) {\n- const payload = action.payload;\n- const isNotLocalID = (localID: ?string) => localID !== payload.localID;\n- const newMessages = _pickBy(\n- (messageInfo: RawMessageInfo) => messageInfo.type !== 0 ||\n- isNotLocalID(messageInfo.localID),\n- )(messageStore.messages);\n- const newMessageIDs =\n- messageStore.threads[payload.threadID].messageIDs.filter(isNotLocalID);\n+ const { localID } = action.payload;\nreturn {\n- messages: newMessages,\n- threads: {\n- ...messageStore.threads,\n- [payload.threadID]: {\n- ...messageStore.threads[payload.threadID],\n- messageIDs: newMessageIDs,\n- },\n+ messages: messageStore.messages,\n+ threads: messageStore.threads,\n+ local: {\n+ ...messageStore.local,\n+ [localID]: { sendFailed: true },\n},\ncurrentAsOf: messageStore.currentAsOf,\n};\n@@ -652,6 +659,9 @@ function reduceMessageStore(\nmessageStore.threads[threadID].messageIDs.map(replaceMessageKey),\n);\nconst currentAsOf = Math.max(payload.time, messageStore.currentAsOf);\n+ const local = _pickBy(\n+ (localInfo: LocalMessageInfo, key: string) => key !== payload.localID,\n+ )(messageStore.local);\nreturn {\nmessages: newMessages,\nthreads: {\n@@ -661,6 +671,7 @@ function reduceMessageStore(\nmessageIDs: newMessageIDs,\n},\n},\n+ local,\ncurrentAsOf,\n};\n} else if (action.type === saveMessagesActionType) {\n@@ -679,6 +690,7 @@ function reduceMessageStore(\nreturn {\nmessages: newMessageStore.messages,\nthreads: newMessageStore.threads,\n+ local: newMessageStore.local,\n// We avoid bumping currentAsOf because notifs may include a contracted\n// RawMessageInfo, so we want to make sure we still fetch it\ncurrentAsOf: messageStore.currentAsOf,\n@@ -704,6 +716,7 @@ function reduceMessageStore(\nreturn {\nmessages: _omit(messageIDsToPrune)(messageStore.messages),\nthreads: newThreads,\n+ local: _omit(messageIDsToPrune)(messageStore.local),\ncurrentAsOf: messageStore.currentAsOf,\n};\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/types/message-types.js",
"new_path": "lib/types/message-types.js",
"diff": "@@ -496,9 +496,17 @@ export type ThreadMessageInfo = {|\nlastPruned: number, // millisecond timestamp\n|};\n+// Tracks client-local information about a message that hasn't been assigned an\n+// ID by the server yet. As soon as the client gets an ack from the server for\n+// this message, it will clear the LocalMessageInfo.\n+export type LocalMessageInfo = {|\n+ sendFailed?: bool,\n+|};\n+\nexport type MessageStore = {|\nmessages: {[id: string]: RawMessageInfo},\nthreads: {[threadID: string]: ThreadMessageInfo},\n+ local: {[id: string]: LocalMessageInfo},\ncurrentAsOf: number,\n|};\n"
},
{
"change_type": "MODIFY",
"old_path": "native/persist.js",
"new_path": "native/persist.js",
"diff": "@@ -108,6 +108,10 @@ const migrations = {\n...state.connection,\nshowDisconnectedBar: false,\n},\n+ messageStore: {\n+ ...state.messageStore,\n+ local: {},\n+ },\n}),\n};\n"
},
{
"change_type": "MODIFY",
"old_path": "native/redux-setup.js",
"new_path": "native/redux-setup.js",
"diff": "@@ -129,6 +129,7 @@ const defaultState = ({\nmessageStore: {\nmessages: {},\nthreads: {},\n+ local: {},\ncurrentAsOf: 0,\n},\ndrafts: {},\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | Introducing LocalMessageInfo
Will track messages that failed to send. This commit also makes it so those messages don't just disappear anymore. |
129,187 | 26.11.2018 20:17:21 | 28,800 | bc67ab52e129c3e2db4802eadc17b4a60539cd94 | Display delivery icon on native | [
{
"change_type": "MODIFY",
"old_path": "lib/selectors/chat-selectors.js",
"new_path": "lib/selectors/chat-selectors.js",
"diff": "@@ -7,7 +7,9 @@ import {\ntype MessageStore,\ntype TextMessageInfo,\ntype RobotextMessageInfo,\n+ type LocalMessageInfo,\nmessageInfoPropType,\n+ localMessageInfoPropType,\nmessageTypes,\n} from '../types/message-types';\nimport type { UserInfo } from '../types/user-types';\n@@ -22,6 +24,7 @@ import _orderBy from 'lodash/fp/orderBy';\nimport _memoize from 'lodash/memoize';\nimport {\n+ messageKey,\nrobotextForMessageInfo,\ncreateMessageInfo,\n} from '../shared/message-utils';\n@@ -117,6 +120,7 @@ export type ChatMessageInfoItem = {|\n|} | {|\nitemType: \"message\",\nmessageInfo: TextMessageInfo,\n+ localMessageInfo: ?LocalMessageInfo,\nstartsConversation: bool,\nstartsCluster: bool,\nendsCluster: bool,\n@@ -131,6 +135,7 @@ const chatMessageItemPropType = PropTypes.oneOfType([\nPropTypes.shape({\nitemType: PropTypes.oneOf([\"message\"]).isRequired,\nmessageInfo: messageInfoPropType.isRequired,\n+ localMessageInfo: localMessageInfoPropType,\nstartsConversation: PropTypes.bool.isRequired,\nstartsCluster: PropTypes.bool.isRequired,\nendsCluster: PropTypes.bool.isRequired,\n@@ -186,9 +191,11 @@ function createChatMessageItems(\ncontinue;\n}\nif (messageInfo.type === messageTypes.TEXT) {\n+ const localMessageInfo = messageStore.local[messageKey(messageInfo)];\nchatMessageItems.push({\nitemType: \"message\",\nmessageInfo,\n+ localMessageInfo,\nstartsConversation,\nstartsCluster,\nendsCluster: false,\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/types/message-types.js",
"new_path": "lib/types/message-types.js",
"diff": "@@ -503,6 +503,10 @@ export type LocalMessageInfo = {|\nsendFailed?: bool,\n|};\n+export const localMessageInfoPropType = PropTypes.shape({\n+ sendFailed: PropTypes.bool,\n+});\n+\nexport type MessageStore = {|\nmessages: {[id: string]: RawMessageInfo},\nthreads: {[threadID: string]: ThreadMessageInfo},\n"
},
{
"change_type": "MODIFY",
"old_path": "native/chat/message-list.react.js",
"new_path": "native/chat/message-list.react.js",
"diff": "@@ -12,6 +12,7 @@ import type { ViewToken } from 'react-native/Libraries/Lists/ViewabilityHelper';\nimport {\ntype TextMessageInfo,\ntype RobotextMessageInfo,\n+ type LocalMessageInfo,\ntype FetchMessageInfosPayload,\nmessageTypes,\n} from 'lib/types/message-types';\n@@ -81,6 +82,7 @@ export type ChatMessageInfoItemWithHeight =\nRobotextChatMessageInfoItemWithHeight | {|\nitemType: \"message\",\nmessageInfo: TextMessageInfo,\n+ localMessageInfo: ?LocalMessageInfo,\nthreadInfo: ThreadInfo,\nstartsConversation: bool,\nstartsCluster: bool,\n@@ -200,11 +202,15 @@ class InnerMessageList extends React.PureComponent<Props, State> {\nif (item.itemType !== \"message\") {\ncontinue;\n}\n- const messageInfo = item.messageInfo;\n+ const { messageInfo } = item;\nif (messageInfo.type === messageTypes.TEXT) {\n- const style = onlyEmojiRegex.test(messageInfo.text)\n+ const { isViewer } = messageInfo.creator;\n+ const style = [\n+ onlyEmojiRegex.test(messageInfo.text)\n? styles.emojiOnlyText\n- : styles.text;\n+ : styles.text,\n+ isViewer ? styles.viewerMargins : styles.nonViewerMargins,\n+ ];\ntextToMeasure.push({\nid: messageKey(messageInfo),\ntext: messageInfo.text,\n@@ -315,9 +321,14 @@ class InnerMessageList extends React.PureComponent<Props, State> {\n`height for ${messageKey(item.messageInfo)} should be set`,\n);\nif (item.messageInfo.type === messageTypes.TEXT) {\n+ // Conditional due to Flow...\n+ const localMessageInfo = item.localMessageInfo\n+ ? item.localMessageInfo\n+ : null;\nreturn {\nitemType: \"message\",\nmessageInfo: item.messageInfo,\n+ localMessageInfo,\nthreadInfo,\nstartsConversation: item.startsConversation,\nstartsCluster: item.startsCluster,\n@@ -540,15 +551,19 @@ const styles = StyleSheet.create({\nflex: 1,\nbackgroundColor: '#FFFFFF',\n},\n- text: {\n+ viewerMargins: {\n+ left: 24,\n+ right: 42,\n+ },\n+ nonViewerMargins: {\nleft: 24,\nright: 24,\n+ },\n+ text: {\nfontSize: 18,\nfontFamily: 'Arial',\n},\nemojiOnlyText: {\n- left: 24,\n- right: 24,\nfontSize: 36,\nfontFamily: 'Arial',\n},\n"
},
{
"change_type": "MODIFY",
"old_path": "native/chat/message.react.js",
"new_path": "native/chat/message.react.js",
"diff": "@@ -30,7 +30,7 @@ function messageItemHeight(\nheight += robotextMessageItemHeight(item, viewerID);\n}\nif (item.startsConversation) {\n- height += 26; // for time bar\n+ height += 27; // for time bar\n}\nreturn height;\n}\n@@ -97,6 +97,7 @@ const styles = StyleSheet.create({\nconversationHeader: {\ncolor: '#777777',\nfontSize: 14,\n+ paddingTop: 1,\npaddingBottom: 7,\nalignSelf: 'center',\nheight: 26,\n"
},
{
"change_type": "MODIFY",
"old_path": "native/chat/text-message.react.js",
"new_path": "native/chat/text-message.react.js",
"diff": "@@ -17,6 +17,7 @@ import invariant from 'invariant';\nimport PropTypes from 'prop-types';\nimport Color from 'color';\nimport Hyperlink from 'react-native-hyperlink';\n+import Icon from 'react-native-vector-icons/Feather';\nimport { colorIsDark } from 'lib/shared/thread-utils';\nimport { messageKey } from 'lib/shared/message-utils';\n@@ -73,26 +74,37 @@ class TextMessage extends React.PureComponent<Props> {\n}\nrender() {\n- const isViewer = this.props.item.messageInfo.creator.isViewer;\n- let containerStyle = null,\n+ invariant(\n+ this.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 threadColor = this.props.item.threadInfo.color;\n+\n+ const { isViewer } = creator;\n+ let alignStyle = null,\nmessageStyle = {},\ntextCustomStyle = {},\ndarkColor = false;\nif (isViewer) {\n- containerStyle = styles.rightChatBubble;\n- messageStyle.backgroundColor = `#${this.props.item.threadInfo.color}`;\n- darkColor = colorIsDark(this.props.item.threadInfo.color);\n+ alignStyle = styles.rightChatBubble;\n+ messageStyle.backgroundColor = `#${threadColor}`;\n+ darkColor = colorIsDark(threadColor);\ntextCustomStyle.color = darkColor ? 'white' : 'black';\n} else {\n- containerStyle = styles.leftChatBubble;\n+ alignStyle = styles.leftChatBubble;\nmessageStyle.backgroundColor = \"#DDDDDDBB\";\ntextCustomStyle.color = 'black';\n}\n+ const containerStyle = [\n+ styles.alignment,\n+ { marginBottom: this.props.item.endsCluster ? 12 : 5 },\n+ ];\nlet authorName = null;\nif (!isViewer && this.props.item.startsCluster) {\nauthorName = (\n<Text style={styles.authorName}>\n- {stringForUser(this.props.item.messageInfo.creator)}\n+ {stringForUser(creator)}\n</Text>\n);\n}\n@@ -104,48 +116,68 @@ class TextMessage extends React.PureComponent<Props> {\n!isViewer && !this.props.item.startsCluster ? 0 : 8;\nmessageStyle.borderBottomLeftRadius =\n!isViewer && !this.props.item.endsCluster ? 0 : 8;\n- messageStyle.marginBottom = this.props.item.endsCluster ? 12 : 5;\nif (this.props.focused) {\nmessageStyle.backgroundColor =\nColor(messageStyle.backgroundColor).darken(0.15).hex();\n}\ntextCustomStyle.height = this.props.item.textHeight;\n- invariant(\n- this.props.item.messageInfo.type === messageTypes.TEXT,\n- \"TextMessage should only be used for messageTypes.TEXT\",\n+ let deliveryIcon = null;\n+ if (isViewer) {\n+ let deliveryIconName;\n+ if (id !== null && id !== undefined) {\n+ deliveryIconName = \"check-circle\";\n+ } else {\n+ const sendFailed = this.props.item.localMessageInfo\n+ ? this.props.item.localMessageInfo.sendFailed\n+ : null;\n+ deliveryIconName = sendFailed ? \"x-circle\" : \"circle\";\n+ }\n+ deliveryIcon = (\n+ <View style={styles.iconContainer}>\n+ <Icon\n+ name={deliveryIconName}\n+ style={[styles.icon, { color: `#${threadColor}` }]}\n+ />\n+ </View>\n);\n- const text = this.props.item.messageInfo.text;\n+ }\nconst linkStyle = darkColor ? styles.lightLinkText : styles.darkLinkText;\nconst textStyle = onlyEmojiRegex.test(text)\n? styles.emojiOnlyText\n: styles.text;\n- const content = (\n- <View style={[styles.message, messageStyle]}>\n- <Hyperlink linkDefault={true} linkStyle={linkStyle}>\n+ const messageBlob = (\n+ <Hyperlink\n+ linkDefault={true}\n+ style={[styles.message, messageStyle]}\n+ linkStyle={linkStyle}\n+ >\n<Text\nonPress={this.onPress}\nonLongPress={this.onPress}\nstyle={[textStyle, textCustomStyle]}\n>{text}</Text>\n</Hyperlink>\n- </View>\n);\nreturn (\n<View style={containerStyle}>\n{authorName}\n+ <View style={[styles.content, alignStyle]}>\n+ <View style={[styles.messageBlobContainer, alignStyle]}>\n<Tooltip\n- buttonComponent={content}\n+ buttonComponent={messageBlob}\nitems={this.tooltipConfig}\nlabelStyle={styles.popoverLabelStyle}\nonOpenTooltipMenu={this.onFocus}\nonCloseTooltipMenu={this.onBlur}\n- componentWrapperStyle={containerStyle}\nref={this.tooltipRef}\n/>\n</View>\n+ {deliveryIcon}\n+ </View>\n+ </View>\n);\n}\n@@ -194,16 +226,24 @@ const styles = StyleSheet.create({\nfontSize: 36,\nfontFamily: 'Arial',\n},\n+ alignment: {\n+ marginLeft: 12,\n+ marginRight: 7,\n+ },\nmessage: {\n- overflow: 'hidden',\npaddingVertical: 6,\npaddingHorizontal: 12,\n- marginHorizontal: 12,\n+ marginRight: 5,\n+ overflow: 'hidden',\n+ },\n+ messageBlobContainer: {\n+ flex: 1,\n+ flexDirection: 'row',\n},\nauthorName: {\ncolor: '#777777',\nfontSize: 14,\n- paddingHorizontal: 24,\n+ paddingHorizontal: 12,\npaddingVertical: 4,\nheight: 25,\n},\n@@ -220,10 +260,23 @@ const styles = StyleSheet.create({\ncolor: '#444',\n},\nleftChatBubble: {\n- alignSelf: 'flex-start',\n+ justifyContent: 'flex-start',\n},\nrightChatBubble: {\n- alignSelf: 'flex-end',\n+ justifyContent: 'flex-end',\n+ },\n+ content: {\n+ flex: 1,\n+ flexDirection: 'row',\n+ alignItems: 'center',\n+ },\n+ icon: {\n+ fontSize: 16,\n+ textAlign: 'center',\n+ },\n+ iconContainer: {\n+ marginLeft: 2,\n+ width: 16,\n},\n});\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | Display delivery icon on native |
129,187 | 26.11.2018 22:12:15 | 28,800 | 4014d136e2fd4298bdbbca3d981374f051cd67d5 | Allow message send retry on native | [
{
"change_type": "MODIFY",
"old_path": "lib/reducers/message-reducer.js",
"new_path": "lib/reducers/message-reducer.js",
"diff": "@@ -586,9 +586,27 @@ function reduceMessageStore(\nconst { payload } = action;\nconst { localID, threadID } = payload;\ninvariant(localID, `localID should be set on ${action.type}`);\n+\nif (messageStore.messages[localID]) {\n- return messageStore;\n+ const messages = { ...messageStore.messages, [localID]: payload };\n+ const local = _pickBy(\n+ (localInfo: LocalMessageInfo, key: string) => key !== localID,\n+ )(messageStore.local);\n+ const threads = {\n+ ...messageStore.threads,\n+ [threadID]: {\n+ ...messageStore.threads[threadID],\n+ messageIDs: _orderBy([\n+ (messageID: string) => messages[localID].time,\n+ ])('desc')(messageStore.threads[threadID].messageIDs),\n+ },\n+ };\n+ threads[threadID].messageIDs = _orderBy([\n+ (messageID: string) => messages[messageID].time,\n+ ])('desc')(threads[threadID].messageIDs);\n+ return { ...messageStore, messages, threads, local };\n}\n+\nconst { messageIDs } = messageStore.threads[threadID];\nfor (let existingMessageID of messageIDs) {\nconst existingMessageInfo = messageStore.messages[existingMessageID];\n@@ -596,6 +614,7 @@ function reduceMessageStore(\nreturn messageStore;\n}\n}\n+\nreturn {\nmessages: {\n...messageStore.messages,\n"
},
{
"change_type": "MODIFY",
"old_path": "native/chat/text-message.react.js",
"new_path": "native/chat/text-message.react.js",
"diff": "import type { ChatMessageInfoItemWithHeight } from './message-list.react';\nimport { chatMessageItemPropType } from 'lib/selectors/chat-selectors';\nimport type { TooltipItemData } from '../components/tooltip.react';\n-import { messageTypes } from 'lib/types/message-types';\n+import {\n+ messageTypes,\n+ type SendTextMessageResult,\n+ type RawTextMessageInfo,\n+ type RawMessageInfo,\n+} from 'lib/types/message-types';\n+import type { AppState } from '../redux-setup';\n+import type { DispatchActionPromise } from 'lib/utils/action-utils';\nimport React from 'react';\nimport {\n@@ -20,23 +27,40 @@ import Hyperlink from 'react-native-hyperlink';\nimport Icon from 'react-native-vector-icons/Feather';\nimport { colorIsDark } from 'lib/shared/thread-utils';\n-import { messageKey } from 'lib/shared/message-utils';\n+import { messageID, messageKey } from 'lib/shared/message-utils';\nimport { stringForUser } from 'lib/shared/user-utils';\nimport { onlyEmojiRegex } from 'lib/shared/emojis';\n+import { connect } from 'lib/utils/redux-utils';\n+import {\n+ sendMessageActionTypes,\n+ sendMessage,\n+} from 'lib/actions/message-actions';\nimport Tooltip from '../components/tooltip.react';\n+import Button from '../components/button.react';\nfunction textMessageItemHeight(\nitem: ChatMessageInfoItemWithHeight,\nviewerID: ?string,\n) {\n- let height = 17 + item.textHeight; // for padding, margin, and text\n- if (!item.messageInfo.creator.isViewer && item.startsCluster) {\n+ const { messageInfo, textHeight, startsCluster, endsCluster } = item;\n+ const { id, creator } = messageInfo;\n+ const { isViewer } = creator;\n+ let height = 17 + textHeight; // for padding, margin, and text\n+ if (!isViewer && startsCluster) {\nheight += 25; // for username\n}\n- if (item.endsCluster) {\n+ if (endsCluster) {\nheight += 7; // extra padding at the end of a cluster\n}\n+ if (\n+ isViewer &&\n+ id !== null && id !== undefined &&\n+ item.localMessageInfo &&\n+ item.localMessageInfo.sendFailed\n+ ) {\n+ height += 22; // extra padding at the end of a cluster\n+ }\nreturn height;\n}\n@@ -44,6 +68,16 @@ type Props = {\nitem: ChatMessageInfoItemWithHeight,\nfocused: bool,\ntoggleFocus: (messageKey: string) => void,\n+ // Redux state\n+ rawMessageInfo: RawMessageInfo,\n+ // Redux dispatch functions\n+ dispatchActionPromise: DispatchActionPromise,\n+ // async functions that hit server APIs\n+ sendMessage: (\n+ threadID: string,\n+ localID: string,\n+ text: string,\n+ ) => Promise<SendTextMessageResult>,\n};\nclass TextMessage extends React.PureComponent<Props> {\n@@ -51,6 +85,9 @@ class TextMessage extends React.PureComponent<Props> {\nitem: chatMessageItemPropType.isRequired,\nfocused: PropTypes.bool.isRequired,\ntoggleFocus: PropTypes.func.isRequired,\n+ rawMessageInfo: PropTypes.object.isRequired,\n+ dispatchActionPromise: PropTypes.func.isRequired,\n+ sendMessage: PropTypes.func.isRequired,\n};\ntooltipConfig: $ReadOnlyArray<TooltipItemData>;\ntooltip: ?Tooltip;\n@@ -123,6 +160,7 @@ class TextMessage extends React.PureComponent<Props> {\ntextCustomStyle.height = this.props.item.textHeight;\nlet deliveryIcon = null;\n+ let failedSendInfo = null;\nif (isViewer) {\nlet deliveryIconName;\nif (id !== null && id !== undefined) {\n@@ -131,7 +169,23 @@ class TextMessage extends React.PureComponent<Props> {\nconst sendFailed = this.props.item.localMessageInfo\n? this.props.item.localMessageInfo.sendFailed\n: null;\n- deliveryIconName = sendFailed ? \"x-circle\" : \"circle\";\n+ if (sendFailed) {\n+ deliveryIconName = \"x-circle\";\n+ failedSendInfo = (\n+ <View style={styles.failedSendInfo}>\n+ <Text style={styles.deliveryFailed} numberOfLines={1}>\n+ DELIVERY FAILED.\n+ </Text>\n+ <Button onPress={this.retrySend}>\n+ <Text style={styles.retrySend} numberOfLines={1}>\n+ RETRY?\n+ </Text>\n+ </Button>\n+ </View>\n+ );\n+ } else {\n+ deliveryIconName = \"circle\";\n+ }\n}\ndeliveryIcon = (\n<View style={styles.iconContainer}>\n@@ -177,6 +231,7 @@ class TextMessage extends React.PureComponent<Props> {\n</View>\n{deliveryIcon}\n</View>\n+ {failedSendInfo}\n</View>\n);\n}\n@@ -215,6 +270,49 @@ class TextMessage extends React.PureComponent<Props> {\n}\n}\n+ retrySend = () => {\n+ const { rawMessageInfo } = this.props;\n+ invariant(\n+ rawMessageInfo.type === messageTypes.TEXT,\n+ \"TextMessage should only be used for messageTypes.TEXT\",\n+ );\n+ const newRawMessageInfo = {\n+ ...rawMessageInfo,\n+ time: Date.now(),\n+ };\n+ this.props.dispatchActionPromise(\n+ sendMessageActionTypes,\n+ this.sendMessageAction(newRawMessageInfo),\n+ undefined,\n+ newRawMessageInfo,\n+ );\n+ }\n+\n+ async sendMessageAction(messageInfo: RawTextMessageInfo) {\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.sendMessage(\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}\nconst styles = StyleSheet.create({\n@@ -278,9 +376,39 @@ const styles = StyleSheet.create({\nmarginLeft: 2,\nwidth: 16,\n},\n+ failedSendInfo: {\n+ paddingTop: 5,\n+ flex: 1,\n+ flexDirection: 'row',\n+ justifyContent: 'flex-end',\n+ marginRight: 20,\n+ },\n+ deliveryFailed: {\n+ paddingHorizontal: 3,\n+ color: '#555555',\n+ },\n+ retrySend: {\n+ paddingHorizontal: 3,\n+ color: \"#036AFF\",\n+ },\n});\n+const ConnectedTextMessage = connect(\n+ (state: AppState, ownProps: { item: ChatMessageInfoItemWithHeight }) => {\n+ const { messageInfo } = ownProps.item;\n+ invariant(\n+ messageInfo.type === messageTypes.TEXT,\n+ \"TextMessage should only be used for messageTypes.TEXT\",\n+ );\n+ const id = messageID(messageInfo);\n+ return {\n+ rawMessageInfo: state.messageStore.messages[id],\n+ };\n+ },\n+ { sendMessage },\n+)(TextMessage);\n+\nexport {\n- TextMessage,\n+ ConnectedTextMessage as TextMessage,\ntextMessageItemHeight,\n};\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | Allow message send retry on native |
129,187 | 26.11.2018 22:56:03 | 28,800 | fabd5c9310d21389e3d93212fc0d5ee9cbe312d8 | [native]
Fixes so we can revert | [
{
"change_type": "MODIFY",
"old_path": "native/chat/chat-thread-list.react.js",
"new_path": "native/chat/chat-thread-list.react.js",
"diff": "@@ -288,7 +288,6 @@ const styles = StyleSheet.create({\n},\ncontainer: {\nflex: 1,\n- backgroundColor: \"#E9E9EF\",\n},\nsearchContainer: {\nbackgroundColor: '#F6F6F6',\n"
},
{
"change_type": "MODIFY",
"old_path": "native/chat/chat.react.js",
"new_path": "native/chat/chat.react.js",
"diff": "@@ -40,6 +40,9 @@ const Chat = createStackNavigator(\ndefaultNavigationOptions: {\nheader: Header,\n},\n+ cardStyle: {\n+ backgroundColor: \"#E9E9EF\",\n+ },\n},\n);\nChat.navigationOptions = ({ navigation }) => ({\n"
},
{
"change_type": "MODIFY",
"old_path": "native/chat/compose-thread.react.js",
"new_path": "native/chat/compose-thread.react.js",
"diff": "@@ -490,7 +490,6 @@ class InnerComposeThread extends React.PureComponent<Props, State> {\nconst styles = StyleSheet.create({\ncontainer: {\nflex: 1,\n- backgroundColor: \"#E9E9EF\",\n},\nparentThreadRow: {\nflexDirection: 'row',\n"
},
{
"change_type": "MODIFY",
"old_path": "native/chat/message-list.react.js",
"new_path": "native/chat/message-list.react.js",
"diff": "@@ -545,7 +545,6 @@ class InnerMessageList extends React.PureComponent<Props, State> {\nconst styles = StyleSheet.create({\ncontainer: {\nflex: 1,\n- backgroundColor: \"#E9E9EF\",\n},\nflatListContainer: {\nflex: 1,\n"
},
{
"change_type": "MODIFY",
"old_path": "native/chat/settings/delete-thread.react.js",
"new_path": "native/chat/settings/delete-thread.react.js",
"diff": "@@ -143,10 +143,7 @@ class InnerDeleteThread extends React.PureComponent<Props, State> {\n: <Text style={styles.saveText}>Delete thread</Text>;\nconst threadInfo = InnerDeleteThread.getThreadInfo(this.props);\nreturn (\n- <ScrollView\n- contentContainerStyle={styles.scrollView}\n- style={styles.container}\n- >\n+ <ScrollView contentContainerStyle={styles.scrollView}>\n<View>\n<Text style={styles.warningText}>\n{`The thread \"${threadInfo.uiName}\" will be permanently deleted. `}\n@@ -242,9 +239,6 @@ class InnerDeleteThread extends React.PureComponent<Props, State> {\n}\nconst styles = StyleSheet.create({\n- container: {\n- backgroundColor: \"#E9E9EF\",\n- },\nscrollView: {\npaddingTop: 24,\n},\n"
},
{
"change_type": "MODIFY",
"old_path": "native/chat/settings/thread-settings.react.js",
"new_path": "native/chat/settings/thread-settings.react.js",
"diff": "@@ -562,7 +562,6 @@ class InnerThreadSettings extends React.PureComponent<Props, State> {\nreturn (\n<FlatList\ndata={listData}\n- style={styles.container}\ncontentContainerStyle={styles.flatList}\nrenderItem={this.renderItem}\n/>\n@@ -717,9 +716,6 @@ class InnerThreadSettings extends React.PureComponent<Props, State> {\n}\nconst styles = StyleSheet.create({\n- container: {\n- backgroundColor: \"#E9E9EF\",\n- },\nflatList: {\npaddingVertical: 16,\n},\n"
},
{
"change_type": "MODIFY",
"old_path": "native/more/build-info.react.js",
"new_path": "native/more/build-info.react.js",
"diff": "@@ -15,10 +15,7 @@ class BuildInfo extends React.PureComponent<Props> {\nrender() {\nreturn (\n- <ScrollView\n- contentContainerStyle={styles.scrollView}\n- style={styles.container}\n- >\n+ <ScrollView contentContainerStyle={styles.scrollView}>\n<View style={styles.section}>\n<View style={styles.row}>\n<Text style={styles.label}>Release</Text>\n@@ -47,9 +44,6 @@ class BuildInfo extends React.PureComponent<Props> {\n}\nconst styles = StyleSheet.create({\n- container: {\n- backgroundColor: \"#E9E9EF\",\n- },\nscrollView: {\npaddingTop: 24,\n},\n"
},
{
"change_type": "MODIFY",
"old_path": "native/more/delete-account.react.js",
"new_path": "native/more/delete-account.react.js",
"diff": "@@ -107,10 +107,7 @@ class InnerDeleteAccount extends React.PureComponent<Props, State> {\n? <ActivityIndicator size=\"small\" color=\"white\" />\n: <Text style={styles.saveText}>Delete account</Text>;\nreturn (\n- <ScrollView\n- contentContainerStyle={styles.scrollView}\n- style={styles.container}\n- >\n+ <ScrollView contentContainerStyle={styles.scrollView}>\n<View>\n<Text style={styles.warningText}>\nYour account will be permanently deleted.\n@@ -213,9 +210,6 @@ class InnerDeleteAccount extends React.PureComponent<Props, State> {\n}\nconst styles = StyleSheet.create({\n- container: {\n- backgroundColor: \"#E9E9EF\",\n- },\nscrollView: {\npaddingTop: 24,\n},\n"
},
{
"change_type": "MODIFY",
"old_path": "native/more/dev-tools.react.js",
"new_path": "native/more/dev-tools.react.js",
"diff": "@@ -171,7 +171,6 @@ class InnerDevTools extends React.PureComponent<Props> {\nconst styles = StyleSheet.create({\ncontainer: {\nflex: 1,\n- backgroundColor: \"#E9E9EF\",\n},\nscrollView: {\npaddingTop: 24,\n"
},
{
"change_type": "MODIFY",
"old_path": "native/more/edit-email.react.js",
"new_path": "native/more/edit-email.react.js",
"diff": "@@ -113,10 +113,7 @@ class InnerEditEmail extends React.PureComponent<Props, State> {\n? <ActivityIndicator size=\"small\" color=\"white\" />\n: <Text style={styles.saveText}>Save</Text>;\nreturn (\n- <ScrollView\n- contentContainerStyle={styles.scrollView}\n- style={styles.container}\n- >\n+ <ScrollView contentContainerStyle={styles.scrollView}>\n<Text style={styles.header}>EMAIL</Text>\n<View style={styles.section}>\n<TextInput\n@@ -290,9 +287,6 @@ class InnerEditEmail extends React.PureComponent<Props, State> {\n}\nconst styles = StyleSheet.create({\n- container: {\n- backgroundColor: \"#E9E9EF\",\n- },\nscrollView: {\npaddingTop: 24,\n},\n"
},
{
"change_type": "MODIFY",
"old_path": "native/more/edit-password.react.js",
"new_path": "native/more/edit-password.react.js",
"diff": "@@ -121,10 +121,7 @@ class InnerEditPassword extends React.PureComponent<Props, State> {\n? <ActivityIndicator size=\"small\" color=\"white\" />\n: <Text style={styles.saveText}>Save</Text>;\nreturn (\n- <ScrollView\n- contentContainerStyle={styles.scrollView}\n- style={styles.container}\n- >\n+ <ScrollView contentContainerStyle={styles.scrollView}>\n<Text style={styles.header}>CURRENT PASSWORD</Text>\n<View style={styles.section}>\n<View style={styles.row}>\n@@ -346,9 +343,6 @@ class InnerEditPassword extends React.PureComponent<Props, State> {\n}\nconst styles = StyleSheet.create({\n- container: {\n- backgroundColor: \"#E9E9EF\",\n- },\nscrollView: {\npaddingTop: 24,\n},\n"
},
{
"change_type": "MODIFY",
"old_path": "native/more/more-screen.react.js",
"new_path": "native/more/more-screen.react.js",
"diff": "@@ -297,7 +297,6 @@ class InnerMoreScreen extends React.PureComponent<Props> {\nconst styles = StyleSheet.create({\ncontainer: {\nflex: 1,\n- backgroundColor: \"#E9E9EF\",\n},\nscrollView: {\npaddingVertical: 24,\n"
},
{
"change_type": "MODIFY",
"old_path": "native/more/more.react.js",
"new_path": "native/more/more.react.js",
"diff": "@@ -34,6 +34,9 @@ const More = createStackNavigator(\ndefaultNavigationOptions: {\nheader: Header,\n},\n+ cardStyle: {\n+ backgroundColor: \"#E9E9EF\",\n+ },\n},\n);\nMore.navigationOptions = ({ navigation }) => ({\n"
},
{
"change_type": "MODIFY",
"old_path": "native/package.json",
"new_path": "native/package.json",
"diff": "\"react-native-segmented-control-tab\": \"^3.2.1\",\n\"react-native-splash-screen\": \"^3.1.1\",\n\"react-native-vector-icons\": \"^4.5.0\",\n- \"react-navigation\": \"3.0.0-rc.5\",\n+ \"react-navigation\": \"^3.0.1\",\n\"react-navigation-redux-helpers\": \"^2.0.8\",\n- \"react-navigation-stack\": \"1.0.0-alpha.34\",\n+ \"react-navigation-stack\": \"^1.0.2\",\n\"react-redux\": \"^5.0.6\",\n\"reactotron-react-native\": \"^2.0.0\",\n\"reactotron-redux\": \"^2.0.0\",\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-navigation/core@3.0.0-alpha.19\":\n- version \"3.0.0-alpha.19\"\n- resolved \"https://registry.yarnpkg.com/@react-navigation/core/-/core-3.0.0-alpha.19.tgz#262f3eb17d4171aaa9229695693d6d877b156bbe\"\n- integrity sha512-INlFaXWOIzQqQV2EESr3wn+qYSSEy90iWBthQFiQ/bNofuSJ8fKqhftYGCI7u2ZKjXbKXc7qF5WfhgyDx9LNjQ==\n+\"@react-navigation/core@^3.0.0\":\n+ version \"3.0.0\"\n+ resolved \"https://registry.yarnpkg.com/@react-navigation/core/-/core-3.0.0.tgz#042c7fcb99331d7b452868d129b4e1cc3a4c60b9\"\n+ integrity sha512-WZH4notU5tZNxtQ1Vl/y8Z0685+nWtyJlfqKf6ybZruah8BC+sml3tKoBqCHzUTybCfYtRT7pPuCgvlpADe3UQ==\ndependencies:\ncreate-react-context \"^0.2.3\"\nhoist-non-react-statics \"^3.0.1\"\nreact-is \"^16.5.2\"\nreact-lifecycles-compat \"^3.0.4\"\n-\"@react-navigation/native@3.0.0-alpha.12\":\n- version \"3.0.0-alpha.12\"\n- resolved \"https://registry.yarnpkg.com/@react-navigation/native/-/native-3.0.0-alpha.12.tgz#7126cf095f23a75e28eab7c02cb67b87ad658a35\"\n- integrity sha512-N3QanN1gRLrwHGk7yzmGYPOVL1OYiYN6jVlOjJYBA1DC/VJIq8vPBX7QzDLl/1+ch9WyOgm6lo/VsvCD0K44pw==\n+\"@react-navigation/native@^3.0.1\":\n+ version \"3.0.2\"\n+ resolved \"https://registry.yarnpkg.com/@react-navigation/native/-/native-3.0.2.tgz#3365846d54f7e0cf4a7e6bc9b5ef574bfe6774ce\"\n+ integrity sha512-DGeP/EvLmoPxkfF9OQg5ZUgfiEA6vfQdYCL3VIkpw5pEVDO9LFvUih9N9ZWcGLBhn6eEXUa4Dx7cyUnvFp04nQ==\ndependencies:\nhoist-non-react-statics \"^3.0.1\"\n+ react-native-gesture-handler \"^1.0.0\"\nreact-native-safe-area-view \"^0.11.0\"\n- react-native-screens \"^1 || ^1.0.0-alpha\"\n+ react-native-screens \"^1.0.0 || ^1.0.0-alpha\"\n\"@types/caseless@*\":\nversion \"0.12.1\"\n@@ -9270,6 +9271,15 @@ react-native-floating-action@^1.9.0:\nresolved \"https://registry.yarnpkg.com/react-native-floating-action/-/react-native-floating-action-1.13.0.tgz#876ab9227c4eda8630020a6a3adc20041870edf3\"\nintegrity sha512-KqqaEO/nIdims+reWq1pPPDptKqEuG9N8Pt+FtnuVUr35HvyWfiwBf91o9ZMRuO2S+X9AKnq+xuy1iuQK77eQQ==\n+react-native-gesture-handler@^1.0.0:\n+ version \"1.0.9\"\n+ resolved \"https://registry.yarnpkg.com/react-native-gesture-handler/-/react-native-gesture-handler-1.0.9.tgz#ddec4d19d51cb6fb54df6eca792ebd76aaef083f\"\n+ integrity sha512-TPaiS8cAGqQA9p1GwjDbgMyNVCO/7cWC05h1rWIX2ZLoB1oSxGEBi5Es211HpBUmsTAzrUGH7M+ASGkAQeYH/A==\n+ dependencies:\n+ hoist-non-react-statics \"^2.3.1\"\n+ invariant \"^2.2.2\"\n+ prop-types \"^15.5.10\"\n+\nreact-native-gesture-handler@^1.0.8:\nversion \"1.0.8\"\nresolved \"https://registry.yarnpkg.com/react-native-gesture-handler/-/react-native-gesture-handler-1.0.8.tgz#c2799741bf6443bb542892b0a36201a6d9ded209\"\n@@ -9319,11 +9329,16 @@ react-native-safe-area-view@^0.11.0:\ndependencies:\nhoist-non-react-statics \"^2.3.1\"\n-react-native-screens@1.0.0-alpha.15, \"react-native-screens@^1 || ^1.0.0-alpha\":\n+react-native-screens@1.0.0-alpha.15:\nversion \"1.0.0-alpha.15\"\nresolved \"https://registry.yarnpkg.com/react-native-screens/-/react-native-screens-1.0.0-alpha.15.tgz#5b5a0041310b46f12048fda1908d52e7290ec18f\"\nintegrity sha512-S2OM/ieD+Krk+0/Z2Vz2rTUWYud5hJgCRZqXRtqEfMgEcGI4FBopXp7mwXCGbA2PFLjZwZSwLlsZ6RX30WnjRw==\n+\"react-native-screens@^1.0.0 || ^1.0.0-alpha\":\n+ version \"1.0.0-alpha.16\"\n+ resolved \"https://registry.yarnpkg.com/react-native-screens/-/react-native-screens-1.0.0-alpha.16.tgz#e3651b7077ea8fa04e8dd3265ad9b87f1f77a758\"\n+ integrity sha512-t+/aq5jQa+Is6afiQHa1P+2UPnwPGY9NT0pSqNr2zQ5llCn8TcPq6GN8xDMuEc08g+y/9R5zWo32hlVStwWn1A==\n+\nreact-native-segmented-control-tab@^3.2.1:\nversion \"3.3.1\"\nresolved \"https://registry.yarnpkg.com/react-native-segmented-control-tab/-/react-native-segmented-control-tab-3.3.1.tgz#6fba6b2a48d4a0a3105f1b2225b5fd176e0dc88b\"\n@@ -9415,10 +9430,10 @@ react-native@0.57.6:\nxmldoc \"^0.4.0\"\nyargs \"^9.0.0\"\n-react-navigation-drawer@1.0.0-alpha.7:\n- version \"1.0.0-alpha.7\"\n- resolved \"https://registry.yarnpkg.com/react-navigation-drawer/-/react-navigation-drawer-1.0.0-alpha.7.tgz#2e8fb56985da6a8fdcf0980cf8cda8d71b69dbf7\"\n- integrity sha512-s5VWEKP3T/gXnxbR5ndFYZPdkdNIEHDrPy+fzj4B4LQDVZ1K3qsYETfAg0EHGzVVk1CD9ljcvGGGFmA182MNYA==\n+react-navigation-drawer@^1.0.1:\n+ version \"1.0.1\"\n+ resolved \"https://registry.yarnpkg.com/react-navigation-drawer/-/react-navigation-drawer-1.0.1.tgz#b419241e5f29b3399e1a0dd910ac3c58db78695c\"\n+ integrity sha512-H0GdNpEvTfP94AOg97Ih5GTnkHegsGziVTbbzBF06nX2C5moNZzoodXZ9fxhGuCayH/9WYnXTCdfOi8fKgU4ww==\ndependencies:\nreact-native-tab-view \"^1.2.0\"\n@@ -9429,31 +9444,31 @@ react-navigation-redux-helpers@^2.0.8:\ndependencies:\ninvariant \"^2.2.2\"\n-react-navigation-stack@1.0.0-alpha.34:\n- version \"1.0.0-alpha.34\"\n- resolved \"https://registry.yarnpkg.com/react-navigation-stack/-/react-navigation-stack-1.0.0-alpha.34.tgz#f071a3edd8259e37f4dedba436e905a932b4d99e\"\n- integrity sha512-wC1cMhIo2Y8J3rAS+Ps6bfm6zyinaOrQy7P8H232TrHLNiw3xUnXXU081lHimC2Hs7Fn4LJ2jP4xMcspQK1nqA==\n+react-navigation-stack@^1.0.2:\n+ version \"1.0.2\"\n+ resolved \"https://registry.yarnpkg.com/react-navigation-stack/-/react-navigation-stack-1.0.2.tgz#40ce0b7b61ce455e5ea2d071119b35ab38d75321\"\n+ integrity sha512-02iKoZRqr467z26lNn3b6oDIlIOj76ogzbSgw5P1WTZW+YuIABlpDGcKuYfJsWkiBC/GdR9Qg8vl/kMepDRICg==\n-react-navigation-tabs@1.0.0-alpha.5:\n- version \"1.0.0-alpha.5\"\n- resolved \"https://registry.yarnpkg.com/react-navigation-tabs/-/react-navigation-tabs-1.0.0-alpha.5.tgz#a12f0c02881c5a824ef6d175e615c45a7b87c9fb\"\n- integrity sha512-abh1oqy+AwRXF5ZGoFN00tqcPyes2A9c6vT/q6GghRukROnmkhdXAO+pNES/lEcE39Sj5ZwzvCGX9aUiYfSb4Q==\n+react-navigation-tabs@^1.0.0:\n+ version \"1.0.0\"\n+ resolved \"https://registry.yarnpkg.com/react-navigation-tabs/-/react-navigation-tabs-1.0.0.tgz#f9fe3eb8b77787551d017d1279ec049c3bed4950\"\n+ integrity sha512-2oWPk+XfwHihgdOBhuAuzzU94NPhwdvuzseL30R3VsggunfVB4cUtNiQjRP4rVVpdGgJygQtws1eRbUsQ9cECA==\ndependencies:\nhoist-non-react-statics \"^2.5.0\"\nprop-types \"^15.6.1\"\nreact-lifecycles-compat \"^3.0.4\"\nreact-native-tab-view \"^1.0.0\"\n-react-navigation@3.0.0-rc.5:\n- version \"3.0.0-rc.5\"\n- resolved \"https://registry.yarnpkg.com/react-navigation/-/react-navigation-3.0.0-rc.5.tgz#0deb31d849f7221f015fc88a2342b342d3833301\"\n- integrity sha512-sd5vzRQnKJ/0Pp5K3JpF6dEW67tulo2NCvcsfE8/xo0stACv2d0oTTdKOYty7kJj8zsJYxNjQhw2YkMFxTK5Yg==\n- dependencies:\n- \"@react-navigation/core\" \"3.0.0-alpha.19\"\n- \"@react-navigation/native\" \"3.0.0-alpha.12\"\n- react-navigation-drawer \"1.0.0-alpha.7\"\n- react-navigation-stack \"1.0.0-alpha.34\"\n- react-navigation-tabs \"1.0.0-alpha.5\"\n+react-navigation@^3.0.1:\n+ version \"3.0.1\"\n+ resolved \"https://registry.yarnpkg.com/react-navigation/-/react-navigation-3.0.1.tgz#dfcec777981ad56f6f1573ba3a021f9d189602b3\"\n+ integrity sha512-ilxCI7COlHbgZuO5MuPGP7UpHJbJUPqnNMrR4HylPfeZEAUaabpsS8NwhYtUB0aU/O5CnzCc6QNpnb9RjZWjQQ==\n+ dependencies:\n+ \"@react-navigation/core\" \"^3.0.0\"\n+ \"@react-navigation/native\" \"^3.0.1\"\n+ react-navigation-drawer \"^1.0.1\"\n+ react-navigation-stack \"^1.0.2\"\n+ react-navigation-tabs \"^1.0.0\"\nreact-proxy@^1.1.7:\nversion \"1.1.8\"\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] react-navigation@3.0.1
Fixes https://github.com/react-navigation/react-navigation-stack/issues/53, so we can revert c993a9fcf3a816077895aeedfedc97df879dfd08 |
129,187 | 27.11.2018 12:07:50 | 28,800 | 867b5399ebc447378ca492d83e77017c0e51348f | [native] Reenable LayoutAnimation on Android
Removed in for some reason? | [
{
"change_type": "MODIFY",
"old_path": "native/app.react.js",
"new_path": "native/app.react.js",
"diff": "@@ -88,6 +88,11 @@ import DisconnectedBarVisibilityHandler\nfrom './navigation/disconnected-bar-visibility-handler.react';\nimport Socket from './socket.react';\n+if (Platform.OS === \"android\") {\n+ UIManager.setLayoutAnimationEnabledExperimental &&\n+ UIManager.setLayoutAnimationEnabledExperimental(true);\n+}\n+\nconst msInDay = 24 * 60 * 60 * 1000;\nconst ReduxifiedRootNavigator = reduxifyNavigator(RootNavigator, \"root\");\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Reenable LayoutAnimation on Android
Removed in 119178fb34e2220148f3b7463d245a171aa10066 for some reason? |
129,187 | 27.11.2018 13:45:05 | 28,800 | fc1e7a7033c5512b2b7f10514876d6481c5011c9 | [native] Extract FailedSend and message retry logic
This avoids Redux-connecting every single message. | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "native/chat/failed-send.react.js",
"diff": "+// @flow\n+\n+import type { ChatMessageInfoItemWithHeight } from './message-list.react';\n+import { chatMessageItemPropType } from 'lib/selectors/chat-selectors';\n+import {\n+ messageTypes,\n+ type SendTextMessageResult,\n+ type RawTextMessageInfo,\n+ type RawMessageInfo,\n+} from 'lib/types/message-types';\n+import type { AppState } from '../redux-setup';\n+import type { DispatchActionPromise } from 'lib/utils/action-utils';\n+\n+import * as React from 'react';\n+import { Text, StyleSheet, View } from 'react-native';\n+import invariant from 'invariant';\n+import PropTypes from 'prop-types';\n+\n+import { messageID } from 'lib/shared/message-utils';\n+import { connect } from 'lib/utils/redux-utils';\n+import {\n+ sendMessageActionTypes,\n+ sendMessage,\n+} from 'lib/actions/message-actions';\n+\n+import Button from '../components/button.react';\n+\n+type Props = {\n+ item: ChatMessageInfoItemWithHeight,\n+ // Redux state\n+ rawMessageInfo: RawMessageInfo,\n+ // Redux dispatch functions\n+ dispatchActionPromise: DispatchActionPromise,\n+ // async functions that hit server APIs\n+ sendMessage: (\n+ threadID: string,\n+ localID: string,\n+ text: string,\n+ ) => Promise<SendTextMessageResult>,\n+};\n+class FailedSend extends React.PureComponent<Props> {\n+\n+ static propTypes = {\n+ item: chatMessageItemPropType.isRequired,\n+ rawMessageInfo: PropTypes.object.isRequired,\n+ dispatchActionPromise: PropTypes.func.isRequired,\n+ sendMessage: PropTypes.func.isRequired,\n+ };\n+\n+ constructor(props: Props) {\n+ super(props);\n+ invariant(\n+ props.item.messageInfo.type === messageTypes.TEXT,\n+ \"TextMessage should only be used for messageTypes.TEXT\",\n+ );\n+ }\n+\n+ componentWillReceiveProps(nextProps: Props) {\n+ invariant(\n+ nextProps.item.messageInfo.type === messageTypes.TEXT,\n+ \"TextMessage should only be used for messageTypes.TEXT\",\n+ );\n+ }\n+\n+ render() {\n+ invariant(\n+ this.props.item.messageInfo.type === messageTypes.TEXT,\n+ \"TextMessage should only be used for messageTypes.TEXT\",\n+ );\n+ const { isViewer } = this.props.item.messageInfo.creator;\n+ if (!isViewer) {\n+ return null;\n+ }\n+ const { id } = this.props.item.messageInfo;\n+ if (id !== null && id !== undefined) {\n+ return null;\n+ }\n+ const sendFailed = this.props.item.localMessageInfo\n+ ? this.props.item.localMessageInfo.sendFailed\n+ : null;\n+ if (!sendFailed) {\n+ return null;\n+ }\n+ return (\n+ <View style={styles.failedSendInfo}>\n+ <Text style={styles.deliveryFailed} numberOfLines={1}>\n+ DELIVERY FAILED.\n+ </Text>\n+ <Button onPress={this.retrySend}>\n+ <Text style={styles.retrySend} numberOfLines={1}>\n+ RETRY?\n+ </Text>\n+ </Button>\n+ </View>\n+ );\n+ }\n+\n+ retrySend = () => {\n+ const { rawMessageInfo } = this.props;\n+ invariant(\n+ rawMessageInfo.type === messageTypes.TEXT,\n+ \"TextMessage should only be used for messageTypes.TEXT\",\n+ );\n+ const newRawMessageInfo = {\n+ ...rawMessageInfo,\n+ time: Date.now(),\n+ };\n+ this.props.dispatchActionPromise(\n+ sendMessageActionTypes,\n+ this.sendMessageAction(newRawMessageInfo),\n+ undefined,\n+ newRawMessageInfo,\n+ );\n+ }\n+\n+ async sendMessageAction(messageInfo: RawTextMessageInfo) {\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.sendMessage(\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+}\n+\n+const styles = StyleSheet.create({\n+ failedSendInfo: {\n+ paddingTop: 5,\n+ flex: 1,\n+ flexDirection: 'row',\n+ justifyContent: 'flex-end',\n+ marginRight: 20,\n+ },\n+ deliveryFailed: {\n+ paddingHorizontal: 3,\n+ color: '#555555',\n+ },\n+ retrySend: {\n+ paddingHorizontal: 3,\n+ color: \"#036AFF\",\n+ },\n+});\n+\n+export default connect(\n+ (state: AppState, ownProps: { item: ChatMessageInfoItemWithHeight }) => {\n+ const { messageInfo } = ownProps.item;\n+ invariant(\n+ messageInfo.type === messageTypes.TEXT,\n+ \"TextMessage should only be used for messageTypes.TEXT\",\n+ );\n+ const id = messageID(messageInfo);\n+ return {\n+ rawMessageInfo: state.messageStore.messages[id],\n+ };\n+ },\n+ { sendMessage },\n+)(FailedSend);\n"
},
{
"change_type": "MODIFY",
"old_path": "native/chat/text-message.react.js",
"new_path": "native/chat/text-message.react.js",
"diff": "@@ -5,21 +5,10 @@ import { chatMessageItemPropType } from 'lib/selectors/chat-selectors';\nimport type { TooltipItemData } from '../components/tooltip.react';\nimport {\nmessageTypes,\n- type SendTextMessageResult,\n- type RawTextMessageInfo,\n- type RawMessageInfo,\n} from 'lib/types/message-types';\n-import type { AppState } from '../redux-setup';\n-import type { DispatchActionPromise } from 'lib/utils/action-utils';\nimport React from 'react';\n-import {\n- Text,\n- StyleSheet,\n- View,\n- TouchableOpacity,\n- Clipboard,\n-} from 'react-native';\n+import { Text, StyleSheet, View, Clipboard } from 'react-native';\nimport invariant from 'invariant';\nimport PropTypes from 'prop-types';\nimport Color from 'color';\n@@ -27,17 +16,12 @@ import Hyperlink from 'react-native-hyperlink';\nimport Icon from 'react-native-vector-icons/Feather';\nimport { colorIsDark } from 'lib/shared/thread-utils';\n-import { messageID, messageKey } from 'lib/shared/message-utils';\n+import { messageKey } from 'lib/shared/message-utils';\nimport { stringForUser } from 'lib/shared/user-utils';\nimport { onlyEmojiRegex } from 'lib/shared/emojis';\n-import { connect } from 'lib/utils/redux-utils';\n-import {\n- sendMessageActionTypes,\n- sendMessage,\n-} from 'lib/actions/message-actions';\nimport Tooltip from '../components/tooltip.react';\n-import Button from '../components/button.react';\n+import FailedSend from './failed-send.react';\nfunction textMessageItemHeight(\nitem: ChatMessageInfoItemWithHeight,\n@@ -68,16 +52,6 @@ type Props = {\nitem: ChatMessageInfoItemWithHeight,\nfocused: bool,\ntoggleFocus: (messageKey: string) => void,\n- // Redux state\n- rawMessageInfo: RawMessageInfo,\n- // Redux dispatch functions\n- dispatchActionPromise: DispatchActionPromise,\n- // async functions that hit server APIs\n- sendMessage: (\n- threadID: string,\n- localID: string,\n- text: string,\n- ) => Promise<SendTextMessageResult>,\n};\nclass TextMessage extends React.PureComponent<Props> {\n@@ -85,9 +59,6 @@ class TextMessage extends React.PureComponent<Props> {\nitem: chatMessageItemPropType.isRequired,\nfocused: PropTypes.bool.isRequired,\ntoggleFocus: PropTypes.func.isRequired,\n- rawMessageInfo: PropTypes.object.isRequired,\n- dispatchActionPromise: PropTypes.func.isRequired,\n- sendMessage: PropTypes.func.isRequired,\n};\ntooltipConfig: $ReadOnlyArray<TooltipItemData>;\ntooltip: ?Tooltip;\n@@ -171,18 +142,7 @@ class TextMessage extends React.PureComponent<Props> {\n: null;\nif (sendFailed) {\ndeliveryIconName = \"x-circle\";\n- failedSendInfo = (\n- <View style={styles.failedSendInfo}>\n- <Text style={styles.deliveryFailed} numberOfLines={1}>\n- DELIVERY FAILED.\n- </Text>\n- <Button onPress={this.retrySend}>\n- <Text style={styles.retrySend} numberOfLines={1}>\n- RETRY?\n- </Text>\n- </Button>\n- </View>\n- );\n+ failedSendInfo = <FailedSend item={this.props.item} />;\n} else {\ndeliveryIconName = \"circle\";\n}\n@@ -270,49 +230,6 @@ class TextMessage extends React.PureComponent<Props> {\n}\n}\n- retrySend = () => {\n- const { rawMessageInfo } = this.props;\n- invariant(\n- rawMessageInfo.type === messageTypes.TEXT,\n- \"TextMessage should only be used for messageTypes.TEXT\",\n- );\n- const newRawMessageInfo = {\n- ...rawMessageInfo,\n- time: Date.now(),\n- };\n- this.props.dispatchActionPromise(\n- sendMessageActionTypes,\n- this.sendMessageAction(newRawMessageInfo),\n- undefined,\n- newRawMessageInfo,\n- );\n- }\n-\n- async sendMessageAction(messageInfo: RawTextMessageInfo) {\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.sendMessage(\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}\nconst styles = StyleSheet.create({\n@@ -376,39 +293,9 @@ const styles = StyleSheet.create({\nmarginLeft: 2,\nwidth: 16,\n},\n- failedSendInfo: {\n- paddingTop: 5,\n- flex: 1,\n- flexDirection: 'row',\n- justifyContent: 'flex-end',\n- marginRight: 20,\n- },\n- deliveryFailed: {\n- paddingHorizontal: 3,\n- color: '#555555',\n- },\n- retrySend: {\n- paddingHorizontal: 3,\n- color: \"#036AFF\",\n- },\n});\n-const ConnectedTextMessage = connect(\n- (state: AppState, ownProps: { item: ChatMessageInfoItemWithHeight }) => {\n- const { messageInfo } = ownProps.item;\n- invariant(\n- messageInfo.type === messageTypes.TEXT,\n- \"TextMessage should only be used for messageTypes.TEXT\",\n- );\n- const id = messageID(messageInfo);\n- return {\n- rawMessageInfo: state.messageStore.messages[id],\n- };\n- },\n- { sendMessage },\n-)(TextMessage);\n-\nexport {\n- ConnectedTextMessage as TextMessage,\n+ TextMessage,\ntextMessageItemHeight,\n};\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Extract FailedSend and message retry logic
This avoids Redux-connecting every single message. |
129,187 | 27.11.2018 16:45:38 | 28,800 | 80e0e1d93c84e66591262b25f7178c73cc678ecf | [web] Display delivery icon and allow message send retry | [
{
"change_type": "MODIFY",
"old_path": "web/chat/chat-message-list.css",
"new_path": "web/chat/chat-message-list.css",
"diff": "@@ -84,7 +84,7 @@ div.conversationHeader {\ntext-transform: uppercase;\ncolor: #777777;\nfont-size: 14px;\n- padding-bottom: 7px;\n+ padding: 7px 0;\ntext-align: center;\n}\ndiv.conversationHeader:last-child {\n@@ -102,7 +102,7 @@ div.robotext {\ndiv.textMessage {\npadding: 6px 12px;\n- margin: 0 12px;\n+ margin: 0 7px 0 12px;\ncursor: pointer;\n}\ndiv.normalTextMessage {\n@@ -124,3 +124,35 @@ span.authorName {\nfont-size: 14px;\npadding: 4px 24px;\n}\n+\n+div.content {\n+ display: flex;\n+ flex-shrink: 0;\n+ align-items: center;\n+ margin-right: 5px;\n+ margin-bottom: 5px;\n+}\n+div.iconContainer {\n+ margin-right: 1px;\n+}\n+div.iconContainer > svg {\n+ height: 16px;\n+}\n+\n+div.failedSend {\n+ text-transform: uppercase;\n+ display: flex;\n+ justify-content: flex-end;\n+ flex-shrink: 0;\n+ font-size: 14px;\n+ margin-right: 20px;\n+}\n+span.deliveryFailed {\n+ padding: 0 3px;\n+ color: #555555;\n+}\n+a.retrySend {\n+ padding: 0 3px;\n+ color: #036AFF;\n+ cursor: pointer;\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "web/chat/failed-send.react.js",
"diff": "+// @flow\n+\n+import {\n+ type ChatMessageInfoItem,\n+ chatMessageItemPropType,\n+} from 'lib/selectors/chat-selectors';\n+import {\n+ messageTypes,\n+ type SendTextMessageResult,\n+ type RawTextMessageInfo,\n+ type RawMessageInfo,\n+} from 'lib/types/message-types';\n+import { type ThreadInfo, threadInfoPropType } from 'lib/types/thread-types';\n+import type { AppState } from '../redux-setup';\n+import type { DispatchActionPromise } from 'lib/utils/action-utils';\n+\n+import * as React from 'react';\n+import invariant from 'invariant';\n+import PropTypes from 'prop-types';\n+\n+import { messageID } from 'lib/shared/message-utils';\n+import { connect } from 'lib/utils/redux-utils';\n+import {\n+ sendMessageActionTypes,\n+ sendMessage,\n+} from 'lib/actions/message-actions';\n+\n+import css from './chat-message-list.css';\n+\n+type Props = {|\n+ item: ChatMessageInfoItem,\n+ threadInfo: ThreadInfo,\n+ // Redux state\n+ rawMessageInfo: RawMessageInfo,\n+ // Redux dispatch functions\n+ dispatchActionPromise: DispatchActionPromise,\n+ // async functions that hit server APIs\n+ sendMessage: (\n+ threadID: string,\n+ localID: string,\n+ text: string,\n+ ) => Promise<SendTextMessageResult>,\n+|};\n+class FailedSend extends React.PureComponent<Props> {\n+\n+ static propTypes = {\n+ item: chatMessageItemPropType.isRequired,\n+ threadInfo: threadInfoPropType.isRequired,\n+ rawMessageInfo: PropTypes.object.isRequired,\n+ dispatchActionPromise: PropTypes.func.isRequired,\n+ sendMessage: PropTypes.func.isRequired,\n+ };\n+\n+ constructor(props: Props) {\n+ super(props);\n+ invariant(\n+ props.item.messageInfo.type === messageTypes.TEXT,\n+ \"TextMessage should only be used for messageTypes.TEXT\",\n+ );\n+ }\n+\n+ componentWillReceiveProps(nextProps: Props) {\n+ invariant(\n+ nextProps.item.messageInfo.type === messageTypes.TEXT,\n+ \"TextMessage should only be used for messageTypes.TEXT\",\n+ );\n+ }\n+\n+ render() {\n+ invariant(\n+ this.props.item.messageInfo.type === messageTypes.TEXT,\n+ \"TextMessage should only be used for messageTypes.TEXT\",\n+ );\n+ const { isViewer } = this.props.item.messageInfo.creator;\n+ if (!isViewer) {\n+ return null;\n+ }\n+ const { id } = this.props.item.messageInfo;\n+ if (id !== null && id !== undefined) {\n+ return null;\n+ }\n+ const sendFailed = this.props.item.localMessageInfo\n+ ? this.props.item.localMessageInfo.sendFailed\n+ : null;\n+ if (!sendFailed) {\n+ return null;\n+ }\n+ return (\n+ <div className={css.failedSend}>\n+ <span>\n+ Delivery failed.\n+ </span>\n+ <a onClick={this.retrySend} className={css.retrySend}>\n+ Retry?\n+ </a>\n+ </div>\n+ );\n+ }\n+\n+ retrySend = (event: SyntheticEvent<HTMLAnchorElement>) => {\n+ event.stopPropagation();\n+\n+ const { rawMessageInfo } = this.props;\n+ invariant(\n+ rawMessageInfo.type === messageTypes.TEXT,\n+ \"TextMessage should only be used for messageTypes.TEXT\",\n+ );\n+ const newRawMessageInfo = {\n+ ...rawMessageInfo,\n+ time: Date.now(),\n+ };\n+ this.props.dispatchActionPromise(\n+ sendMessageActionTypes,\n+ this.sendMessageAction(newRawMessageInfo),\n+ undefined,\n+ newRawMessageInfo,\n+ );\n+ }\n+\n+ async sendMessageAction(messageInfo: RawTextMessageInfo) {\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.sendMessage(\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+}\n+\n+export default connect(\n+ (state: AppState, ownProps: { item: ChatMessageInfoItem }) => {\n+ const { messageInfo } = ownProps.item;\n+ invariant(\n+ messageInfo.type === messageTypes.TEXT,\n+ \"TextMessage should only be used for messageTypes.TEXT\",\n+ );\n+ const id = messageID(messageInfo);\n+ return {\n+ rawMessageInfo: state.messageStore.messages[id],\n+ };\n+ },\n+ { sendMessage },\n+)(FailedSend);\n"
},
{
"change_type": "MODIFY",
"old_path": "web/chat/text-message.react.js",
"new_path": "web/chat/text-message.react.js",
"diff": "@@ -12,6 +12,9 @@ import invariant from 'invariant';\nimport classNames from 'classnames';\nimport Linkify from 'react-linkify';\nimport PropTypes from 'prop-types';\n+import CircleIcon from 'react-feather/dist/icons/circle';\n+import CheckCircleIcon from 'react-feather/dist/icons/check-circle';\n+import XCircleIcon from 'react-feather/dist/icons/x-circle';\nimport { colorIsDark } from 'lib/shared/thread-utils';\nimport { onlyEmojiRegex } from 'lib/shared/emojis';\n@@ -19,6 +22,7 @@ import { stringForUser } from 'lib/shared/user-utils';\nimport { messageKey } from 'lib/shared/message-utils';\nimport css from './chat-message-list.css';\n+import FailedSend from './failed-send.react';\ntype Props = {|\nitem: ChatMessageInfoItem,\n@@ -53,22 +57,26 @@ 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 = this.props.item.messageInfo.text;\n+ const { text, id, creator } = this.props.item.messageInfo;\n+ const threadColor = this.props.threadInfo.color;\n- const isViewer = this.props.item.messageInfo.creator.isViewer;\n+ const { isViewer } = creator;\nconst onlyEmoji = onlyEmojiRegex.test(text);\n- const containerClassName = classNames({\n+ const messageClassName = classNames({\n[css.textMessage]: true,\n[css.normalTextMessage]: !onlyEmoji,\n[css.emojiOnlyTextMessage]: onlyEmoji,\n+ });\n+ const contentClassName = classNames({\n+ [css.content]: true,\n[css.rightChatBubble]: isViewer,\n[css.leftChatBubble]: !isViewer,\n});\nlet darkColor = false;\nconst messageStyle = {};\nif (isViewer) {\n- darkColor = colorIsDark(this.props.threadInfo.color);\n- messageStyle.backgroundColor = `#${this.props.threadInfo.color}`;\n+ darkColor = colorIsDark(threadColor);\n+ messageStyle.backgroundColor = `#${threadColor}`;\nmessageStyle.color = darkColor ? 'white' : 'black';\n} else {\nmessageStyle.backgroundColor = \"#DDDDDDBB\";\n@@ -78,7 +86,7 @@ class TextMessage extends React.PureComponent<Props> {\nif (!isViewer && this.props.item.startsCluster) {\nauthorName = (\n<span className={css.authorName}>\n- {stringForUser(this.props.item.messageInfo.creator)}\n+ {stringForUser(creator)}\n</span>\n);\n}\n@@ -90,19 +98,54 @@ class TextMessage extends React.PureComponent<Props> {\n!isViewer && !this.props.item.startsCluster ? 0 : 8;\nmessageStyle.borderBottomLeftRadius =\n!isViewer && !this.props.item.endsCluster ? 0 : 8;\n- messageStyle.marginBottom = this.props.item.endsCluster ? 12 : 5;\n+\n+ let deliveryIcon = null;\n+ let failedSendInfo = null;\n+ if (isViewer) {\n+ let deliveryIconSpan;\n+ if (id !== null && id !== undefined) {\n+ deliveryIconSpan = <CheckCircleIcon />;\n+ } else {\n+ const sendFailed = this.props.item.localMessageInfo\n+ ? this.props.item.localMessageInfo.sendFailed\n+ : null;\n+ if (sendFailed) {\n+ deliveryIconSpan = <XCircleIcon />;\n+ failedSendInfo = (\n+ <FailedSend\n+ item={this.props.item}\n+ threadInfo={this.props.threadInfo}\n+ />\n+ );\n+ } else {\n+ deliveryIconSpan = <CircleIcon />;\n+ }\n+ }\n+ deliveryIcon = (\n+ <div\n+ className={css.iconContainer}\n+ style={{ color: `#${threadColor}` }}\n+ >\n+ {deliveryIconSpan}\n+ </div>\n+ );\n+ }\nreturn (\n<React.Fragment>\n+ {failedSendInfo}\n+ <div className={contentClassName}>\n<div\n- className={containerClassName}\nonClick={this.onClick}\n+ className={messageClassName}\nstyle={messageStyle}\n>\n<Linkify>\n{text}\n</Linkify>\n</div>\n+ {deliveryIcon}\n+ </div>\n{authorName}\n</React.Fragment>\n);\n"
},
{
"change_type": "MODIFY",
"old_path": "web/package.json",
"new_path": "web/package.json",
"diff": "\"react\": \"^16.2.0\",\n\"react-color\": \"^2.13.0\",\n\"react-dom\": \"^16.2.0\",\n+ \"react-feather\": \"^1.1.4\",\n\"react-hot-loader\": \"^4.2.0\",\n\"react-linkify\": \"^0.2.2\",\n\"react-redux\": \"^5.0.5\",\n"
},
{
"change_type": "MODIFY",
"old_path": "yarn.lock",
"new_path": "yarn.lock",
"diff": "@@ -9165,15 +9165,7 @@ react-deep-force-update@^2.1.1:\nresolved \"https://registry.yarnpkg.com/react-deep-force-update/-/react-deep-force-update-2.1.3.tgz#740612322e617bcced38f61794a4af75dc3d98e7\"\nintegrity sha512-lqD4eHKVuB65RyO/hGbEST53E2/GPbcIPcFYyeW/p4vNngtH4G7jnKGlU6u1OqrFo0uNfIvwuBOg98IbLHlNEA==\n-react-devtools-core@^3.4.1:\n- version \"3.4.2\"\n- resolved \"https://registry.yarnpkg.com/react-devtools-core/-/react-devtools-core-3.4.2.tgz#4888b428f1db9a3078fdff66a1da14f71fb1680e\"\n- integrity sha512-1pqbxenMeOiVPLf5Fm69woc+Q/pb/lLfWCizJuVJQDm9v7x0fcr76VMcq6Q30Onv3ikkfrlAQgOcOdCk/0t5tA==\n- dependencies:\n- shell-quote \"^1.6.1\"\n- ws \"^3.3.1\"\n-\n-react-devtools-core@^3.4.2:\n+react-devtools-core@^3.4.1, react-devtools-core@^3.4.2:\nversion \"3.4.2\"\nresolved \"https://registry.yarnpkg.com/react-devtools-core/-/react-devtools-core-3.4.2.tgz#4888b428f1db9a3078fdff66a1da14f71fb1680e\"\nintegrity sha512-1pqbxenMeOiVPLf5Fm69woc+Q/pb/lLfWCizJuVJQDm9v7x0fcr76VMcq6Q30Onv3ikkfrlAQgOcOdCk/0t5tA==\n@@ -9203,6 +9195,11 @@ react-dom@^16.2.0:\nprop-types \"^15.6.2\"\nscheduler \"^0.10.0\"\n+react-feather@^1.1.4:\n+ version \"1.1.4\"\n+ resolved \"https://registry.yarnpkg.com/react-feather/-/react-feather-1.1.4.tgz#d0143da95f9d52843cf13a553091573a7c617897\"\n+ integrity sha512-Odke3WUl00+a2scGQKlep4m+qDESl/x+PsTRB3v6fAV/2dteF4EaRjqhX8h7HM3mU3V3v0xGTv8Z5S26bpQ5PQ==\n+\nreact-hot-loader@^3.1.3:\nversion \"3.1.3\"\nresolved \"https://registry.yarnpkg.com/react-hot-loader/-/react-hot-loader-3.1.3.tgz#6f92877326958c7cb0134b512474517869126082\"\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [web] Display delivery icon and allow message send retry |
129,187 | 28.11.2018 17:26:27 | 28,800 | 6f3d8af16acb23fafa56d7b149dc326bb94685e6 | [web] Visual tweaks to "send failed" div | [
{
"change_type": "MODIFY",
"old_path": "web/chat/chat-message-list.css",
"new_path": "web/chat/chat-message-list.css",
"diff": "@@ -102,7 +102,7 @@ div.robotext {\ndiv.textMessage {\npadding: 6px 12px;\n- margin: 0 7px 0 12px;\n+ margin: 0 4px 0 12px;\ncursor: pointer;\n}\ndiv.normalTextMessage {\n@@ -113,12 +113,6 @@ div.emojiOnlyTextMessage {\nfont-size: 32px;\nfont-family: sans-serif;\n}\n-div.leftChatBubble {\n- align-self: flex-start;\n-}\n-div.rightChatBubble {\n- align-self: flex-end;\n-}\nspan.authorName {\ncolor: #777777;\nfont-size: 14px;\n@@ -129,9 +123,16 @@ div.content {\ndisplay: flex;\nflex-shrink: 0;\nalign-items: center;\n- margin-right: 5px;\nmargin-bottom: 5px;\n}\n+div.nonViewerContent {\n+ align-self: flex-start;\n+ margin-right: 8px;\n+}\n+div.viewerContent {\n+ align-self: flex-end;\n+ margin-right: 4px;\n+}\ndiv.iconContainer {\nmargin-right: 1px;\n}\n@@ -145,7 +146,8 @@ div.failedSend {\njustify-content: flex-end;\nflex-shrink: 0;\nfont-size: 14px;\n- margin-right: 20px;\n+ margin-right: 30px;\n+ padding-bottom: 6px;\n}\nspan.deliveryFailed {\npadding: 0 3px;\n"
},
{
"change_type": "MODIFY",
"old_path": "web/chat/text-message.react.js",
"new_path": "web/chat/text-message.react.js",
"diff": "@@ -69,8 +69,8 @@ class TextMessage extends React.PureComponent<Props> {\n});\nconst contentClassName = classNames({\n[css.content]: true,\n- [css.rightChatBubble]: isViewer,\n- [css.leftChatBubble]: !isViewer,\n+ [css.viewerContent]: isViewer,\n+ [css.nonViewerContent]: !isViewer,\n});\nlet darkColor = false;\nconst messageStyle = {};\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [web] Visual tweaks to "send failed" div |
129,187 | 28.11.2018 17:26:46 | 28,800 | 9682f69bc9739860a8a6e9b66626bd4673770a89 | [lib] Ensure reordering of messageIDs after message send success | [
{
"change_type": "MODIFY",
"old_path": "lib/reducers/message-reducer.js",
"new_path": "lib/reducers/message-reducer.js",
"diff": "@@ -597,13 +597,10 @@ function reduceMessageStore(\n[threadID]: {\n...messageStore.threads[threadID],\nmessageIDs: _orderBy([\n- (messageID: string) => messages[localID].time,\n+ (messageID: string) => messages[messageID].time,\n])('desc')(messageStore.threads[threadID].messageIDs),\n},\n};\n- threads[threadID].messageIDs = _orderBy([\n- (messageID: string) => messages[messageID].time,\n- ])('desc')(threads[threadID].messageIDs);\nreturn { ...messageStore, messages, threads, local };\n}\n@@ -674,9 +671,10 @@ function reduceMessageStore(\ntime: payload.time,\n};\nconst threadID = payload.threadID;\n- const newMessageIDs = _uniq(\n- messageStore.threads[threadID].messageIDs.map(replaceMessageKey),\n- );\n+ const newMessageIDs = _flow(\n+ _uniq,\n+ _orderBy([ (messageID: string) => newMessages[messageID].time ])('desc'),\n+ )(messageStore.threads[threadID].messageIDs.map(replaceMessageKey));\nconst currentAsOf = Math.max(payload.time, messageStore.currentAsOf);\nconst local = _pickBy(\n(localInfo: LocalMessageInfo, key: string) => key !== payload.localID,\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [lib] Ensure reordering of messageIDs after message send success |
129,187 | 28.11.2018 17:32:54 | 28,800 | 279d6e963b002624f804c4e327b6d1d11665410f | Make message failed delivery indicator red | [
{
"change_type": "MODIFY",
"old_path": "native/chat/text-message.react.js",
"new_path": "native/chat/text-message.react.js",
"diff": "@@ -134,6 +134,7 @@ class TextMessage extends React.PureComponent<Props> {\nlet failedSendInfo = null;\nif (isViewer) {\nlet deliveryIconName;\n+ let deliveryIconColor = threadColor;\nif (id !== null && id !== undefined) {\ndeliveryIconName = \"check-circle\";\n} else {\n@@ -142,6 +143,7 @@ class TextMessage extends React.PureComponent<Props> {\n: null;\nif (sendFailed) {\ndeliveryIconName = \"x-circle\";\n+ deliveryIconColor = \"FF0000\";\nfailedSendInfo = <FailedSend item={this.props.item} />;\n} else {\ndeliveryIconName = \"circle\";\n@@ -151,7 +153,7 @@ class TextMessage extends React.PureComponent<Props> {\n<View style={styles.iconContainer}>\n<Icon\nname={deliveryIconName}\n- style={[styles.icon, { color: `#${threadColor}` }]}\n+ style={[styles.icon, { color: `#${deliveryIconColor}` }]}\n/>\n</View>\n);\n"
},
{
"change_type": "MODIFY",
"old_path": "web/chat/text-message.react.js",
"new_path": "web/chat/text-message.react.js",
"diff": "@@ -103,6 +103,7 @@ class TextMessage extends React.PureComponent<Props> {\nlet failedSendInfo = null;\nif (isViewer) {\nlet deliveryIconSpan;\n+ let deliveryIconColor = threadColor;\nif (id !== null && id !== undefined) {\ndeliveryIconSpan = <CheckCircleIcon />;\n} else {\n@@ -111,6 +112,7 @@ class TextMessage extends React.PureComponent<Props> {\n: null;\nif (sendFailed) {\ndeliveryIconSpan = <XCircleIcon />;\n+ deliveryIconColor = \"FF0000\";\nfailedSendInfo = (\n<FailedSend\nitem={this.props.item}\n@@ -124,7 +126,7 @@ class TextMessage extends React.PureComponent<Props> {\ndeliveryIcon = (\n<div\nclassName={css.iconContainer}\n- style={{ color: `#${threadColor}` }}\n+ style={{ color: `#${deliveryIconColor}` }}\n>\n{deliveryIconSpan}\n</div>\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | Make message failed delivery indicator red |
129,187 | 30.11.2018 11:15:16 | 18,000 | d95d6d4eec66910942d7cf3e11eb502d8d9202c9 | [lib] Never include deviceToken in crash payloads | [
{
"change_type": "MODIFY",
"old_path": "lib/utils/sanitization.js",
"new_path": "lib/utils/sanitization.js",
"diff": "@@ -6,6 +6,7 @@ import type {\nAppState,\n} from '../types/redux-types';\nimport { setNewSessionActionType } from './action-utils';\n+import { setDeviceTokenActionTypes } from '../actions/device-actions';\nfunction sanitizeAction(action: BaseAction): BaseAction {\nif (action.type === setNewSessionActionType) {\n@@ -29,13 +30,28 @@ function sanitizeAction(action: BaseAction): BaseAction {\n},\n};\n}\n+ } else if (action.type === setDeviceTokenActionTypes.started) {\n+ return {\n+ type: \"SET_DEVICE_TOKEN_STARTED\",\n+ payload: \"FAKE\",\n+ loadingInfo: action.loadingInfo,\n+ };\n+ } else if (action.type === setDeviceTokenActionTypes.success) {\n+ return {\n+ type: \"SET_DEVICE_TOKEN_SUCCESS\",\n+ payload: \"FAKE\",\n+ loadingInfo: action.loadingInfo,\n+ };\n}\nreturn action;\n}\nfunction sanitizeState<T>(state: AppState): AppState {\nif (state.cookie !== undefined && state.cookie !== null) {\n- return ({ ...state, cookie: null }: NativeAppState);\n+ state = ({ ...state, cookie: null }: NativeAppState);\n+ }\n+ if (state.deviceToken !== undefined && state.deviceToken !== null) {\n+ state = ({ ...state, deviceToken: null }: NativeAppState);\n}\nreturn state;\n}\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [lib] Never include deviceToken in crash payloads |
129,187 | 30.11.2018 11:26:51 | 18,000 | 5b047230b894f0ca5bcafb234955b182fa511bf4 | [native] Fix stateVersion upgrade code to set nextLocalID to highest + 1
It was setting it just to the highest, which can be -1, which leads to a crash. | [
{
"change_type": "MODIFY",
"old_path": "native/persist.js",
"new_path": "native/persist.js",
"diff": "@@ -89,7 +89,7 @@ const migrations = {\n}),\n[9]: (state: AppState) => ({\n...state,\n- nextLocalID: highestLocalIDSelector(state),\n+ nextLocalID: highestLocalIDSelector(state) + 1,\nconnection: {\n...state.connection,\nlateResponses: [],\n@@ -104,6 +104,9 @@ const migrations = {\n}),\n[10]: (state: AppState) => ({\n...state,\n+ // Doing this again because in earlier codeVersions I accidentally forgot\n+ // to add 1\n+ nextLocalID: highestLocalIDSelector(state) + 1,\nconnection: {\n...state.connection,\nshowDisconnectedBar: false,\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Fix stateVersion upgrade code to set nextLocalID to highest + 1
It was setting it just to the highest, which can be -1, which leads to a crash. |
129,187 | 30.11.2018 12:23:12 | 18,000 | 4a9b932118e543b54a918260ff8d83793be54159 | [server] Include ServerError payload in serverSocketMessageTypes.ERROR | [
{
"change_type": "MODIFY",
"old_path": "server/src/socket/socket.js",
"new_path": "server/src/socket/socket.js",
"diff": "@@ -311,11 +311,20 @@ class Socket {\nthis.ws.close(4101, error.message);\nreturn;\n}\n+ if (error.payload) {\nthis.sendMessage({\ntype: serverSocketMessageTypes.ERROR,\nresponseTo,\nmessage: error.message,\n+ payload: error.payload,\n});\n+ } else {\n+ this.sendMessage({\n+ type: serverSocketMessageTypes.ERROR,\n+ responseTo,\n+ message: error.message,\n+ });\n+ }\nif (error.message === \"not_logged_in\") {\nthis.ws.close(4102, error.message);\n} else if (error.message === \"session_mutated_from_socket\") {\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [server] Include ServerError payload in serverSocketMessageTypes.ERROR |
129,187 | 30.11.2018 12:36:37 | 18,000 | f48c2906dd07474170439fe75dae8c096643c004 | [server] Sanitize reportTypes.ERROR | [
{
"change_type": "MODIFY",
"old_path": "server/src/creators/report-creator.js",
"new_path": "server/src/creators/report-creator.js",
"diff": "@@ -14,6 +14,7 @@ import bots from 'lib/facts/bots';\nimport _isEqual from 'lodash/fp/isEqual';\nimport { filterRawEntryInfosByCalendarQuery } from 'lib/shared/entry-utils';\n+import { sanitizeAction, sanitizeState } from 'lib/utils/sanitization';\nimport { dbQuery, SQL } from '../database';\nimport createIDs from './id-creator';\n@@ -44,6 +45,12 @@ async function createReport(\n} else {\n({ type, platformDetails, ...report } = request);\ntime = Date.now();\n+ report = {\n+ ...report,\n+ preloadedState: sanitizeState(report.preloadedState),\n+ currentState: sanitizeState(report.currentState),\n+ actions: report.actions.map(sanitizeAction),\n+ };\n}\nconst row = [\nid,\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [server] Sanitize reportTypes.ERROR |
129,187 | 30.11.2018 14:03:55 | 18,000 | 8a83b9859ef5f0a010a1cf729c82f3e29d9847da | [native] Add LoadingIndicator to Entry
Several other changes/improvement to `Entry` included. | [
{
"change_type": "MODIFY",
"old_path": "native/calendar/calendar.react.js",
"new_path": "native/calendar/calendar.react.js",
"diff": "@@ -954,15 +954,7 @@ class InnerCalendar extends React.PureComponent<Props, State> {\n}\nthis.latestExtraData = {\nactiveEntries: _pickBy(\n- (_, key: string) => {\n- if (visibleEntries[key]) {\n- return true;\n- }\n- const item = _find\n- (item => item.entryInfo && entryKey(item.entryInfo) === key)\n- (ldwh);\n- return !!item;\n- },\n+ (_, key: string) => visibleEntries[key],\n)(this.latestExtraData.activeEntries),\nvisibleEntries,\n};\n"
},
{
"change_type": "MODIFY",
"old_path": "native/calendar/entry.react.js",
"new_path": "native/calendar/entry.react.js",
"diff": "@@ -74,6 +74,7 @@ import {\nforegroundKeySelector,\nnonThreadCalendarQuery,\n} from '../selectors/nav-selectors';\n+import LoadingIndicator from './loading-indicator.react';\ntype Props = {\nnavigation: NavigationScreenProp<NavigationRoute>,\n@@ -141,7 +142,7 @@ class InternalEntry extends React.Component<Props, State> {\nsuper(props);\ninvariant(props.threadInfo, \"should be set\");\nthis.state = {\n- editing: InternalEntry.isActive(props),\n+ editing: false,\ntext: props.entryInfo.text,\nloadingStatus: \"inactive\",\nheight: props.entryInfo.textHeight,\n@@ -151,6 +152,7 @@ class InternalEntry extends React.Component<Props, State> {\n// threadInfo is undefined.\nthreadInfo: props.threadInfo,\n};\n+ this.state.editing = InternalEntry.isActive(props, this.state);\n}\nguardedSetState(input: $Shape<State>) {\n@@ -159,49 +161,46 @@ class InternalEntry extends React.Component<Props, State> {\n}\n}\n- componentWillReceiveProps(nextProps: Props) {\n- const wasActive = InternalEntry.isActive(this.props);\n- const willBeActive = InternalEntry.isActive(nextProps);\n+ shouldComponentUpdate(nextProps: Props, nextState: State) {\n+ const omitEntryInfo = _omit([\"entryInfo\"]);\n+ return !shallowequal(nextState, this.state) ||\n+ !shallowequal(omitEntryInfo(nextProps), omitEntryInfo(this.props)) ||\n+ !_isEqual(nextProps.entryInfo)(this.props.entryInfo);\n+ }\n+\n+ componentDidUpdate(prevProps: Props, prevState: State) {\n+ const wasActive = InternalEntry.isActive(prevProps, prevState);\n+ const isActive = InternalEntry.isActive(this.props, this.state);\n+\nif (\n- !willBeActive &&\n- (nextProps.entryInfo.text !== this.props.entryInfo.text ||\n- nextProps.entryInfo.textHeight !== this.props.entryInfo.textHeight) &&\n- (nextProps.entryInfo.text !== this.state.text ||\n- nextProps.entryInfo.textHeight !== this.state.height)\n+ !isActive &&\n+ (this.props.entryInfo.text !== prevProps.entryInfo.text ||\n+ this.props.entryInfo.textHeight !== prevProps.entryInfo.textHeight) &&\n+ (this.props.entryInfo.text !== this.state.text ||\n+ this.props.entryInfo.textHeight !== this.state.height)\n) {\nthis.guardedSetState({\n- text: nextProps.entryInfo.text,\n- height: nextProps.entryInfo.textHeight,\n+ text: this.props.entryInfo.text,\n+ height: this.props.entryInfo.textHeight,\n});\n+ this.currentlySaving = null;\n}\n+\nif (\n- nextProps.threadInfo &&\n- !_isEqual(nextProps.threadInfo)(this.state.threadInfo)\n+ this.props.threadInfo &&\n+ !_isEqual(this.props.threadInfo)(this.state.threadInfo)\n) {\n- this.guardedSetState({ threadInfo: nextProps.threadInfo });\n- }\n- if (!nextProps.active && wasActive && this.textInput) {\n- this.textInput.blur();\n- this.completeEdit();\n- }\n+ this.guardedSetState({ threadInfo: this.props.threadInfo });\n}\n- shouldComponentUpdate(nextProps: Props, nextState: State) {\n- const omitEntryInfo = _omit([\"entryInfo\"]);\n- return !shallowequal(nextState, this.state) ||\n- !shallowequal(omitEntryInfo(nextProps), omitEntryInfo(this.props)) ||\n- !_isEqual(nextProps.entryInfo)(this.props.entryInfo);\n+ // Our parent will set the active prop to false if something else gets\n+ // pressed or if the Entry is scrolled out of view. In either of those cases\n+ // we should complete the edit process.\n+ if (!this.props.active && prevProps.active) {\n+ this.completeEdit();\n}\n- componentWillUpdate(nextProps: Props, nextState: State) {\n- const wasActive = InternalEntry.isActive(this.props);\n- const willBeActive = InternalEntry.isActive(nextProps);\n- const wasEditing = InternalEntry.isEditing(this.props, this.state);\n- const willBeEditing = InternalEntry.isEditing(nextProps, nextState);\n- if (!willBeEditing && wasEditing && this.textInput) {\n- this.textInput.blur();\n- }\n- if (nextState.height !== this.state.height || willBeActive !== wasActive) {\n+ if (this.state.height !== prevState.height || isActive !== wasActive) {\nLayoutAnimation.easeInEaseOut();\n}\n}\n@@ -216,17 +215,16 @@ class InternalEntry extends React.Component<Props, State> {\nthis.props.entryRef(entryKey(this.props.entryInfo), null);\n}\n- static isActive(props: Props) {\n- return props.active || !props.entryInfo.id;\n- }\n-\n- static isEditing(props: Props, state: State) {\n- return (props.active && state.editing) || !props.entryInfo.id;\n+ static isActive(props: Props, state: State) {\n+ return props.active ||\n+ state.editing ||\n+ !props.entryInfo.id ||\n+ state.loadingStatus !== \"inactive\";\n}\nrender() {\n- const active = InternalEntry.isActive(this.props);\n- const editing = InternalEntry.isEditing(this.props, this.state);\n+ const active = InternalEntry.isActive(this.props, this.state);\n+ const { editing } = this.state;\nconst darkColor = colorIsDark(this.state.threadInfo.color);\nlet actionLinks = null;\n@@ -297,6 +295,10 @@ class InternalEntry extends React.Component<Props, State> {\n</Button>\n</View>\n<View style={styles.rightLinks}>\n+ <LoadingIndicator\n+ loadingStatus={this.state.loadingStatus}\n+ color={actionLinksColor}\n+ />\n<Button\nonPress={this.onPressThreadName}\niosFormat=\"highlight\"\n@@ -384,7 +386,7 @@ class InternalEntry extends React.Component<Props, State> {\ntextInputRef = (textInput: ?TextInput) => {\nthis.textInput = textInput;\n- if (textInput && InternalEntry.isEditing(this.props, this.state)) {\n+ if (textInput && this.state.editing) {\nthis.enterEditMode();\n}\n}\n@@ -414,9 +416,17 @@ class InternalEntry extends React.Component<Props, State> {\nsetActive = () => this.props.makeActive(entryKey(this.props.entryInfo), true);\ncompleteEdit = () => {\n+ // This gets called from CalendarInputBar (save button above keyboard),\n+ // onPressEdit (save button in Entry action links), and in\n+ // componentDidUpdate above when Calendar sets this Entry to inactive.\n+ // Calendar does this if something else gets pressed or the Entry is\n+ // scrolled out of view. Note that an Entry won't consider itself inactive\n+ // until it's done updating the server with its state, and if the network\n+ // requests fail it may stay \"active\".\n+ if (this.textInput) {\n+ this.textInput.blur();\n+ }\nthis.onBlur();\n- this.guardedSetState({ editing: false });\n- this.props.makeActive(entryKey(this.props.entryInfo), false);\n}\nonBlur = () => {\n@@ -425,6 +435,8 @@ class InternalEntry extends React.Component<Props, State> {\n} else if (this.props.entryInfo.text !== this.state.text) {\nthis.save();\n}\n+ this.guardedSetState({ editing: false });\n+ this.props.makeActive(entryKey(this.props.entryInfo), false);\n}\nsave = () => {\n@@ -466,6 +478,7 @@ class InternalEntry extends React.Component<Props, State> {\n}\n}\n+ this.guardedSetState({ loadingStatus: \"loading\" });\nif (!serverID) {\nthis.props.dispatchActionPromise(\ncreateEntryActionTypes,\n@@ -483,7 +496,6 @@ class InternalEntry extends React.Component<Props, State> {\nconst localID = this.props.entryInfo.localID;\ninvariant(localID, \"if there's no serverID, there should be a localID\");\nconst curSaveAttempt = this.nextSaveAttemptIndex++;\n- this.guardedSetState({ loadingStatus: \"loading\" });\ntry {\nconst response = await this.props.createEntry({\ntext,\n@@ -520,7 +532,6 @@ class InternalEntry extends React.Component<Props, State> {\nasync saveAction(entryID: string, newText: string) {\nconst curSaveAttempt = this.nextSaveAttemptIndex++;\n- this.guardedSetState({ loadingStatus: \"loading\" });\ntry {\nconst response = await this.props.saveEntry({\nentryID,\n@@ -538,17 +549,22 @@ class InternalEntry extends React.Component<Props, State> {\nthis.guardedSetState({ loadingStatus: \"error\" });\n}\nif (e instanceof ServerError && e.message === 'concurrent_modification') {\n+ const revertedText = e.payload.db;\nconst onRefresh = () => {\n- this.guardedSetState({ loadingStatus: \"inactive\" });\n+ this.guardedSetState({\n+ loadingStatus: \"inactive\",\n+ text: revertedText,\n+ });\n+ this.currentlySaving = revertedText;\nthis.props.dispatchActionPayload(\nconcurrentModificationResetActionType,\n- { id: entryID, dbText: e.payload.db },\n+ { id: entryID, dbText: revertedText },\n);\n};\nAlert.alert(\n\"Concurrent modification\",\n\"It looks like somebody is attempting to modify that field at the \" +\n- \"same time as you! Please refresh the entry and try again.\",\n+ \"same time as you! Please try again.\",\n[\n{ text: 'OK', onPress: onRefresh },\n],\n@@ -564,7 +580,7 @@ class InternalEntry extends React.Component<Props, State> {\n}\nonPressEdit = () => {\n- if (InternalEntry.isEditing(this.props, this.state)) {\n+ if (this.state.editing) {\nthis.completeEdit();\n} else {\nthis.guardedSetState({ editing: true });\n@@ -641,7 +657,7 @@ const styles = StyleSheet.create({\n},\ntextInput: {\nposition: 'absolute',\n- top: Platform.OS === \"android\" ? 5 : 0,\n+ top: Platform.OS === \"android\" ? 2 : 0,\nleft: 10,\nright: 10,\npadding: 0,\n@@ -693,6 +709,7 @@ const styles = StyleSheet.create({\n},\npencilIcon: {\npaddingTop: 1,\n+ lineHeight: 13,\n},\n});\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "native/calendar/loading-indicator.react.js",
"diff": "+// @flow\n+\n+import type { LoadingStatus } from 'lib/types/loading-types';\n+\n+import * as React from 'react';\n+import { ActivityIndicator, StyleSheet, Platform } from 'react-native';\n+import Icon from 'react-native-vector-icons/Feather';\n+\n+type Props = {|\n+ loadingStatus: LoadingStatus,\n+ color: string,\n+|};\n+function LoadingIndicator(props: Props) {\n+ if (props.loadingStatus === \"error\") {\n+ return <Icon name=\"x-circle\" style={styles.errorIcon} />;\n+ } else if (props.loadingStatus === \"loading\") {\n+ return <ActivityIndicator size=\"small\" color={props.color} />;\n+ } else {\n+ return null;\n+ }\n+}\n+\n+const styles = StyleSheet.create({\n+ errorIcon: {\n+ color: 'red',\n+ paddingTop: Platform.OS === \"android\" ? 6 : 4,\n+ fontSize: 16,\n+ },\n+});\n+\n+export default LoadingIndicator;\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Add LoadingIndicator to Entry
Several other changes/improvement to `Entry` included. |
129,187 | 30.11.2018 15:27:49 | 18,000 | 2e09820092079e2825df6013a35d91fcb583612d | Retry entry saves after reconnecting
Also some improvements to web `Entry`:
1. Don't re-save the same string twice in a row
2. Allow clicking on `textarea` while it's focused
3. Avoid temporary revert after saving | [
{
"change_type": "MODIFY",
"old_path": "native/calendar/entry.react.js",
"new_path": "native/calendar/entry.react.js",
"diff": "@@ -76,7 +76,7 @@ import {\n} from '../selectors/nav-selectors';\nimport LoadingIndicator from './loading-indicator.react';\n-type Props = {\n+type Props = {|\nnavigation: NavigationScreenProp<NavigationRoute>,\nentryInfo: EntryInfoWithHeight,\nvisible: bool,\n@@ -90,6 +90,7 @@ type Props = {\ncalendarQuery: () => CalendarQuery,\nthreadPickerActive: bool,\nforegroundKey: string,\n+ online: bool,\n// Redux dispatch functions\ndispatchActionPayload: DispatchActionPayload,\ndispatchActionPromise: DispatchActionPromise,\n@@ -97,7 +98,7 @@ type Props = {\ncreateEntry: (info: CreateEntryInfo) => Promise<CreateEntryPayload>,\nsaveEntry: (info: SaveEntryInfo) => Promise<SaveEntryResult>,\ndeleteEntry: (info: DeleteEntryInfo) => Promise<DeleteEntryPayload>,\n-};\n+|};\ntype State = {|\nediting: bool,\ntext: string,\n@@ -123,6 +124,7 @@ class InternalEntry extends React.Component<Props, State> {\ncalendarQuery: PropTypes.func.isRequired,\nthreadPickerActive: PropTypes.bool.isRequired,\nforegroundKey: PropTypes.string.isRequired,\n+ online: PropTypes.bool.isRequired,\ndispatchActionPayload: PropTypes.func.isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\ncreateEntry: PropTypes.func.isRequired,\n@@ -203,6 +205,14 @@ class InternalEntry extends React.Component<Props, State> {\nif (this.state.height !== prevState.height || isActive !== wasActive) {\nLayoutAnimation.easeInEaseOut();\n}\n+\n+ if (\n+ this.props.online &&\n+ !prevProps.online &&\n+ this.state.loadingStatus === \"error\"\n+ ) {\n+ this.save();\n+ }\n}\ncomponentDidMount() {\n@@ -526,6 +536,8 @@ class InternalEntry extends React.Component<Props, State> {\nif (curSaveAttempt + 1 === this.nextSaveAttemptIndex) {\nthis.guardedSetState({ loadingStatus: \"error\" });\n}\n+ this.currentlySaving = null;\n+ this.creating = false;\nthrow e;\n}\n}\n@@ -548,6 +560,7 @@ class InternalEntry extends React.Component<Props, State> {\nif (curSaveAttempt + 1 === this.nextSaveAttemptIndex) {\nthis.guardedSetState({ loadingStatus: \"error\" });\n}\n+ this.currentlySaving = null;\nif (e instanceof ServerError && e.message === 'concurrent_modification') {\nconst revertedText = e.payload.db;\nconst onRefresh = () => {\n@@ -555,7 +568,6 @@ class InternalEntry extends React.Component<Props, State> {\nloadingStatus: \"inactive\",\ntext: revertedText,\n});\n- this.currentlySaving = revertedText;\nthis.props.dispatchActionPayload(\nconcurrentModificationResetActionType,\n{ id: entryID, dbText: revertedText },\n@@ -724,6 +736,7 @@ const Entry = connect(\ncalendarQuery: nonThreadCalendarQuery(state),\nthreadPickerActive: activeThreadPickerSelector(state),\nforegroundKey: foregroundKeySelector(state),\n+ online: state.connection.status === \"connected\",\n}),\n{ createEntry, saveEntry, deleteEntry },\n)(InternalEntry);\n"
},
{
"change_type": "MODIFY",
"old_path": "web/calendar/entry.react.js",
"new_path": "web/calendar/entry.react.js",
"diff": "@@ -50,7 +50,7 @@ import { HistoryVector, DeleteVector } from '../vectors.react';\nimport LogInFirstModal from '../modals/account/log-in-first-modal.react';\nimport { nonThreadCalendarQuery } from '../selectors/nav-selectors';\n-type Props = {\n+type Props = {|\ninnerRef: (key: string, me: Entry) => void,\nentryInfo: EntryInfo,\nfocusOnFirstEntryNewerThan: (time: number) => void,\n@@ -60,6 +60,7 @@ type Props = {\nthreadInfo: ThreadInfo,\nloggedIn: bool,\ncalendarQuery: () => CalendarQuery,\n+ online: bool,\n// Redux dispatch functions\ndispatchActionPayload: DispatchActionPayload,\ndispatchActionPromise: DispatchActionPromise,\n@@ -67,21 +68,37 @@ type Props = {\ncreateEntry: (info: CreateEntryInfo) => Promise<CreateEntryPayload>,\nsaveEntry: (info: SaveEntryInfo) => Promise<SaveEntryResult>,\ndeleteEntry: (info: DeleteEntryInfo) => Promise<DeleteEntryPayload>,\n-};\n-type State = {\n+|};\n+type State = {|\nfocused: bool,\nloadingStatus: LoadingStatus,\ntext: string,\n-};\n-\n+|};\nclass Entry extends React.PureComponent<Props, State> {\n+ static propTypes = {\n+ innerRef: PropTypes.func.isRequired,\n+ entryInfo: entryInfoPropType.isRequired,\n+ focusOnFirstEntryNewerThan: PropTypes.func.isRequired,\n+ setModal: PropTypes.func.isRequired,\n+ tabIndex: PropTypes.number.isRequired,\n+ threadInfo: threadInfoPropType.isRequired,\n+ loggedIn: PropTypes.bool.isRequired,\n+ calendarQuery: PropTypes.func.isRequired,\n+ online: PropTypes.bool.isRequired,\n+ dispatchActionPayload: PropTypes.func.isRequired,\n+ dispatchActionPromise: PropTypes.func.isRequired,\n+ createEntry: PropTypes.func.isRequired,\n+ saveEntry: PropTypes.func.isRequired,\n+ deleteEntry: PropTypes.func.isRequired,\n+ };\ntextarea: ?HTMLTextAreaElement;\ncreating: bool;\nneedsUpdateAfterCreation: bool;\nneedsDeleteAfterCreation: bool;\nnextSaveAttemptIndex: number;\nmounted: bool;\n+ currentlySaving: ?string;\nconstructor(props: Props) {\nsuper(props);\n@@ -94,7 +111,6 @@ class Entry extends React.PureComponent<Props, State> {\nthis.needsUpdateAfterCreation = false;\nthis.needsDeleteAfterCreation = false;\nthis.nextSaveAttemptIndex = 0;\n- this.mounted = true;\n}\nguardedSetState(input) {\n@@ -104,6 +120,7 @@ class Entry extends React.PureComponent<Props, State> {\n}\ncomponentDidMount() {\n+ this.mounted = true;\nthis.props.innerRef(entryKey(this.props.entryInfo), this);\nthis.updateHeight();\n// Whenever a new Entry is created, focus on it\n@@ -112,9 +129,22 @@ class Entry extends React.PureComponent<Props, State> {\n}\n}\n- componentWillReceiveProps(nextProps: Props) {\n- if (!this.state.focused && this.state.text !== nextProps.entryInfo.text) {\n- this.setState({ text: nextProps.entryInfo.text });\n+ componentDidUpdate(prevProps: Props) {\n+ if (\n+ !this.state.focused &&\n+ this.props.entryInfo.text !== this.state.text &&\n+ this.props.entryInfo.text !== prevProps.entryInfo.text\n+ ) {\n+ this.setState({ text: this.props.entryInfo.text });\n+ this.currentlySaving = null;\n+ }\n+\n+ if (\n+ this.props.online &&\n+ !prevProps.online &&\n+ this.state.loadingStatus === \"error\"\n+ ) {\n+ this.save();\n}\n}\n@@ -127,7 +157,7 @@ class Entry extends React.PureComponent<Props, State> {\n}\nonMouseDown = (event: SyntheticEvent<HTMLDivElement>) => {\n- if (this.state.focused) {\n+ if (this.state.focused && event.target !== this.textarea) {\n// Don't lose focus when some non-textarea part is clicked\nevent.preventDefault();\n}\n@@ -224,16 +254,26 @@ class Entry extends React.PureComponent<Props, State> {\n}\nonFocus = () => {\n+ if (!this.state.focused) {\nthis.setState({ focused: true });\n}\n+ }\nonBlur = (event: SyntheticEvent<HTMLTextAreaElement>) => {\nthis.setState({ focused: false });\nif (this.state.text.trim() === \"\") {\n- this.delete(this.props.entryInfo.id, false);\n+ this.delete();\n} else if (this.props.entryInfo.text !== this.state.text) {\n- this.save(this.props.entryInfo.id, this.state.text);\n+ this.save();\n+ }\n}\n+\n+ delete() {\n+ this.dispatchDelete(this.props.entryInfo.id, false);\n+ }\n+\n+ save() {\n+ this.dispatchSave(this.props.entryInfo.id, this.state.text);\n}\nonChange = (event: SyntheticEvent<HTMLTextAreaElement>) => {\n@@ -264,7 +304,12 @@ class Entry extends React.PureComponent<Props, State> {\n}\n}\n- save(serverID: ?string, newText: string) {\n+ dispatchSave(serverID: ?string, newText: string) {\n+ if (this.currentlySaving === newText) {\n+ return;\n+ }\n+ this.currentlySaving = newText;\n+\nif (newText.trim() === \"\") {\n// We don't save the empty string, since as soon as the element loses\n// focus it'll get deleted\n@@ -319,17 +364,19 @@ class Entry extends React.PureComponent<Props, State> {\nthis.creating = false;\nif (this.needsUpdateAfterCreation) {\nthis.needsUpdateAfterCreation = false;\n- this.save(response.entryID, this.state.text);\n+ this.dispatchSave(response.entryID, this.state.text);\n}\nif (this.needsDeleteAfterCreation) {\nthis.needsDeleteAfterCreation = false;\n- this.delete(response.entryID, false);\n+ this.dispatchDelete(response.entryID, false);\n}\nreturn response;\n} catch(e) {\nif (curSaveAttempt + 1 === this.nextSaveAttemptIndex) {\nthis.guardedSetState({ loadingStatus: \"error\" });\n}\n+ this.currentlySaving = null;\n+ this.creating = false;\nthrow e;\n}\n}\n@@ -353,6 +400,7 @@ class Entry extends React.PureComponent<Props, State> {\nif (curSaveAttempt + 1 === this.nextSaveAttemptIndex) {\nthis.guardedSetState({ loadingStatus: \"error\" });\n}\n+ this.currentlySaving = null;\nif (e instanceof ServerError && e.message === 'concurrent_modification') {\nconst onRefresh = () => {\nthis.setState(\n@@ -387,10 +435,10 @@ class Entry extends React.PureComponent<Props, State> {\n);\nreturn;\n}\n- this.delete(this.props.entryInfo.id, true);\n+ this.dispatchDelete(this.props.entryInfo.id, true);\n}\n- delete(serverID: ?string, focusOnNextEntry: bool) {\n+ dispatchDelete(serverID: ?string, focusOnNextEntry: bool) {\nconst { localID } = this.props.entryInfo;\nthis.props.dispatchActionPromise(\ndeleteEntryActionTypes,\n@@ -444,31 +492,13 @@ class Entry extends React.PureComponent<Props, State> {\nexport type InnerEntry = Entry;\n-Entry.propTypes = {\n- innerRef: PropTypes.func.isRequired,\n- entryInfo: entryInfoPropType.isRequired,\n- focusOnFirstEntryNewerThan: PropTypes.func.isRequired,\n- setModal: PropTypes.func.isRequired,\n- tabIndex: PropTypes.number.isRequired,\n- threadInfo: threadInfoPropType.isRequired,\n- loggedIn: PropTypes.bool.isRequired,\n- calendarQuery: PropTypes.func.isRequired,\n- dispatchActionPayload: PropTypes.func.isRequired,\n- dispatchActionPromise: PropTypes.func.isRequired,\n- createEntry: PropTypes.func.isRequired,\n- saveEntry: PropTypes.func.isRequired,\n- deleteEntry: PropTypes.func.isRequired,\n-}\n-\n-type OwnProps = {\n- entryInfo: EntryInfo,\n-};\nexport default connect(\n- (state: AppState, ownProps: OwnProps) => ({\n+ (state: AppState, ownProps: { entryInfo: EntryInfo }) => ({\nthreadInfo: threadInfoSelector(state)[ownProps.entryInfo.threadID],\nloggedIn: !!(state.currentUserInfo &&\n!state.currentUserInfo.anonymous && true),\ncalendarQuery: nonThreadCalendarQuery(state),\n+ online: state.connection.status === \"connected\",\n}),\n{ createEntry, saveEntry, deleteEntry },\n)(Entry);\n"
},
{
"change_type": "MODIFY",
"old_path": "web/style.css",
"new_path": "web/style.css",
"diff": "@@ -190,6 +190,7 @@ span.entry-error {\nright: 5px;\nfont-size: 16px;\nwidth: 6px;\n+ color: red !important;\n}\ndiv.action-links {\nline-height: 90%;\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | Retry entry saves after reconnecting
Also some improvements to web `Entry`:
1. Don't re-save the same string twice in a row
2. Allow clicking on `textarea` while it's focused
3. Avoid temporary revert after saving |
129,187 | 30.11.2018 15:30:51 | 18,000 | 08d88542dc8ed73102c7549e06e669572fe99d05 | [lib] Don't consider errors to be late responses | [
{
"change_type": "MODIFY",
"old_path": "lib/socket/inflight-requests.js",
"new_path": "lib/socket/inflight-requests.js",
"diff": "@@ -124,24 +124,27 @@ class InflightRequests {\n// We create this object so we can pass it by reference to the timeout\n// function below. That function will avoid setting this request as late if\n// the response has already arrived.\n- const requestResult = { success: false, lateResponse: false };\n+ const requestResult = { concluded: false, lateResponse: false };\ntry {\nconst response = await Promise.race([\nresponsePromise,\nthis.timeout(messageID, expectedType, requestResult),\n]);\n- requestResult.success = true;\n+ requestResult.concluded = true;\nif (requestResult.lateResponse) {\nthis.setLateResponse(messageID, false);\n}\nthis.clearRequest(inflightRequest);\nreturn response;\n} catch (e) {\n+ requestResult.concluded = true;\nthis.clearRequest(inflightRequest);\nif (e instanceof SocketTimeout) {\nthis.rejectAll(new Error(\"socket closed due to timeout\"));\nthis.timeoutCallback();\n+ } else if (requestResult.lateResponse) {\n+ this.setLateResponse(messageID, false);\n}\nthrow e;\n}\n@@ -150,11 +153,11 @@ class InflightRequests {\nasync timeout(\nmessageID: number,\nexpectedType: ServerSocketMessageType,\n- requestResult: {| success: bool, lateResponse: bool |},\n+ requestResult: {| concluded: bool, lateResponse: bool |},\n) {\nawait sleep(clientRequestVisualTimeout);\n- if (requestResult.success) {\n- // We're just doing this to bail out. If requestResult.success, we can\n+ if (requestResult.concluded) {\n+ // We're just doing this to bail out. If requestResult.concluded we can\n// conclude that responsePromise already won the race. Returning here\n// gives Flow errors since Flow is worried response will be undefined.\nthrow new Error();\n@@ -183,6 +186,8 @@ class InflightRequests {\n? new ServerError(message.message, message.payload)\n: new ServerError(message.message);\ninflightRequest.reject(error);\n+ } else if (message.type === serverSocketMessageTypes.AUTH_ERROR) {\n+ inflightRequest.reject(new SocketOffline(\"auth_error\"));\n} else if (\nmessage.type === serverSocketMessageTypes.STATE_SYNC &&\ninflightRequest.expectedResponseType ===\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [lib] Don't consider errors to be late responses |
129,187 | 30.11.2018 16:02:57 | 18,000 | 9db83590a60d9d3fd8e873a73988537ebf4ca9ac | codeVersion -> 26 | [
{
"change_type": "MODIFY",
"old_path": "lib/facts/version.json",
"new_path": "lib/facts/version.json",
"diff": "{\n- \"currentCodeVersion\": 25\n+ \"currentCodeVersion\": 26\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "native/android/app/build.gradle",
"new_path": "native/android/app/build.gradle",
"diff": "@@ -109,8 +109,8 @@ android {\napplicationId \"org.squadcal\"\nminSdkVersion rootProject.ext.minSdkVersion\ntargetSdkVersion rootProject.ext.targetSdkVersion\n- versionCode 25\n- versionName \"0.0.25\"\n+ versionCode 26\n+ versionName \"0.0.26\"\nndk {\nabiFilters \"armeabi-v7a\", \"x86\"\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "native/ios/SquadCal/Info.plist",
"new_path": "native/ios/SquadCal/Info.plist",
"diff": "<key>CFBundlePackageType</key>\n<string>APPL</string>\n<key>CFBundleShortVersionString</key>\n- <string>0.0.25</string>\n+ <string>0.0.26</string>\n<key>CFBundleSignature</key>\n<string>????</string>\n<key>CFBundleVersion</key>\n- <string>25</string>\n+ <string>26</string>\n<key>LSApplicationQueriesSchemes</key>\n<array>\n<string>org-appextension-feature-password-management</string>\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | codeVersion -> 26 |
129,187 | 02.12.2018 23:34:20 | 18,000 | 70c8bf94628e2a7bea628219328042ae3ab9d6e8 | [native] Undo Calendar changes in LoadingIndicator commit
Relevant commit:
Basically I forgot this was needed for an edge case. Also I renamed `Calendar`'s `tabActive` prop to `calendarActive`. | [
{
"change_type": "MODIFY",
"old_path": "native/calendar/calendar.react.js",
"new_path": "native/calendar/calendar.react.js",
"diff": "@@ -115,7 +115,7 @@ type Props = {\nnavigation: NavigationScreenProp<NavigationRoute>,\n// Redux state\nlistData: ?$ReadOnlyArray<CalendarItem>,\n- tabActive: bool,\n+ calendarActive: bool,\nthreadPickerOpen: bool,\nstartDate: string,\nendDate: string,\n@@ -159,7 +159,7 @@ class InnerCalendar extends React.PureComponent<Props, State> {\ndateString: PropTypes.string.isRequired,\n}),\n])),\n- tabActive: PropTypes.bool.isRequired,\n+ calendarActive: PropTypes.bool.isRequired,\nthreadPickerOpen: PropTypes.bool.isRequired,\nstartDate: PropTypes.string.isRequired,\nendDate: PropTypes.string.isRequired,\n@@ -361,7 +361,7 @@ class InnerCalendar extends React.PureComponent<Props, State> {\nnextProps.listData.length < this.props.listData.length &&\nthis.flatList\n) {\n- if (!nextProps.tabActive) {\n+ if (!nextProps.calendarActive) {\n// If the currentCalendarQuery gets reset we scroll to the center\nthis.scrollToToday();\n} else if (Date.now() - this.lastForegrounded < 500) {\n@@ -388,7 +388,7 @@ class InnerCalendar extends React.PureComponent<Props, State> {\n// If there are fewer items in our new data, which happens when the\n// current calendar query gets reset due to inactivity, let's reset the\n// scroll position to the center (today)\n- if (!nextProps.tabActive) {\n+ if (!nextProps.calendarActive) {\nsetTimeout(() => this.scrollToToday(), 50);\n}\nthis.firstScrollUpOnAndroidComplete = false;\n@@ -589,7 +589,7 @@ class InnerCalendar extends React.PureComponent<Props, State> {\nscrollToToday(animated: ?bool = undefined) {\nif (animated === undefined) {\n- animated = this.props.tabActive;\n+ animated = this.props.calendarActive;\n}\nconst ldwh = this.state.listDataWithHeights;\ninvariant(ldwh, \"should be set\");\n@@ -954,7 +954,22 @@ class InnerCalendar extends React.PureComponent<Props, State> {\n}\nthis.latestExtraData = {\nactiveEntries: _pickBy(\n- (_, key: string) => visibleEntries[key],\n+ (_, key: string) => {\n+ if (visibleEntries[key]) {\n+ return true;\n+ }\n+ // We don't automatically set scrolled-away entries to be inactive\n+ // because entries can be out-of-view at creation time if they need to\n+ // be scrolled into view (see onEnterEntryEditMode). If Entry could\n+ // distinguish the reasons its active prop gets set to false, it could\n+ // differentiate the out-of-view case from the something-pressed case,\n+ // and then we could set scrolled-away entries to be inactive without\n+ // worrying about this edge case. Until then...\n+ const item = _find\n+ (item => item.entryInfo && entryKey(item.entryInfo) === key)\n+ (ldwh);\n+ return !!item;\n+ },\n)(this.latestExtraData.activeEntries),\nvisibleEntries,\n};\n@@ -1098,7 +1113,7 @@ const activeThreadPickerSelector =\nconst Calendar = connect(\n(state: AppState) => ({\nlistData: calendarListData(state),\n- tabActive: activeTabSelector(state) || activeThreadPickerSelector(state),\n+ calendarActive: activeTabSelector(state) || activeThreadPickerSelector(state),\nthreadPickerOpen: activeThreadPickerSelector(state)\n|| !!state.navInfo.navigationState.isTransitioning,\nstartDate: state.navInfo.startDate,\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Undo Calendar changes in LoadingIndicator commit
Relevant commit: 8a83b9859ef5f0a010a1cf729c82f3e29d9847da
Basically I forgot this was needed for an edge case. Also I renamed `Calendar`'s `tabActive` prop to `calendarActive`. |
129,187 | 03.12.2018 12:52:19 | 18,000 | 9825465b729b902d1a29eb7d292be4113f05bd7d | Rename things to prepare for multimedia messages
1. `sendMessage` -> `sendTextMessage`
2. `SendTextMessageResponse` -> `SendMessageResponse`
3. `SendTextMessageResult` -> `SendMessageResult`
4. `SendTextMessagePayload` -> `SendMessagePayload`
5. Add `messageSentFromRoute` to `redux-persist` blacklist
6. `errorReportDownloadHandler` -> `errorReportDownloadResponder` | [
{
"change_type": "MODIFY",
"old_path": "lib/actions/message-actions.js",
"new_path": "lib/actions/message-actions.js",
"diff": "@@ -5,7 +5,7 @@ import type {\nRawMessageInfo,\nMessageTruncationStatus,\nFetchMessageInfosPayload,\n- SendTextMessageResult,\n+ SendMessageResult,\n} from '../types/message-types';\nimport type { UserInfo } from '../types/user-types';\n@@ -56,17 +56,17 @@ async function fetchMostRecentMessages(\n};\n}\n-const sendMessageActionTypes = Object.freeze({\n- started: \"SEND_MESSAGE_STARTED\",\n- success: \"SEND_MESSAGE_SUCCESS\",\n- failed: \"SEND_MESSAGE_FAILED\",\n+const sendTextMessageActionTypes = Object.freeze({\n+ started: \"SEND_TEXT_MESSAGE_STARTED\",\n+ success: \"SEND_TEXT_MESSAGE_SUCCESS\",\n+ failed: \"SEND_TEXT_MESSAGE_FAILED\",\n});\n-async function sendMessage(\n+async function sendTextMessage(\nfetchJSON: FetchJSON,\nthreadID: string,\nlocalID: string,\ntext: string,\n-): Promise<SendTextMessageResult> {\n+): Promise<SendMessageResult> {\nconst response = await fetchJSON(\n'create_text_message',\n{ threadID, localID, text },\n@@ -84,7 +84,7 @@ export {\nfetchMessagesBeforeCursor,\nfetchMostRecentMessagesActionTypes,\nfetchMostRecentMessages,\n- sendMessageActionTypes,\n- sendMessage,\n+ sendTextMessageActionTypes,\n+ sendTextMessage,\nsaveMessagesActionType,\n};\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/reducers/local-id-reducer.js",
"new_path": "lib/reducers/local-id-reducer.js",
"diff": "@@ -9,7 +9,7 @@ import {\nhighestLocalIDSelector,\n} from '../selectors/local-id-selectors';\nimport { rehydrateActionType } from '../types/redux-types';\n-import { sendMessageActionTypes } from '../actions/message-actions';\n+import { sendTextMessageActionTypes } from '../actions/message-actions';\nimport { createLocalEntryActionType } from '../actions/entry-actions';\nexport default function reduceNextLocalID(state: number, action: BaseAction) {\n@@ -17,7 +17,7 @@ export default function reduceNextLocalID(state: number, action: BaseAction) {\nif (action.type === rehydrateActionType) {\nnewCandidate = highestLocalIDSelector(action.payload) + 1;\n} else if (\n- action.type === sendMessageActionTypes.started ||\n+ action.type === sendTextMessageActionTypes.started ||\naction.type === createLocalEntryActionType\n) {\nconst { localID } = action.payload;\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/reducers/message-reducer.js",
"new_path": "lib/reducers/message-reducer.js",
"diff": "@@ -70,7 +70,7 @@ import {\nimport {\nfetchMessagesBeforeCursorActionTypes,\nfetchMostRecentMessagesActionTypes,\n- sendMessageActionTypes,\n+ sendTextMessageActionTypes,\nsaveMessagesActionType,\n} from '../actions/message-actions';\nimport threadWatcher from '../shared/thread-watcher';\n@@ -170,9 +170,9 @@ function mergeNewMessages(\n} else if (currentLocalMessageInfo && currentLocalMessageInfo.localID) {\n// If the client has a RawMessageInfo with this localID, but not with\n// the serverID, that means the message creation succeeded but the\n- // sendMessageActionTypes.success never got processed. We set a key in\n- // localIDsToServerIDs here to fix the messageIDs for the rest of the\n- // MessageStore too.\n+ // sendTextMessageActionTypes.success never got processed. We set a\n+ // key in localIDsToServerIDs here to fix the messageIDs for the rest\n+ // of the MessageStore too.\ninvariant(inputLocalID, \"should be set\");\nlocalIDsToServerIDs.set(inputLocalID, inputID);\nmessageInfo = {\n@@ -582,7 +582,7 @@ function reduceMessageStore(\nnewThreadInfos,\naction.type,\n);\n- } else if (action.type === sendMessageActionTypes.started) {\n+ } else if (action.type === sendTextMessageActionTypes.started) {\nconst { payload } = action;\nconst { localID, threadID } = payload;\ninvariant(localID, `localID should be set on ${action.type}`);\n@@ -630,7 +630,7 @@ function reduceMessageStore(\nlocal: messageStore.local,\ncurrentAsOf: messageStore.currentAsOf,\n};\n- } else if (action.type === sendMessageActionTypes.failed) {\n+ } else if (action.type === sendTextMessageActionTypes.failed) {\nconst { localID } = action.payload;\nreturn {\nmessages: messageStore.messages,\n@@ -641,7 +641,7 @@ function reduceMessageStore(\n},\ncurrentAsOf: messageStore.currentAsOf,\n};\n- } else if (action.type === sendMessageActionTypes.success) {\n+ } else if (action.type === sendTextMessageActionTypes.success) {\nconst payload = action.payload;\nconst replaceMessageKey =\n(messageKey: string) => messageKey === payload.localID\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/types/message-types.js",
"new_path": "lib/types/message-types.js",
"diff": "@@ -586,25 +586,26 @@ export type MessagesResponse = {|\n|};\nexport const defaultNumberPerThread = 20;\n-export type SendTextMessageRequest = {|\n- threadID: string,\n- localID?: string,\n- text: string,\n-|};\n-export type SendTextMessageResponse = {|\n+export type SendMessageResponse = {|\nnewMessageInfo: RawMessageInfo,\n|};\n-export type SendTextMessageResult = {|\n+export type SendMessageResult = {|\nid: string,\ntime: number,\n|};\n-export type SendTextMessagePayload = {|\n+export type SendMessagePayload = {|\nlocalID: string,\nserverID: string,\nthreadID: string,\ntime: number,\n|};\n+export type SendTextMessageRequest = {|\n+ threadID: string,\n+ localID?: string,\n+ text: string,\n+|};\n+\n// Used for the message info included in log-in type actions\nexport type GenericMessagesResult = {|\nmessageInfos: RawMessageInfo[],\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/types/redux-types.js",
"new_path": "lib/types/redux-types.js",
"diff": "@@ -38,7 +38,7 @@ import type {\nRawTextMessageInfo,\nRawMessageInfo,\nFetchMessageInfosPayload,\n- SendTextMessagePayload,\n+ SendMessagePayload,\nSaveMessagesPayload,\nMessagesResultWithUserInfos,\nMessageStorePrunePayload,\n@@ -440,11 +440,11 @@ export type BaseAction =\npayload: FetchMessageInfosPayload,\nloadingInfo: LoadingInfo,\n|} | {|\n- type: \"SEND_MESSAGE_STARTED\",\n+ type: \"SEND_TEXT_MESSAGE_STARTED\",\nloadingInfo: LoadingInfo,\npayload: RawTextMessageInfo,\n|} | {|\n- type: \"SEND_MESSAGE_FAILED\",\n+ type: \"SEND_TEXT_MESSAGE_FAILED\",\nerror: true,\npayload: Error & {\nlocalID: string,\n@@ -452,8 +452,8 @@ export type BaseAction =\n},\nloadingInfo: LoadingInfo,\n|} | {|\n- type: \"SEND_MESSAGE_SUCCESS\",\n- payload: SendTextMessagePayload,\n+ type: \"SEND_TEXT_MESSAGE_SUCCESS\",\n+ payload: SendMessagePayload,\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"SEARCH_USERS_STARTED\",\n"
},
{
"change_type": "MODIFY",
"old_path": "native/chat/chat-input-bar.react.js",
"new_path": "native/chat/chat-input-bar.react.js",
"diff": "@@ -7,7 +7,7 @@ import type {\n} from 'lib/utils/action-utils';\nimport {\ntype RawTextMessageInfo,\n- type SendTextMessageResult,\n+ type SendMessageResult,\nmessageTypes,\n} from 'lib/types/message-types';\nimport {\n@@ -38,8 +38,8 @@ import invariant from 'invariant';\nimport { connect } from 'lib/utils/redux-utils';\nimport {\n- sendMessageActionTypes,\n- sendMessage,\n+ sendTextMessageActionTypes,\n+ sendTextMessage,\n} from 'lib/actions/message-actions';\nimport { saveDraftActionType } from 'lib/reducers/draft-reducer';\nimport { threadHasPermission, viewerIsMember } from 'lib/shared/thread-utils';\n@@ -67,11 +67,11 @@ type Props = {\ndispatchActionPayload: DispatchActionPayload,\ndispatchActionPromise: DispatchActionPromise,\n// async functions that hit server APIs\n- sendMessage: (\n+ sendTextMessage: (\nthreadID: string,\nlocalID: string,\ntext: string,\n- ) => Promise<SendTextMessageResult>,\n+ ) => Promise<SendMessageResult>,\njoinThread: (request: ClientThreadJoinRequest) => Promise<ThreadJoinPayload>,\n};\ntype State = {\n@@ -89,7 +89,7 @@ class ChatInputBar extends React.PureComponent<Props, State> {\nnextLocalID: PropTypes.number.isRequired,\ndispatchActionPayload: PropTypes.func.isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\n- sendMessage: PropTypes.func.isRequired,\n+ sendTextMessage: PropTypes.func.isRequired,\njoinThread: PropTypes.func.isRequired,\n};\ntextInput: ?TextInput;\n@@ -266,7 +266,7 @@ class ChatInputBar extends React.PureComponent<Props, State> {\ntime: Date.now(),\n}: RawTextMessageInfo);\nthis.props.dispatchActionPromise(\n- sendMessageActionTypes,\n+ sendTextMessageActionTypes,\nthis.sendMessageAction(messageInfo),\nundefined,\nmessageInfo,\n@@ -280,7 +280,7 @@ class ChatInputBar extends React.PureComponent<Props, State> {\nlocalID !== null && localID !== undefined,\n\"localID should be set\",\n);\n- const result = await this.props.sendMessage(\n+ const result = await this.props.sendTextMessage(\nmessageInfo.threadID,\nlocalID,\nmessageInfo.text,\n@@ -398,5 +398,5 @@ export default connect(\nnextLocalID: state.nextLocalID,\n};\n},\n- { sendMessage, joinThread },\n+ { sendTextMessage, joinThread },\n)(ChatInputBar);\n"
},
{
"change_type": "MODIFY",
"old_path": "native/chat/failed-send.react.js",
"new_path": "native/chat/failed-send.react.js",
"diff": "@@ -4,7 +4,7 @@ import type { ChatMessageInfoItemWithHeight } from './message-list.react';\nimport { chatMessageItemPropType } from 'lib/selectors/chat-selectors';\nimport {\nmessageTypes,\n- type SendTextMessageResult,\n+ type SendMessageResult,\ntype RawTextMessageInfo,\ntype RawMessageInfo,\n} from 'lib/types/message-types';\n@@ -19,8 +19,8 @@ import PropTypes from 'prop-types';\nimport { messageID } from 'lib/shared/message-utils';\nimport { connect } from 'lib/utils/redux-utils';\nimport {\n- sendMessageActionTypes,\n- sendMessage,\n+ sendTextMessageActionTypes,\n+ sendTextMessage,\n} from 'lib/actions/message-actions';\nimport Button from '../components/button.react';\n@@ -32,11 +32,11 @@ type Props = {\n// Redux dispatch functions\ndispatchActionPromise: DispatchActionPromise,\n// async functions that hit server APIs\n- sendMessage: (\n+ sendTextMessage: (\nthreadID: string,\nlocalID: string,\ntext: string,\n- ) => Promise<SendTextMessageResult>,\n+ ) => Promise<SendMessageResult>,\n};\nclass FailedSend extends React.PureComponent<Props> {\n@@ -44,7 +44,7 @@ class FailedSend extends React.PureComponent<Props> {\nitem: chatMessageItemPropType.isRequired,\nrawMessageInfo: PropTypes.object.isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\n- sendMessage: PropTypes.func.isRequired,\n+ sendTextMessage: PropTypes.func.isRequired,\n};\nconstructor(props: Props) {\n@@ -106,7 +106,7 @@ class FailedSend extends React.PureComponent<Props> {\ntime: Date.now(),\n};\nthis.props.dispatchActionPromise(\n- sendMessageActionTypes,\n+ sendTextMessageActionTypes,\nthis.sendMessageAction(newRawMessageInfo),\nundefined,\nnewRawMessageInfo,\n@@ -120,7 +120,7 @@ class FailedSend extends React.PureComponent<Props> {\nlocalID !== null && localID !== undefined,\n\"localID should be set\",\n);\n- const result = await this.props.sendMessage(\n+ const result = await this.props.sendTextMessage(\nmessageInfo.threadID,\nlocalID,\nmessageInfo.text,\n@@ -170,5 +170,5 @@ export default connect(\nrawMessageInfo: state.messageStore.messages[id],\n};\n},\n- { sendMessage },\n+ { sendTextMessage },\n)(FailedSend);\n"
},
{
"change_type": "MODIFY",
"old_path": "native/persist.js",
"new_path": "native/persist.js",
"diff": "@@ -16,8 +16,8 @@ import { nativeCalendarQuery } from './selectors/nav-selectors';\nimport { defaultNotifPermissionAlertInfo } from './push/alerts';\nconst blacklist = __DEV__\n- ? [ 'loadingStatuses', 'foreground' ]\n- : [ 'loadingStatuses', 'foreground', 'navInfo' ];\n+ ? [ 'loadingStatuses', 'foreground', 'messageSentFromRoute' ]\n+ : [ 'loadingStatuses', 'foreground', 'messageSentFromRoute', 'navInfo' ];\nconst migrations = {\n[1]: (state: AppState) => ({\n"
},
{
"change_type": "MODIFY",
"old_path": "native/redux-setup.js",
"new_path": "native/redux-setup.js",
"diff": "@@ -41,7 +41,7 @@ import { AppState as NativeAppState, Platform } from 'react-native';\nimport baseReducer from 'lib/reducers/master-reducer';\nimport { notificationPressActionType } from 'lib/shared/notif-utils';\nimport {\n- sendMessageActionTypes,\n+ sendTextMessageActionTypes,\nsaveMessagesActionType,\n} from 'lib/actions/message-actions';\nimport { reduxLoggerMiddleware } from 'lib/utils/redux-logger';\n@@ -198,7 +198,7 @@ function reducer(state: AppState = defaultState, action: *) {\nconst oldState = state;\n- if (action.type === sendMessageActionTypes.started) {\n+ if (action.type === sendTextMessageActionTypes.started) {\nconst chatRoute = chatRouteFromNavInfo(state.navInfo);\nconst currentChatSubroute = currentLeafRoute(chatRoute);\nconst messageSentFromRoute =\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/responders/message-responders.js",
"new_path": "server/src/responders/message-responders.js",
"diff": "@@ -8,7 +8,7 @@ import {\ntype FetchMessageInfosResult,\ntype FetchMessageInfosRequest,\ndefaultNumberPerThread,\n- type SendTextMessageResponse,\n+ type SendMessageResponse,\ntype TextMessageData,\n} from 'lib/types/message-types';\n@@ -31,7 +31,7 @@ const sendTextMessageRequestInputValidator = tShape({\nasync function textMessageCreationResponder(\nviewer: Viewer,\ninput: any,\n-): Promise<SendTextMessageResponse> {\n+): Promise<SendMessageResponse> {\nconst request: SendTextMessageRequest = input;\nawait validateInput(viewer, sendTextMessageRequestInputValidator, request);\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/responders/report-responders.js",
"new_path": "server/src/responders/report-responders.js",
"diff": "@@ -115,7 +115,7 @@ async function errorReportFetchInfosResponder(\nreturn await fetchErrorReportInfos(viewer, request);\n}\n-async function errorReportDownloadHandler(\n+async function errorReportDownloadResponder(\nviewer: Viewer,\nreq: $Request,\nres: $Response,\n@@ -135,5 +135,5 @@ async function errorReportDownloadHandler(\nexport {\nreportCreationResponder,\nerrorReportFetchInfosResponder,\n- errorReportDownloadHandler,\n+ errorReportDownloadResponder,\n};\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/server.js",
"new_path": "server/src/server.js",
"diff": "@@ -16,7 +16,7 @@ import urlFacts from '../facts/url';\nimport './cron';\nimport { jsonEndpoints } from './endpoints';\nimport { websiteResponder } from './responders/website-responders';\n-import { errorReportDownloadHandler } from './responders/report-responders';\n+import { errorReportDownloadResponder } from './responders/report-responders';\nconst { baseRoutePath } = urlFacts;\n@@ -57,7 +57,7 @@ if (cluster.isMaster) {\nrouter.get(\n'/download_error_report/:reportID',\n- downloadHandler(errorReportDownloadHandler),\n+ downloadHandler(errorReportDownloadResponder),\n);\n// $FlowFixMe express-ws has side effects that can't be typed\nrouter.ws('/ws', onConnection);\n"
},
{
"change_type": "MODIFY",
"old_path": "web/chat/chat-input-bar.react.js",
"new_path": "web/chat/chat-input-bar.react.js",
"diff": "@@ -14,7 +14,7 @@ import {\n} from 'lib/types/thread-types';\nimport {\ntype RawTextMessageInfo,\n- type SendTextMessageResult,\n+ type SendMessageResult,\nmessageTypes,\n} from 'lib/types/message-types';\n@@ -26,8 +26,8 @@ import PropTypes from 'prop-types';\nimport { connect } from 'lib/utils/redux-utils';\nimport {\n- sendMessageActionTypes,\n- sendMessage,\n+ sendTextMessageActionTypes,\n+ sendTextMessage,\n} from 'lib/actions/message-actions';\nimport {\njoinThreadActionTypes,\n@@ -50,11 +50,11 @@ type Props = {|\n// Redux dispatch functions\ndispatchActionPromise: DispatchActionPromise,\n// async functions that hit server APIs\n- sendMessage: (\n+ sendTextMessage: (\nthreadID: string,\nlocalID: string,\ntext: string,\n- ) => Promise<SendTextMessageResult>,\n+ ) => Promise<SendMessageResult>,\njoinThread: (request: ClientThreadJoinRequest) => Promise<ThreadJoinPayload>,\n|};\ntype State = {|\n@@ -69,7 +69,7 @@ class ChatInputBar extends React.PureComponent<Props, State> {\ncalendarQuery: PropTypes.func.isRequired,\nnextLocalID: PropTypes.number.isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\n- sendMessage: PropTypes.func.isRequired,\n+ sendTextMessage: PropTypes.func.isRequired,\njoinThread: PropTypes.func.isRequired,\n};\nstate = {\n@@ -225,7 +225,7 @@ class ChatInputBar extends React.PureComponent<Props, State> {\ntime: Date.now(),\n}: RawTextMessageInfo);\nthis.props.dispatchActionPromise(\n- sendMessageActionTypes,\n+ sendTextMessageActionTypes,\nthis.sendMessageAction(messageInfo),\nundefined,\nmessageInfo,\n@@ -239,7 +239,7 @@ class ChatInputBar extends React.PureComponent<Props, State> {\nlocalID !== null && localID !== undefined,\n\"localID should be set\",\n);\n- const result = await this.props.sendMessage(\n+ const result = await this.props.sendTextMessage(\nmessageInfo.threadID,\nlocalID,\nmessageInfo.text,\n@@ -292,5 +292,5 @@ export default connect(\ncalendarQuery: nonThreadCalendarQuery(state),\nnextLocalID: state.nextLocalID,\n}),\n- { sendMessage, joinThread },\n+ { sendTextMessage, joinThread },\n)(ChatInputBar);\n"
},
{
"change_type": "MODIFY",
"old_path": "web/chat/failed-send.react.js",
"new_path": "web/chat/failed-send.react.js",
"diff": "@@ -6,7 +6,7 @@ import {\n} from 'lib/selectors/chat-selectors';\nimport {\nmessageTypes,\n- type SendTextMessageResult,\n+ type SendMessageResult,\ntype RawTextMessageInfo,\ntype RawMessageInfo,\n} from 'lib/types/message-types';\n@@ -21,8 +21,8 @@ import PropTypes from 'prop-types';\nimport { messageID } from 'lib/shared/message-utils';\nimport { connect } from 'lib/utils/redux-utils';\nimport {\n- sendMessageActionTypes,\n- sendMessage,\n+ sendTextMessageActionTypes,\n+ sendTextMessage,\n} from 'lib/actions/message-actions';\nimport css from './chat-message-list.css';\n@@ -35,11 +35,11 @@ type Props = {|\n// Redux dispatch functions\ndispatchActionPromise: DispatchActionPromise,\n// async functions that hit server APIs\n- sendMessage: (\n+ sendTextMessage: (\nthreadID: string,\nlocalID: string,\ntext: string,\n- ) => Promise<SendTextMessageResult>,\n+ ) => Promise<SendMessageResult>,\n|};\nclass FailedSend extends React.PureComponent<Props> {\n@@ -48,7 +48,7 @@ class FailedSend extends React.PureComponent<Props> {\nthreadInfo: threadInfoPropType.isRequired,\nrawMessageInfo: PropTypes.object.isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\n- sendMessage: PropTypes.func.isRequired,\n+ sendTextMessage: PropTypes.func.isRequired,\n};\nconstructor(props: Props) {\n@@ -110,7 +110,7 @@ class FailedSend extends React.PureComponent<Props> {\ntime: Date.now(),\n};\nthis.props.dispatchActionPromise(\n- sendMessageActionTypes,\n+ sendTextMessageActionTypes,\nthis.sendMessageAction(newRawMessageInfo),\nundefined,\nnewRawMessageInfo,\n@@ -124,7 +124,7 @@ class FailedSend extends React.PureComponent<Props> {\nlocalID !== null && localID !== undefined,\n\"localID should be set\",\n);\n- const result = await this.props.sendMessage(\n+ const result = await this.props.sendTextMessage(\nmessageInfo.threadID,\nlocalID,\nmessageInfo.text,\n@@ -156,5 +156,5 @@ export default connect(\nrawMessageInfo: state.messageStore.messages[id],\n};\n},\n- { sendMessage },\n+ { sendTextMessage },\n)(FailedSend);\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | Rename things to prepare for multimedia messages
1. `sendMessage` -> `sendTextMessage`
2. `SendTextMessageResponse` -> `SendMessageResponse`
3. `SendTextMessageResult` -> `SendMessageResult`
4. `SendTextMessagePayload` -> `SendMessagePayload`
5. Add `messageSentFromRoute` to `redux-persist` blacklist
6. `errorReportDownloadHandler` -> `errorReportDownloadResponder` |
129,187 | 03.12.2018 14:51:21 | 18,000 | 35549e4805a597f8a94054f22e6fca7fe6f92457 | [server] Initial support for multimedia upload
Currently just logs the input and returns dummy data. | [
{
"change_type": "MODIFY",
"old_path": "lib/types/message-types.js",
"new_path": "lib/types/message-types.js",
"diff": "@@ -606,6 +606,8 @@ export type SendTextMessageRequest = {|\ntext: string,\n|};\n+export type SendMultimediaMessageResponse = SendMessageResult;\n+\n// Used for the message info included in log-in type actions\nexport type GenericMessagesResult = {|\nmessageInfos: RawMessageInfo[],\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "server/flow-typed/npm/file-type_vx.x.x.js",
"diff": "+// flow-typed signature: f49f546a028646c3de3ad98d746dd7ef\n+// flow-typed version: <<STUB>>/file-type_v^10.6.0/flow_v0.78.0\n+\n+/**\n+ * This is an autogenerated libdef stub for:\n+ *\n+ * 'file-type'\n+ *\n+ * Fill this stub out by replacing all the `any` types.\n+ *\n+ * Once filled out, we encourage you to share your work with the\n+ * community by sending a pull request to:\n+ * https://github.com/flowtype/flow-typed\n+ */\n+\n+declare module 'file-type' {\n+ declare module.exports: any;\n+}\n+\n+/**\n+ * We include stubs for each file inside this npm package in case you need to\n+ * require those files directly. Feel free to delete any files that aren't\n+ * needed.\n+ */\n+\n+\n+// Filename aliases\n+declare module 'file-type/index' {\n+ declare module.exports: $Exports<'file-type'>;\n+}\n+declare module 'file-type/index.js' {\n+ declare module.exports: $Exports<'file-type'>;\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "server/flow-typed/npm/multer_vx.x.x.js",
"diff": "+// flow-typed signature: 1e2e387873efb7434b6795527015e0a5\n+// flow-typed version: <<STUB>>/multer_v^1.4.1/flow_v0.78.0\n+\n+/**\n+ * This is an autogenerated libdef stub for:\n+ *\n+ * 'multer'\n+ *\n+ * Fill this stub out by replacing all the `any` types.\n+ *\n+ * Once filled out, we encourage you to share your work with the\n+ * community by sending a pull request to:\n+ * https://github.com/flowtype/flow-typed\n+ */\n+\n+declare module 'multer' {\n+ declare module.exports: any;\n+}\n+\n+/**\n+ * We include stubs for each file inside this npm package in case you need to\n+ * require those files directly. Feel free to delete any files that aren't\n+ * needed.\n+ */\n+declare module 'multer/lib/counter' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'multer/lib/file-appender' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'multer/lib/make-middleware' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'multer/lib/multer-error' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'multer/lib/remove-uploaded-files' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'multer/storage/disk' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'multer/storage/memory' {\n+ declare module.exports: any;\n+}\n+\n+// Filename aliases\n+declare module 'multer/index' {\n+ declare module.exports: $Exports<'multer'>;\n+}\n+declare module 'multer/index.js' {\n+ declare module.exports: $Exports<'multer'>;\n+}\n+declare module 'multer/lib/counter.js' {\n+ declare module.exports: $Exports<'multer/lib/counter'>;\n+}\n+declare module 'multer/lib/file-appender.js' {\n+ declare module.exports: $Exports<'multer/lib/file-appender'>;\n+}\n+declare module 'multer/lib/make-middleware.js' {\n+ declare module.exports: $Exports<'multer/lib/make-middleware'>;\n+}\n+declare module 'multer/lib/multer-error.js' {\n+ declare module.exports: $Exports<'multer/lib/multer-error'>;\n+}\n+declare module 'multer/lib/remove-uploaded-files.js' {\n+ declare module.exports: $Exports<'multer/lib/remove-uploaded-files'>;\n+}\n+declare module 'multer/storage/disk.js' {\n+ declare module.exports: $Exports<'multer/storage/disk'>;\n+}\n+declare module 'multer/storage/memory.js' {\n+ declare module.exports: $Exports<'multer/storage/memory'>;\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "server/package.json",
"new_path": "server/package.json",
"diff": "\"denodeify\": \"^1.2.1\",\n\"express\": \"^4.16.2\",\n\"express-ws\": \"^4.0.0\",\n+ \"file-type\": \"^10.6.0\",\n\"firebase-admin\": \"^5.7.0\",\n\"invariant\": \"^2.2.2\",\n\"lib\": \"0.0.1\",\n\"lodash\": \"^4.17.5\",\n+ \"multer\": \"^1.4.1\",\n\"mysql2\": \"^1.5.1\",\n\"node-schedule\": \"^1.3.0\",\n\"nodemailer\": \"^4.4.2\",\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/responders/handlers.js",
"new_path": "server/src/responders/handlers.js",
"diff": "@@ -18,6 +18,7 @@ export type JSONResponder = (viewer: Viewer, input: any) => Promise<*>;\nexport type DownloadResponder\n= (viewer: Viewer, req: $Request, res: $Response) => Promise<void>;\nexport type HTMLResponder = (viewer: Viewer, url: string) => Promise<string>;\n+export type UploadResponder = (viewer: Viewer, req: $Request) => Promise<*>;\nfunction jsonHandler(responder: JSONResponder) {\nreturn async (req: $Request, res: $Response) => {\n@@ -94,14 +95,6 @@ async function handleException(\nres.json(result);\n}\n-async function handleAsyncPromise(promise: Promise<any>) {\n- try {\n- await promise;\n- } catch (error) {\n- console.warn(error);\n- }\n-}\n-\nfunction htmlHandler(responder: HTMLResponder) {\nreturn async (req: $Request, res: $Response) => {\ntry {\n@@ -118,9 +111,39 @@ function htmlHandler(responder: HTMLResponder) {\n};\n}\n+function uploadHandler(responder: UploadResponder) {\n+ return async (req: $Request, res: $Response) => {\n+ let viewer;\n+ try {\n+ if (!req.body || typeof req.body !== \"object\") {\n+ throw new ServerError('invalid_parameters');\n+ }\n+ viewer = await fetchViewerForJSONRequest(req);\n+ const responderResult = await responder(viewer, req);\n+ if (res.headersSent) {\n+ return;\n+ }\n+ const result = { ...responderResult };\n+ addCookieToJSONResponse(viewer, res, result);\n+ res.json({ success: true, ...result });\n+ } catch (e) {\n+ await handleException(e, res, viewer);\n+ }\n+ };\n+}\n+\n+async function handleAsyncPromise(promise: Promise<any>) {\n+ try {\n+ await promise;\n+ } catch (error) {\n+ console.warn(error);\n+ }\n+}\n+\nexport {\njsonHandler,\ndownloadHandler,\nhtmlHandler,\n+ uploadHandler,\nhandleAsyncPromise,\n};\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/server.js",
"new_path": "server/src/server.js",
"diff": "@@ -10,6 +10,7 @@ import {\njsonHandler,\ndownloadHandler,\nhtmlHandler,\n+ uploadHandler,\n} from './responders/handlers';\nimport { onConnection } from './socket/socket';\nimport urlFacts from '../facts/url';\n@@ -17,6 +18,10 @@ import './cron';\nimport { jsonEndpoints } from './endpoints';\nimport { websiteResponder } from './responders/website-responders';\nimport { errorReportDownloadResponder } from './responders/report-responders';\n+import {\n+ multerProcessor,\n+ multimediaMessageCreationResponder,\n+} from './uploads/uploads';\nconst { baseRoutePath } = urlFacts;\n@@ -63,6 +68,12 @@ if (cluster.isMaster) {\nrouter.ws('/ws', onConnection);\nrouter.get('*', htmlHandler(websiteResponder));\n+ router.post(\n+ '/create_multimedia_message',\n+ multerProcessor,\n+ uploadHandler(multimediaMessageCreationResponder),\n+ );\n+\nserver.use(baseRoutePath, router);\nserver.listen(parseInt(process.env.PORT) || 3000, 'localhost');\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "server/src/uploads/uploads.js",
"diff": "+// @flow\n+\n+import type { Viewer } from '../session/viewer';\n+import type { $Request } from 'express';\n+import type { SendMultimediaMessageResponse } from 'lib/types/message-types';\n+\n+import multer from 'multer';\n+import fileType from 'file-type';\n+\n+const upload = multer();\n+const multerProcessor = upload.array('multimedia');\n+\n+type MulterFile = {|\n+ fieldname: string,\n+ originalname: string,\n+ encoding: string,\n+ mimetype: string,\n+ buffer: Buffer,\n+ size: number,\n+|};\n+\n+async function multimediaMessageCreationResponder(\n+ viewer: Viewer,\n+ req: $Request & { files?: $ReadOnlyArray<MulterFile> },\n+): Promise<SendMultimediaMessageResponse> {\n+ console.log(req.body);\n+ console.log(req.files);\n+ return { id: \"test\", time: 5 };\n+}\n+\n+export {\n+ multerProcessor,\n+ multimediaMessageCreationResponder,\n+};\n"
},
{
"change_type": "MODIFY",
"old_path": "yarn.lock",
"new_path": "yarn.lock",
"diff": "@@ -1186,6 +1186,11 @@ apn@^2.2.0:\nnode-forge \"^0.7.1\"\nverror \"^1.10.0\"\n+append-field@^1.0.0:\n+ version \"1.0.0\"\n+ resolved \"https://registry.yarnpkg.com/append-field/-/append-field-1.0.0.tgz#1e3440e915f0b1203d23748e78edd7b9b5b43e56\"\n+ integrity sha1-HjRA6RXwsSA9I3SOeO3XubW0PlY=\n+\nappend-transform@^0.4.0:\nversion \"0.4.0\"\nresolved \"https://registry.yarnpkg.com/append-transform/-/append-transform-0.4.0.tgz#d76ebf8ca94d276e247a36bad44a4b74ab611991\"\n@@ -2573,6 +2578,14 @@ bun@^0.0.12:\ndependencies:\nreadable-stream \"~1.0.32\"\n+busboy@^0.2.11:\n+ version \"0.2.14\"\n+ resolved \"https://registry.yarnpkg.com/busboy/-/busboy-0.2.14.tgz#6c2a622efcf47c57bbbe1e2a9c37ad36c7925453\"\n+ integrity sha1-bCpiLvz0fFe7vh4qnDetNseSVFM=\n+ dependencies:\n+ dicer \"0.2.5\"\n+ readable-stream \"1.1.x\"\n+\nbytebuffer@~5:\nversion \"5.0.1\"\nresolved \"https://registry.yarnpkg.com/bytebuffer/-/bytebuffer-5.0.1.tgz#582eea4b1a873b6d020a48d58df85f0bba6cfddd\"\n@@ -3046,7 +3059,7 @@ concat-map@0.0.1:\nresolved \"https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b\"\nintegrity sha1-2Klr13/Wjfd5OnMDajug1UBdR3s=\n-concat-stream@1.6.2, concat-stream@^1.5.0, concat-stream@^1.6.0:\n+concat-stream@1.6.2, concat-stream@^1.5.0, concat-stream@^1.5.2, concat-stream@^1.6.0:\nversion \"1.6.2\"\nresolved \"https://registry.yarnpkg.com/concat-stream/-/concat-stream-1.6.2.tgz#904bdf194cd3122fc675c77fc4ac3d4ff0fd1a34\"\nintegrity sha512-27HBghJxjiZtIk3Ycvn/4kbJk/1uZuJFfuPEns6LaEvpvG1f0hTea8lilrouyo9mVc2GWdcEZ8OLoGmSADlrCw==\n@@ -3623,6 +3636,14 @@ detect-node@^2.0.3:\nresolved \"https://registry.yarnpkg.com/detect-node/-/detect-node-2.0.4.tgz#014ee8f8f669c5c58023da64b8179c083a28c46c\"\nintegrity sha512-ZIzRpLJrOj7jjP2miAtgqIfmzbxa4ZOr5jJc601zklsfEx9oTzmmj2nVpIPRpNlRTIh8lc1kyViIY7BWSGNmKw==\n+dicer@0.2.5:\n+ version \"0.2.5\"\n+ resolved \"https://registry.yarnpkg.com/dicer/-/dicer-0.2.5.tgz#5996c086bb33218c812c090bddc09cd12facb70f\"\n+ integrity sha1-WZbAhrszIYyBLAkL3cCc0S+stw8=\n+ dependencies:\n+ readable-stream \"1.1.x\"\n+ streamsearch \"0.1.2\"\n+\ndiff-match-patch@^1.0.0:\nversion \"1.0.4\"\nresolved \"https://registry.yarnpkg.com/diff-match-patch/-/diff-match-patch-1.0.4.tgz#6ac4b55237463761c4daf0dc603eb869124744b1\"\n@@ -4464,6 +4485,11 @@ figures@^2.0.0:\ndependencies:\nescape-string-regexp \"^1.0.5\"\n+file-type@^10.6.0:\n+ version \"10.6.0\"\n+ resolved \"https://registry.yarnpkg.com/file-type/-/file-type-10.6.0.tgz#95a94871d26b39f137a03cfd25450f0a56a38143\"\n+ integrity sha512-GNOg09GC+rZzxetGZFoL7QOnWXRqvWuEdKURIJlr0d6MW107Iwy6voG1PPOrm5meG6ls59WkBmBMAZdVSVajRQ==\n+\nfilename-regex@^2.0.0:\nversion \"2.0.1\"\nresolved \"https://registry.yarnpkg.com/filename-regex/-/filename-regex-2.0.1.tgz#c1c4b9bee3e09725ddb106b75c1e301fe2f18b26\"\n@@ -7543,6 +7569,20 @@ ms@^2.0.0, ms@^2.1.1:\nresolved \"https://registry.yarnpkg.com/ms/-/ms-2.1.1.tgz#30a5864eb3ebb0a66f2ebe6d727af06a09d86e0a\"\nintegrity sha512-tgp+dl5cGk28utYktBsrFqA7HKgrhgPsg6Z/EfhWI4gl1Hwq8B/GmY/0oXZ6nF8hDVesS/FpnYaD/kOWhYQvyg==\n+multer@^1.4.1:\n+ version \"1.4.1\"\n+ resolved \"https://registry.yarnpkg.com/multer/-/multer-1.4.1.tgz#24b12a416a22fec2ade810539184bf138720159e\"\n+ integrity sha512-zzOLNRxzszwd+61JFuAo0fxdQfvku12aNJgnla0AQ+hHxFmfc/B7jBVuPr5Rmvu46Jze/iJrFpSOsD7afO8SDw==\n+ dependencies:\n+ append-field \"^1.0.0\"\n+ busboy \"^0.2.11\"\n+ concat-stream \"^1.5.2\"\n+ mkdirp \"^0.5.1\"\n+ object-assign \"^4.1.1\"\n+ on-finished \"^2.3.0\"\n+ type-is \"^1.6.4\"\n+ xtend \"^4.0.0\"\n+\nmulticast-dns-service-types@^1.1.0:\nversion \"1.1.0\"\nresolved \"https://registry.yarnpkg.com/multicast-dns-service-types/-/multicast-dns-service-types-1.1.0.tgz#899f11d9686e5e05cb91b35d5f0e63b773cfc901\"\n@@ -7951,7 +7991,7 @@ obuf@^1.0.0, obuf@^1.1.1:\nresolved \"https://registry.yarnpkg.com/obuf/-/obuf-1.1.2.tgz#09bea3343d41859ebd446292d11c9d4db619084e\"\nintegrity sha512-PX1wu0AmAdPqOL1mWhqmlOd8kOIZQwGZw6rh7uby9fTc5lhaOWFLX3I6R1hrF9k3zUY40e6igsLGkDXK92LJNg==\n-on-finished@~2.3.0:\n+on-finished@^2.3.0, on-finished@~2.3.0:\nversion \"2.3.0\"\nresolved \"https://registry.yarnpkg.com/on-finished/-/on-finished-2.3.0.tgz#20f1336481b083cd75337992a16971aa2d906947\"\nintegrity sha1-IPEzZIGwg811M3mSoWlxqi2QaUc=\n@@ -9656,6 +9696,16 @@ read-pkg@^3.0.0:\nnormalize-package-data \"^2.3.2\"\npath-type \"^3.0.0\"\n+readable-stream@1.1.x, readable-stream@~1.1.9:\n+ version \"1.1.14\"\n+ resolved \"https://registry.yarnpkg.com/readable-stream/-/readable-stream-1.1.14.tgz#7cf4c54ef648e3813084c636dd2079e166c081d9\"\n+ integrity sha1-fPTFTvZI44EwhMY23SB54WbAgdk=\n+ dependencies:\n+ core-util-is \"~1.0.0\"\n+ inherits \"~2.0.1\"\n+ isarray \"0.0.1\"\n+ string_decoder \"~0.10.x\"\n+\nreadable-stream@^2.0.0, readable-stream@^2.0.1, readable-stream@^2.0.2, readable-stream@^2.0.6, readable-stream@^2.1.5, readable-stream@^2.2.2, readable-stream@^2.2.9, readable-stream@^2.3.3, readable-stream@^2.3.6:\nversion \"2.3.6\"\nresolved \"https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.3.6.tgz#b11c27d88b8ff1fbe070643cf94b0c79ae1b0aaf\"\n@@ -9679,16 +9729,6 @@ readable-stream@~1.0.32:\nisarray \"0.0.1\"\nstring_decoder \"~0.10.x\"\n-readable-stream@~1.1.9:\n- version \"1.1.14\"\n- resolved \"https://registry.yarnpkg.com/readable-stream/-/readable-stream-1.1.14.tgz#7cf4c54ef648e3813084c636dd2079e166c081d9\"\n- integrity sha1-fPTFTvZI44EwhMY23SB54WbAgdk=\n- dependencies:\n- core-util-is \"~1.0.0\"\n- inherits \"~2.0.1\"\n- isarray \"0.0.1\"\n- string_decoder \"~0.10.x\"\n-\nreadable-stream@~2.1.5:\nversion \"2.1.5\"\nresolved \"https://registry.yarnpkg.com/readable-stream/-/readable-stream-2.1.5.tgz#66fa8b720e1438b364681f2ad1a63c618448c9d0\"\n@@ -10789,6 +10829,11 @@ stream-shift@^1.0.0:\nresolved \"https://registry.yarnpkg.com/stream-shift/-/stream-shift-1.0.0.tgz#d5c752825e5367e786f78e18e445ea223a155952\"\nintegrity sha1-1cdSgl5TZ+eG944Y5EXqIjoVWVI=\n+streamsearch@0.1.2:\n+ version \"0.1.2\"\n+ resolved \"https://registry.yarnpkg.com/streamsearch/-/streamsearch-0.1.2.tgz#808b9d0e56fc273d809ba57338e929919a1a9f1a\"\n+ integrity sha1-gIudDlb8Jz2Am6VzOOkpkZoanxo=\n+\nstrict-uri-encode@^1.0.0:\nversion \"1.1.0\"\nresolved \"https://registry.yarnpkg.com/strict-uri-encode/-/strict-uri-encode-1.1.0.tgz#279b225df1d582b1f54e65addd4352e18faa0713\"\n@@ -11242,7 +11287,7 @@ type-check@~0.3.2:\ndependencies:\nprelude-ls \"~1.1.2\"\n-type-is@~1.6.16:\n+type-is@^1.6.4, type-is@~1.6.16:\nversion \"1.6.16\"\nresolved \"https://registry.yarnpkg.com/type-is/-/type-is-1.6.16.tgz#f89ce341541c672b25ee7ae3c73dee3b2be50194\"\nintegrity sha512-HRkVv/5qY2G6I8iab9cI7v1bOIdhm94dVjQCPFElW9W+3GeDOSHmy2EBYe4VTApuzolPcmgFTN3ftVJRKR2J9Q==\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [server] Initial support for multimedia upload
Currently just logs the input and returns dummy data. |
129,187 | 03.12.2018 15:04:49 | 18,000 | 6c1a56713e9ad01b8356e5bbd8c29c6fa9cdf0c8 | [server] Treat empty string sessionID or cookie as null
Necessary since `FormData` doesn't accept `null`, so we need another way to communicate that the `sessionID` or `cookie` ought to be set but isn't. | [
{
"change_type": "MODIFY",
"old_path": "server/src/session/cookies.js",
"new_path": "server/src/session/cookies.js",
"diff": "@@ -309,7 +309,7 @@ async function fetchViewerFromRequestBody(\n};\n}\nconst cookiePair = body.cookie;\n- if (cookiePair === null) {\n+ if (cookiePair === null || cookiePair === \"\") {\nreturn {\ntype: \"nonexistant\",\ncookieName: null,\n@@ -351,9 +351,12 @@ function getSessionParameterInfoFromRequestBody(\nreq: $Request,\n): SessionParameterInfo {\nconst body = (req.body: any);\n- const sessionID = body.sessionID !== undefined || req.method !== \"GET\"\n+ let sessionID = body.sessionID !== undefined || req.method !== \"GET\"\n? body.sessionID\n: null;\n+ if (sessionID === \"\") {\n+ sessionID = null;\n+ }\nconst sessionIdentifierType = req.method === \"GET\" || sessionID !== undefined\n? sessionIdentifierTypes.BODY_SESSION_ID\n: sessionIdentifierTypes.COOKIE_ID;\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [server] Treat empty string sessionID or cookie as null
Necessary since `FormData` doesn't accept `null`, so we need another way to communicate that the `sessionID` or `cookie` ought to be set but isn't. |
129,187 | 03.12.2018 18:00:38 | 18,000 | 3766c8df2661b133258bef237326f0768b2d8e6b | Basic client support for multimedia upload
This is gonna be different on native vs. web... | [
{
"change_type": "MODIFY",
"old_path": "lib/utils/fetch-json.js",
"new_path": "lib/utils/fetch-json.js",
"diff": "@@ -22,6 +22,7 @@ import { ServerError, FetchTimeout } from './errors';\nimport { getConfig } from './config';\nimport sleep from './sleep';\nimport { SocketOffline, SocketTimeout } from '../socket/inflight-requests';\n+import { uploadBlob } from './upload-blob';\n// You'll notice that this is not the type of the fetchJSON function below. This\n// is because the first several parameters to that functon get bound in by the\n@@ -29,6 +30,7 @@ import { SocketOffline, SocketTimeout } from '../socket/inflight-requests';\n// fetchJSON function that gets passed to the action function in lib/actions.\nexport type FetchJSONOptions = {|\ntimeout?: number, // in milliseconds\n+ blobUpload?: bool,\n|};\nexport type FetchJSON = (\nendpoint: Endpoint,\n@@ -90,6 +92,12 @@ async function fetchJSON(\nthrow new SocketOffline(\"socket_offline\");\n}\n+ const url = urlPrefix ? `${urlPrefix}/${endpoint}` : endpoint;\n+\n+ let fetchPromise;\n+ if (options && options.blobUpload) {\n+ fetchPromise = uploadBlob(url, cookie, sessionID, input);\n+ } else {\nconst mergedData: RequestData = { input };\nif (getConfig().setCookieOnRequest) {\n// We make sure that if setCookieOnRequest is true, we never set cookie to\n@@ -107,18 +115,18 @@ async function fetchJSON(\n// not logged in on web.\nmergedData.sessionID = sessionID ? sessionID : null;\n}\n-\n- const url = urlPrefix ? `${urlPrefix}/${endpoint}` : endpoint;\n- const fetchPromise = fetch(url, {\n- 'method': 'POST',\n+ fetchPromise = fetch(url, {\n+ method: 'POST',\n// This is necessary to allow cookie headers to get passed down to us\n- 'credentials': 'same-origin',\n- 'body': JSON.stringify(mergedData),\n- 'headers': {\n+ credentials: 'same-origin',\n+ body: JSON.stringify(mergedData),\n+ headers: {\n'Accept': 'application/json',\n'Content-Type': 'application/json',\n},\n});\n+ }\n+\nconst timeout = options && options.timeout\n? options.timeout\n: defaultTimeout;\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "lib/utils/upload-blob.js",
"diff": "+// @flow\n+\n+import invariant from 'invariant';\n+\n+import { getConfig } from './config';\n+\n+function uploadBlob(\n+ url: string,\n+ cookie: ?string,\n+ sessionID: ?string,\n+ input: {[key: string]: mixed},\n+): Promise<*> {\n+ const formData = new FormData();\n+ if (getConfig().setCookieOnRequest) {\n+ // We make sure that if setCookieOnRequest is true, we never set cookie to\n+ // undefined. null has a special meaning here: we don't currently have a\n+ // cookie, and we want the server to specify the new cookie it will generate\n+ // in the response body rather than the response header. See\n+ // session-types.js for more details on why we specify cookies in the body.\n+ formData.append('cookie', cookie ? cookie : \"\");\n+ }\n+ if (getConfig().setSessionIDOnRequest) {\n+ // We make sure that if setSessionIDOnRequest is true, we never set\n+ // sessionID to undefined. null has a special meaning here: we cannot\n+ // consider the cookieID to be a unique session identifier, but we do not\n+ // have a sessionID to use either. This should only happen when the user is\n+ // not logged in on web.\n+ formData.append('sessionID', sessionID ? sessionID : \"\");\n+ }\n+\n+ for (let key in input) {\n+ if (key === \"multimedia\") {\n+ continue;\n+ }\n+ const value = input[key];\n+ invariant(\n+ typeof value === \"string\",\n+ \"blobUpload calls can only handle string values for non-multimedia keys\",\n+ );\n+ formData.append(key, value);\n+ }\n+ const { multimedia } = input;\n+ if (multimedia && Array.isArray(multimedia)) {\n+ for (let media of multimedia) {\n+ // We perform an any-cast here because of React Native. Though Blob\n+ // support was introduced in react-native@0.54, it isn't compatible with\n+ // FormData. Instead, React Native requires a specific object format.\n+ formData.append('multimedia', (media: any));\n+ }\n+ }\n+\n+ return fetch(url, {\n+ method: 'POST',\n+ // This is necessary to allow cookie headers to get passed down to us\n+ credentials: 'same-origin',\n+ body: formData,\n+ headers: {\n+ 'Content-Type': 'multipart/form-data',\n+ 'Accept': 'application/json',\n+ },\n+ });\n+}\n+\n+export {\n+ uploadBlob,\n+};\n"
},
{
"change_type": "MODIFY",
"old_path": "native/ios/SquadCal.xcodeproj/project.pbxproj",
"new_path": "native/ios/SquadCal.xcodeproj/project.pbxproj",
"diff": "7FB58AC11E7F6BD900B4C1B1 /* OpenSans-Regular.ttf in Resources */ = {isa = PBXBuildFile; fileRef = 7FB58ABC1E7F6BC600B4C1B1 /* OpenSans-Regular.ttf */; };\n7FB58AC21E7F6BDB00B4C1B1 /* OpenSans-Semibold.ttf in Resources */ = {isa = PBXBuildFile; fileRef = 7FB58ABD1E7F6BC600B4C1B1 /* OpenSans-Semibold.ttf */; };\n7FB58AC31E7F6BDC00B4C1B1 /* OpenSans-Semibold.ttf in Resources */ = {isa = PBXBuildFile; fileRef = 7FB58ABD1E7F6BC600B4C1B1 /* OpenSans-Semibold.ttf */; };\n+ 7FC7F3F521B5E0540083848D /* libRCTBlob.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 7FC7F3F221B5E0270083848D /* libRCTBlob.a */; };\n7FF1294020047B8B0051F874 /* libRNVectorIcons.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 7FB58ABA1E7F6B4400B4C1B1 /* libRNVectorIcons.a */; };\n7FF1294120047BAC0051F874 /* libRNKeychain.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 7FEB2DEC1E8D64D200C4B763 /* libRNKeychain.a */; };\n832341BD1AAA6AB300B99B32 /* libRCTText.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 832341B51AAA6A8300B99B32 /* libRCTText.a */; };\nremoteGlobalIDString = 52E319201C0655C200265D56;\nremoteInfo = OnePassword;\n};\n+ 7FC7F3F121B5E0270083848D /* PBXContainerItemProxy */ = {\n+ isa = PBXContainerItemProxy;\n+ containerPortal = 7FC7F3EC21B5E0270083848D /* RCTBlob.xcodeproj */;\n+ proxyType = 2;\n+ remoteGlobalIDString = 358F4ED71D1E81A9004DF814;\n+ remoteInfo = RCTBlob;\n+ };\n+ 7FC7F3F321B5E0270083848D /* PBXContainerItemProxy */ = {\n+ isa = PBXContainerItemProxy;\n+ containerPortal = 7FC7F3EC21B5E0270083848D /* RCTBlob.xcodeproj */;\n+ proxyType = 2;\n+ remoteGlobalIDString = ADD01A681E09402E00F6D226;\n+ remoteInfo = \"RCTBlob-tvOS\";\n+ };\n7FEB2DEB1E8D64D200C4B763 /* PBXContainerItemProxy */ = {\nisa = PBXContainerItemProxy;\ncontainerPortal = 95EEFC35D4D14053ACA7E064 /* RNKeychain.xcodeproj */;\n7FB58ABB1E7F6BC600B4C1B1 /* Anaheim-Regular.ttf */ = {isa = PBXFileReference; lastKnownFileType = file; path = \"Anaheim-Regular.ttf\"; sourceTree = \"<group>\"; };\n7FB58ABC1E7F6BC600B4C1B1 /* OpenSans-Regular.ttf */ = {isa = PBXFileReference; lastKnownFileType = file; path = \"OpenSans-Regular.ttf\"; sourceTree = \"<group>\"; };\n7FB58ABD1E7F6BC600B4C1B1 /* OpenSans-Semibold.ttf */ = {isa = PBXFileReference; lastKnownFileType = file; path = \"OpenSans-Semibold.ttf\"; sourceTree = \"<group>\"; };\n+ 7FC7F3EC21B5E0270083848D /* RCTBlob.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = \"wrapper.pb-project\"; name = RCTBlob.xcodeproj; path = \"../../node_modules/react-native/Libraries/Blob/RCTBlob.xcodeproj\"; sourceTree = \"<group>\"; };\n7FCFD8BD1E81B8DF00629B0E /* SquadCal.entitlements */ = {isa = PBXFileReference; lastKnownFileType = text.plist.entitlements; name = SquadCal.entitlements; path = SquadCal/SquadCal.entitlements; sourceTree = \"<group>\"; };\n832341B01AAA6A8300B99B32 /* RCTText.xcodeproj */ = {isa = PBXFileReference; lastKnownFileType = \"wrapper.pb-project\"; name = RCTText.xcodeproj; path = \"../node_modules/react-native/Libraries/Text/RCTText.xcodeproj\"; sourceTree = \"<group>\"; };\n8B6A1FF570694BFCB0D65D0E /* libSplashScreen.a */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = archive.ar; path = libSplashScreen.a; sourceTree = \"<group>\"; };\nisa = PBXFrameworksBuildPhase;\nbuildActionMask = 2147483647;\nfiles = (\n+ 7FC7F3F521B5E0540083848D /* libRCTBlob.a in Frameworks */,\n7F5B10EA200534C300FE096A /* libRNNotifications.a in Frameworks */,\n7FF1294120047BAC0051F874 /* libRNKeychain.a in Frameworks */,\n7FF1294020047B8B0051F874 /* libRNVectorIcons.a in Frameworks */,\nname = Products;\nsourceTree = \"<group>\";\n};\n+ 7FC7F3ED21B5E0270083848D /* Products */ = {\n+ isa = PBXGroup;\n+ children = (\n+ 7FC7F3F221B5E0270083848D /* libRCTBlob.a */,\n+ 7FC7F3F421B5E0270083848D /* libRCTBlob-tvOS.a */,\n+ );\n+ name = Products;\n+ sourceTree = \"<group>\";\n+ };\n7FEB2DCE1E8D64D200C4B763 /* Products */ = {\nisa = PBXGroup;\nchildren = (\n832341AE1AAA6A7D00B99B32 /* Libraries */ = {\nisa = PBXGroup;\nchildren = (\n+ 7FC7F3EC21B5E0270083848D /* RCTBlob.xcodeproj */,\n5E91572D1DD0AC6500FF2AA8 /* RCTAnimation.xcodeproj */,\n146833FF1AC3E56700842450 /* React.xcodeproj */,\n00C302A71ABCB8CE00DB3ED1 /* RCTActionSheet.xcodeproj */,\nProductGroup = 5E91572E1DD0AC6500FF2AA8 /* Products */;\nProjectRef = 5E91572D1DD0AC6500FF2AA8 /* RCTAnimation.xcodeproj */;\n},\n+ {\n+ ProductGroup = 7FC7F3ED21B5E0270083848D /* Products */;\n+ ProjectRef = 7FC7F3EC21B5E0270083848D /* RCTBlob.xcodeproj */;\n+ },\n{\nProductGroup = 00C302B61ABCB90400DB3ED1 /* Products */;\nProjectRef = 00C302B51ABCB90400DB3ED1 /* RCTGeolocation.xcodeproj */;\nremoteRef = 7FB58AD31E80C21000B4C1B1 /* PBXContainerItemProxy */;\nsourceTree = BUILT_PRODUCTS_DIR;\n};\n+ 7FC7F3F221B5E0270083848D /* libRCTBlob.a */ = {\n+ isa = PBXReferenceProxy;\n+ fileType = archive.ar;\n+ path = libRCTBlob.a;\n+ remoteRef = 7FC7F3F121B5E0270083848D /* PBXContainerItemProxy */;\n+ sourceTree = BUILT_PRODUCTS_DIR;\n+ };\n+ 7FC7F3F421B5E0270083848D /* libRCTBlob-tvOS.a */ = {\n+ isa = PBXReferenceProxy;\n+ fileType = archive.ar;\n+ path = \"libRCTBlob-tvOS.a\";\n+ remoteRef = 7FC7F3F321B5E0270083848D /* PBXContainerItemProxy */;\n+ sourceTree = BUILT_PRODUCTS_DIR;\n+ };\n7FEB2DEC1E8D64D200C4B763 /* libRNKeychain.a */ = {\nisa = PBXReferenceProxy;\nfileType = archive.ar;\n);\nrunOnlyForDeploymentPostprocessing = 0;\nshellPath = /bin/sh;\n- shellScript = \"export NODE_BINARY=node\\n../node_modules/react-native/scripts/react-native-xcode.sh\";\n+ shellScript = \"export NODE_BINARY=node\\n../node_modules/react-native/scripts/react-native-xcode.sh\\n\";\n};\n2D02E4CB1E0B4B27006451C7 /* Bundle React Native Code And Images */ = {\nisa = PBXShellScriptBuildPhase;\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | Basic client support for multimedia upload
This is gonna be different on native vs. web... |
129,187 | 03.12.2018 18:14:02 | 18,000 | 687cf0fb4bd5fcba1b4bf4fcfd34c7055ad2ae57 | Introduce PreviewableMessageInfo
Soon to be differentiated from `RobotextMessageInfo` | [
{
"change_type": "MODIFY",
"old_path": "lib/shared/message-utils.js",
"new_path": "lib/shared/message-utils.js",
"diff": "@@ -4,6 +4,7 @@ import {\ntype MessageInfo,\ntype RawMessageInfo,\ntype RobotextMessageInfo,\n+ type PreviewableMessageInfo,\ntype TextMessageInfo,\ntype MessageData,\ntype MessageType,\n@@ -576,6 +577,13 @@ function shimUnsupportedRawMessageInfos(\nreturn [ ...rawMessageInfos ];\n}\n+function messagePreviewText(\n+ messageInfo: PreviewableMessageInfo,\n+ threadInfo: ThreadInfo,\n+): string {\n+ return robotextToRawString(robotextForMessageInfo(messageInfo, threadInfo));\n+}\n+\nexport {\nmessageKey,\nmessageID,\n@@ -591,4 +599,5 @@ export {\nusersInMessageInfos,\ncombineTruncationStatuses,\nshimUnsupportedRawMessageInfos,\n+ messagePreviewText,\n};\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/types/message-types.js",
"new_path": "lib/types/message-types.js",
"diff": "@@ -353,7 +353,8 @@ export type RobotextMessageInfo = {|\nrobotext: string,\nunsupportedMessageInfo: Object,\n|};\n-export type MessageInfo = TextMessageInfo | RobotextMessageInfo;\n+export type PreviewableMessageInfo = RobotextMessageInfo;\n+export type MessageInfo = TextMessageInfo | PreviewableMessageInfo;\nexport const messageInfoPropType = PropTypes.oneOfType([\nPropTypes.shape({\n"
},
{
"change_type": "MODIFY",
"old_path": "native/chat/message-preview.react.js",
"new_path": "native/chat/message-preview.react.js",
"diff": "@@ -10,10 +10,7 @@ import { type ThreadInfo, threadInfoPropType } from 'lib/types/thread-types';\nimport React from 'react';\nimport { StyleSheet, Text } from 'react-native';\n-import {\n- robotextForMessageInfo,\n- robotextToRawString,\n-} from 'lib/shared/message-utils';\n+import { messagePreviewText } from 'lib/shared/message-utils';\nimport {\nthreadIsPersonalChat,\nthreadIsTwoPersonChat,\n@@ -55,16 +52,13 @@ class MessagePreview extends React.PureComponent<Props> {\n</Text>\n);\n} else {\n- const robotext = robotextToRawString(robotextForMessageInfo(\n- messageInfo,\n- this.props.threadInfo,\n- ));\n+ const preview = messagePreviewText(messageInfo, this.props.threadInfo);\nreturn (\n<Text\n- style={[styles.lastMessage, styles.robotext, unreadStyle]}\n+ style={[styles.lastMessage, styles.preview, unreadStyle]}\nnumberOfLines={1}\n>\n- {robotext}\n+ {preview}\n</Text>\n);\n}\n@@ -82,7 +76,7 @@ const styles = StyleSheet.create({\nusername: {\ncolor: '#AAAAAA',\n},\n- robotext: {\n+ preview: {\ncolor: '#AAAAAA',\n},\nunread: {\n"
},
{
"change_type": "MODIFY",
"old_path": "web/chat/message-preview.react.js",
"new_path": "web/chat/message-preview.react.js",
"diff": "@@ -10,10 +10,7 @@ import { type ThreadInfo, threadInfoPropType } from 'lib/types/thread-types';\nimport * as React from 'react';\nimport classNames from 'classnames';\n-import {\n- robotextForMessageInfo,\n- robotextToRawString,\n-} from 'lib/shared/message-utils';\n+import { messagePreviewText } from 'lib/shared/message-utils';\nimport {\nthreadIsPersonalChat,\nthreadIsTwoPersonChat,\n@@ -62,16 +59,13 @@ class MessagePreview extends React.PureComponent<Props> {\n</div>\n);\n} else {\n- const robotext = robotextToRawString(robotextForMessageInfo(\n- messageInfo,\n- this.props.threadInfo,\n- ));\n+ const preview = messagePreviewText(messageInfo, this.props.threadInfo);\nconst colorStyle = unread ? css.black : css.light;\nreturn (\n<div\nclassName={classNames([css.lastMessage, colorStyle])}\n>\n- {robotext}\n+ {preview}\n</div>\n);\n}\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | Introduce PreviewableMessageInfo
Soon to be differentiated from `RobotextMessageInfo` |
129,187 | 03.12.2018 18:58:55 | 18,000 | ff08087c9904585b81f140daa2c5faec3f7d366d | Introducing messageTypes.MULTIMEDIA
For render, currently just shows dummy robotext | [
{
"change_type": "MODIFY",
"old_path": "lib/selectors/chat-selectors.js",
"new_path": "lib/selectors/chat-selectors.js",
"diff": "@@ -5,7 +5,7 @@ import { type ThreadInfo, threadInfoPropType } from '../types/thread-types';\nimport {\ntype MessageInfo,\ntype MessageStore,\n- type TextMessageInfo,\n+ type OptimisticallyCreatableMessageInfo,\ntype RobotextMessageInfo,\ntype LocalMessageInfo,\nmessageInfoPropType,\n@@ -119,7 +119,7 @@ export type ChatMessageInfoItem = {|\nrobotext: string,\n|} | {|\nitemType: \"message\",\n- messageInfo: TextMessageInfo,\n+ messageInfo: OptimisticallyCreatableMessageInfo,\nlocalMessageInfo: ?LocalMessageInfo,\nstartsConversation: bool,\nstartsCluster: bool,\n@@ -190,7 +190,10 @@ function createChatMessageItems(\nif (!messageInfo) {\ncontinue;\n}\n- if (messageInfo.type === messageTypes.TEXT) {\n+ if (\n+ messageInfo.type === messageTypes.TEXT ||\n+ messageInfo.type === messageTypes.MULTIMEDIA\n+ ) {\nconst localMessageInfo = messageStore.local[messageKey(messageInfo)];\nchatMessageItems.push({\nitemType: \"message\",\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "lib/shared/media-utils.js",
"diff": "+// @flow\n+\n+import type { Media } from '../types/media-types';\n+\n+import invariant from 'invariant';\n+\n+function contentStringForMediaArray(media: $ReadOnlyArray<Media>): string {\n+ invariant(media.length > 0, \"there should be some media\");\n+ if (media.length === 1) {\n+ return `a ${media[0].type}`;\n+ }\n+ let firstType;\n+ for (let single of media) {\n+ if (!firstType) {\n+ firstType = single.type;\n+ }\n+ if (firstType === single.type) {\n+ continue;\n+ } else {\n+ return \"media\";\n+ }\n+ }\n+ invariant(firstType, \"there should be some media\");\n+ return `${firstType}s`;\n+}\n+\n+export {\n+ contentStringForMediaArray,\n+};\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/shared/message-utils.js",
"new_path": "lib/shared/message-utils.js",
"diff": "@@ -22,6 +22,7 @@ import _maxBy from 'lodash/fp/maxBy';\nimport { prettyDate } from '../utils/date-utils';\nimport { userIDsToRelativeUserInfos } from '../selectors/user-selectors';\n+import { contentStringForMediaArray } from './media-utils';\n// Prefers localID\nfunction messageKey(messageInfo: MessageInfo | RawMessageInfo): string {\n@@ -581,6 +582,11 @@ function messagePreviewText(\nmessageInfo: PreviewableMessageInfo,\nthreadInfo: ThreadInfo,\n): string {\n+ if (messageInfo.type === messageTypes.MULTIMEDIA) {\n+ const creator = robotextForUser(messageInfo.creator);\n+ const mediaContentString = contentStringForMediaArray(messageInfo.media);\n+ return `${creator} sent ${mediaContentString}`;\n+ }\nreturn robotextToRawString(robotextForMessageInfo(messageInfo, threadInfo));\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "lib/types/media-types.js",
"diff": "+// @flow\n+\n+import PropTypes from 'prop-types';\n+\n+type MediaType = \"photo\" | \"video\";\n+\n+export type Media = {|\n+ uri: string,\n+ type: MediaType,\n+|};\n+\n+export const mediaPropType = PropTypes.shape({\n+ uri: PropTypes.string.isRequired,\n+ type: PropTypes.oneOf([ \"photo\", \"video\" ]).isRequired,\n+});\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/types/message-types.js",
"new_path": "lib/types/message-types.js",
"diff": "@@ -12,6 +12,7 @@ import {\ntype UserInfo,\ntype UserInfos,\n} from './user-types';\n+import { type Media, mediaPropType } from './media-types';\nimport invariant from 'invariant';\nimport PropTypes from 'prop-types';\n@@ -36,6 +37,7 @@ export const messageTypes = Object.freeze({\n// a RawMessageInfo and a MessageInfo. Note that native/persist.js handles\n// converting these MessageInfos when the client is upgraded.\nUNSUPPORTED: 13,\n+ MULTIMEDIA: 14,\n});\nexport type MessageType = $Values<typeof messageTypes>;\nexport function assertMessageType(\n@@ -55,7 +57,8 @@ export function assertMessageType(\nourMessageType === 10 ||\nourMessageType === 11 ||\nourMessageType === 12 ||\n- ourMessageType === 13,\n+ ourMessageType === 13 ||\n+ ourMessageType === 14,\n\"number is not MessageType enum\",\n);\nreturn ourMessageType;\n@@ -171,6 +174,14 @@ type RestoreEntryMessageData = {|\ndate: string,\ntext: string,\n|};\n+export type MultimediaMessageData = {|\n+ type: 14,\n+ localID?: string, // for optimistic creations. included by new clients\n+ threadID: string,\n+ creatorID: string,\n+ time: number,\n+ media: $ReadOnlyArray<Media>,\n+|};\nexport type MessageData =\n| TextMessageData\n| CreateThreadMessageData\n@@ -184,12 +195,21 @@ export type MessageData =\n| CreateEntryMessageData\n| EditEntryMessageData\n| DeleteEntryMessageData\n- | RestoreEntryMessageData;\n+ | RestoreEntryMessageData\n+ | MultimediaMessageData;\nexport type RawTextMessageInfo = {|\n...TextMessageData,\nid?: string, // null if local copy without ID yet\n|};\n+export type RawMultimediaMessageInfo = {|\n+ ...MultimediaMessageData,\n+ id?: string, // null if local copy without ID yet\n+|};\n+type RawOptimisticallyCreatableMessageInfo =\n+ | RawTextMessageInfo\n+ | RawMultimediaMessageInfo;\n+\ntype RawRobotextMessageInfo = {|\n...CreateThreadMessageData,\nid: string,\n@@ -235,7 +255,9 @@ type RawRobotextMessageInfo = {|\nrobotext: string,\nunsupportedMessageInfo: Object,\n|};\n-export type RawMessageInfo = RawTextMessageInfo | RawRobotextMessageInfo;\n+export type RawMessageInfo =\n+ | RawOptimisticallyCreatableMessageInfo\n+ | RawRobotextMessageInfo;\nexport type TextMessageInfo = {|\ntype: 0,\n@@ -246,6 +268,19 @@ export type TextMessageInfo = {|\ntime: number, // millisecond timestamp\ntext: string,\n|};\n+export type MultimediaMessageInfo = {|\n+ type: 14,\n+ id?: string, // null if local copy without ID yet\n+ localID?: string, // for optimistic creations\n+ threadID: string,\n+ creator: RelativeUserInfo,\n+ time: number, // millisecond timestamp\n+ media: $ReadOnlyArray<Media>,\n+|};\n+export type OptimisticallyCreatableMessageInfo =\n+ | TextMessageInfo\n+ | MultimediaMessageInfo;\n+\nexport type RobotextMessageInfo = {|\ntype: 1,\nid: string,\n@@ -353,13 +388,19 @@ export type RobotextMessageInfo = {|\nrobotext: string,\nunsupportedMessageInfo: Object,\n|};\n-export type PreviewableMessageInfo = RobotextMessageInfo;\n-export type MessageInfo = TextMessageInfo | PreviewableMessageInfo;\n+export type PreviewableMessageInfo =\n+ | RobotextMessageInfo\n+ | MultimediaMessageInfo;\nexport function messageTypeIsRobotext(messageType: MessageType) {\n- return messageType !== messageTypes.TEXT;\n+ return messageType !== messageTypes.TEXT &&\n+ messageType !== messageTypes.MULTIMEDIA;\n}\n+export type MessageInfo =\n+ | OptimisticallyCreatableMessageInfo\n+ | RobotextMessageInfo;\n+\nexport const messageInfoPropType = PropTypes.oneOfType([\nPropTypes.shape({\ntype: PropTypes.oneOf([ messageTypes.TEXT ]).isRequired,\n@@ -492,6 +533,15 @@ export const messageInfoPropType = PropTypes.oneOfType([\nrobotext: PropTypes.string.isRequired,\nunsupportedMessageInfo: PropTypes.object.isRequired,\n}),\n+ PropTypes.shape({\n+ type: PropTypes.oneOf([ messageTypes.MULTIMEDIA ]).isRequired,\n+ id: PropTypes.string,\n+ localID: PropTypes.string,\n+ threadID: PropTypes.string.isRequired,\n+ creator: relativeUserInfoPropType.isRequired,\n+ time: PropTypes.number.isRequired,\n+ media: PropTypes.arrayOf(mediaPropType).isRequired,\n+ }),\n]);\nexport type ThreadMessageInfo = {|\n"
},
{
"change_type": "MODIFY",
"old_path": "native/chat/message-list.react.js",
"new_path": "native/chat/message-list.react.js",
"diff": "@@ -10,7 +10,7 @@ import {\n} from 'lib/selectors/chat-selectors';\nimport type { ViewToken } from 'react-native/Libraries/Lists/ViewabilityHelper';\nimport {\n- type TextMessageInfo,\n+ type OptimisticallyCreatableMessageInfo,\ntype RobotextMessageInfo,\ntype LocalMessageInfo,\ntype FetchMessageInfosPayload,\n@@ -81,7 +81,7 @@ export type RobotextChatMessageInfoItemWithHeight = {|\nexport type ChatMessageInfoItemWithHeight =\nRobotextChatMessageInfoItemWithHeight | {|\nitemType: \"message\",\n- messageInfo: TextMessageInfo,\n+ messageInfo: OptimisticallyCreatableMessageInfo,\nlocalMessageInfo: ?LocalMessageInfo,\nthreadInfo: ThreadInfo,\nstartsConversation: bool,\n@@ -320,7 +320,10 @@ class InnerMessageList extends React.PureComponent<Props, State> {\ntextHeight,\n`height for ${messageKey(item.messageInfo)} should be set`,\n);\n- if (item.messageInfo.type === messageTypes.TEXT) {\n+ if (\n+ item.messageInfo.type === messageTypes.TEXT ||\n+ item.messageInfo.type === messageTypes.MULTIMEDIA\n+ ) {\n// Conditional due to Flow...\nconst localMessageInfo = item.localMessageInfo\n? item.localMessageInfo\n"
},
{
"change_type": "MODIFY",
"old_path": "native/chat/message.react.js",
"new_path": "native/chat/message.react.js",
"diff": "@@ -18,6 +18,7 @@ import {\nRobotextMessage,\nrobotextMessageItemHeight,\n} from './robotext-message.react';\n+import MultimediaMessage from './multimedia-message.react';\nfunction messageItemHeight(\nitem: ChatMessageInfoItemWithHeight,\n@@ -75,6 +76,13 @@ class Message extends React.PureComponent<Props> {\ntoggleFocus={this.props.toggleFocus}\n/>\n);\n+ } else if (this.props.item.messageInfo.type === messageTypes.MULTIMEDIA) {\n+ message = (\n+ <MultimediaMessage\n+ item={this.props.item}\n+ toggleFocus={this.props.toggleFocus}\n+ />\n+ );\n} else {\nmessage = (\n<RobotextMessage\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "native/chat/multimedia-message.react.js",
"diff": "+// @flow\n+\n+import type { ChatMessageInfoItemWithHeight } from './message-list.react';\n+import { chatMessageItemPropType } from 'lib/selectors/chat-selectors';\n+import { messageTypes } from 'lib/types/message-types';\n+\n+import * as React from 'react';\n+import {\n+ Text,\n+ StyleSheet,\n+ TouchableWithoutFeedback,\n+} from 'react-native';\n+import invariant from 'invariant';\n+import PropTypes from 'prop-types';\n+\n+import { messageKey } from 'lib/shared/message-utils';\n+\n+type Props = {|\n+ item: ChatMessageInfoItemWithHeight,\n+ toggleFocus: (messageKey: string) => void,\n+|};\n+class MultimediaMessage extends React.PureComponent<Props> {\n+\n+ static propTypes = {\n+ item: chatMessageItemPropType.isRequired,\n+ toggleFocus: PropTypes.func.isRequired,\n+ };\n+\n+ constructor(props: Props) {\n+ super(props);\n+ invariant(\n+ props.item.messageInfo.type === messageTypes.MULTIMEDIA,\n+ \"MultimediaMessage should only be used for messageTypes.MULTIMEDIA\",\n+ );\n+ }\n+\n+ componentWillReceiveProps(nextProps: Props) {\n+ invariant(\n+ nextProps.item.messageInfo.type === messageTypes.MULTIMEDIA,\n+ \"MultimediaMessage should only be used for messageTypes.MULTIMEDIA\",\n+ );\n+ }\n+\n+ render() {\n+ return (\n+ <TouchableWithoutFeedback onPress={this.onPress}>\n+ <Text style={styles.robotext}>Blah blah image</Text>\n+ </TouchableWithoutFeedback>\n+ );\n+ }\n+\n+ onPress = () => {\n+ this.props.toggleFocus(messageKey(this.props.item.messageInfo));\n+ }\n+\n+}\n+\n+const styles = StyleSheet.create({\n+ robotext: {\n+ textAlign: 'center',\n+ color: '#333333',\n+ paddingVertical: 6,\n+ marginBottom: 5,\n+ marginHorizontal: 24,\n+ fontSize: 15,\n+ fontFamily: 'Arial',\n+ },\n+});\n+\n+export default MultimediaMessage;\n"
},
{
"change_type": "MODIFY",
"old_path": "web/chat/message.react.js",
"new_path": "web/chat/message.react.js",
"diff": "@@ -14,6 +14,7 @@ import { longAbsoluteDate } from 'lib/utils/date-utils';\nimport TextMessage from './text-message.react';\nimport RobotextMessage from './robotext-message.react';\n+import MultimediaMessage from './multimedia-message.react';\nimport css from './chat-message-list.css';\ntype Props = {|\n@@ -49,6 +50,13 @@ class Message extends React.PureComponent<Props> {\ntoggleFocus={this.props.toggleFocus}\n/>\n);\n+ } else if (this.props.item.messageInfo.type === messageTypes.MULTIMEDIA) {\n+ message = (\n+ <MultimediaMessage\n+ item={this.props.item}\n+ toggleFocus={this.props.toggleFocus}\n+ />\n+ );\n} else {\nmessage = (\n<RobotextMessage\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "web/chat/multimedia-message.react.js",
"diff": "+// @flow\n+\n+import {\n+ type ChatMessageInfoItem,\n+ chatMessageItemPropType,\n+} from 'lib/selectors/chat-selectors';\n+import { messageTypes } from 'lib/types/message-types';\n+\n+import * as React from 'react';\n+import invariant from 'invariant';\n+import PropTypes from 'prop-types';\n+\n+import { messageKey } from 'lib/shared/message-utils';\n+\n+import css from './chat-message-list.css';\n+\n+type Props = {|\n+ item: ChatMessageInfoItem,\n+ toggleFocus: (messageKey: string) => void,\n+|};\n+class MultimediaMessage extends React.PureComponent<Props> {\n+\n+ static propTypes = {\n+ item: chatMessageItemPropType.isRequired,\n+ toggleFocus: PropTypes.func.isRequired,\n+ };\n+\n+ constructor(props: Props) {\n+ super(props);\n+ invariant(\n+ props.item.messageInfo.type === messageTypes.MULTIMEDIA,\n+ \"MultimediaMessage should only be used for messageTypes.MULTIMEDIA\",\n+ );\n+ }\n+\n+ componentWillReceiveProps(nextProps: Props) {\n+ invariant(\n+ nextProps.item.messageInfo.type === messageTypes.MULTIMEDIA,\n+ \"MultimediaMessage should only be used for messageTypes.MULTIMEDIA\",\n+ );\n+ }\n+\n+ render() {\n+ invariant(\n+ this.props.item.messageInfo.type === messageTypes.MULTIMEDIA,\n+ \"MultimediaMessage should only be used for messageTypes.MULTIMEDIA\",\n+ );\n+ return (\n+ <div className={css.robotext} onClick={this.onClick}>\n+ Blah blah image\n+ </div>\n+ );\n+ }\n+\n+ onClick = (event: SyntheticEvent<HTMLAnchorElement>) => {\n+ event.stopPropagation();\n+ this.props.toggleFocus(messageKey(this.props.item.messageInfo));\n+ }\n+\n+}\n+\n+export default MultimediaMessage;\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | Introducing messageTypes.MULTIMEDIA
For render, currently just shows dummy robotext |
129,187 | 04.12.2018 19:16:29 | 18,000 | e70fc3581bed2a62cfa8db79e7c3d887e855cb1b | Web UI and handlers for uploading multimedia | [
{
"change_type": "MODIFY",
"old_path": "lib/actions/message-actions.js",
"new_path": "lib/actions/message-actions.js",
"diff": "@@ -77,6 +77,25 @@ async function sendTextMessage(\n};\n}\n+const sendMultimediaMessageActionTypes = Object.freeze({\n+ started: \"SEND_MULTIMEDIA_MESSAGE_STARTED\",\n+ success: \"SEND_MULTIMEDIA_MESSAGE_SUCCESS\",\n+ failed: \"SEND_MULTIMEDIA_MESSAGE_FAILED\",\n+});\n+async function sendMultimediaMessage(\n+ fetchJSON: FetchJSON,\n+ threadID: string,\n+ localID: string,\n+ multimedia: $ReadOnlyArray<Object>,\n+): Promise<SendMessageResult> {\n+ const response = await fetchJSON(\n+ 'create_multimedia_message',\n+ { threadID, localID, multimedia },\n+ { blobUpload: true },\n+ );\n+ return { id: response.id, time: response.time };\n+}\n+\nconst saveMessagesActionType = \"SAVE_MESSAGES\";\nexport {\n@@ -86,5 +105,7 @@ export {\nfetchMostRecentMessages,\nsendTextMessageActionTypes,\nsendTextMessage,\n+ sendMultimediaMessageActionTypes,\n+ sendMultimediaMessage,\nsaveMessagesActionType,\n};\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/types/endpoints.js",
"new_path": "lib/types/endpoints.js",
"diff": "@@ -6,19 +6,18 @@ export type APIRequest = {|\n|};\nexport type SocketAPIHandler = (request: APIRequest) => Promise<Object>;\n-// Endpoints that can cause session changes should occur over HTTP, since the\n-// socket code does not currently support changing sessions. In the future they\n-// could be made to work for native, but cookie changes on web require HTTP\n-// since websockets aren't able to Set-Cookie.\nexport type Endpoint =\n- | SessionChangingEndpoint\n+ | HTTPOnlyEndpoint\n| SocketOnlyEndpoint\n| SocketSafeEndpoint;\n-// Note that technically any endpoint can cause a sessionChange, and in that\n-// case the server will close the socket with a specific error code, and the\n-// client will proceed via HTTP.\n-export const sessionChangingEndpoints = Object.freeze({\n+// Endpoints that can cause session changes should occur over HTTP, since the\n+// socket code does not currently support changing sessions. In the future they\n+// could be made to work for native, but cookie changes on web require HTTP\n+// since websockets aren't able to Set-Cookie. Note that technically any\n+// endpoint can cause a sessionChange, and in that case the server will close\n+// the socket with a specific error code, and the client will proceed via HTTP.\n+const sessionChangingEndpoints = Object.freeze({\nLOG_OUT: 'log_out',\nDELETE_ACCOUNT: 'delete_account',\nCREATE_ACCOUNT: 'create_account',\n@@ -27,13 +26,25 @@ export const sessionChangingEndpoints = Object.freeze({\n});\ntype SessionChangingEndpoint = $Values<typeof sessionChangingEndpoints>;\n-export const socketOnlyEndpoints = Object.freeze({\n+// We do uploads over HTTP as well. This is because Websockets use TCP, which\n+// guarantees ordering. That means that if we start an upload, any messages we\n+// try to send the server after the upload starts will have to wait until the\n+// upload ends. To avoid blocking other messages we upload using HTTP\n+// multipart/form-data.\n+const uploadEndpoints = Object.freeze({\n+ CREATE_MULTIMEDIA_MESSAGE: 'create_multimedia_message',\n+});\n+type UploadEndpoint = $Values<typeof uploadEndpoints>;\n+\n+type HTTPOnlyEndpoint = SessionChangingEndpoint | UploadEndpoint;\n+\n+const socketOnlyEndpoints = Object.freeze({\nUPDATE_ACTIVITY: 'update_activity',\nUPDATE_CALENDAR_QUERY: 'update_calendar_query',\n});\ntype SocketOnlyEndpoint = $Values<typeof socketOnlyEndpoints>;\n-export const socketSafeEndpoints = Object.freeze({\n+const socketSafeEndpoints = Object.freeze({\nUPDATE_USER_SUBSCRIPTION: 'update_user_subscription',\nUPDATE_DEVICE_TOKEN: 'update_device_token',\nUPDATE_ACCOUNT: 'update_account',\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/types/redux-types.js",
"new_path": "lib/types/redux-types.js",
"diff": "@@ -36,6 +36,7 @@ import type { UserSearchResult } from '../types/search-types';\nimport type {\nMessageStore,\nRawTextMessageInfo,\n+ RawMultimediaMessageInfo,\nRawMessageInfo,\nFetchMessageInfosPayload,\nSendMessagePayload,\n@@ -455,6 +456,22 @@ export type BaseAction =\ntype: \"SEND_TEXT_MESSAGE_SUCCESS\",\npayload: SendMessagePayload,\nloadingInfo: LoadingInfo,\n+ |} | {|\n+ type: \"SEND_MULTIMEDIA_MESSAGE_STARTED\",\n+ loadingInfo: LoadingInfo,\n+ payload: RawMultimediaMessageInfo,\n+ |} | {|\n+ type: \"SEND_MULTIMEDIA_MESSAGE_FAILED\",\n+ error: true,\n+ payload: Error & {\n+ localID: string,\n+ threadID: string,\n+ },\n+ loadingInfo: LoadingInfo,\n+ |} | {|\n+ type: \"SEND_MULTIMEDIA_MESSAGE_SUCCESS\",\n+ payload: SendMessagePayload,\n+ loadingInfo: LoadingInfo,\n|} | {|\ntype: \"SEARCH_USERS_STARTED\",\npayload?: void,\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/utils/upload-blob.js",
"new_path": "lib/utils/upload-blob.js",
"diff": "@@ -55,7 +55,6 @@ function uploadBlob(\ncredentials: 'same-origin',\nbody: formData,\nheaders: {\n- 'Content-Type': 'multipart/form-data',\n'Accept': 'application/json',\n},\n});\n"
},
{
"change_type": "MODIFY",
"old_path": "web/chat/chat-input-bar.react.js",
"new_path": "web/chat/chat-input-bar.react.js",
"diff": "@@ -14,6 +14,7 @@ import {\n} from 'lib/types/thread-types';\nimport {\ntype RawTextMessageInfo,\n+ type RawMultimediaMessageInfo,\ntype SendMessageResult,\nmessageTypes,\n} from 'lib/types/message-types';\n@@ -22,12 +23,15 @@ import * as React from 'react';\nimport invariant from 'invariant';\nimport FontAwesomeIcon from '@fortawesome/react-fontawesome';\nimport faChevronRight from '@fortawesome/fontawesome-free-solid/faChevronRight';\n+import faFileImage from '@fortawesome/fontawesome-free-regular/faFileImage';\nimport PropTypes from 'prop-types';\nimport { connect } from 'lib/utils/redux-utils';\nimport {\nsendTextMessageActionTypes,\nsendTextMessage,\n+ sendMultimediaMessageActionTypes,\n+ sendMultimediaMessage,\n} from 'lib/actions/message-actions';\nimport {\njoinThreadActionTypes,\n@@ -55,6 +59,11 @@ type Props = {|\nlocalID: string,\ntext: string,\n) => Promise<SendMessageResult>,\n+ sendMultimediaMessage: (\n+ threadID: string,\n+ localID: string,\n+ multimedia: $ReadOnlyArray<Object>,\n+ ) => Promise<SendMessageResult>,\njoinThread: (request: ClientThreadJoinRequest) => Promise<ThreadJoinPayload>,\n|};\ntype State = {|\n@@ -70,12 +79,14 @@ class ChatInputBar extends React.PureComponent<Props, State> {\nnextLocalID: PropTypes.number.isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\nsendTextMessage: PropTypes.func.isRequired,\n+ sendMultimediaMessage: PropTypes.func.isRequired,\njoinThread: PropTypes.func.isRequired,\n};\nstate = {\nmessageText: \"\",\n};\n- textarea: ?HTMLTextAreaElement = null;\n+ textarea: ?HTMLTextAreaElement;\n+ multimediaInput: ?HTMLInputElement;\ncomponentDidMount() {\nthis.updateHeight();\n@@ -132,6 +143,17 @@ class ChatInputBar extends React.PureComponent<Props, State> {\nonKeyDown={this.onKeyDown}\nref={this.textareaRef}\n/>\n+ <a className={css.multimediaUpload} onClick={this.onMultimediaClick}>\n+ <input\n+ type=\"file\"\n+ onChange={this.onMultimediaFileChange}\n+ ref={this.multimediaInputRef}\n+ multiple\n+ />\n+ <FontAwesomeIcon\n+ icon={faFileImage}\n+ />\n+ </a>\n<a className={css.send} onClick={this.onSend}>\nSend\n<FontAwesomeIcon\n@@ -226,13 +248,13 @@ class ChatInputBar extends React.PureComponent<Props, State> {\n}: RawTextMessageInfo);\nthis.props.dispatchActionPromise(\nsendTextMessageActionTypes,\n- this.sendMessageAction(messageInfo),\n+ this.sendTextMessageAction(messageInfo),\nundefined,\nmessageInfo,\n);\n}\n- async sendMessageAction(messageInfo: RawTextMessageInfo) {\n+ async sendTextMessageAction(messageInfo: RawTextMessageInfo) {\ntry {\nconst { localID } = messageInfo;\ninvariant(\n@@ -257,6 +279,72 @@ class ChatInputBar extends React.PureComponent<Props, State> {\n}\n}\n+ multimediaInputRef = (multimediaInput: ?HTMLInputElement) => {\n+ this.multimediaInput = multimediaInput;\n+ }\n+\n+ onMultimediaClick = (event: SyntheticEvent<HTMLInputElement>) => {\n+ if (this.multimediaInput) {\n+ this.multimediaInput.click();\n+ }\n+ }\n+\n+ onMultimediaFileChange = (event: SyntheticInputEvent<HTMLInputElement>) => {\n+ const files = [...event.target.files];\n+ if (files.length === 0) {\n+ return;\n+ }\n+ const localID = `local${this.props.nextLocalID}`;\n+ const creatorID = this.props.viewerID;\n+ invariant(creatorID, \"should have viewer ID in order to send a message\");\n+ const messageInfo = ({\n+ type: messageTypes.MULTIMEDIA,\n+ localID,\n+ threadID: this.props.threadInfo.id,\n+ creatorID,\n+ time: Date.now(),\n+ media: files.map(file => ({\n+ uri: URL.createObjectURL(file),\n+ // TODO type\n+ type: \"photo\",\n+ })),\n+ }: RawMultimediaMessageInfo);\n+ this.props.dispatchActionPromise(\n+ sendMultimediaMessageActionTypes,\n+ this.sendMultimediaMessageAction(messageInfo, files),\n+ undefined,\n+ messageInfo,\n+ );\n+ }\n+\n+ async sendMultimediaMessageAction(\n+ messageInfo: RawMultimediaMessageInfo,\n+ files: $ReadOnlyArray<File>,\n+ ) {\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.sendMultimediaMessage(\n+ messageInfo.threadID,\n+ localID,\n+ files,\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+\nonClickJoin = (event: SyntheticEvent<HTMLAnchorElement>) => {\nevent.preventDefault();\nthis.props.dispatchActionPromise(\n@@ -292,5 +380,5 @@ export default connect(\ncalendarQuery: nonThreadCalendarQuery(state),\nnextLocalID: state.nextLocalID,\n}),\n- { sendTextMessage, joinThread },\n+ { sendTextMessage, sendMultimediaMessage, joinThread },\n)(ChatInputBar);\n"
},
{
"change_type": "MODIFY",
"old_path": "web/chat/chat-message-list.css",
"new_path": "web/chat/chat-message-list.css",
"diff": "@@ -158,3 +158,22 @@ a.retrySend {\ncolor: #036AFF;\ncursor: pointer;\n}\n+a.multimediaUpload {\n+ cursor: pointer;\n+}\n+a.multimediaUpload > input[type=\"file\"] {\n+ position: absolute;\n+ top: 0;\n+ bottom: 0;\n+ left: 0;\n+ right: 0;\n+ margin: 0;\n+ opacity: 0;\n+ padding: 0;\n+}\n+a.multimediaUpload > svg {\n+ padding: 0 8px;\n+ font-size: 20px;\n+ color: #8A8A8A;\n+ cursor: pointer;\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "web/package.json",
"new_path": "web/package.json",
"diff": "},\n\"dependencies\": {\n\"@fortawesome/fontawesome\": \"^1.1.5\",\n+ \"@fortawesome/fontawesome-free-regular\": \"^5.0.10\",\n\"@fortawesome/fontawesome-free-solid\": \"^5.0.10\",\n\"@fortawesome/react-fontawesome\": \"^0.0.18\",\n\"babel-polyfill\": \"^6.23.0\",\n"
},
{
"change_type": "MODIFY",
"old_path": "yarn.lock",
"new_path": "yarn.lock",
"diff": "resolved \"https://registry.yarnpkg.com/@fortawesome/fontawesome-common-types/-/fontawesome-common-types-0.1.7.tgz#4336c4b06d0b5608ff1215464b66fcf9f4795284\"\nintegrity sha512-ego8jRVSHfq/iq4KRZJKQeUAdi3ZjGNrqw4oPN3fNdvTBnLCSntwVCnc37bsAJP9UB8MhrTfPnZYxkv2vpS4pg==\n+\"@fortawesome/fontawesome-free-regular@^5.0.10\":\n+ version \"5.0.13\"\n+ resolved \"https://registry.yarnpkg.com/@fortawesome/fontawesome-free-regular/-/fontawesome-free-regular-5.0.13.tgz#eb78c30184e3f456a423a1dcfa0f682f7b50de4a\"\n+ integrity sha512-36lz9Idww1L4QaaTcv7GZiOeIP9emJFDUsedvRovI10kmwyd6rN0PKkIjnq0FB4foLhX4Rou8vnbCCmjtqiLug==\n+ dependencies:\n+ \"@fortawesome/fontawesome-common-types\" \"^0.1.7\"\n+\n\"@fortawesome/fontawesome-free-solid@^5.0.10\":\nversion \"5.0.13\"\nresolved \"https://registry.yarnpkg.com/@fortawesome/fontawesome-free-solid/-/fontawesome-free-solid-5.0.13.tgz#24b61aaf471a9d34a5364b052d64a516285ba894\"\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | Web UI and handlers for uploading multimedia |
129,187 | 05.12.2018 19:52:31 | 18,000 | 21a85dcb28e9565f185e0b1a83456b403b955711 | [web] Add mimetype validation to web client
1. File dialog should filter based on extension
2. Resultant `File` options are validated and their mimetypes and extensions corrected based on magic numbers | [
{
"change_type": "MODIFY",
"old_path": "lib/package.json",
"new_path": "lib/package.json",
"diff": "\"color\": \"^1.0.3\",\n\"dateformat\": \"^2.0.0\",\n\"fast-json-stable-stringify\": \"^2.0.0\",\n+ \"file-type\": \"^10.6.0\",\n\"invariant\": \"^2.2.2\",\n\"lodash\": \"^4.17.5\",\n\"prop-types\": \"^15.6.0\",\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/types/media-types.js",
"new_path": "lib/types/media-types.js",
"diff": "import PropTypes from 'prop-types';\n-type MediaType = \"photo\" | \"video\";\n+export type MediaType = \"photo\" | \"video\";\nexport type Media = {|\nuri: string,\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "lib/utils/media-utils.js",
"diff": "+// @flow\n+\n+import type { MediaType } from '../types/media-types';\n+\n+import fileType from 'file-type';\n+\n+type FileInfo = {| name: string, mime: string |};\n+function fileInfoFromData(\n+ data: Uint8Array | Buffer,\n+ fileName: string,\n+): ?FileInfo {\n+ const fileTypeResult = fileType(data);\n+ if (!fileTypeResult) {\n+ return null;\n+ }\n+ const { ext, mime } = fileTypeResult;\n+ const [ readableFileName, extension ] = fileName.split('.');\n+ return { name: `${readableFileName}.${ext}`, mime };\n+}\n+\n+function blobToArrayBuffer(blob: Blob): Promise<ArrayBuffer> {\n+ const fileReader = new FileReader();\n+ return new Promise((resolve, reject) => {\n+ fileReader.onerror = error => {\n+ fileReader.abort();\n+ reject(error);\n+ };\n+ fileReader.onload = (event) => {\n+ resolve(event.target.result);\n+ };\n+ fileReader.readAsArrayBuffer(blob);\n+ });\n+}\n+\n+// Returns null if unsupported\n+type FileValidationResult = {|\n+ file: File,\n+ mediaType: MediaType,\n+|};\n+async function validateFile(file: File): Promise<?FileValidationResult> {\n+ const arrayBuffer = await blobToArrayBuffer(file);\n+ const fileInfo = fileInfoFromData(new Uint8Array(arrayBuffer), file.name);\n+ if (!fileInfo) {\n+ return null;\n+ }\n+ const { name, mime } = fileInfo;\n+ const mediaType = mimeTypesToMediaTypes[mime];\n+ if (!mediaType) {\n+ return null;\n+ }\n+ const fixedFile = name !== file.name || mime !== file.type\n+ ? new File([ file ], name, { type: mime })\n+ : file;\n+ return { file: fixedFile, mediaType };\n+}\n+\n+const mimeTypesToMediaTypes = {\n+ \"image/png\": \"photo\",\n+ \"image/jpeg\": \"photo\",\n+ \"image/gif\": \"photo\",\n+};\n+const allowedMimeTypeString = Object.keys(mimeTypesToMediaTypes).join(',');\n+\n+export {\n+ fileInfoFromData,\n+ validateFile,\n+ allowedMimeTypeString,\n+};\n"
},
{
"change_type": "MODIFY",
"old_path": "server/package.json",
"new_path": "server/package.json",
"diff": "\"denodeify\": \"^1.2.1\",\n\"express\": \"^4.16.2\",\n\"express-ws\": \"^4.0.0\",\n- \"file-type\": \"^10.6.0\",\n\"firebase-admin\": \"^5.7.0\",\n\"invariant\": \"^2.2.2\",\n\"lib\": \"0.0.1\",\n"
},
{
"change_type": "MODIFY",
"old_path": "web/chat/chat-input-bar.react.js",
"new_path": "web/chat/chat-input-bar.react.js",
"diff": "@@ -39,6 +39,7 @@ import {\n} from 'lib/actions/thread-actions';\nimport { createLoadingStatusSelector } from 'lib/selectors/loading-selectors';\nimport { threadHasPermission, viewerIsMember } from 'lib/shared/thread-utils';\n+import { validateFile, allowedMimeTypeString } from 'lib/utils/media-utils';\nimport css from './chat-message-list.css';\nimport LoadingIndicator from '../loading-indicator.react';\n@@ -148,6 +149,7 @@ class ChatInputBar extends React.PureComponent<Props, State> {\ntype=\"file\"\nonChange={this.onMultimediaFileChange}\nref={this.multimediaInputRef}\n+ accept={allowedMimeTypeString}\nmultiple\n/>\n<FontAwesomeIcon\n@@ -289,11 +291,12 @@ class ChatInputBar extends React.PureComponent<Props, State> {\n}\n}\n- onMultimediaFileChange = (event: SyntheticInputEvent<HTMLInputElement>) => {\n- const files = [...event.target.files];\n- if (files.length === 0) {\n- return;\n- }\n+ onMultimediaFileChange = async (event: SyntheticInputEvent<HTMLInputElement>) => {\n+ const validationResult = await Promise.all(\n+ [...event.target.files].map(validateFile)\n+ );\n+ const validatedFileInfo = validationResult.filter(Boolean);\n+ const files = validatedFileInfo.map(({ file }) => file);\nconst localID = `local${this.props.nextLocalID}`;\nconst creatorID = this.props.viewerID;\ninvariant(creatorID, \"should have viewer ID in order to send a message\");\n@@ -303,10 +306,9 @@ class ChatInputBar extends React.PureComponent<Props, State> {\nthreadID: this.props.threadInfo.id,\ncreatorID,\ntime: Date.now(),\n- media: files.map(file => ({\n+ media: validatedFileInfo.map(({ file, mediaType }) => ({\nuri: URL.createObjectURL(file),\n- // TODO type\n- type: \"photo\",\n+ type: mediaType,\n})),\n}: RawMultimediaMessageInfo);\nthis.props.dispatchActionPromise(\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [web] Add mimetype validation to web client
1. File dialog should filter based on extension
2. Resultant `File` options are validated and their mimetypes and extensions corrected based on magic numbers |
129,187 | 05.12.2018 21:19:14 | 18,000 | 8c9413f286af74a15d4e0577eec82555068ddf86 | [server] Add mimetype validation to server | [
{
"change_type": "MODIFY",
"old_path": "lib/utils/media-utils.js",
"new_path": "lib/utils/media-utils.js",
"diff": "@@ -14,6 +14,10 @@ function fileInfoFromData(\nreturn null;\n}\nconst { ext, mime } = fileTypeResult;\n+ const mediaType = mimeTypesToMediaTypes[mime];\n+ if (!mediaType) {\n+ return null;\n+ }\nconst [ readableFileName, extension ] = fileName.split('.');\nreturn { name: `${readableFileName}.${ext}`, mime };\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/uploads/uploads.js",
"new_path": "server/src/uploads/uploads.js",
"diff": "@@ -7,6 +7,9 @@ import type { SendMultimediaMessageResponse } from 'lib/types/message-types';\nimport multer from 'multer';\nimport fileType from 'file-type';\n+import { fileInfoFromData } from 'lib/utils/media-utils';\n+import { ServerError } from 'lib/utils/errors';\n+\nconst upload = multer();\nconst multerProcessor = upload.array('multimedia');\n@@ -24,7 +27,18 @@ async function multimediaMessageCreationResponder(\nreq: $Request & { files?: $ReadOnlyArray<MulterFile> },\n): Promise<SendMultimediaMessageResponse> {\nconsole.log(req.body);\n- console.log(req.files);\n+ const { files } = req;\n+ if (!files) {\n+ throw new ServerError('invalid_parameters');\n+ }\n+ const multerFilesWithInfos = files.map(multerFile => ({\n+ multerFile,\n+ fileInfo: fileInfoFromData(multerFile.buffer, multerFile.originalname),\n+ })).filter(Boolean);\n+ if (multerFilesWithInfos.length === 0) {\n+ throw new ServerError('invalid_parameters');\n+ }\n+ console.log(multerFilesWithInfos);\nreturn { id: \"test\", time: 5 };\n}\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [server] Add mimetype validation to server |
129,187 | 07.12.2018 11:15:33 | 18,000 | 48fff7d50b1daaf936a495e56240989585c7a657 | [web] Add border in chat view | [
{
"change_type": "MODIFY",
"old_path": "web/chat/chat-message-list.css",
"new_path": "web/chat/chat-message-list.css",
"diff": "@@ -19,6 +19,7 @@ div.messageContainer > div {\ndiv.inputBar {\ndisplay: flex;\nflex-direction: column;\n+ border-top: 2px solid #E4E4E4;\n}\ndiv.inputBarTextInput {\ndisplay: flex;\n"
},
{
"change_type": "MODIFY",
"old_path": "web/chat/chat-thread-list.css",
"new_path": "web/chat/chat-thread-list.css",
"diff": "@@ -5,6 +5,7 @@ div.container {\nbottom: 0;\noverflow-y: auto;\nbackground-color: white;\n+ border-right: 2px solid #E4E4E4;\n}\na.thread {\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [web] Add border in chat view |
129,187 | 07.12.2018 12:04:15 | 18,000 | 55367acfc617ed67fdfd318ea28206952a112994 | Move web-specific media-utils to web folder | [
{
"change_type": "MODIFY",
"old_path": "lib/utils/media-utils.js",
"new_path": "lib/utils/media-utils.js",
"diff": "// @flow\n-import type { MediaType } from '../types/media-types';\n-\nimport fileType from 'file-type';\ntype FileInfo = {| name: string, mime: string |};\n@@ -22,51 +20,13 @@ function fileInfoFromData(\nreturn { name: `${readableFileName}.${ext}`, mime };\n}\n-function blobToArrayBuffer(blob: Blob): Promise<ArrayBuffer> {\n- const fileReader = new FileReader();\n- return new Promise((resolve, reject) => {\n- fileReader.onerror = error => {\n- fileReader.abort();\n- reject(error);\n- };\n- fileReader.onload = (event) => {\n- resolve(event.target.result);\n- };\n- fileReader.readAsArrayBuffer(blob);\n- });\n-}\n-\n-// Returns null if unsupported\n-type FileValidationResult = {|\n- file: File,\n- mediaType: MediaType,\n-|};\n-async function validateFile(file: File): Promise<?FileValidationResult> {\n- const arrayBuffer = await blobToArrayBuffer(file);\n- const fileInfo = fileInfoFromData(new Uint8Array(arrayBuffer), file.name);\n- if (!fileInfo) {\n- return null;\n- }\n- const { name, mime } = fileInfo;\n- const mediaType = mimeTypesToMediaTypes[mime];\n- if (!mediaType) {\n- return null;\n- }\n- const fixedFile = name !== file.name || mime !== file.type\n- ? new File([ file ], name, { type: mime })\n- : file;\n- return { file: fixedFile, mediaType };\n-}\n-\nconst mimeTypesToMediaTypes = {\n\"image/png\": \"photo\",\n\"image/jpeg\": \"photo\",\n\"image/gif\": \"photo\",\n};\n-const allowedMimeTypeString = Object.keys(mimeTypesToMediaTypes).join(',');\nexport {\nfileInfoFromData,\n- validateFile,\n- allowedMimeTypeString,\n+ mimeTypesToMediaTypes,\n};\n"
},
{
"change_type": "MODIFY",
"old_path": "web/chat/chat-input-bar.react.js",
"new_path": "web/chat/chat-input-bar.react.js",
"diff": "@@ -39,11 +39,11 @@ import {\n} from 'lib/actions/thread-actions';\nimport { createLoadingStatusSelector } from 'lib/selectors/loading-selectors';\nimport { threadHasPermission, viewerIsMember } from 'lib/shared/thread-utils';\n-import { validateFile, allowedMimeTypeString } from 'lib/utils/media-utils';\nimport css from './chat-message-list.css';\nimport LoadingIndicator from '../loading-indicator.react';\nimport { nonThreadCalendarQuery } from '../selectors/nav-selectors';\n+import { validateFile, allowedMimeTypeString } from '../utils/media-utils';\ntype Props = {|\nthreadInfo: ThreadInfo,\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "web/utils/media-utils.js",
"diff": "+// @flow\n+\n+import type { MediaType } from 'lib/types/media-types';\n+\n+import {\n+ fileInfoFromData,\n+ mimeTypesToMediaTypes,\n+} from 'lib/utils/media-utils';\n+\n+function blobToArrayBuffer(blob: Blob): Promise<ArrayBuffer> {\n+ const fileReader = new FileReader();\n+ return new Promise((resolve, reject) => {\n+ fileReader.onerror = error => {\n+ fileReader.abort();\n+ reject(error);\n+ };\n+ fileReader.onload = (event) => {\n+ resolve(event.target.result);\n+ };\n+ fileReader.readAsArrayBuffer(blob);\n+ });\n+}\n+\n+// Returns null if unsupported\n+type FileValidationResult = {|\n+ file: File,\n+ mediaType: MediaType,\n+|};\n+async function validateFile(file: File): Promise<?FileValidationResult> {\n+ const arrayBuffer = await blobToArrayBuffer(file);\n+ const fileInfo = fileInfoFromData(new Uint8Array(arrayBuffer), file.name);\n+ if (!fileInfo) {\n+ return null;\n+ }\n+ const { name, mime } = fileInfo;\n+ const mediaType = mimeTypesToMediaTypes[mime];\n+ if (!mediaType) {\n+ return null;\n+ }\n+ const fixedFile = name !== file.name || mime !== file.type\n+ ? new File([ file ], name, { type: mime })\n+ : file;\n+ return { file: fixedFile, mediaType };\n+}\n+\n+const allowedMimeTypeString = Object.keys(mimeTypesToMediaTypes).join(',');\n+\n+export {\n+ validateFile,\n+ allowedMimeTypeString,\n+};\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | Move web-specific media-utils to web folder |
129,187 | 07.12.2018 12:12:37 | 18,000 | 875c6691544c84d018537933f3fc4ea09c6b04e5 | Multimedia preview on web | [
{
"change_type": "MODIFY",
"old_path": "lib/types/media-types.js",
"new_path": "lib/types/media-types.js",
"diff": "@@ -9,7 +9,20 @@ export type Media = {|\ntype: MediaType,\n|};\n+const mediaTypePropType = PropTypes.oneOf([ \"photo\", \"video\" ]);\n+\nexport const mediaPropType = PropTypes.shape({\nuri: PropTypes.string.isRequired,\n- type: PropTypes.oneOf([ \"photo\", \"video\" ]).isRequired,\n+ type: mediaTypePropType.isRequired,\n+});\n+\n+export type PendingMultimediaUpload = {|\n+ file: File,\n+ mediaType: MediaType,\n+ uri: string,\n+|};\n+export const pendingMultimediaUploadPropType = PropTypes.shape({\n+ file: PropTypes.object.isRequired,\n+ mediaType: mediaTypePropType.isRequired,\n+ uri: PropTypes.string.isRequired,\n});\n"
},
{
"change_type": "MODIFY",
"old_path": "web/chat/chat-input-bar.react.js",
"new_path": "web/chat/chat-input-bar.react.js",
"diff": "@@ -18,6 +18,7 @@ import {\ntype SendMessageResult,\nmessageTypes,\n} from 'lib/types/message-types';\n+import type { PendingMultimediaUpload } from 'lib/types/media-types';\nimport * as React from 'react';\nimport invariant from 'invariant';\n@@ -44,6 +45,7 @@ import css from './chat-message-list.css';\nimport LoadingIndicator from '../loading-indicator.react';\nimport { nonThreadCalendarQuery } from '../selectors/nav-selectors';\nimport { validateFile, allowedMimeTypeString } from '../utils/media-utils';\n+import MultimediaPreview from './multimedia-preview.react';\ntype Props = {|\nthreadInfo: ThreadInfo,\n@@ -69,6 +71,7 @@ type Props = {|\n|};\ntype State = {|\nmessageText: string,\n+ pendingUploads: $ReadOnlyArray<PendingMultimediaUpload>,\n|};\nclass ChatInputBar extends React.PureComponent<Props, State> {\n@@ -85,6 +88,7 @@ class ChatInputBar extends React.PureComponent<Props, State> {\n};\nstate = {\nmessageText: \"\",\n+ pendingUploads: [],\n};\ntextarea: ?HTMLTextAreaElement;\nmultimediaInput: ?HTMLInputElement;\n@@ -132,6 +136,17 @@ class ChatInputBar extends React.PureComponent<Props, State> {\n);\n}\n+ const multimediaPreviews = this.state.pendingUploads.map(pendingUpload => (\n+ <MultimediaPreview\n+ pendingUpload={pendingUpload}\n+ remove={this.removePendingUpload}\n+ key={pendingUpload.uri}\n+ />\n+ ));\n+ const previews = multimediaPreviews.length > 0\n+ ? <div className={css.previews}>{multimediaPreviews}</div>\n+ : null;\n+\nlet content;\nif (threadHasPermission(this.props.threadInfo, threadPermissions.VOICED)) {\ncontent = (\n@@ -157,11 +172,11 @@ class ChatInputBar extends React.PureComponent<Props, State> {\n/>\n</a>\n<a className={css.send} onClick={this.onSend}>\n- Send\n<FontAwesomeIcon\nicon={faChevronRight}\nclassName={css.sendButton}\n/>\n+ Send\n</a>\n</div>\n);\n@@ -199,6 +214,7 @@ class ChatInputBar extends React.PureComponent<Props, State> {\nreturn (\n<div className={css.inputBar}>\n{joinButton}\n+ {previews}\n{content}\n</div>\n);\n@@ -231,12 +247,21 @@ class ChatInputBar extends React.PureComponent<Props, State> {\nsend() {\nconst text = this.state.messageText.trim();\n- if (!text) {\n+ if (text) {\n// TODO we should make the send button appear dynamically\n// iff trimmed text is nonempty, just like native\n- return;\n+ this.dispatchTextMessageAction(text);\n+ }\n+\n+ const { pendingUploads } = this.state;\n+ if (pendingUploads.length > 0) {\n+ this.dispatchMultimediaMessageAction(pendingUploads);\n}\n+ }\n+\n+ dispatchTextMessageAction(text: string) {\nthis.updateText(\"\");\n+\nconst localID = `local${this.props.nextLocalID}`;\nconst creatorID = this.props.viewerID;\ninvariant(creatorID, \"should have viewer ID in order to send a message\");\n@@ -296,7 +321,35 @@ class ChatInputBar extends React.PureComponent<Props, State> {\n[...event.target.files].map(validateFile)\n);\nconst validatedFileInfo = validationResult.filter(Boolean);\n- const files = validatedFileInfo.map(({ file }) => file);\n+ const pendingUploads = validatedFileInfo.map(({ file, mediaType }) => ({\n+ file,\n+ mediaType,\n+ uri: URL.createObjectURL(file),\n+ }));\n+ this.setState(prevState => ({\n+ pendingUploads: [ ...prevState.pendingUploads, ...pendingUploads ],\n+ }));\n+ }\n+\n+ removePendingUpload = (pendingUpload: PendingMultimediaUpload) => {\n+ if (this.multimediaInput) {\n+ this.multimediaInput.value = null;\n+ }\n+ this.setState(prevState => ({\n+ pendingUploads: prevState.pendingUploads.filter(\n+ candidate => candidate !== pendingUpload,\n+ ),\n+ }));\n+ }\n+\n+ dispatchMultimediaMessageAction(\n+ pendingUploads: $ReadOnlyArray<PendingMultimediaUpload>,\n+ ) {\n+ this.setState({ pendingUploads: [] });\n+ if (this.multimediaInput) {\n+ this.multimediaInput.value = null;\n+ }\n+\nconst localID = `local${this.props.nextLocalID}`;\nconst creatorID = this.props.viewerID;\ninvariant(creatorID, \"should have viewer ID in order to send a message\");\n@@ -306,11 +359,12 @@ class ChatInputBar extends React.PureComponent<Props, State> {\nthreadID: this.props.threadInfo.id,\ncreatorID,\ntime: Date.now(),\n- media: validatedFileInfo.map(({ file, mediaType }) => ({\n- uri: URL.createObjectURL(file),\n+ media: pendingUploads.map(({ uri, mediaType }) => ({\n+ uri,\ntype: mediaType,\n})),\n}: RawMultimediaMessageInfo);\n+ const files = pendingUploads.map(({ file }) => file);\nthis.props.dispatchActionPromise(\nsendMultimediaMessageActionTypes,\nthis.sendMultimediaMessageAction(messageInfo, files),\n"
},
{
"change_type": "MODIFY",
"old_path": "web/chat/chat-message-list.css",
"new_path": "web/chat/chat-message-list.css",
"diff": "@@ -51,7 +51,7 @@ a.send {\ncursor: pointer;\n}\nsvg.sendButton {\n- padding-left: 8px;\n+ padding: 0 4px;\nfont-size: 24px;\ncolor: #88BB88;\n}\n@@ -161,20 +161,49 @@ a.retrySend {\n}\na.multimediaUpload {\ncursor: pointer;\n+ position: relative;\n}\na.multimediaUpload > input[type=\"file\"] {\n+ visibility: hidden;\nposition: absolute;\ntop: 0;\nbottom: 0;\nleft: 0;\nright: 0;\nmargin: 0;\n- opacity: 0;\npadding: 0;\n}\na.multimediaUpload > svg {\n- padding: 0 8px;\n+ padding: 0 6px;\nfont-size: 20px;\ncolor: #8A8A8A;\ncursor: pointer;\n}\n+\n+div.previews {\n+ overflow-x: auto;\n+ white-space: nowrap;\n+}\n+span.preview {\n+ margin: 10px;\n+ position: relative;\n+ display: inline-block;\n+}\n+span.preview > img {\n+ max-height: 200px;\n+ max-width: 200px;\n+}\n+span.preview > svg {\n+ display: none;\n+ position: absolute;\n+ cursor: pointer;\n+ top: 3px;\n+ right: 3px;\n+ color: white;\n+ border-radius: 50%;\n+ box-shadow: inset 0px 0px 5px rgba(0,0,0,0.5);\n+ background-color: #222222AA;\n+}\n+span.preview:hover > svg {\n+ display: inherit;\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "web/chat/multimedia-preview.react.js",
"diff": "+// @flow\n+\n+import {\n+ type PendingMultimediaUpload,\n+ pendingMultimediaUploadPropType,\n+} from 'lib/types/media-types';\n+\n+import * as React from 'react';\n+import PropTypes from 'prop-types';\n+import XCircleIcon from 'react-feather/dist/icons/x-circle';\n+\n+import css from './chat-message-list.css';\n+\n+type Props = {|\n+ pendingUpload: PendingMultimediaUpload,\n+ remove: (pendingUpload: PendingMultimediaUpload) => void,\n+|};\n+class MultimediaPreview extends React.PureComponent<Props> {\n+\n+ static propTypes = {\n+ pendingUpload: pendingMultimediaUploadPropType.isRequired,\n+ remove: PropTypes.func.isRequired,\n+ };\n+\n+ render() {\n+ return (\n+ <span className={css.preview}>\n+ <img src={this.props.pendingUpload.uri} />\n+ <XCircleIcon onClick={this.remove} />\n+ </span>\n+ );\n+ }\n+\n+ remove = () => {\n+ this.props.remove(this.props.pendingUpload);\n+ }\n+\n+}\n+\n+export default MultimediaPreview;\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | Multimedia preview on web |
129,187 | 21.12.2018 14:08:46 | 18,000 | 4731482bda5f0d4158c3193b874eee24398d7799 | [web] Type fix for HTMLInputElement.value reset | [
{
"change_type": "MODIFY",
"old_path": "web/chat/chat-input-bar.react.js",
"new_path": "web/chat/chat-input-bar.react.js",
"diff": "@@ -333,7 +333,7 @@ class ChatInputBar extends React.PureComponent<Props, State> {\nremovePendingUpload = (pendingUpload: PendingMultimediaUpload) => {\nif (this.multimediaInput) {\n- this.multimediaInput.value = null;\n+ this.multimediaInput.value = \"\";\n}\nthis.setState(prevState => ({\npendingUploads: prevState.pendingUploads.filter(\n@@ -347,7 +347,7 @@ class ChatInputBar extends React.PureComponent<Props, State> {\n) {\nthis.setState({ pendingUploads: [] });\nif (this.multimediaInput) {\n- this.multimediaInput.value = null;\n+ this.multimediaInput.value = \"\";\n}\nconst localID = `local${this.props.nextLocalID}`;\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [web] Type fix for HTMLInputElement.value reset |
129,187 | 21.12.2018 15:05:49 | 18,000 | 345a13e44b7ed7c078f67f086a870d6a18d9f120 | Isolate drafts state to native
We are about to introduce a different mechanism to cache `ThreadInfo`-local state like drafts on web. | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "lib/actions/miscellaneous-action-types.js",
"diff": "+// @flow\n+\n+export const saveDraftActionType = \"SAVE_DRAFT\";\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/reducers/master-reducer.js",
"new_path": "lib/reducers/master-reducer.js",
"diff": "@@ -14,7 +14,6 @@ import reduceThreadInfos from './thread-reducer';\nimport reduceBaseNavInfo from './nav-reducer';\nimport { reduceMessageStore } from './message-reducer';\nimport reduceUpdatesCurrentAsOf from './updates-reducer';\n-import { reduceDrafts } from './draft-reducer';\nimport reduceURLPrefix from './url-prefix-reducer';\nimport reduceCalendarFilters from './calendar-filters-reducer';\nimport reduceConnectionInfo from './connection-reducer';\n@@ -76,7 +75,6 @@ export default function baseReducer<N: BaseNavInfo, T: BaseAppState<N>>(\nthreadStore,\nuserInfos: reduceUserInfos(state.userInfos, action),\nmessageStore: reduceMessageStore(state.messageStore, action, threadInfos),\n- drafts: reduceDrafts(state.drafts, action),\nupdatesCurrentAsOf,\nurlPrefix: reduceURLPrefix(state.urlPrefix, action),\ncalendarFilters: reduceCalendarFilters(\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/types/redux-types.js",
"new_path": "lib/types/redux-types.js",
"diff": "@@ -78,7 +78,6 @@ export type BaseAppState<NavInfo: BaseNavInfo> = {\nthreadStore: ThreadStore,\nuserInfos: {[id: string]: UserInfo},\nmessageStore: MessageStore,\n- drafts: {[key: string]: string},\nupdatesCurrentAsOf: number, // millisecond timestamp\nloadingStatuses: {[key: string]: {[idx: number]: LoadingStatus}},\ncalendarFilters: $ReadOnlyArray<CalendarFilter>,\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/utils/redux-logger.js",
"new_path": "lib/utils/redux-logger.js",
"diff": "@@ -6,7 +6,7 @@ import {\nrehydrateActionType,\n} from '../types/redux-types';\n-import { saveDraftActionType } from '../reducers/draft-reducer';\n+import { saveDraftActionType } from '../actions/miscellaneous-action-types';\nconst uninterestingActionTypes = new Set([ saveDraftActionType ]);\n"
},
{
"change_type": "MODIFY",
"old_path": "native/chat/chat-input-bar.react.js",
"new_path": "native/chat/chat-input-bar.react.js",
"diff": "@@ -41,7 +41,7 @@ import {\nsendTextMessageActionTypes,\nsendTextMessage,\n} from 'lib/actions/message-actions';\n-import { saveDraftActionType } from 'lib/reducers/draft-reducer';\n+import { saveDraftActionType } from 'lib/actions/miscellaneous-action-types';\nimport { threadHasPermission, viewerIsMember } from 'lib/shared/thread-utils';\nimport {\njoinThreadActionTypes,\n"
},
{
"change_type": "RENAME",
"old_path": "lib/reducers/draft-reducer.js",
"new_path": "native/reducers/draft-reducer.js",
"diff": "// @flow\n-import type { BaseAction } from '../types/redux-types';\n-\nimport {\nlogOutActionTypes,\ndeleteAccountActionTypes,\n-} from '../actions/user-actions';\n-import { setNewSessionActionType } from '../utils/action-utils';\n-\n-const saveDraftActionType = \"SAVE_DRAFT\";\n+} from 'lib/actions/user-actions';\n+import { setNewSessionActionType } from 'lib/utils/action-utils';\n+import { saveDraftActionType } from 'lib/actions/miscellaneous-action-types';\n-function reduceDrafts(\n+export default function reduceDrafts(\nstate: ?{[key: string]: string},\n- action: BaseAction,\n+ action: *,\n): {[key: string]: string} {\nif (!state) {\nstate = {};\n@@ -32,8 +29,3 @@ function reduceDrafts(\n}\nreturn state;\n}\n-\n-export {\n- saveDraftActionType,\n- reduceDrafts,\n-};\n"
},
{
"change_type": "MODIFY",
"old_path": "native/redux-setup.js",
"new_path": "native/redux-setup.js",
"diff": "@@ -81,6 +81,7 @@ import {\nMessageListRouteName,\n} from './navigation/route-names';\nimport reactotron from './reactotron';\n+import reduceDrafts from './reducers/draft-reducer';\nconst createStore = reactotron\n? reactotron.createStore\n@@ -240,7 +241,10 @@ function reducer(state: AppState = defaultState, action: *) {\n}\n}\n- state = baseReducer(state, action);\n+ state = {\n+ ...baseReducer(state, action),\n+ drafts: reduceDrafts(state.drafts, action),\n+ };\nlet navInfo = reduceNavInfo(state, action, state.threadStore.threadInfos);\nif (navInfo && navInfo !== state.navInfo) {\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/responders/website-responders.js",
"new_path": "server/src/responders/website-responders.js",
"diff": "@@ -145,7 +145,6 @@ async function websiteResponder(viewer: Viewer, url: string): Promise<string> {\n...threadUserInfos,\n},\nmessageStore,\n- drafts: {},\nupdatesCurrentAsOf: initialTime,\nloadingStatuses: {},\ncalendarFilters: defaultCalendarFilters,\n"
},
{
"change_type": "MODIFY",
"old_path": "web/redux-setup.js",
"new_path": "web/redux-setup.js",
"diff": "@@ -51,7 +51,6 @@ export type AppState = {|\nthreadStore: ThreadStore,\nuserInfos: {[id: string]: UserInfo},\nmessageStore: MessageStore,\n- drafts: {[key: string]: string},\nupdatesCurrentAsOf: number,\nloadingStatuses: {[key: string]: {[idx: number]: LoadingStatus}},\ncalendarFilters: $ReadOnlyArray<CalendarFilter>,\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | Isolate drafts state to native
We are about to introduce a different mechanism to cache `ThreadInfo`-local state like drafts on web. |
129,187 | 21.12.2018 17:03:00 | 18,000 | 33f86ec4d50ab130f5fa43d5b02a7aff76b0763d | [web] Lift ChatInputState
This allows us to persist drafts of messages on a per-thread basis | [
{
"change_type": "MODIFY",
"old_path": "web/chat/chat-input-bar.react.js",
"new_path": "web/chat/chat-input-bar.react.js",
"diff": "@@ -19,6 +19,10 @@ import {\nmessageTypes,\n} from 'lib/types/message-types';\nimport type { PendingMultimediaUpload } from 'lib/types/media-types';\n+import {\n+ chatInputStatePropType,\n+ type ChatInputState,\n+} from './chat-input-state';\nimport * as React from 'react';\nimport invariant from 'invariant';\n@@ -26,6 +30,7 @@ import FontAwesomeIcon from '@fortawesome/react-fontawesome';\nimport faChevronRight from '@fortawesome/fontawesome-free-solid/faChevronRight';\nimport faFileImage from '@fortawesome/fontawesome-free-regular/faFileImage';\nimport PropTypes from 'prop-types';\n+import _difference from 'lodash/fp/difference';\nimport { connect } from 'lib/utils/redux-utils';\nimport {\n@@ -44,11 +49,12 @@ import { threadHasPermission, viewerIsMember } from 'lib/shared/thread-utils';\nimport css from './chat-message-list.css';\nimport LoadingIndicator from '../loading-indicator.react';\nimport { nonThreadCalendarQuery } from '../selectors/nav-selectors';\n-import { validateFile, allowedMimeTypeString } from '../utils/media-utils';\n+import { allowedMimeTypeString } from '../utils/media-utils';\nimport MultimediaPreview from './multimedia-preview.react';\ntype Props = {|\nthreadInfo: ThreadInfo,\n+ chatInputState: ChatInputState,\n// Redux state\nviewerID: ?string,\njoinThreadLoadingStatus: LoadingStatus,\n@@ -69,14 +75,11 @@ type Props = {|\n) => Promise<SendMessageResult>,\njoinThread: (request: ClientThreadJoinRequest) => Promise<ThreadJoinPayload>,\n|};\n-type State = {|\n- messageText: string,\n- pendingUploads: $ReadOnlyArray<PendingMultimediaUpload>,\n-|};\n-class ChatInputBar extends React.PureComponent<Props, State> {\n+class ChatInputBar extends React.PureComponent<Props> {\nstatic propTypes = {\nthreadInfo: threadInfoPropType.isRequired,\n+ chatInputState: chatInputStatePropType.isRequired,\nviewerID: PropTypes.string,\njoinThreadLoadingStatus: loadingStatusPropType.isRequired,\ncalendarQuery: PropTypes.func.isRequired,\n@@ -86,10 +89,6 @@ class ChatInputBar extends React.PureComponent<Props, State> {\nsendMultimediaMessage: PropTypes.func.isRequired,\njoinThread: PropTypes.func.isRequired,\n};\n- state = {\n- messageText: \"\",\n- pendingUploads: [],\n- };\ntextarea: ?HTMLTextAreaElement;\nmultimediaInput: ?HTMLInputElement;\n@@ -97,7 +96,28 @@ class ChatInputBar extends React.PureComponent<Props, State> {\nthis.updateHeight();\n}\n- updateHeight = () => {\n+ componentDidUpdate(prevProps: Props) {\n+ const { chatInputState } = this.props;\n+ const prevChatInputState = prevProps.chatInputState;\n+ if (chatInputState.draft !== prevChatInputState.draft) {\n+ this.updateHeight();\n+ }\n+ if (\n+ this.multimediaInput &&\n+ _difference(\n+ prevChatInputState.pendingUploads,\n+ )(\n+ chatInputState.pendingUploads,\n+ ).length > 0\n+ ) {\n+ // Whenever a pending upload is removed, we reset the file\n+ // HTMLInputElement's value field, so that if the same upload occurs again\n+ // the onChange call doesn't get filtered\n+ this.multimediaInput.value = \"\";\n+ }\n+ }\n+\n+ updateHeight() {\nconst textarea = this.textarea;\nif (textarea) {\ntextarea.style.height = 'auto';\n@@ -136,10 +156,11 @@ class ChatInputBar extends React.PureComponent<Props, State> {\n);\n}\n- const multimediaPreviews = this.state.pendingUploads.map(pendingUpload => (\n+ const multimediaPreviews =\n+ this.props.chatInputState.pendingUploads.map(pendingUpload => (\n<MultimediaPreview\npendingUpload={pendingUpload}\n- remove={this.removePendingUpload}\n+ remove={this.props.chatInputState.removePendingUpload}\nkey={pendingUpload.uri}\n/>\n));\n@@ -154,7 +175,7 @@ class ChatInputBar extends React.PureComponent<Props, State> {\n<textarea\nrows=\"1\"\nplaceholder=\"Send a message...\"\n- value={this.state.messageText}\n+ value={this.props.chatInputState.draft}\nonChange={this.onChangeMessageText}\nonKeyDown={this.onKeyDown}\nref={this.textareaRef}\n@@ -225,8 +246,7 @@ class ChatInputBar extends React.PureComponent<Props, State> {\n}\nonChangeMessageText = (event: SyntheticEvent<HTMLTextAreaElement>) => {\n- const messageText = event.currentTarget.value;\n- this.updateText(messageText);\n+ this.props.chatInputState.setDraft(event.currentTarget.value);\n}\nonKeyDown = (event: SyntheticKeyboardEvent<HTMLTextAreaElement>) => {\n@@ -236,31 +256,27 @@ class ChatInputBar extends React.PureComponent<Props, State> {\n}\n}\n- updateText(messageText: string) {\n- this.setState({ messageText }, this.updateHeight);\n- }\n-\nonSend = (event: SyntheticEvent<HTMLAnchorElement>) => {\nevent.preventDefault();\nthis.send();\n}\nsend() {\n- const text = this.state.messageText.trim();\n+ const text = this.props.chatInputState.draft.trim();\nif (text) {\n// TODO we should make the send button appear dynamically\n// iff trimmed text is nonempty, just like native\nthis.dispatchTextMessageAction(text);\n}\n- const { pendingUploads } = this.state;\n+ const { pendingUploads } = this.props.chatInputState;\nif (pendingUploads.length > 0) {\nthis.dispatchMultimediaMessageAction(pendingUploads);\n}\n}\ndispatchTextMessageAction(text: string) {\n- this.updateText(\"\");\n+ this.props.chatInputState.setDraft(\"\");\nconst localID = `local${this.props.nextLocalID}`;\nconst creatorID = this.props.viewerID;\n@@ -316,39 +332,14 @@ class ChatInputBar extends React.PureComponent<Props, State> {\n}\n}\n- onMultimediaFileChange = async (event: SyntheticInputEvent<HTMLInputElement>) => {\n- const validationResult = await Promise.all(\n- [...event.target.files].map(validateFile)\n- );\n- const validatedFileInfo = validationResult.filter(Boolean);\n- const pendingUploads = validatedFileInfo.map(({ file, mediaType }) => ({\n- file,\n- mediaType,\n- uri: URL.createObjectURL(file),\n- }));\n- this.setState(prevState => ({\n- pendingUploads: [ ...prevState.pendingUploads, ...pendingUploads ],\n- }));\n- }\n-\n- removePendingUpload = (pendingUpload: PendingMultimediaUpload) => {\n- if (this.multimediaInput) {\n- this.multimediaInput.value = \"\";\n- }\n- this.setState(prevState => ({\n- pendingUploads: prevState.pendingUploads.filter(\n- candidate => candidate !== pendingUpload,\n- ),\n- }));\n+ onMultimediaFileChange = (event: SyntheticInputEvent<HTMLInputElement>) => {\n+ this.props.chatInputState.appendFiles([...event.target.files]);\n}\ndispatchMultimediaMessageAction(\npendingUploads: $ReadOnlyArray<PendingMultimediaUpload>,\n) {\n- this.setState({ pendingUploads: [] });\n- if (this.multimediaInput) {\n- this.multimediaInput.value = \"\";\n- }\n+ this.props.chatInputState.clearPendingUploads();\nconst localID = `local${this.props.nextLocalID}`;\nconst creatorID = this.props.viewerID;\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "web/chat/chat-input-state-container.react.js",
"diff": "+// @flow\n+\n+import type { AppState } from '../redux-setup';\n+import type { PendingMultimediaUpload } from 'lib/types/media-types';\n+\n+import * as React from 'react';\n+import PropTypes from 'prop-types';\n+import { createSelector } from 'reselect';\n+import _memoize from 'lodash/memoize';\n+\n+import { connect } from 'lib/utils/redux-utils';\n+\n+import ChatMessageList from './chat-message-list.react';\n+import { validateFile } from '../utils/media-utils';\n+\n+type Props = {|\n+ // Redux state\n+ activeChatThreadID: ?string,\n+|};\n+type State = {|\n+ pendingUploads: {[threadID: string]: $ReadOnlyArray<PendingMultimediaUpload>},\n+ drafts: {[threadID: string]: string},\n+|};\n+class ChatInputStateContainer extends React.PureComponent<Props, State> {\n+\n+ static propTypes = {\n+ activeChatThreadID: PropTypes.string,\n+ };\n+ state = {\n+ pendingUploads: {},\n+ drafts: {},\n+ };\n+\n+ chatInputStateSelector = _memoize((threadID: string) => createSelector(\n+ (state: State) => state.pendingUploads[threadID],\n+ (state: State) => state.drafts[threadID],\n+ (\n+ pendingUploads: ?$ReadOnlyArray<PendingMultimediaUpload>,\n+ draft: ?string,\n+ ) => ({\n+ pendingUploads: pendingUploads ? pendingUploads : [],\n+ draft: draft ? draft : \"\",\n+ appendFiles: (files: $ReadOnlyArray<File>) =>\n+ this.appendFiles(threadID, files),\n+ removePendingUpload: (pendingUpload: PendingMultimediaUpload) =>\n+ this.removePendingUpload(threadID, pendingUpload),\n+ clearPendingUploads: () => this.clearPendingUploads(threadID),\n+ setDraft: (draft: string) => this.setDraft(threadID, draft),\n+ }),\n+ ));\n+\n+ async appendFiles(threadID: string, files: $ReadOnlyArray<File>) {\n+ const validationResult = await Promise.all(files.map(validateFile));\n+ const validatedFileInfo = validationResult.filter(Boolean);\n+ if (validatedFileInfo.length === 0) {\n+ return;\n+ }\n+ const newUploads = validatedFileInfo.map(({ file, mediaType }) => ({\n+ file,\n+ mediaType,\n+ uri: URL.createObjectURL(file),\n+ }));\n+ this.setState(prevState => {\n+ const prevUploads = prevState.pendingUploads[threadID];\n+ const mergedUploads = prevUploads\n+ ? [ ...prevUploads, ...newUploads ]\n+ : newUploads;\n+ return {\n+ pendingUploads: {\n+ ...prevState.pendingUploads,\n+ [threadID]: mergedUploads,\n+ },\n+ };\n+ });\n+ }\n+\n+ removePendingUpload(\n+ threadID: string,\n+ pendingUpload: PendingMultimediaUpload,\n+ ) {\n+ this.setState(prevState => {\n+ const currentPendingUploads = prevState.pendingUploads[threadID];\n+ if (!currentPendingUploads) {\n+ return {};\n+ }\n+ const newPendingUploads = currentPendingUploads.filter(\n+ candidate => candidate !== pendingUpload,\n+ );\n+ if (newPendingUploads.length === currentPendingUploads.length) {\n+ return {};\n+ }\n+ return {\n+ pendingUploads: {\n+ ...prevState.pendingUploads,\n+ [threadID]: newPendingUploads,\n+ },\n+ };\n+ });\n+ }\n+\n+ clearPendingUploads(threadID: string) {\n+ this.setState(prevState => {\n+ if (prevState.pendingUploads[threadID].length === 0) {\n+ return {};\n+ }\n+ return {\n+ pendingUploads: {\n+ ...prevState.pendingUploads,\n+ [threadID]: [],\n+ },\n+ };\n+ });\n+ }\n+\n+ setDraft(threadID: string, draft: string) {\n+ this.setState(prevState => ({\n+ drafts: {\n+ ...prevState.drafts,\n+ [threadID]: draft,\n+ },\n+ }));\n+ }\n+\n+ render() {\n+ const { activeChatThreadID } = this.props;\n+ const chatInputState = activeChatThreadID\n+ ? this.chatInputStateSelector(activeChatThreadID)(this.state)\n+ : null;\n+ return (\n+ <ChatMessageList\n+ activeChatThreadID={activeChatThreadID}\n+ chatInputState={chatInputState}\n+ />\n+ );\n+ }\n+\n+}\n+\n+export default connect((state: AppState) => ({\n+ activeChatThreadID: state.navInfo.activeChatThreadID,\n+}))(ChatInputStateContainer);\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "web/chat/chat-input-state.js",
"diff": "+// @flow\n+\n+import {\n+ type PendingMultimediaUpload,\n+ pendingMultimediaUploadPropType,\n+} from 'lib/types/media-types';\n+\n+import PropTypes from 'prop-types';\n+\n+export type ChatInputState = {|\n+ pendingUploads: $ReadOnlyArray<PendingMultimediaUpload>,\n+ draft: string,\n+ appendFiles: (files: $ReadOnlyArray<File>) => Promise<void>,\n+ removePendingUpload: (pendingUpload: PendingMultimediaUpload) => void,\n+ clearPendingUploads: () => void,\n+ setDraft: (draft: string) => void,\n+|};\n+export const chatInputStatePropType = PropTypes.shape({\n+ pendingUploads: PropTypes.arrayOf(pendingMultimediaUploadPropType).isRequired,\n+ draft: PropTypes.string.isRequired,\n+ appendFiles: PropTypes.func.isRequired,\n+ removePendingUpload: PropTypes.func.isRequired,\n+ clearPendingUploads: PropTypes.func.isRequired,\n+ setDraft: PropTypes.func.isRequired,\n+});\n"
},
{
"change_type": "MODIFY",
"old_path": "web/chat/chat-message-list.react.js",
"new_path": "web/chat/chat-message-list.react.js",
"diff": "@@ -8,6 +8,10 @@ import {\nimport { type ThreadInfo, threadInfoPropType } from 'lib/types/thread-types';\nimport type { DispatchActionPromise } from 'lib/utils/action-utils';\nimport type { FetchMessageInfosPayload } from 'lib/types/message-types';\n+import {\n+ chatInputStatePropType,\n+ type ChatInputState,\n+} from './chat-input-state';\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\n@@ -33,8 +37,9 @@ import LoadingIndicator from '../loading-indicator.react';\nimport css from './chat-message-list.css';\ntype Props = {|\n- // Redux state\nactiveChatThreadID: ?string,\n+ chatInputState: ?ChatInputState,\n+ // Redux state\nthreadInfo: ?ThreadInfo,\nmessageListData: ?$ReadOnlyArray<ChatMessageItem>,\nstartReached: bool,\n@@ -56,6 +61,7 @@ class ChatMessageList extends React.PureComponent<Props, State> {\nstatic propTypes = {\nactiveChatThreadID: PropTypes.string,\n+ chatInputState: chatInputStatePropType,\nthreadInfo: threadInfoPropType,\nmessageListData: PropTypes.arrayOf(chatMessageItemPropType),\nstartReached: PropTypes.bool.isRequired,\n@@ -157,18 +163,22 @@ class ChatMessageList extends React.PureComponent<Props, State> {\n}\nrender() {\n- if (!this.props.messageListData) {\n+ const { messageListData, threadInfo, chatInputState } = this.props;\n+ if (!messageListData) {\nreturn <div className={css.container} />;\n}\n- const messages = this.props.messageListData.map(this.renderItem);\n- const threadInfo = this.props.threadInfo;\n+ const messages = messageListData.map(this.renderItem);\ninvariant(threadInfo, \"ThreadInfo should be set if messageListData is\");\n+ invariant(chatInputState, \"ChatInputState should be set\");\nreturn (\n<div className={css.container}>\n<div className={css.messageContainer} ref={this.messageContainerRef}>\n{messages}\n</div>\n- <ChatInputBar threadInfo={threadInfo} />\n+ <ChatInputBar\n+ threadInfo={threadInfo}\n+ chatInputState={chatInputState}\n+ />\n</div>\n);\n}\n@@ -223,10 +233,9 @@ registerFetchKey(fetchMessagesBeforeCursorActionTypes);\nregisterFetchKey(fetchMostRecentMessagesActionTypes);\nexport default connect(\n- (state: AppState) => {\n- const activeChatThreadID = state.navInfo.activeChatThreadID;\n+ (state: AppState, ownProps: { activeChatThreadID: ?string }) => {\n+ const { activeChatThreadID } = ownProps;\nreturn {\n- activeChatThreadID,\nthreadInfo: activeChatThreadID\n? threadInfoSelector(state)[activeChatThreadID]\n: null,\n"
},
{
"change_type": "MODIFY",
"old_path": "web/chat/chat.react.js",
"new_path": "web/chat/chat.react.js",
"diff": "import * as React from 'react';\nimport ChatThreadList from './chat-thread-list.react';\n-import ChatMessageList from './chat-message-list.react';\n+import ChatInputStateContainer from './chat-input-state-container.react';\ntype Props = {|\n|};\n@@ -13,7 +13,7 @@ class Chat extends React.PureComponent<Props> {\nreturn (\n<React.Fragment>\n<ChatThreadList />\n- <ChatMessageList />\n+ <ChatInputStateContainer />\n</React.Fragment>\n);\n}\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [web] Lift ChatInputState
This allows us to persist drafts of messages on a per-thread basis |
129,187 | 21.12.2018 17:31:51 | 18,000 | 9d5a7a6f0e913ba029626943ae6f4b2d98d4d0e0 | [web] Define height relative to main content | [
{
"change_type": "MODIFY",
"old_path": "web/chat/chat-message-list.css",
"new_path": "web/chat/chat-message-list.css",
"diff": "div.container {\nmargin-left: 400px;\n- height: calc(100% - 62px);\n+ height: 100%;\nbackground-color: white;\ndisplay: flex;\nflex-direction: column;\n"
},
{
"change_type": "MODIFY",
"old_path": "web/style.css",
"new_path": "web/style.css",
"diff": "@@ -107,11 +107,12 @@ div.chatBadge {\ndiv.main-content-container {\nmargin-top: 62px;\n- min-height: calc(100% - 62px);\n+ height: calc(100% - 62px);\n+ position: relative;\n}\ndiv.main-content {\nbackground-color: #FFFFFFD5;\n- min-height: calc(100% - 62px);\n+ min-height: 100%;\noverflow-x: hidden;\n}\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [web] Define height relative to main content |
129,187 | 21.12.2018 17:36:51 | 18,000 | 60a1ae6e515b45197f3cb5e230c3333da5162fe3 | [web] Drag 'n' drop support for multimedia uploads | [
{
"change_type": "MODIFY",
"old_path": "web/chat/chat-message-list.css",
"new_path": "web/chat/chat-message-list.css",
"diff": "@@ -4,6 +4,11 @@ div.container {\nbackground-color: white;\ndisplay: flex;\nflex-direction: column;\n+ box-sizing: border-box;\n+}\n+div.activeContainer {\n+ border: 2px solid #5989D6;\n+ margin-left: 402px;\n}\ndiv.messageContainer {\nflex-grow: 1;\n"
},
{
"change_type": "MODIFY",
"old_path": "web/chat/chat-message-list.react.js",
"new_path": "web/chat/chat-message-list.react.js",
"diff": "@@ -16,6 +16,14 @@ import {\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport invariant from 'invariant';\n+import {\n+ DropTarget,\n+ DropTargetMonitor,\n+ ConnectDropTarget,\n+ DropTargetConnector,\n+} from 'react-dnd';\n+import { NativeTypes } from 'react-dnd-html5-backend';\n+import classNames from 'classnames';\nimport { connect } from 'lib/utils/redux-utils';\nimport { messageKey } from 'lib/shared/message-utils';\n@@ -36,7 +44,7 @@ import Message from './message.react';\nimport LoadingIndicator from '../loading-indicator.react';\nimport css from './chat-message-list.css';\n-type Props = {|\n+type PassedProps = {|\nactiveChatThreadID: ?string,\nchatInputState: ?ChatInputState,\n// Redux state\n@@ -54,6 +62,15 @@ type Props = {|\nthreadID: string,\n) => Promise<FetchMessageInfosPayload>,\n|};\n+type ReactDnDProps = {|\n+ isActive: bool,\n+ connectDropTarget: ConnectDropTarget,\n+|};\n+\n+type Props = {|\n+ ...PassedProps,\n+ ...ReactDnDProps,\n+|};\ntype State = {|\nfocusedMessageKey: ?string,\n|};\n@@ -163,15 +180,25 @@ class ChatMessageList extends React.PureComponent<Props, State> {\n}\nrender() {\n- const { messageListData, threadInfo, chatInputState } = this.props;\n+ const {\n+ messageListData,\n+ threadInfo,\n+ chatInputState,\n+ connectDropTarget,\n+ isActive,\n+ } = this.props;\nif (!messageListData) {\nreturn <div className={css.container} />;\n}\nconst messages = messageListData.map(this.renderItem);\ninvariant(threadInfo, \"ThreadInfo should be set if messageListData is\");\ninvariant(chatInputState, \"ChatInputState should be set\");\n- return (\n- <div className={css.container}>\n+ const containerStyle = classNames({\n+ [css.container]: true,\n+ [css.activeContainer]: isActive,\n+ });\n+ return connectDropTarget(\n+ <div className={containerStyle}>\n<div className={css.messageContainer} ref={this.messageContainerRef}>\n{messages}\n</div>\n@@ -179,7 +206,7 @@ class ChatMessageList extends React.PureComponent<Props, State> {\nthreadInfo={threadInfo}\nchatInputState={chatInputState}\n/>\n- </div>\n+ </div>,\n);\n}\n@@ -232,7 +259,7 @@ class ChatMessageList extends React.PureComponent<Props, State> {\nregisterFetchKey(fetchMessagesBeforeCursorActionTypes);\nregisterFetchKey(fetchMostRecentMessagesActionTypes);\n-export default connect(\n+const ReduxConnectedChatMessageList = connect(\n(state: AppState, ownProps: { activeChatThreadID: ?string }) => {\nconst { activeChatThreadID } = ownProps;\nreturn {\n@@ -246,3 +273,19 @@ export default connect(\n},\n{ fetchMessagesBeforeCursor, fetchMostRecentMessages },\n)(ChatMessageList);\n+\n+export default DropTarget(\n+ NativeTypes.FILE,\n+ {\n+ drop: (props: PassedProps, monitor: DropTargetMonitor) => {\n+ const { files } = monitor.getItem();\n+ if (props.chatInputState && files.length > 0) {\n+ props.chatInputState.appendFiles(files);\n+ }\n+ },\n+ },\n+ (connect: DropTargetConnector, monitor: DropTargetMonitor) => ({\n+ connectDropTarget: connect.dropTarget(),\n+ isActive: monitor.isOver() && monitor.canDrop(),\n+ }),\n+)(ReduxConnectedChatMessageList);\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "web/flow-typed/npm/react-dnd-html5-backend_vx.x.x.js",
"diff": "+// flow-typed signature: 3a65c86a3aa91668377c3aebf103505d\n+// flow-typed version: <<STUB>>/react-dnd-html5-backend_v^7.0.2/flow_v0.78.0\n+\n+/**\n+ * This is an autogenerated libdef stub for:\n+ *\n+ * 'react-dnd-html5-backend'\n+ *\n+ * Fill this stub out by replacing all the `any` types.\n+ *\n+ * Once filled out, we encourage you to share your work with the\n+ * community by sending a pull request to:\n+ * https://github.com/flowtype/flow-typed\n+ */\n+\n+declare module 'react-dnd-html5-backend' {\n+ declare module.exports: any;\n+}\n+\n+/**\n+ * We include stubs for each file inside this npm package in case you need to\n+ * require those files directly. Feel free to delete any files that aren't\n+ * needed.\n+ */\n+declare module 'react-dnd-html5-backend/dist/ReactDnDHTML5Backend' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'react-dnd-html5-backend/dist/ReactDnDHTML5Backend.min' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'react-dnd-html5-backend/lib/BrowserDetector' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'react-dnd-html5-backend/lib/EnterLeaveCounter' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'react-dnd-html5-backend/lib/getEmptyImage' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'react-dnd-html5-backend/lib/HTML5Backend' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'react-dnd-html5-backend/lib/index' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'react-dnd-html5-backend/lib/interfaces' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'react-dnd-html5-backend/lib/MonotonicInterpolant' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'react-dnd-html5-backend/lib/NativeDragSources' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'react-dnd-html5-backend/lib/NativeTypes' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'react-dnd-html5-backend/lib/OffsetUtils' {\n+ declare module.exports: any;\n+}\n+\n+// Filename aliases\n+declare module 'react-dnd-html5-backend/dist/ReactDnDHTML5Backend.js' {\n+ declare module.exports: $Exports<'react-dnd-html5-backend/dist/ReactDnDHTML5Backend'>;\n+}\n+declare module 'react-dnd-html5-backend/dist/ReactDnDHTML5Backend.min.js' {\n+ declare module.exports: $Exports<'react-dnd-html5-backend/dist/ReactDnDHTML5Backend.min'>;\n+}\n+declare module 'react-dnd-html5-backend/lib/BrowserDetector.js' {\n+ declare module.exports: $Exports<'react-dnd-html5-backend/lib/BrowserDetector'>;\n+}\n+declare module 'react-dnd-html5-backend/lib/EnterLeaveCounter.js' {\n+ declare module.exports: $Exports<'react-dnd-html5-backend/lib/EnterLeaveCounter'>;\n+}\n+declare module 'react-dnd-html5-backend/lib/getEmptyImage.js' {\n+ declare module.exports: $Exports<'react-dnd-html5-backend/lib/getEmptyImage'>;\n+}\n+declare module 'react-dnd-html5-backend/lib/HTML5Backend.js' {\n+ declare module.exports: $Exports<'react-dnd-html5-backend/lib/HTML5Backend'>;\n+}\n+declare module 'react-dnd-html5-backend/lib/index.js' {\n+ declare module.exports: $Exports<'react-dnd-html5-backend/lib/index'>;\n+}\n+declare module 'react-dnd-html5-backend/lib/interfaces.js' {\n+ declare module.exports: $Exports<'react-dnd-html5-backend/lib/interfaces'>;\n+}\n+declare module 'react-dnd-html5-backend/lib/MonotonicInterpolant.js' {\n+ declare module.exports: $Exports<'react-dnd-html5-backend/lib/MonotonicInterpolant'>;\n+}\n+declare module 'react-dnd-html5-backend/lib/NativeDragSources.js' {\n+ declare module.exports: $Exports<'react-dnd-html5-backend/lib/NativeDragSources'>;\n+}\n+declare module 'react-dnd-html5-backend/lib/NativeTypes.js' {\n+ declare module.exports: $Exports<'react-dnd-html5-backend/lib/NativeTypes'>;\n+}\n+declare module 'react-dnd-html5-backend/lib/OffsetUtils.js' {\n+ declare module.exports: $Exports<'react-dnd-html5-backend/lib/OffsetUtils'>;\n+}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "web/flow-typed/npm/react-dnd_vx.x.x.js",
"diff": "+// flow-typed signature: ad591b923c6bc2a7450989be2b5d7053\n+// flow-typed version: <<STUB>>/react-dnd_v^7.0.2/flow_v0.78.0\n+\n+/**\n+ * This is an autogenerated libdef stub for:\n+ *\n+ * 'react-dnd'\n+ *\n+ * Fill this stub out by replacing all the `any` types.\n+ *\n+ * Once filled out, we encourage you to share your work with the\n+ * community by sending a pull request to:\n+ * https://github.com/flowtype/flow-typed\n+ */\n+\n+declare module 'react-dnd' {\n+ declare module.exports: any;\n+}\n+\n+/**\n+ * We include stubs for each file inside this npm package in case you need to\n+ * require those files directly. Feel free to delete any files that aren't\n+ * needed.\n+ */\n+declare module 'react-dnd/dist/ReactDnD' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'react-dnd/dist/ReactDnD.min' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'react-dnd/lib/createSourceConnector' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'react-dnd/lib/createSourceFactory' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'react-dnd/lib/createSourceMonitor' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'react-dnd/lib/createTargetConnector' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'react-dnd/lib/createTargetFactory' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'react-dnd/lib/createTargetMonitor' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'react-dnd/lib/decorateHandler' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'react-dnd/lib/DragDropContext' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'react-dnd/lib/DragLayer' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'react-dnd/lib/DragSource' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'react-dnd/lib/DropTarget' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'react-dnd/lib/index' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'react-dnd/lib/interfaces' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'react-dnd/lib/registerSource' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'react-dnd/lib/registerTarget' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'react-dnd/lib/utils/checkDecoratorArguments' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'react-dnd/lib/utils/cloneWithRef' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'react-dnd/lib/utils/disposables/CompositeDisposable' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'react-dnd/lib/utils/disposables/Disposable' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'react-dnd/lib/utils/disposables/index' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'react-dnd/lib/utils/disposables/SerialDisposable' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'react-dnd/lib/utils/isValidType' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'react-dnd/lib/wrapConnectorHooks' {\n+ declare module.exports: any;\n+}\n+\n+// Filename aliases\n+declare module 'react-dnd/dist/ReactDnD.js' {\n+ declare module.exports: $Exports<'react-dnd/dist/ReactDnD'>;\n+}\n+declare module 'react-dnd/dist/ReactDnD.min.js' {\n+ declare module.exports: $Exports<'react-dnd/dist/ReactDnD.min'>;\n+}\n+declare module 'react-dnd/lib/createSourceConnector.js' {\n+ declare module.exports: $Exports<'react-dnd/lib/createSourceConnector'>;\n+}\n+declare module 'react-dnd/lib/createSourceFactory.js' {\n+ declare module.exports: $Exports<'react-dnd/lib/createSourceFactory'>;\n+}\n+declare module 'react-dnd/lib/createSourceMonitor.js' {\n+ declare module.exports: $Exports<'react-dnd/lib/createSourceMonitor'>;\n+}\n+declare module 'react-dnd/lib/createTargetConnector.js' {\n+ declare module.exports: $Exports<'react-dnd/lib/createTargetConnector'>;\n+}\n+declare module 'react-dnd/lib/createTargetFactory.js' {\n+ declare module.exports: $Exports<'react-dnd/lib/createTargetFactory'>;\n+}\n+declare module 'react-dnd/lib/createTargetMonitor.js' {\n+ declare module.exports: $Exports<'react-dnd/lib/createTargetMonitor'>;\n+}\n+declare module 'react-dnd/lib/decorateHandler.js' {\n+ declare module.exports: $Exports<'react-dnd/lib/decorateHandler'>;\n+}\n+declare module 'react-dnd/lib/DragDropContext.js' {\n+ declare module.exports: $Exports<'react-dnd/lib/DragDropContext'>;\n+}\n+declare module 'react-dnd/lib/DragLayer.js' {\n+ declare module.exports: $Exports<'react-dnd/lib/DragLayer'>;\n+}\n+declare module 'react-dnd/lib/DragSource.js' {\n+ declare module.exports: $Exports<'react-dnd/lib/DragSource'>;\n+}\n+declare module 'react-dnd/lib/DropTarget.js' {\n+ declare module.exports: $Exports<'react-dnd/lib/DropTarget'>;\n+}\n+declare module 'react-dnd/lib/index.js' {\n+ declare module.exports: $Exports<'react-dnd/lib/index'>;\n+}\n+declare module 'react-dnd/lib/interfaces.js' {\n+ declare module.exports: $Exports<'react-dnd/lib/interfaces'>;\n+}\n+declare module 'react-dnd/lib/registerSource.js' {\n+ declare module.exports: $Exports<'react-dnd/lib/registerSource'>;\n+}\n+declare module 'react-dnd/lib/registerTarget.js' {\n+ declare module.exports: $Exports<'react-dnd/lib/registerTarget'>;\n+}\n+declare module 'react-dnd/lib/utils/checkDecoratorArguments.js' {\n+ declare module.exports: $Exports<'react-dnd/lib/utils/checkDecoratorArguments'>;\n+}\n+declare module 'react-dnd/lib/utils/cloneWithRef.js' {\n+ declare module.exports: $Exports<'react-dnd/lib/utils/cloneWithRef'>;\n+}\n+declare module 'react-dnd/lib/utils/disposables/CompositeDisposable.js' {\n+ declare module.exports: $Exports<'react-dnd/lib/utils/disposables/CompositeDisposable'>;\n+}\n+declare module 'react-dnd/lib/utils/disposables/Disposable.js' {\n+ declare module.exports: $Exports<'react-dnd/lib/utils/disposables/Disposable'>;\n+}\n+declare module 'react-dnd/lib/utils/disposables/index.js' {\n+ declare module.exports: $Exports<'react-dnd/lib/utils/disposables/index'>;\n+}\n+declare module 'react-dnd/lib/utils/disposables/SerialDisposable.js' {\n+ declare module.exports: $Exports<'react-dnd/lib/utils/disposables/SerialDisposable'>;\n+}\n+declare module 'react-dnd/lib/utils/isValidType.js' {\n+ declare module.exports: $Exports<'react-dnd/lib/utils/isValidType'>;\n+}\n+declare module 'react-dnd/lib/wrapConnectorHooks.js' {\n+ declare module.exports: $Exports<'react-dnd/lib/wrapConnectorHooks'>;\n+}\n"
},
{
"change_type": "MODIFY",
"old_path": "web/package.json",
"new_path": "web/package.json",
"diff": "\"prop-types\": \"^15.6.0\",\n\"react\": \"^16.2.0\",\n\"react-color\": \"^2.13.0\",\n+ \"react-dnd\": \"^7.0.2\",\n+ \"react-dnd-html5-backend\": \"^7.0.2\",\n\"react-dom\": \"^16.2.0\",\n\"react-feather\": \"^1.1.4\",\n\"react-hot-loader\": \"^4.2.0\",\n"
},
{
"change_type": "MODIFY",
"old_path": "web/root.js",
"new_path": "web/root.js",
"diff": "@@ -12,6 +12,8 @@ import thunk from 'redux-thunk';\nimport {\ncomposeWithDevTools,\n} from 'redux-devtools-extension/logOnlyInProduction';\n+import HTML5Backend from 'react-dnd-html5-backend';\n+import { DragDropContext } from 'react-dnd';\nimport { reduxLoggerMiddleware } from 'lib/utils/redux-logger';\n@@ -30,14 +32,19 @@ const store: Store<AppState, Action> = createStore(\n);\nconst RootRouter = () => (\n- <React.Fragment>\n<Router history={history.getHistoryObject()}>\n<Route path=\"*\" component={App} />\n</Router>\n+);\n+const ReactDnDConnectedRootRouter = DragDropContext(HTML5Backend)(RootRouter);\n+\n+const RootComponent = () => (\n+ <React.Fragment>\n+ <ReactDnDConnectedRootRouter />\n<Socket />\n</React.Fragment>\n);\n-const RootHMR = hot(module)(RootRouter);\n+const RootHMR = hot(module)(RootComponent);\nconst RootProvider = () => (\n<Provider store={store}>\n"
},
{
"change_type": "MODIFY",
"old_path": "web/style.css",
"new_path": "web/style.css",
"diff": "@@ -86,7 +86,7 @@ ul.nav-bar > li.current-tab > div > a {\n}\nul.nav-bar > li.current-tab > div {\nbackground-color: #FFFFFFD5;\n- padding: 18px 20px 20px 20px;\n+ padding: 18px 20px 19px 20px;\n}\nsvg.nav-bar-icon {\npadding-right: 8px;\n"
},
{
"change_type": "MODIFY",
"old_path": "yarn.lock",
"new_path": "yarn.lock",
"diff": "@@ -1345,7 +1345,7 @@ art@^0.10.0:\nresolved \"https://registry.yarnpkg.com/art/-/art-0.10.3.tgz#b01d84a968ccce6208df55a733838c96caeeaea2\"\nintegrity sha512-HXwbdofRTiJT6qZX/FnchtldzJjS3vkLJxQilc3Xj+ma2MXjY4UAyQ0ls1XZYVnDvVIBiFZbC6QsvtW86TD6tQ==\n-asap@~2.0.3, asap@~2.0.6:\n+asap@^2.0.6, asap@~2.0.3, asap@~2.0.6:\nversion \"2.0.6\"\nresolved \"https://registry.yarnpkg.com/asap/-/asap-2.0.6.tgz#e50347611d7e690943208bbdafebcbc2fb866d46\"\nintegrity sha1-5QNHYR1+aQlDIIu9r+vLwvuGbUY=\n@@ -2743,6 +2743,11 @@ chalk@^2.0.0, chalk@^2.0.1, chalk@^2.1.0, chalk@^2.3.1, chalk@^2.4.1:\nescape-string-regexp \"^1.0.5\"\nsupports-color \"^5.3.0\"\n+change-emitter@^0.1.2:\n+ version \"0.1.6\"\n+ resolved \"https://registry.yarnpkg.com/change-emitter/-/change-emitter-0.1.6.tgz#e8b2fe3d7f1ab7d69a32199aff91ea6931409515\"\n+ integrity sha1-6LL+PX8at9aaMhma/5HqaTFAlRU=\n+\nchardet@^0.4.0:\nversion \"0.4.2\"\nresolved \"https://registry.yarnpkg.com/chardet/-/chardet-0.4.2.tgz#b5473b33dc97c424e5d98dc87d55d4d8a29c8bf2\"\n@@ -3678,6 +3683,16 @@ dir-glob@^2.0.0:\narrify \"^1.0.1\"\npath-type \"^3.0.0\"\n+dnd-core@^7.0.2:\n+ version \"7.0.2\"\n+ resolved \"https://registry.yarnpkg.com/dnd-core/-/dnd-core-7.0.2.tgz#6c080eb57243fa0372fd083b3db242d9eb525010\"\n+ integrity sha512-InwRBi6zTndtE3+3nTYpLJkYMEr7utSR7OziAoSFhtQsbUfJE1KeqxM+ZFRIMKn6ehxUTAC+QU6QC7IG9u86Mg==\n+ dependencies:\n+ asap \"^2.0.6\"\n+ invariant \"^2.2.4\"\n+ lodash \"^4.17.11\"\n+ redux \"^4.0.1\"\n+\ndns-equal@^1.0.0:\nversion \"1.0.0\"\nresolved \"https://registry.yarnpkg.com/dns-equal/-/dns-equal-1.0.0.tgz#b39e7f1da6eb0a75ba9c17324b34753c47e0654d\"\n@@ -4451,7 +4466,7 @@ fbjs-scripts@^1.0.0:\nsemver \"^5.1.0\"\nthrough2 \"^2.0.0\"\n-fbjs@^0.8.0, fbjs@^0.8.9:\n+fbjs@^0.8.0, fbjs@^0.8.1, fbjs@^0.8.9:\nversion \"0.8.17\"\nresolved \"https://registry.yarnpkg.com/fbjs/-/fbjs-0.8.17.tgz#c4d598ead6949112653d6588b01a5cdcd9f90fdd\"\nintegrity sha1-xNWY6taUkRJlPWWIsBpc3Nn5D90=\n@@ -5567,7 +5582,7 @@ interpret@^1.0.0:\nresolved \"https://registry.yarnpkg.com/interpret/-/interpret-1.1.0.tgz#7ed1b1410c6a0e0f78cf95d3b8440c63f78b8614\"\nintegrity sha1-ftGxQQxqDg94z5XTuEQMY/eLhhQ=\n-invariant@^2.2.1, invariant@^2.2.2, invariant@^2.2.4:\n+invariant@^2.1.0, invariant@^2.2.1, invariant@^2.2.2, invariant@^2.2.4:\nversion \"2.2.4\"\nresolved \"https://registry.yarnpkg.com/invariant/-/invariant-2.2.4.tgz#610f3c92c9359ce1db616e538008d23ff35158e6\"\nintegrity sha512-phJfQVBuaJM5raOpJjSfkiD6BpbCE4Ns//LaXl6wGYtUBY83nWS6Rf9tXm2e8VaK60JEjYldbPif/A2B1C2gNA==\n@@ -6898,7 +6913,7 @@ lodash@^3.2.0:\nresolved \"https://registry.yarnpkg.com/lodash/-/lodash-3.10.1.tgz#5bf45e8e49ba4189e17d482789dfd15bd140b7b6\"\nintegrity sha1-W/Rejkm6QYnhfUgnid/RW9FAt7Y=\n-lodash@^4.0.0, lodash@^4.0.1, lodash@^4.13.1, lodash@^4.17.10, lodash@^4.17.2, lodash@^4.17.4, lodash@^4.17.5, lodash@^4.2.1, lodash@^4.3.0, lodash@^4.5.1, lodash@^4.6.1:\n+lodash@^4.0.0, lodash@^4.0.1, lodash@^4.13.1, lodash@^4.17.10, lodash@^4.17.11, lodash@^4.17.2, lodash@^4.17.4, lodash@^4.17.5, lodash@^4.2.1, lodash@^4.3.0, lodash@^4.5.1, lodash@^4.6.1:\nversion \"4.17.11\"\nresolved \"https://registry.yarnpkg.com/lodash/-/lodash-4.17.11.tgz#b39ea6229ef607ecd89e2c8df12536891cac9b8d\"\nintegrity sha512-cQKh8igo5QUhZ7lg38DYWAxMvjSAKG0A8wGSVimP07SIUEK2UO+arSRKbRZWtelMtN5V0Hkwh5ryOto/SshYIg==\n@@ -6940,7 +6955,7 @@ longest@^1.0.1:\nresolved \"https://registry.yarnpkg.com/longest/-/longest-1.0.1.tgz#30a0b2da38f73770e8294a0d22e6625ed77d0097\"\nintegrity sha1-MKCy2jj3N3DoKUoNIuZiXtd9AJc=\n-loose-envify@^1.0.0, loose-envify@^1.1.0, loose-envify@^1.2.0, loose-envify@^1.3.1:\n+loose-envify@^1.0.0, loose-envify@^1.1.0, loose-envify@^1.2.0, loose-envify@^1.3.1, loose-envify@^1.4.0:\nversion \"1.4.0\"\nresolved \"https://registry.yarnpkg.com/loose-envify/-/loose-envify-1.4.0.tgz#71ee51fa7be4caec1a63839f7e682d8132d30caf\"\nintegrity sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==\n@@ -9232,6 +9247,26 @@ react-devtools@^3.0.0:\nreact-devtools-core \"^3.4.1\"\nupdate-notifier \"^2.1.0\"\n+react-dnd-html5-backend@^7.0.2:\n+ version \"7.0.2\"\n+ resolved \"https://registry.yarnpkg.com/react-dnd-html5-backend/-/react-dnd-html5-backend-7.0.2.tgz#f74181ca0ff05be13eb6094629c5ad560f558a7e\"\n+ integrity sha512-BPhmHeQjvhPXRykHvFLbM+TJFrrarcuf/mIArNEmXzZuNhLfbOnHtMSzR8lPwodABcDAYj7hEF7vTABXX298vA==\n+ dependencies:\n+ dnd-core \"^7.0.2\"\n+ lodash \"^4.17.11\"\n+\n+react-dnd@^7.0.2:\n+ version \"7.0.2\"\n+ resolved \"https://registry.yarnpkg.com/react-dnd/-/react-dnd-7.0.2.tgz#8f5611a6e877592932c082d6280c64d1c817f420\"\n+ integrity sha512-nJnHJo/tNQjyod234+hPNopWHPvgH0gujf3pcdJWRe3l0GL+jSXXwXJ2SFwIHkVmxPYrx8+gbKU3+Pq26p6fkg==\n+ dependencies:\n+ dnd-core \"^7.0.2\"\n+ hoist-non-react-statics \"^3.1.0\"\n+ invariant \"^2.1.0\"\n+ lodash \"^4.17.11\"\n+ recompose \"^0.30.0\"\n+ shallowequal \"^1.1.0\"\n+\nreact-dom@^16.2.0:\nversion \"16.6.0\"\nresolved \"https://registry.yarnpkg.com/react-dom/-/react-dom-16.6.0.tgz#6375b8391e019a632a89a0988bce85f0cc87a92f\"\n@@ -9287,7 +9322,7 @@ react-is@^16.6.1:\nresolved \"https://registry.yarnpkg.com/react-is/-/react-is-16.6.3.tgz#d2d7462fcfcbe6ec0da56ad69047e47e56e7eac0\"\nintegrity sha512-u7FDWtthB4rWibG/+mFbVd5FvdI20yde86qKGx4lVUTWmPlSWQ4QxbBIrrs+HnXGbxOUlUzTAP/VDmvCwaP2yA==\n-react-lifecycles-compat@^3.0.0, react-lifecycles-compat@^3.0.4:\n+react-lifecycles-compat@^3.0.0, react-lifecycles-compat@^3.0.2, react-lifecycles-compat@^3.0.4:\nversion \"3.0.4\"\nresolved \"https://registry.yarnpkg.com/react-lifecycles-compat/-/react-lifecycles-compat-3.0.4.tgz#4f1a273afdfc8f3488a8c516bfda78f872352362\"\nintegrity sha512-fBASbA6LnOU9dOU2eW7aQ8xmYBSXUIWr+UmF9b1efZBazGNO+rcXT/icdKnYm2pTwcRylVUYwW7H1PHfLekVzA==\n@@ -9765,6 +9800,18 @@ realpath-native@^1.0.0:\ndependencies:\nutil.promisify \"^1.0.0\"\n+recompose@^0.30.0:\n+ version \"0.30.0\"\n+ resolved \"https://registry.yarnpkg.com/recompose/-/recompose-0.30.0.tgz#82773641b3927e8c7d24a0d87d65aeeba18aabd0\"\n+ integrity sha512-ZTrzzUDa9AqUIhRk4KmVFihH0rapdCSMFXjhHbNrjAWxBuUD/guYlyysMnuHjlZC/KRiOKRtB4jf96yYSkKE8w==\n+ dependencies:\n+ \"@babel/runtime\" \"^7.0.0\"\n+ change-emitter \"^0.1.2\"\n+ fbjs \"^0.8.1\"\n+ hoist-non-react-statics \"^2.3.1\"\n+ react-lifecycles-compat \"^3.0.2\"\n+ symbol-observable \"^1.0.4\"\n+\nredbox-react@^1.3.6:\nversion \"1.6.0\"\nresolved \"https://registry.yarnpkg.com/redbox-react/-/redbox-react-1.6.0.tgz#e753ac02595bc1bf695b3935889a4f5b1b5a21a1\"\n@@ -9850,6 +9897,14 @@ redux@^3.7.1, redux@^3.7.2:\nloose-envify \"^1.1.0\"\nsymbol-observable \"^1.0.3\"\n+redux@^4.0.1:\n+ version \"4.0.1\"\n+ resolved \"https://registry.yarnpkg.com/redux/-/redux-4.0.1.tgz#436cae6cc40fbe4727689d7c8fae44808f1bfef5\"\n+ integrity sha512-R7bAtSkk7nY6O/OYMVR9RiBI+XghjF9rlbl5806HJbQph0LJVHZrU5oaO4q70eUKiqMRqm4y07KLTlMZ2BlVmg==\n+ dependencies:\n+ loose-envify \"^1.4.0\"\n+ symbol-observable \"^1.2.0\"\n+\nregenerate-unicode-properties@^7.0.0:\nversion \"7.0.0\"\nresolved \"https://registry.yarnpkg.com/regenerate-unicode-properties/-/regenerate-unicode-properties-7.0.0.tgz#107405afcc4a190ec5ed450ecaa00ed0cafa7a4c\"\n@@ -10417,7 +10472,7 @@ sha.js@^2.4.0, sha.js@^2.4.8:\ninherits \"^2.0.1\"\nsafe-buffer \"^5.0.1\"\n-shallowequal@^1.0.2:\n+shallowequal@^1.0.2, shallowequal@^1.1.0:\nversion \"1.1.0\"\nresolved \"https://registry.yarnpkg.com/shallowequal/-/shallowequal-1.1.0.tgz#188d521de95b9087404fd4dcb68b13df0ae4e7f8\"\nintegrity sha512-y0m1JoUZSlPAjXVtPPW70aZWfIL/dSP7AFkRnniLCrK/8MDKog3TySTBmckD+RObVxH0v4Tox67+F14PdED2oQ==\n@@ -11010,7 +11065,7 @@ svgo@^0.7.0:\nsax \"~1.2.1\"\nwhet.extend \"~0.9.9\"\n-symbol-observable@^1.0.3:\n+symbol-observable@^1.0.3, symbol-observable@^1.0.4, symbol-observable@^1.2.0:\nversion \"1.2.0\"\nresolved \"https://registry.yarnpkg.com/symbol-observable/-/symbol-observable-1.2.0.tgz#c22688aed4eab3cdc2dfeacbb561660560a00804\"\nintegrity sha512-e900nM8RRtGhlV36KGEU9k65K3mPb1WV70OdjfxlG2EAuM1noi/E/BaW/uMhL7bPEssK8QV57vN3esixjUvcXQ==\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [web] Drag 'n' drop support for multimedia uploads |
129,187 | 02.01.2019 18:07:01 | 18,000 | c153ad884ecf219e914d7d93c5afd83a895248d6 | [lib] Move fetchJSON timeout to timeouts.js | [
{
"change_type": "MODIFY",
"old_path": "lib/shared/timeouts.js",
"new_path": "lib/shared/timeouts.js",
"diff": "@@ -18,6 +18,10 @@ export const clientRequestVisualTimeout = 3000; // in milliseconds\n// likely on the client side.\nexport const clientRequestSocketTimeout = 5000; // in milliseconds\n+// FetchJSON will timeout a request after 10 seconds. When using sockets this is\n+// preempted by the above timeout, so it really only applies for HTTP requests.\n+export const fetchJSONTimeout = 10000; // in milliseconds\n+\n// The server expects to get a request at least every three seconds from the\n// client. If it doesn't get a request within a fifteen second window, it will\n// close the connection.\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/utils/fetch-json.js",
"new_path": "lib/utils/fetch-json.js",
"diff": "@@ -23,6 +23,7 @@ import { getConfig } from './config';\nimport sleep from './sleep';\nimport { SocketOffline, SocketTimeout } from '../socket/inflight-requests';\nimport { uploadBlob } from './upload-blob';\n+import { fetchJSONTimeout } from '../shared/timeouts';\n// You'll notice that this is not the type of the fetchJSON function below. This\n// is because the first several parameters to that functon get bound in by the\n@@ -37,7 +38,6 @@ export type FetchJSON = (\ninput: Object,\noptions?: ?FetchJSONOptions,\n) => Promise<Object>;\n-const defaultTimeout = 10000;\ntype RequestData = {|\ninput: {[key: string]: mixed},\n@@ -129,7 +129,7 @@ async function fetchJSON(\nconst timeout = options && options.timeout\n? options.timeout\n- : defaultTimeout;\n+ : fetchJSONTimeout;\nconst rejectPromise = (async () => {\nawait sleep(timeout);\nthrow new FetchTimeout(`fetchJSON timed out call to ${endpoint}`, endpoint);\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [lib] Move fetchJSON timeout to timeouts.js |
129,187 | 02.01.2019 22:21:36 | 18,000 | 30e483e59be0bef8502dd81cb36741435a6d56fe | [lib] Move uploadBlob to use XMLHTTPRequest instead of fetch
We need `onprogress`... | [
{
"change_type": "MODIFY",
"old_path": "lib/utils/errors.js",
"new_path": "lib/utils/errors.js",
"diff": "@@ -27,7 +27,7 @@ class ServerError extends ExtendableError {\n// Used for input validators on server-side only\nsanitizedInput: mixed;\n- constructor(error: string, payload?: Object) {\n+ constructor(error: string, payload?: ?Object) {\nsuper(error);\nthis.payload = payload;\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/utils/fetch-json.js",
"new_path": "lib/utils/fetch-json.js",
"diff": "@@ -25,14 +25,21 @@ import { SocketOffline, SocketTimeout } from '../socket/inflight-requests';\nimport { uploadBlob } from './upload-blob';\nimport { fetchJSONTimeout } from '../shared/timeouts';\n-// You'll notice that this is not the type of the fetchJSON function below. This\n-// is because the first several parameters to that functon get bound in by the\n-// helpers in lib/utils/action-utils.js. This type represents the form of the\n-// fetchJSON function that gets passed to the action function in lib/actions.\nexport type FetchJSONOptions = {|\ntimeout?: number, // in milliseconds\nblobUpload?: bool,\n|};\n+\n+export type FetchJSONServerResponse = $Shape<{|\n+ cookieChange: ServerSessionChange,\n+ error: string,\n+ payload: Object\n+|}>;\n+\n+// You'll notice that this is not the type of the fetchJSON function below. This\n+// is because the first several parameters to that functon get bound in by the\n+// helpers in lib/utils/action-utils.js. This type represents the form of the\n+// fetchJSON function that gets passed to the action function in lib/actions.\nexport type FetchJSON = (\nendpoint: Endpoint,\ninput: Object,\n@@ -94,9 +101,9 @@ async function fetchJSON(\nconst url = urlPrefix ? `${urlPrefix}/${endpoint}` : endpoint;\n- let fetchPromise;\n+ let jsonPromise;\nif (options && options.blobUpload) {\n- fetchPromise = uploadBlob(url, cookie, sessionID, input);\n+ jsonPromise = uploadBlob(url, cookie, sessionID, input, options);\n} else {\nconst mergedData: RequestData = { input };\nif (getConfig().setCookieOnRequest) {\n@@ -115,7 +122,8 @@ async function fetchJSON(\n// not logged in on web.\nmergedData.sessionID = sessionID ? sessionID : null;\n}\n- fetchPromise = fetch(url, {\n+ jsonPromise = (async (): Promise<FetchJSONServerResponse> => {\n+ const response = await fetch(url, {\nmethod: 'POST',\n// This is necessary to allow cookie headers to get passed down to us\ncredentials: 'same-origin',\n@@ -125,6 +133,14 @@ async function fetchJSON(\n'Content-Type': 'application/json',\n},\n});\n+ const text = await response.text();\n+ try {\n+ return _cloneDeep(JSON.parse(text));\n+ } catch (e) {\n+ console.log(text);\n+ throw e;\n+ }\n+ })();\n}\nconst timeout = options && options.timeout\n@@ -134,16 +150,7 @@ async function fetchJSON(\nawait sleep(timeout);\nthrow new FetchTimeout(`fetchJSON timed out call to ${endpoint}`, endpoint);\n})();\n- const response = await Promise.race([ fetchPromise, rejectPromise ]);\n-\n- const text = await response.text();\n- let json;\n- try {\n- json = _cloneDeep(JSON.parse(text));\n- } catch (e) {\n- console.log(text);\n- throw e;\n- }\n+ const json = await Promise.race([ jsonPromise, rejectPromise ]);\nconst { cookieChange, error, payload } = json;\nconst sessionChange: ?ServerSessionChange = cookieChange;\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/utils/upload-blob.js",
"new_path": "lib/utils/upload-blob.js",
"diff": "// @flow\n+import type { FetchJSONOptions, FetchJSONServerResponse } from './fetch-json';\n+\nimport invariant from 'invariant';\n+import _cloneDeep from 'lodash/fp/cloneDeep';\nimport { getConfig } from './config';\n-function uploadBlob(\n+async function uploadBlob(\nurl: string,\ncookie: ?string,\nsessionID: ?string,\ninput: {[key: string]: mixed},\n-): Promise<*> {\n+ options?: ?FetchJSONOptions,\n+): Promise<FetchJSONServerResponse> {\nconst formData = new FormData();\nif (getConfig().setCookieOnRequest) {\n// We make sure that if setCookieOnRequest is true, we never set cookie to\n@@ -49,15 +53,25 @@ function uploadBlob(\n}\n}\n- return fetch(url, {\n- method: 'POST',\n- // This is necessary to allow cookie headers to get passed down to us\n- credentials: 'same-origin',\n- body: formData,\n- headers: {\n- 'Accept': 'application/json',\n- },\n+ const xhr = new XMLHttpRequest();\n+ xhr.open('POST', url);\n+ xhr.withCredentials = true;\n+ xhr.setRequestHeader('Accept', 'application/json');\n+\n+ const responsePromise = new Promise((resolve, reject) => {\n+ xhr.onload = () => {\n+ const text = xhr.responseText;\n+ try {\n+ resolve(_cloneDeep(JSON.parse(text)));\n+ } catch (e) {\n+ console.log(text);\n+ reject(e);\n+ }\n+ };\n});\n+\n+ xhr.send(formData);\n+ return await responsePromise;\n}\nexport {\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [lib] Move uploadBlob to use XMLHTTPRequest instead of fetch
We need `onprogress`... |
129,187 | 02.01.2019 22:26:55 | 18,000 | a192f15c66bba546de98e98295b488db6a54d67d | [lib] Add FetchJSONOptions.onProgress | [
{
"change_type": "MODIFY",
"old_path": "lib/utils/fetch-json.js",
"new_path": "lib/utils/fetch-json.js",
"diff": "@@ -25,10 +25,11 @@ import { SocketOffline, SocketTimeout } from '../socket/inflight-requests';\nimport { uploadBlob } from './upload-blob';\nimport { fetchJSONTimeout } from '../shared/timeouts';\n-export type FetchJSONOptions = {|\n- timeout?: number, // in milliseconds\n- blobUpload?: bool,\n-|};\n+export type FetchJSONOptions = $Shape<{|\n+ timeout: number, // in milliseconds\n+ blobUpload: bool,\n+ onProgress: (percent: number) => void,\n+|}>;\nexport type FetchJSONServerResponse = $Shape<{|\ncookieChange: ServerSessionChange,\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/utils/upload-blob.js",
"new_path": "lib/utils/upload-blob.js",
"diff": "@@ -58,6 +58,13 @@ async function uploadBlob(\nxhr.withCredentials = true;\nxhr.setRequestHeader('Accept', 'application/json');\n+ if (options && options.onProgress) {\n+ const { onProgress } = options;\n+ xhr.onprogress = ({ loaded, total }) => {\n+ onProgress(loaded / total);\n+ };\n+ }\n+\nconst responsePromise = new Promise((resolve, reject) => {\nxhr.onload = () => {\nconst text = xhr.responseText;\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [lib] Add FetchJSONOptions.onProgress |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.