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
26.04.2018 12:23:26
14,400
2dbbf895e7f788f08619e5d292f5dddec349b6b6
[native] codeVersion -> 12 See below commits for why we're doing this
[ { "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 16\ntargetSdkVersion 22\n- versionCode 11\n- versionName \"0.0.11\"\n+ versionCode 12\n+ versionName \"0.0.12\"\nndk {\nabiFilters \"armeabi-v7a\", \"x86\"\n}\n" }, { "change_type": "MODIFY", "old_path": "native/android/app/src/main/AndroidManifest.xml", "new_path": "native/android/app/src/main/AndroidManifest.xml", "diff": "xmlns:android=\"http://schemas.android.com/apk/res/android\"\nxmlns:tools=\"http://schemas.android.com/tools\"\npackage=\"org.squadcal\"\n- android:versionCode=\"11\"\n- android:versionName=\"0.0.11\"\n+ android:versionCode=\"12\"\n+ android:versionName=\"0.0.12\"\n>\n<uses-permission android:name=\"android.permission.INTERNET\" />\n<uses-permission android:name=\"android.permission.SYSTEM_ALERT_WINDOW\"/>\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.11</string>\n+ <string>0.0.12</string>\n<key>CFBundleSignature</key>\n<string>????</string>\n<key>CFBundleVersion</key>\n- <string>11</string>\n+ <string>12</string>\n<key>LSApplicationQueriesSchemes</key>\n<array>\n<string>org-appextension-feature-password-management</string>\n" }, { "change_type": "MODIFY", "old_path": "native/persist.js", "new_path": "native/persist.js", "diff": "@@ -67,7 +67,7 @@ const persistConfig = {\nmigrate: createMigrate(migrations, { debug: __DEV__ }),\n};\n-const codeVersion = 11;\n+const codeVersion = 12;\n// This local exists to avoid a circular dependency where redux-setup needs to\n// import all the navigation and screen stuff, but some of those screens want to\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] codeVersion -> 12 See below commits for why we're doing this
129,187
27.04.2018 15:05:09
14,400
51c5e95b84f54f5f25e4e0a3382d919bb9f2257f
[server] Reorder some statements in pingResponder to satisfy Flow
[ { "change_type": "MODIFY", "old_path": "server/src/responders/ping-responders.js", "new_path": "server/src/responders/ping-responders.js", "diff": "@@ -12,7 +12,6 @@ import invariant from 'invariant';\nimport { ServerError } from 'lib/utils/errors';\nimport { mostRecentMessageTimestamp } from 'lib/shared/message-utils';\nimport { mostRecentUpdateTimestamp } from 'lib/shared/update-utils';\n-import { isSet } from 'lib/shared/core';\nimport { validateInput, tShape, tPlatform } from '../utils/validation-utils';\nimport { entryQueryInputValidator } from './entry-responders';\n@@ -112,6 +111,7 @@ async function pingResponder(\n}\n}\n+ const oldUpdatesCurrentAsOf = request.updatesCurrentAsOf;\nconst [\nmessagesResult,\nthreadsResult,\n@@ -128,8 +128,8 @@ async function pingResponder(\nfetchThreadInfos(viewer),\nfetchEntryInfos(viewer, request.calendarQuery),\nfetchCurrentUserInfo(viewer),\n- isSet(request.updatesCurrentAsOf)\n- ? fetchUpdateInfos(viewer, request.updatesCurrentAsOf)\n+ oldUpdatesCurrentAsOf !== null && oldUpdatesCurrentAsOf !== undefined\n+ ? fetchUpdateInfos(viewer, oldUpdatesCurrentAsOf)\n: null,\nclientResponsePromises.length > 0\n? Promise.all(clientResponsePromises)\n@@ -139,19 +139,22 @@ async function pingResponder(\nlet updatesResult = null;\nconst timestampUpdatePromises = [ updateActivityTime(viewer) ];\nif (newUpdates) {\n- invariant(request.updatesCurrentAsOf, \"should be set\");\n- const updatesCurrentAsOf = mostRecentUpdateTimestamp(\n+ invariant(\n+ oldUpdatesCurrentAsOf !== null && oldUpdatesCurrentAsOf !== undefined,\n+ \"should be set\",\n+ );\n+ const newUpdatesCurrentAsOf = mostRecentUpdateTimestamp(\nnewUpdates,\n- request.updatesCurrentAsOf,\n+ oldUpdatesCurrentAsOf,\n);\nif (newUpdates.length > 0) {\ntimestampUpdatePromises.push(\n- recordDeliveredUpdate(viewer.cookieID, updatesCurrentAsOf),\n+ recordDeliveredUpdate(viewer.cookieID, newUpdatesCurrentAsOf),\n);\n}\nupdatesResult = {\nnewUpdates,\n- currentAsOf: updatesCurrentAsOf,\n+ currentAsOf: newUpdatesCurrentAsOf,\n};\n}\nawait Promise.all(timestampUpdatePromises);\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Reorder some statements in pingResponder to satisfy Flow
129,187
01.05.2018 13:55:21
14,400
1d2a81858018d9322d64d545e054d38ab5eb0623
[web] Remove react-helmet (This wasn't being used)
[ { "change_type": "DELETE", "old_path": "web/flow-typed/npm/react-helmet_v5.x.x.js", "new_path": null, "diff": "-// flow-typed signature: c0fb6fa2ea9be0c11b3ced1f95a09e56\n-// flow-typed version: 5af8bb5901/react-helmet_v5.x.x/flow_>=v0.53.x\n-\n-declare module 'react-helmet' {\n- declare type Props = {\n- base?: Object,\n- bodyAttributes?: Object,\n- children?: React$Node,\n- defaultTitle?: string,\n- defer?: boolean,\n- encodeSpecialCharacters?: boolean,\n- htmlAttributes?: Object,\n- link?: Array<Object>,\n- meta?: Array<Object>,\n- noscript?: Array<Object>,\n- onChangeClientState?: (\n- newState?: Object,\n- addedTags?: Object,\n- removeTags?: Object\n- ) => any,\n- script?: Array<Object>,\n- style?: Array<Object>,\n- title?: string,\n- titleAttributes?: Object,\n- titleTemplate?: string,\n- }\n-\n- declare interface TagMethods {\n- toString(): string;\n- toComponent(): [React$Element<*>] | React$Element<*> | Array<Object>;\n- }\n-\n- declare interface StateOnServer {\n- base: TagMethods;\n- bodyAttributes: TagMethods,\n- htmlAttributes: TagMethods;\n- link: TagMethods;\n- meta: TagMethods;\n- noscript: TagMethods;\n- script: TagMethods;\n- style: TagMethods;\n- title: TagMethods;\n- }\n-\n- declare class Helmet extends React$Component<Props> {\n- static rewind(): StateOnServer;\n- static renderStatic(): StateOnServer;\n- static canUseDom(canUseDOM: boolean): void;\n- }\n-\n- declare export default typeof Helmet\n- declare export var Helmet: typeof Helmet\n-}\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-helmet\": \"^5.2.0\",\n\"react-hot-loader\": \"^3.0.0-beta.6\",\n\"react-redux\": \"^5.0.5\",\n\"react-router\": \"^4.1.1\",\n" }, { "change_type": "MODIFY", "old_path": "yarn.lock", "new_path": "yarn.lock", "diff": "@@ -3247,10 +3247,6 @@ execa@^0.8.0:\nsignal-exit \"^3.0.0\"\nstrip-eof \"^1.0.0\"\n-exenv@^1.2.1:\n- version \"1.2.2\"\n- resolved \"https://registry.yarnpkg.com/exenv/-/exenv-1.2.2.tgz#2ae78e85d9894158670b03d47bec1f03bd91bb9d\"\n-\nexpand-brackets@^0.1.4:\nversion \"0.1.5\"\nresolved \"https://registry.yarnpkg.com/expand-brackets/-/expand-brackets-0.1.5.tgz#df07284e342a807cd733ac5af72411e581d1177b\"\n@@ -7452,15 +7448,6 @@ react-dom@^16.2.0:\nobject-assign \"^4.1.1\"\nprop-types \"^15.6.0\"\n-react-helmet@^5.2.0:\n- version \"5.2.0\"\n- resolved \"https://registry.yarnpkg.com/react-helmet/-/react-helmet-5.2.0.tgz#a81811df21313a6d55c5f058c4aeba5d6f3d97a7\"\n- dependencies:\n- deep-equal \"^1.0.1\"\n- object-assign \"^4.1.1\"\n- prop-types \"^15.5.4\"\n- react-side-effect \"^1.1.0\"\n-\nreact-hot-loader@^3.0.0-beta.6, react-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@@ -7711,13 +7698,6 @@ react-router@^4.1.1, react-router@^4.2.0:\nprop-types \"^15.5.4\"\nwarning \"^3.0.0\"\n-react-side-effect@^1.1.0:\n- version \"1.1.5\"\n- resolved \"https://registry.yarnpkg.com/react-side-effect/-/react-side-effect-1.1.5.tgz#f26059e50ed9c626d91d661b9f3c8bb38cd0ff2d\"\n- dependencies:\n- exenv \"^1.2.1\"\n- shallowequal \"^1.0.1\"\n-\nreact-test-renderer@^15.6.1:\nversion \"15.6.2\"\nresolved \"https://registry.yarnpkg.com/react-test-renderer/-/react-test-renderer-15.6.2.tgz#d0333434fc2c438092696ca770da5ed48037efa8\"\n@@ -8435,7 +8415,7 @@ sha.js@^2.4.0, sha.js@^2.4.8:\ninherits \"^2.0.1\"\nsafe-buffer \"^5.0.1\"\n-shallowequal@^1.0.1, shallowequal@^1.0.2:\n+shallowequal@^1.0.2:\nversion \"1.0.2\"\nresolved \"https://registry.yarnpkg.com/shallowequal/-/shallowequal-1.0.2.tgz#1561dbdefb8c01408100319085764da3fcf83f8f\"\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[web] Remove react-helmet (This wasn't being used)
129,187
04.05.2018 20:01:46
14,400
5d15baf954c5e1b642b35b8be4416a743e1c9df9
[web] Unbreak log in and reset password Frustrating combo of things to be broke at the same time...
[ { "change_type": "MODIFY", "old_path": "server/src/responders/user-responders.js", "new_path": "server/src/responders/user-responders.js", "diff": "@@ -182,9 +182,10 @@ async function logInResponder(\n): Promise<LogInResponse> {\nvalidateInput(logInRequestInputValidator, input);\nconst request: LogInRequest = input;\n- request.calendarQuery = normalizeCalendarQuery(request.calendarQuery);\n- const calendarQuery = request.calendarQuery;\n+ const calendarQuery = request.calendarQuery\n+ ? normalizeCalendarQuery(request.calendarQuery)\n+ : null;\nconst promises = {};\nif (calendarQuery) {\npromises.verifyCalendarQueryThreadIDs =\n@@ -273,7 +274,9 @@ async function passwordUpdateResponder(\n): Promise<LogInResponse> {\nvalidateInput(updatePasswordRequestInputValidator, input);\nconst request: UpdatePasswordRequest = input;\n+ if (request.calendarQuery) {\nrequest.calendarQuery = normalizeCalendarQuery(request.calendarQuery);\n+ }\nconst response = await updatePassword(viewer, request);\nif (request.deviceTokenUpdateRequest) {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[web] Unbreak log in and reset password Frustrating combo of things to be broke at the same time...
129,187
07.05.2018 13:35:41
14,400
667d0f1534fb371b6600a48d40c586a6fc90060a
[server] SQL backups
[ { "change_type": "ADD", "old_path": null, "new_path": "server/flow-typed/npm/dateformat_vx.x.x.js", "diff": "+// flow-typed signature: d63e285272cb03960fc6ee354729a649\n+// flow-typed version: <<STUB>>/dateformat_v^3.0.3/flow_v0.64.0\n+\n+/**\n+ * This is an autogenerated libdef stub for:\n+ *\n+ * 'dateformat'\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 'dateformat' {\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 'dateformat/lib/dateformat' {\n+ declare module.exports: any;\n+}\n+\n+// Filename aliases\n+declare module 'dateformat/lib/dateformat.js' {\n+ declare module.exports: $Exports<'dateformat/lib/dateformat'>;\n+}\n" }, { "change_type": "MODIFY", "old_path": "server/flow-typed/npm/lib_vx.x.x.js", "new_path": "server/flow-typed/npm/lib_vx.x.x.js", "diff": "-// flow-typed signature: 7246e2d17248caa0cc26cf7a85e85688\n+// flow-typed signature: 5d7a7a79bbbee5c961f518d9cc4d656b\n// flow-typed version: <<STUB>>/lib_v0.0.1/flow_v0.64.0\n/**\n@@ -118,6 +118,10 @@ declare module 'lib/permissions/thread-permissions' {\ndeclare module.exports: any;\n}\n+declare module 'lib/reducers/calendar-filters-reducer' {\n+ declare module.exports: any;\n+}\n+\ndeclare module 'lib/reducers/cookie-reducer' {\ndeclare module.exports: any;\n}\n@@ -178,6 +182,10 @@ declare module 'lib/reducers/user-reducer' {\ndeclare module.exports: any;\n}\n+declare module 'lib/selectors/calendar-filter-selectors' {\n+ declare module.exports: any;\n+}\n+\ndeclare module 'lib/selectors/loading-selectors' {\ndeclare module.exports: any;\n}\n@@ -278,6 +286,10 @@ declare module 'lib/types/entry-types' {\ndeclare module.exports: any;\n}\n+declare module 'lib/types/filter-types' {\n+ declare module.exports: any;\n+}\n+\ndeclare module 'lib/types/history-types' {\ndeclare module.exports: any;\n}\n@@ -451,6 +463,9 @@ declare module 'lib/flow-typed/npm/whatwg-fetch_vx.x.x.js' {\ndeclare module 'lib/permissions/thread-permissions.js' {\ndeclare module.exports: $Exports<'lib/permissions/thread-permissions'>;\n}\n+declare module 'lib/reducers/calendar-filters-reducer.js' {\n+ declare module.exports: $Exports<'lib/reducers/calendar-filters-reducer'>;\n+}\ndeclare module 'lib/reducers/cookie-reducer.js' {\ndeclare module.exports: $Exports<'lib/reducers/cookie-reducer'>;\n}\n@@ -496,6 +511,9 @@ declare module 'lib/reducers/url-prefix-reducer.js' {\ndeclare module 'lib/reducers/user-reducer.js' {\ndeclare module.exports: $Exports<'lib/reducers/user-reducer'>;\n}\n+declare module 'lib/selectors/calendar-filter-selectors.js' {\n+ declare module.exports: $Exports<'lib/selectors/calendar-filter-selectors'>;\n+}\ndeclare module 'lib/selectors/loading-selectors.js' {\ndeclare module.exports: $Exports<'lib/selectors/loading-selectors'>;\n}\n@@ -571,6 +589,9 @@ declare module 'lib/types/endpoints.js' {\ndeclare module 'lib/types/entry-types.js' {\ndeclare module.exports: $Exports<'lib/types/entry-types'>;\n}\n+declare module 'lib/types/filter-types.js' {\n+ declare module.exports: $Exports<'lib/types/filter-types'>;\n+}\ndeclare module 'lib/types/history-types.js' {\ndeclare module.exports: $Exports<'lib/types/history-types'>;\n}\n" }, { "change_type": "MODIFY", "old_path": "server/package.json", "new_path": "server/package.json", "diff": "\"apn\": \"^2.2.0\",\n\"common-tags\": \"^1.7.2\",\n\"cookie-parser\": \"^1.4.3\",\n+ \"dateformat\": \"^3.0.3\",\n\"express\": \"^4.16.2\",\n\"firebase-admin\": \"^5.7.0\",\n\"invariant\": \"^2.2.2\",\n" }, { "change_type": "ADD", "old_path": null, "new_path": "server/src/backups.js", "diff": "+// @flow\n+\n+import fs from 'fs';\n+import childProcess from 'child_process';\n+import zlib from 'zlib';\n+import dateFormat from 'dateformat';\n+\n+import dbConfig from '../secrets/db_config';\n+import backupConfig from '../facts/backups';\n+\n+const backupDirectory = \"/Users/ashoat\";\n+\n+async function backupDB() {\n+ if (!backupConfig || !backupConfig.enabled) {\n+ return;\n+ }\n+ const dateString = dateFormat(\"yyyy-mm-dd-HH:MM\");\n+ const filename = `${backupConfig.directory}/squadcal.${dateString}.sql.gz`;\n+ try {\n+ await backupDBToFile(filename);\n+ } catch(e) {\n+ console.log('error!', e);\n+ }\n+}\n+\n+function backupDBToFile(filePath: string): Promise<void> {\n+ const writeStream = fs.createWriteStream(filePath);\n+ const mysqlDump = childProcess.spawn(\n+ 'mysqldump',\n+ [\n+ '-u',\n+ dbConfig.user,\n+ `-p${dbConfig.password}`,\n+ dbConfig.database,\n+ ],\n+ );\n+ return new Promise((resolve, reject) => {\n+ mysqlDump\n+ .stdout\n+ .pipe(zlib.createGzip())\n+ .pipe(writeStream)\n+ .on('finish', resolve)\n+ .on('error', reject);\n+ });\n+}\n+\n+export {\n+ backupDB,\n+};\n" }, { "change_type": "MODIFY", "old_path": "server/src/cron.js", "new_path": "server/src/cron.js", "diff": "@@ -15,6 +15,7 @@ import { deleteOrphanedMessages } from './deleters/message-deleters';\nimport { deleteOrphanedFocused } from './deleters/activity-deleters';\nimport { deleteOrphanedNotifs } from './deleters/notif-deleters';\nimport { deleteExpiredUpdates } from './deleters/update-deleters';\n+import { backupDB } from './backups';\nif (cluster.isMaster) {\nschedule.scheduleJob(\n@@ -36,4 +37,8 @@ if (cluster.isMaster) {\nawait deleteExpiredUpdates();\n},\n);\n+ schedule.scheduleJob(\n+ \"* * * * * \",\n+ backupDB,\n+ );\n}\n" }, { "change_type": "MODIFY", "old_path": "yarn.lock", "new_path": "yarn.lock", "diff": "@@ -2623,6 +2623,10 @@ dateformat@^2.0.0:\nversion \"2.2.0\"\nresolved \"https://registry.yarnpkg.com/dateformat/-/dateformat-2.2.0.tgz#4065e2013cf9fb916ddfd82efb506ad4c6769062\"\n+dateformat@^3.0.3:\n+ version \"3.0.3\"\n+ resolved \"https://registry.yarnpkg.com/dateformat/-/dateformat-3.0.3.tgz#a6e37499a4d9a9cf85ef5872044d62901c9889ae\"\n+\ndebug@2.6.9, debug@^2.1.3, debug@^2.2.0, debug@^2.3.3, debug@^2.6.6, debug@^2.6.8:\nversion \"2.6.9\"\nresolved \"https://registry.yarnpkg.com/debug/-/debug-2.6.9.tgz#5d128515df134ff327e90a4c93f4e077a536341f\"\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] SQL backups
129,187
07.05.2018 14:30:05
14,400
0c61fb51ebf638ba8b30b932f897a3e0671d8b66
[server] Delete oldest backup if no space left
[ { "change_type": "MODIFY", "old_path": "server/src/backups.js", "new_path": "server/src/backups.js", "diff": "@@ -8,9 +8,14 @@ import dateFormat from 'dateformat';\nimport dbConfig from '../secrets/db_config';\nimport backupConfig from '../facts/backups';\n-const backupDirectory = \"/Users/ashoat\";\n+// $FlowFixMe\n+const readdir = Promise.denodeify(fs.readdir);\n+// $FlowFixMe\n+const lstat = Promise.denodeify(fs.lstat);\n+// $FlowFixMe\n+const unlink = Promise.denodeify(fs.unlink);\n-async function backupDB() {\n+async function backupDB(retries: number = 2) {\nif (!backupConfig || !backupConfig.enabled) {\nreturn;\n}\n@@ -19,7 +24,14 @@ async function backupDB() {\ntry {\nawait backupDBToFile(filename);\n} catch (e) {\n- console.log('error!', e);\n+ if (e.code !== \"ENOSPC\") {\n+ throw e;\n+ }\n+ if (!retries) {\n+ throw e;\n+ }\n+ await deleteOldestBackup();\n+ await backupDB(retries - 1);\n}\n}\n@@ -44,6 +56,26 @@ function backupDBToFile(filePath: string): Promise<void> {\n});\n}\n+async function deleteOldestBackup() {\n+ const files = await readdir(backupConfig.directory);\n+ let oldestFile;\n+ for (let file of files) {\n+ if (!file.endsWith(\".sql.gz\")) {\n+ continue;\n+ }\n+ const stat = await lstat(`${backupConfig.directory}/${file}`);\n+ if (stat.isDirectory()) {\n+ continue;\n+ }\n+ if (!oldestFile || stat.mtime < oldestFile.mtime) {\n+ oldestFile = { file, mtime: stat.mtime };\n+ }\n+ }\n+ if (oldestFile) {\n+ await unlink(`${backupConfig.directory}/${oldestFile.file}`);\n+ }\n+}\n+\nexport {\nbackupDB,\n};\n" }, { "change_type": "MODIFY", "old_path": "server/src/cron.js", "new_path": "server/src/cron.js", "diff": "@@ -21,6 +21,7 @@ if (cluster.isMaster) {\nschedule.scheduleJob(\n'30 3 * * *',\nasync () => {\n+ try {\n// Do everything one at a time to reduce load since we're in no hurry,\n// and since some queries depend on previous ones.\nawait deleteExpiredCookies();\n@@ -35,10 +36,25 @@ if (cluster.isMaster) {\nawait deleteOrphanedFocused();\nawait deleteOrphanedNotifs();\nawait deleteExpiredUpdates();\n+ } catch (e) {\n+ console.warn(\n+ \"encountered error while trying to clean database\",\n+ e,\n+ );\n+ }\n},\n);\nschedule.scheduleJob(\n\"* * * * * \",\n- backupDB,\n+ async () => {\n+ try {\n+ await backupDB();\n+ } catch (e) {\n+ console.warn(\n+ \"encountered error while trying to backup database\",\n+ e,\n+ );\n+ }\n+ },\n);\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Delete oldest backup if no space left
129,187
07.05.2018 14:37:20
14,400
e7e05de2075914fbf2931c896dcd4853ab89ce7a
[server] Use denodeify from separate package Apparently node only makes it available in `loader.mjs`???
[ { "change_type": "ADD", "old_path": null, "new_path": "server/flow-typed/npm/denodeify_vx.x.x.js", "diff": "+// flow-typed signature: 26ed4f6305aed1cfbce8ce001b7a00bd\n+// flow-typed version: <<STUB>>/denodeify_v^1.2.1/flow_v0.64.0\n+\n+/**\n+ * This is an autogenerated libdef stub for:\n+ *\n+ * 'denodeify'\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 'denodeify' {\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 'denodeify/test/es6-promise-test' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'denodeify/test/es6-shim-test' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'denodeify/test/helpers' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'denodeify/test/lie-test' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'denodeify/test/native-promise-only-test' {\n+ declare module.exports: any;\n+}\n+\n+// Filename aliases\n+declare module 'denodeify/index' {\n+ declare module.exports: $Exports<'denodeify'>;\n+}\n+declare module 'denodeify/index.js' {\n+ declare module.exports: $Exports<'denodeify'>;\n+}\n+declare module 'denodeify/test/es6-promise-test.js' {\n+ declare module.exports: $Exports<'denodeify/test/es6-promise-test'>;\n+}\n+declare module 'denodeify/test/es6-shim-test.js' {\n+ declare module.exports: $Exports<'denodeify/test/es6-shim-test'>;\n+}\n+declare module 'denodeify/test/helpers.js' {\n+ declare module.exports: $Exports<'denodeify/test/helpers'>;\n+}\n+declare module 'denodeify/test/lie-test.js' {\n+ declare module.exports: $Exports<'denodeify/test/lie-test'>;\n+}\n+declare module 'denodeify/test/native-promise-only-test.js' {\n+ declare module.exports: $Exports<'denodeify/test/native-promise-only-test'>;\n+}\n" }, { "change_type": "MODIFY", "old_path": "server/package.json", "new_path": "server/package.json", "diff": "\"common-tags\": \"^1.7.2\",\n\"cookie-parser\": \"^1.4.3\",\n\"dateformat\": \"^3.0.3\",\n+ \"denodeify\": \"^1.2.1\",\n\"express\": \"^4.16.2\",\n\"firebase-admin\": \"^5.7.0\",\n\"invariant\": \"^2.2.2\",\n" }, { "change_type": "MODIFY", "old_path": "server/src/backups.js", "new_path": "server/src/backups.js", "diff": "@@ -4,16 +4,14 @@ import fs from 'fs';\nimport childProcess from 'child_process';\nimport zlib from 'zlib';\nimport dateFormat from 'dateformat';\n+import denodeify from 'denodeify';\nimport dbConfig from '../secrets/db_config';\nimport backupConfig from '../facts/backups';\n-// $FlowFixMe\n-const readdir = Promise.denodeify(fs.readdir);\n-// $FlowFixMe\n-const lstat = Promise.denodeify(fs.lstat);\n-// $FlowFixMe\n-const unlink = Promise.denodeify(fs.unlink);\n+const readdir = denodeify(fs.readdir);\n+const lstat = denodeify(fs.lstat);\n+const unlink = denodeify(fs.unlink);\nasync function backupDB(retries: number = 2) {\nif (!backupConfig || !backupConfig.enabled) {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Use denodeify from separate package Apparently node only makes it available in `loader.mjs`???
129,187
10.05.2018 10:21:17
14,400
0be008bcd2a20f61685fd9004a281119dde4c5dd
[web] Style tweaks and fixes for filter panel
[ { "change_type": "MODIFY", "old_path": "web/style.css", "new_path": "web/style.css", "diff": "@@ -317,6 +317,8 @@ div.calendar-filters-container {\nbackground-image: url(../images/background.png);\nbackground-size: 3000px 2000px;\nbackground-attachment: fixed;\n+ display: flex;\n+ flex-direction: column;\n}\ndiv.calendar-filters {\ncolor: #DDDDDD;\n@@ -471,7 +473,7 @@ div.calendar-filter-category {\nh2.calendar-nav {\nfont-family: 'Anaheim', sans-serif;\ntext-align: center;\n- margin: 0 auto 15px auto;\n+ margin: 8px auto 0px auto;\nwidth: 200px;\ncolor: #333333;\n}\n@@ -498,7 +500,7 @@ a.calendar-filters-button {\nbackground-color: #444455AA;\npadding: 8px 18px;\nborder-radius: 18px;\n- margin: 5px 15px;\n+ margin: 0 15px 5px 15px;\nfont-size: 16px;\ncursor: pointer;\ntext-transform: uppercase;\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[web] Style tweaks and fixes for filter panel
129,187
10.05.2018 12:30:29
14,400
c944cbfdda20a74b901a668b6111bc55fa2d68c0
Moving chat-selectors.js into lib so we can access it from web
[ { "change_type": "RENAME", "old_path": "native/selectors/chat-selectors.js", "new_path": "lib/selectors/chat-selectors.js", "diff": "// @flow\n-import type { AppState } from '../redux-setup';\n-import { type ThreadInfo, threadInfoPropType } from 'lib/types/thread-types';\n+import type { BaseAppState } from '../types/redux-types';\n+import { type ThreadInfo, threadInfoPropType } from '../types/thread-types';\nimport {\ntype MessageInfo,\ntype MessageStore,\n@@ -9,8 +9,8 @@ import {\ntype RobotextMessageInfo,\nmessageInfoPropType,\nmessageTypes,\n-} from 'lib/types/message-types';\n-import type { UserInfo } from 'lib/types/user-types';\n+} from '../types/message-types';\n+import type { UserInfo } from '../types/user-types';\nimport { createSelector } from 'reselect';\nimport PropTypes from 'prop-types';\n@@ -24,8 +24,8 @@ import _memoize from 'lodash/memoize';\nimport {\nrobotextForMessageInfo,\ncreateMessageInfo,\n-} from 'lib/shared/message-utils';\n-import { threadInfoSelector } from 'lib/selectors/thread-selectors';\n+} from '../shared/message-utils';\n+import { threadInfoSelector } from './thread-selectors';\nexport type ChatThreadItem = {|\ntype: \"chatThreadItem\",\n@@ -41,9 +41,9 @@ const chatThreadItemPropType = PropTypes.shape({\n});\nconst chatListData = createSelector(\nthreadInfoSelector,\n- (state: AppState) => state.messageStore,\n- (state: AppState) => state.currentUserInfo && state.currentUserInfo.id,\n- (state: AppState) => state.userInfos,\n+ (state: BaseAppState<*>) => state.messageStore,\n+ (state: BaseAppState<*>) => state.currentUserInfo && state.currentUserInfo.id,\n+ (state: BaseAppState<*>) => state.userInfos,\n(\nthreadInfos: {[id: string]: ThreadInfo},\nmessageStore: MessageStore,\n@@ -122,9 +122,9 @@ const chatMessageItemPropType = PropTypes.oneOfType([\n]);\nconst msInFiveMinutes = 5 * 60 * 1000;\nconst baseMessageListData = (threadID: string) => createSelector(\n- (state: AppState) => state.messageStore,\n- (state: AppState) => state.currentUserInfo && state.currentUserInfo.id,\n- (state: AppState) => state.userInfos,\n+ (state: BaseAppState<*>) => state.messageStore,\n+ (state: BaseAppState<*>) => state.currentUserInfo && state.currentUserInfo.id,\n+ (state: BaseAppState<*>) => state.userInfos,\nthreadInfoSelector,\n(\nmessageStore: MessageStore,\n" }, { "change_type": "MODIFY", "old_path": "native/chat/chat-thread-list-item.react.js", "new_path": "native/chat/chat-thread-list-item.react.js", "diff": "// @flow\n-import type { ChatThreadItem } from '../selectors/chat-selectors';\n-import { chatThreadItemPropType } from '../selectors/chat-selectors';\n+import {\n+ type ChatThreadItem,\n+ chatThreadItemPropType,\n+} from 'lib/selectors/chat-selectors';\nimport type { ThreadInfo } from 'lib/types/thread-types';\nimport { shortAbsoluteDate } from 'lib/utils/date-utils';\n" }, { "change_type": "MODIFY", "old_path": "native/chat/chat-thread-list.react.js", "new_path": "native/chat/chat-thread-list.react.js", "diff": "import type { AppState } from '../redux-setup';\nimport type { ThreadInfo } from 'lib/types/thread-types';\n-import type { ChatThreadItem } from '../selectors/chat-selectors';\n-import { chatThreadItemPropType } from '../selectors/chat-selectors';\n+import {\n+ type ChatThreadItem,\n+ chatThreadItemPropType,\n+} from 'lib/selectors/chat-selectors';\nimport type { NavigationScreenProp, NavigationRoute } from 'react-navigation';\nimport * as React from 'react';\n@@ -25,8 +27,8 @@ import { viewerIsMember } from 'lib/shared/thread-utils';\nimport { threadSearchIndex } from 'lib/selectors/nav-selectors';\nimport SearchIndex from 'lib/shared/search-index';\nimport { connect } from 'lib/utils/redux-utils';\n+import { chatListData } from 'lib/selectors/chat-selectors';\n-import { chatListData } from '../selectors/chat-selectors';\nimport ChatThreadListItem from './chat-thread-list-item.react';\nimport { MessageListRouteName } from './message-list.react';\nimport ComposeThreadButton from './compose-thread-button.react';\n" }, { "change_type": "MODIFY", "old_path": "native/chat/message-list.react.js", "new_path": "native/chat/message-list.react.js", "diff": "import type { AppState } from '../redux-setup';\nimport type { NavigationScreenProp, NavigationRoute } from 'react-navigation';\nimport { type ThreadInfo, threadInfoPropType } from 'lib/types/thread-types';\n-import type {\n- ChatMessageItem,\n- ChatMessageInfoItem,\n-} from '../selectors/chat-selectors';\n-import { chatMessageItemPropType } from '../selectors/chat-selectors';\n+import {\n+ type ChatMessageItem,\n+ type ChatMessageInfoItem,\n+ chatMessageItemPropType,\n+} from 'lib/selectors/chat-selectors';\nimport type { ViewToken } from 'react-native/Libraries/Lists/ViewabilityHelper';\nimport {\ntype TextMessageInfo,\n@@ -47,8 +47,8 @@ import { viewerIsMember } from 'lib/shared/thread-utils';\nimport { registerFetchKey } from 'lib/reducers/loading-reducer';\nimport { threadInfoSelector } from 'lib/selectors/thread-selectors';\nimport { onlyEmojiRegex } from 'lib/shared/emojis';\n+import { messageListData } from 'lib/selectors/chat-selectors';\n-import { messageListData } from '../selectors/chat-selectors';\nimport { Message, messageItemHeight } from './message.react';\nimport TextHeightMeasurer from '../text-height-measurer.react';\nimport ChatInputBar from './chat-input-bar.react';\n" }, { "change_type": "MODIFY", "old_path": "native/chat/message.react.js", "new_path": "native/chat/message.react.js", "diff": "// @flow\nimport type { ChatMessageInfoItemWithHeight } from './message-list.react';\n-import { chatMessageItemPropType } from '../selectors/chat-selectors';\n+import { chatMessageItemPropType } from 'lib/selectors/chat-selectors';\nimport { messageTypes } from 'lib/types/message-types';\nimport React from 'react';\n" }, { "change_type": "MODIFY", "old_path": "native/chat/robotext-message.react.js", "new_path": "native/chat/robotext-message.react.js", "diff": "import { type ThreadInfo, threadInfoPropType } from 'lib/types/thread-types';\nimport type { ChatMessageInfoItemWithHeight } from './message-list.react';\n-import { chatMessageItemPropType } from '../selectors/chat-selectors';\n+import { chatMessageItemPropType } from 'lib/selectors/chat-selectors';\nimport type { Dispatch } from 'lib/types/redux-types';\nimport type { AppState } from '../redux-setup';\nimport { messageTypes } from 'lib/types/message-types';\n" }, { "change_type": "MODIFY", "old_path": "native/chat/text-message.react.js", "new_path": "native/chat/text-message.react.js", "diff": "import { type ThreadInfo, threadInfoPropType } from 'lib/types/thread-types';\nimport type { ChatMessageInfoItemWithHeight } from './message-list.react';\n-import { chatMessageItemPropType } from '../selectors/chat-selectors';\n+import { chatMessageItemPropType } from 'lib/selectors/chat-selectors';\nimport type { TooltipItemData } from '../components/tooltip.react';\nimport { messageTypes } from 'lib/types/message-types';\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Moving chat-selectors.js into lib so we can access it from web
129,187
11.05.2018 19:48:18
14,400
ae6605972d5e61a1ce68278e44067486e03f7b98
[web] Include currently selected thread in web chat thread list
[ { "change_type": "MODIFY", "old_path": "lib/selectors/chat-selectors.js", "new_path": "lib/selectors/chat-selectors.js", "diff": "@@ -40,21 +40,14 @@ const chatThreadItemPropType = PropTypes.shape({\nmostRecentMessageInfo: messageInfoPropType,\nlastUpdatedTime: PropTypes.number.isRequired,\n});\n-const chatListData = createSelector(\n- threadInfoSelector,\n- (state: BaseAppState<*>) => state.messageStore,\n- (state: BaseAppState<*>) => state.currentUserInfo && state.currentUserInfo.id,\n- (state: BaseAppState<*>) => state.userInfos,\n- (\n+\n+function createChatThreadItem(\n+ threadInfo: ThreadInfo,\nthreadInfos: {[id: string]: ThreadInfo},\nmessageStore: MessageStore,\nviewerID: ?string,\nuserInfos: {[id: string]: UserInfo},\n- ): ChatThreadItem[] => _flow(\n- // TODO change this to viewerIsMember once I figure out how to include\n- // non-visible threads in the ChatThreadList\n- _filter(viewerCanSeeThread),\n- _map((threadInfo: ThreadInfo): ChatThreadItem => {\n+): ChatThreadItem {\nconst thread = messageStore.threads[threadInfo.id];\nif (!thread || thread.messageIDs.length === 0) {\nreturn {\n@@ -89,7 +82,29 @@ const chatListData = createSelector(\nmostRecentMessageInfo,\nlastUpdatedTime: mostRecentMessageInfo.time,\n};\n- }),\n+}\n+\n+const chatListData = createSelector(\n+ threadInfoSelector,\n+ (state: BaseAppState<*>) => state.messageStore,\n+ (state: BaseAppState<*>) => state.currentUserInfo && state.currentUserInfo.id,\n+ (state: BaseAppState<*>) => state.userInfos,\n+ (\n+ threadInfos: {[id: string]: ThreadInfo},\n+ messageStore: MessageStore,\n+ viewerID: ?string,\n+ userInfos: {[id: string]: UserInfo},\n+ ): ChatThreadItem[] => _flow(\n+ // TODO change this to viewerIsMember once I figure out how to include\n+ // non-visible threads in the ChatThreadList\n+ _filter(viewerCanSeeThread),\n+ _map((threadInfo: ThreadInfo): ChatThreadItem => createChatThreadItem(\n+ threadInfo,\n+ threadInfos,\n+ messageStore,\n+ viewerID,\n+ userInfos,\n+ )),\n_orderBy(\"lastUpdatedTime\")(\"desc\"),\n)(threadInfos),\n);\n@@ -215,6 +230,7 @@ const baseMessageListData = (threadID: string) => createSelector(\nconst messageListData = _memoize(baseMessageListData);\nexport {\n+ createChatThreadItem,\nchatThreadItemPropType,\nchatListData,\nchatMessageItemPropType,\n" }, { "change_type": "MODIFY", "old_path": "web/chat/chat-thread-list.react.js", "new_path": "web/chat/chat-thread-list.react.js", "diff": "@@ -11,7 +11,7 @@ import * as React from 'react';\nimport PropTypes from 'prop-types';\nimport { connect } from 'lib/utils/redux-utils';\n-import { chatListData } from 'lib/selectors/chat-selectors';\n+import { webChatListData } from '../selectors/chat-selectors';\nimport css from './chat-thread-list.css';\nimport ChatThreadListItem from './chat-thread-list-item.react';\n@@ -52,7 +52,7 @@ class ChatThreadList extends React.PureComponent<Props> {\nexport default connect(\n(state: AppState) => ({\n- chatListData: chatListData(state),\n+ chatListData: webChatListData(state),\nnavInfo: state.navInfo,\n}),\nnull,\n" }, { "change_type": "MODIFY", "old_path": "web/dist/app.build.js", "new_path": "web/dist/app.build.js", "diff": "@@ -9369,6 +9369,7 @@ module.exports = forOwn;\n/***/ (function(module, __webpack_exports__, __webpack_require__) {\n\"use strict\";\n+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"c\", function() { return createChatThreadItem; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"b\", function() { return chatThreadItemPropType; });\n/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"a\", function() { return chatListData; });\n/* unused harmony export chatMessageItemPropType */\n@@ -9419,10 +9420,8 @@ const chatThreadItemPropType = __WEBPACK_IMPORTED_MODULE_3_prop_types___default.\nmostRecentMessageInfo: __WEBPACK_IMPORTED_MODULE_1__types_message_types__[\"b\" /* messageInfoPropType */],\nlastUpdatedTime: __WEBPACK_IMPORTED_MODULE_3_prop_types___default.a.number.isRequired\n});\n-const chatListData = Object(__WEBPACK_IMPORTED_MODULE_2_reselect__[\"createSelector\"])(__WEBPACK_IMPORTED_MODULE_11__thread_selectors__[\"f\" /* threadInfoSelector */], state => state.messageStore, state => state.currentUserInfo && state.currentUserInfo.id, state => state.userInfos, (threadInfos, messageStore, viewerID, userInfos) => __WEBPACK_IMPORTED_MODULE_5_lodash_fp_flow___default()(\n-// TODO change this to viewerIsMember once I figure out how to include\n-// non-visible threads in the ChatThreadList\n-__WEBPACK_IMPORTED_MODULE_6_lodash_fp_filter___default()(__WEBPACK_IMPORTED_MODULE_12__shared_thread_utils__[\"i\" /* viewerCanSeeThread */]), __WEBPACK_IMPORTED_MODULE_7_lodash_fp_map___default()(threadInfo => {\n+\n+function createChatThreadItem(threadInfo, threadInfos, messageStore, viewerID, userInfos) {\nconst thread = messageStore.threads[threadInfo.id];\nif (!thread || thread.messageIDs.length === 0) {\nreturn {\n@@ -9452,7 +9451,12 @@ __WEBPACK_IMPORTED_MODULE_6_lodash_fp_filter___default()(__WEBPACK_IMPORTED_MODU\nmostRecentMessageInfo,\nlastUpdatedTime: mostRecentMessageInfo.time\n};\n-}), __WEBPACK_IMPORTED_MODULE_8_lodash_fp_orderBy___default()(\"lastUpdatedTime\")(\"desc\"))(threadInfos));\n+}\n+\n+const chatListData = Object(__WEBPACK_IMPORTED_MODULE_2_reselect__[\"createSelector\"])(__WEBPACK_IMPORTED_MODULE_11__thread_selectors__[\"f\" /* threadInfoSelector */], state => state.messageStore, state => state.currentUserInfo && state.currentUserInfo.id, state => state.userInfos, (threadInfos, messageStore, viewerID, userInfos) => __WEBPACK_IMPORTED_MODULE_5_lodash_fp_flow___default()(\n+// TODO change this to viewerIsMember once I figure out how to include\n+// non-visible threads in the ChatThreadList\n+__WEBPACK_IMPORTED_MODULE_6_lodash_fp_filter___default()(__WEBPACK_IMPORTED_MODULE_12__shared_thread_utils__[\"i\" /* viewerCanSeeThread */]), __WEBPACK_IMPORTED_MODULE_7_lodash_fp_map___default()(threadInfo => createChatThreadItem(threadInfo, threadInfos, messageStore, viewerID, userInfos)), __WEBPACK_IMPORTED_MODULE_8_lodash_fp_orderBy___default()(\"lastUpdatedTime\")(\"desc\"))(threadInfos));\nconst chatMessageItemPropType = __WEBPACK_IMPORTED_MODULE_3_prop_types___default.a.oneOfType([__WEBPACK_IMPORTED_MODULE_3_prop_types___default.a.shape({\nitemType: __WEBPACK_IMPORTED_MODULE_3_prop_types___default.a.oneOf([\"loader\"]).isRequired\n@@ -59346,9 +59350,10 @@ module.exports = {\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3_prop_types__ = __webpack_require__(1);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_3_prop_types___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_3_prop_types__);\n/* harmony import */ var __WEBPACK_IMPORTED_MODULE_4_lib_utils_redux_utils__ = __webpack_require__(11);\n-/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__chat_thread_list_css__ = __webpack_require__(148);\n-/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__chat_thread_list_css___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_5__chat_thread_list_css__);\n-/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__chat_thread_list_item_react__ = __webpack_require__(606);\n+/* harmony import */ var __WEBPACK_IMPORTED_MODULE_5__selectors_chat_selectors__ = __webpack_require__(609);\n+/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__chat_thread_list_css__ = __webpack_require__(148);\n+/* harmony import */ var __WEBPACK_IMPORTED_MODULE_6__chat_thread_list_css___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_6__chat_thread_list_css__);\n+/* harmony import */ var __WEBPACK_IMPORTED_MODULE_7__chat_thread_list_item_react__ = __webpack_require__(606);\n@@ -59365,7 +59370,7 @@ module.exports = {\nclass ChatThreadList extends __WEBPACK_IMPORTED_MODULE_2_react__[\"PureComponent\"] {\nrender() {\n- const threads = this.props.chatListData.map(item => __WEBPACK_IMPORTED_MODULE_2_react__[\"createElement\"](__WEBPACK_IMPORTED_MODULE_6__chat_thread_list_item_react__[\"a\" /* default */], {\n+ const threads = this.props.chatListData.map(item => __WEBPACK_IMPORTED_MODULE_2_react__[\"createElement\"](__WEBPACK_IMPORTED_MODULE_7__chat_thread_list_item_react__[\"a\" /* default */], {\nitem: item,\nactive: item.threadInfo.id === this.props.navInfo.activeChatThreadID,\nnavInfo: this.props.navInfo,\n@@ -59374,7 +59379,7 @@ class ChatThreadList extends __WEBPACK_IMPORTED_MODULE_2_react__[\"PureComponent\"\n}));\nreturn __WEBPACK_IMPORTED_MODULE_2_react__[\"createElement\"](\n'div',\n- { className: __WEBPACK_IMPORTED_MODULE_5__chat_thread_list_css___default.a.container },\n+ { className: __WEBPACK_IMPORTED_MODULE_6__chat_thread_list_css___default.a.container },\nthreads\n);\n}\n@@ -59391,7 +59396,7 @@ Object.defineProperty(ChatThreadList, 'propTypes', {\n}\n});\n/* harmony default export */ __webpack_exports__[\"a\"] = (Object(__WEBPACK_IMPORTED_MODULE_4_lib_utils_redux_utils__[\"a\" /* connect */])(state => ({\n- chatListData: Object(__WEBPACK_IMPORTED_MODULE_1_lib_selectors_chat_selectors__[\"a\" /* chatListData */])(state),\n+ chatListData: Object(__WEBPACK_IMPORTED_MODULE_5__selectors_chat_selectors__[\"a\" /* webChatListData */])(state),\nnavInfo: state.navInfo\n}), null, true)(ChatThreadList));\n@@ -59648,5 +59653,45 @@ module.exports = {\n\"sr-only-focusable\": \"_-node_modules--fortawesome-fontawesome-styles__sr-only-focusable--1CAEA\"\n};\n+/***/ }),\n+/* 609 */\n+/***/ (function(module, __webpack_exports__, __webpack_require__) {\n+\n+\"use strict\";\n+/* harmony export (binding) */ __webpack_require__.d(__webpack_exports__, \"a\", function() { return webChatListData; });\n+/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_reselect__ = __webpack_require__(17);\n+/* harmony import */ var __WEBPACK_IMPORTED_MODULE_0_reselect___default = __webpack_require__.n(__WEBPACK_IMPORTED_MODULE_0_reselect__);\n+/* harmony import */ var __WEBPACK_IMPORTED_MODULE_1_lib_selectors_thread_selectors__ = __webpack_require__(27);\n+/* harmony import */ var __WEBPACK_IMPORTED_MODULE_2_lib_selectors_chat_selectors__ = __webpack_require__(147);\n+\n+\n+\n+\n+\n+const activeChatThreadItem = Object(__WEBPACK_IMPORTED_MODULE_0_reselect__[\"createSelector\"])(__WEBPACK_IMPORTED_MODULE_1_lib_selectors_thread_selectors__[\"f\" /* threadInfoSelector */], state => state.messageStore, state => state.currentUserInfo && state.currentUserInfo.id, state => state.userInfos, state => state.navInfo.activeChatThreadID, (threadInfos, messageStore, viewerID, userInfos, activeChatThreadID) => {\n+ if (!activeChatThreadID) {\n+ return null;\n+ }\n+ const threadInfo = threadInfos[activeChatThreadID];\n+ if (!threadInfo) {\n+ return null;\n+ }\n+ return Object(__WEBPACK_IMPORTED_MODULE_2_lib_selectors_chat_selectors__[\"c\" /* createChatThreadItem */])(threadInfo, threadInfos, messageStore, viewerID, userInfos);\n+});\n+\n+const webChatListData = Object(__WEBPACK_IMPORTED_MODULE_0_reselect__[\"createSelector\"])(__WEBPACK_IMPORTED_MODULE_2_lib_selectors_chat_selectors__[\"a\" /* chatListData */], activeChatThreadItem, (data, activeItem) => {\n+ if (!activeItem) {\n+ return data;\n+ }\n+ for (let item of data) {\n+ if (item.threadInfo.id === activeItem.threadInfo.id) {\n+ return data;\n+ }\n+ }\n+ return [activeItem, ...data];\n+});\n+\n+\n+\n/***/ })\n/******/ ]);\n\\ No newline at end of file\n" }, { "change_type": "ADD", "old_path": null, "new_path": "web/selectors/chat-selectors.js", "diff": "+// @flow\n+\n+import type { AppState } from '../redux-setup';\n+import type { ThreadInfo } from 'lib/types/thread-types';\n+import type { MessageStore } from 'lib/types/message-types';\n+import type { UserInfo } from 'lib/types/user-types';\n+\n+import { createSelector } from 'reselect';\n+\n+import { threadInfoSelector } from 'lib/selectors/thread-selectors';\n+import {\n+ type ChatThreadItem,\n+ createChatThreadItem,\n+ chatListData,\n+} from 'lib/selectors/chat-selectors';\n+\n+const activeChatThreadItem = createSelector(\n+ threadInfoSelector,\n+ (state: AppState) => state.messageStore,\n+ (state: AppState) => state.currentUserInfo && state.currentUserInfo.id,\n+ (state: AppState) => state.userInfos,\n+ (state: AppState) => state.navInfo.activeChatThreadID,\n+ (\n+ threadInfos: {[id: string]: ThreadInfo},\n+ messageStore: MessageStore,\n+ viewerID: ?string,\n+ userInfos: {[id: string]: UserInfo},\n+ activeChatThreadID: ?string,\n+ ): ?ChatThreadItem => {\n+ if (!activeChatThreadID) {\n+ return null;\n+ }\n+ const threadInfo = threadInfos[activeChatThreadID];\n+ if (!threadInfo) {\n+ return null;\n+ }\n+ return createChatThreadItem(\n+ threadInfo,\n+ threadInfos,\n+ messageStore,\n+ viewerID,\n+ userInfos,\n+ );\n+ },\n+);\n+\n+const webChatListData = createSelector(\n+ chatListData,\n+ activeChatThreadItem,\n+ (\n+ data: ChatThreadItem[],\n+ activeItem: ?ChatThreadItem,\n+ ): ChatThreadItem[] => {\n+ if (!activeItem) {\n+ return data;\n+ }\n+ for (let item of data) {\n+ if (item.threadInfo.id === activeItem.threadInfo.id) {\n+ return data;\n+ }\n+ }\n+ return [activeItem, ...data];\n+ },\n+);\n+\n+export {\n+ webChatListData,\n+};\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[web] Include currently selected thread in web chat thread list
129,187
11.05.2018 19:53:37
14,400
af97a2e6569af48867d92b970f190161bb426d9d
[server] Verify activeChatThreadID before setting it in navInfo
[ { "change_type": "MODIFY", "old_path": "server/src/responders/website-responders.js", "new_path": "server/src/responders/website-responders.js", "diff": "@@ -34,7 +34,7 @@ import { navInfoFromURL } from 'web/url-utils';\nimport { Viewer } from '../session/viewer';\nimport { handleCodeVerificationRequest } from '../models/verification';\nimport { fetchMessageInfos } from '../fetchers/message-fetchers';\n-import { fetchThreadInfos } from '../fetchers/thread-fetchers';\n+import { verifyThreadID, fetchThreadInfos } from '../fetchers/thread-fetchers';\nimport { fetchEntryInfos } from '../fetchers/entry-fetchers';\nimport { fetchCurrentUserInfo } from '../fetchers/user-fetchers';\nimport { updateActivityTime } from '../updaters/activity-updaters';\n@@ -86,6 +86,12 @@ async function websiteResponder(viewer: Viewer, url: string): Promise<string> {\nmostRecentMessageTimestamp(rawMessageInfos, initialTime),\nthreadInfos,\n);\n+ if (navInfo.activeChatThreadID) {\n+ const validThreadID = await verifyThreadID(navInfo.activeChatThreadID);\n+ if (!validThreadID) {\n+ navInfo.activeChatThreadID = null;\n+ }\n+ }\nif (!navInfo.activeChatThreadID) {\nconst mostRecentThread = mostRecentReadThread(messageStore, threadInfos);\nif (mostRecentThread) {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Verify activeChatThreadID before setting it in navInfo
129,187
14.05.2018 13:44:11
14,400
f3dab9590d426d1c0659e56abc071daea19ebe5d
Use redux-utils everywhere instead of react-redux directly
[ { "change_type": "MODIFY", "old_path": "native/account/logged-out-modal.react.js", "new_path": "native/account/logged-out-modal.react.js", "diff": "@@ -35,13 +35,11 @@ import {\nimport invariant from 'invariant';\nimport Icon from 'react-native-vector-icons/FontAwesome';\nimport OnePassword from 'react-native-onepassword';\n-import { connect } from 'react-redux';\nimport PropTypes from 'prop-types';\nimport { SafeAreaView } from 'react-navigation';\nimport _isEqual from 'lodash/fp/isEqual';\nimport {\n- includeDispatchActionProps,\nfetchNewCookieFromNativeCredentials,\ncreateBoundServerCallsSelector,\n} from 'lib/utils/action-utils';\n@@ -52,6 +50,7 @@ import {\n} from 'lib/actions/user-actions';\nimport sleep from 'lib/utils/sleep';\nimport { dispatchPing } from 'lib/shared/ping-utils';\n+import { connect } from 'lib/utils/redux-utils';\nimport {\nwindowHeight,\n@@ -848,7 +847,8 @@ const LoggedOutModal = connect(\npingActionInput: pingActionInput(state),\ndeviceToken: state.deviceToken,\n}),\n- includeDispatchActionProps,\n+ null,\n+ true,\n)(InnerLoggedOutModal);\nexport {\n" }, { "change_type": "MODIFY", "old_path": "native/calendar/thread-picker.react.js", "new_path": "native/calendar/thread-picker.react.js", "diff": "@@ -8,7 +8,6 @@ import type { DispatchActionPayload } from 'lib/utils/action-utils';\nimport React from 'react';\nimport PropTypes from 'prop-types';\nimport { View, Text, StyleSheet, Platform } from 'react-native';\n-import { connect } from 'react-redux';\nimport invariant from 'invariant';\nimport {\n@@ -18,9 +17,9 @@ import {\ncreateLocalEntry,\ncreateLocalEntryActionType,\n} from 'lib/actions/entry-actions';\n-import { includeDispatchActionProps } from 'lib/utils/action-utils';\nimport { threadSearchIndex } from 'lib/selectors/nav-selectors';\nimport SearchIndex from 'lib/shared/search-index';\n+import { connect } from 'lib/utils/redux-utils';\nimport ThreadList from '../components/thread-list.react';\nimport KeyboardAvoidingModal from '../components/keyboard-avoiding-modal.react';\n@@ -104,5 +103,6 @@ export default connect(\nthreadSearchIndex: threadSearchIndex(state),\n};\n},\n- includeDispatchActionProps,\n+ null,\n+ true,\n)(ThreadPicker);\n" }, { "change_type": "MODIFY", "old_path": "native/chat/robotext-message.react.js", "new_path": "native/chat/robotext-message.react.js", "diff": "@@ -15,12 +15,11 @@ import {\n} from 'react-native';\nimport invariant from 'invariant';\nimport PropTypes from 'prop-types';\n-import { connect } from 'react-redux';\nimport Hyperlink from 'react-native-hyperlink';\nimport { messageKey, robotextToRawString } from 'lib/shared/message-utils';\n-import { includeDispatchActionProps } from 'lib/utils/action-utils';\nimport { threadInfoSelector } from 'lib/selectors/thread-selectors';\n+import { connect } from 'lib/utils/redux-utils';\nimport { MessageListRouteName } from './message-list.react';\n@@ -144,7 +143,8 @@ const ThreadEntity = connect(\n(state: AppState, ownProps: { id: string }) => ({\nthreadInfo: threadInfoSelector(state)[ownProps.id],\n}),\n- includeDispatchActionProps,\n+ null,\n+ true,\n)(InnerThreadEntity);\nfunction ColorEntity(props: {| color: string |}) {\n" }, { "change_type": "MODIFY", "old_path": "native/chat/settings/thread-settings.react.js", "new_path": "native/chat/settings/thread-settings.react.js", "diff": "@@ -16,7 +16,6 @@ import type { AppState } from '../../redux-setup';\nimport type { CategoryType } from './thread-settings-category.react';\nimport React from 'react';\n-import { connect } from 'react-redux';\nimport PropTypes from 'prop-types';\nimport { FlatList, StyleSheet, View } from 'react-native';\nimport Modal from 'react-native-modal';\n@@ -43,6 +42,7 @@ import {\nviewerCanSeeThread,\n} from 'lib/shared/thread-utils';\nimport threadWatcher from 'lib/shared/thread-watcher';\n+import { connect } from 'lib/utils/redux-utils';\nimport {\nThreadSettingsCategoryHeader,\n@@ -790,7 +790,7 @@ const somethingIsSaving = (\nconst ThreadSettingsRouteName = 'ThreadSettings';\nconst ThreadSettings = connect(\n- (state: AppState, ownProps: { navigation: NavProp }): * => {\n+ (state: AppState, ownProps: { navigation: NavProp }) => {\nconst threadID = ownProps.navigation.state.params.threadInfo.id;\nconst threadMembers =\nrelativeMemberInfoSelectorForMembersOfThread(threadID)(state);\n" }, { "change_type": "MODIFY", "old_path": "native/connected-status-bar.react.js", "new_path": "native/connected-status-bar.react.js", "diff": "@@ -4,11 +4,11 @@ import type { AppState } from './redux-setup';\nimport type { LoadingStatus } from 'lib/types/loading-types';\nimport React from 'react';\n-import { connect } from 'react-redux';\nimport { StatusBar } from 'react-native';\nimport PropTypes from 'prop-types';\nimport { globalLoadingStatusSelector } from 'lib/selectors/loading-selectors';\n+import { connect } from 'lib/utils/redux-utils';\ntype InjectedProps = {\nglobalLoadingStatus: LoadingStatus,\n" }, { "change_type": "MODIFY", "old_path": "native/navigation-setup.js", "new_path": "native/navigation-setup.js", "diff": "@@ -31,7 +31,6 @@ import _includes from 'lodash/fp/includes';\nimport { Alert, BackHandler, Platform } from 'react-native';\nimport React from 'react';\nimport PropTypes from 'prop-types';\n-import { connect } from 'react-redux';\nimport { infoFromURL } from 'lib/utils/url-utils';\nimport { fifteenDaysEarlier, fifteenDaysLater } from 'lib/utils/date-utils';\n@@ -52,6 +51,7 @@ import {\n} from 'lib/actions/thread-actions';\nimport { notificationPressActionType } from 'lib/shared/notif-utils';\nimport { threadInfoFromRawThreadInfo } from 'lib/shared/thread-utils';\n+import { connect } from 'lib/utils/redux-utils';\nimport {\nCalendar,\n@@ -186,7 +186,7 @@ class WrappedAppNavigator\n}\nconst AppRouteName = 'App';\nconst isForegroundSelector = createIsForegroundSelector(AppRouteName);\n-const ReduxWrappedAppNavigator = connect((state: AppState): * => {\n+const ReduxWrappedAppNavigator = connect((state: AppState) => {\nconst appNavState = state.navInfo.navigationState.routes[0];\ninvariant(\nappNavState.index !== undefined &&\n" }, { "change_type": "MODIFY", "old_path": "web/calendar/thread-picker.react.js", "new_path": "web/calendar/thread-picker.react.js", "diff": "@@ -5,13 +5,13 @@ import { threadInfoPropType } from 'lib/types/thread-types';\nimport type { AppState } from '../redux-setup';\nimport * as React from 'react';\n-import { connect } from 'react-redux';\nimport invariant from 'invariant';\nimport PropTypes from 'prop-types';\nimport {\nonScreenEntryEditableThreadInfos,\n} from 'lib/selectors/thread-selectors';\n+import { connect } from 'lib/utils/redux-utils';\nimport css from '../style.css';\nimport { LeftPager, RightPager } from '../vectors.react';\n@@ -211,6 +211,6 @@ ThreadPicker.propTypes = {\nclosePicker: PropTypes.func.isRequired,\n};\n-export default connect((state: AppState): * => ({\n+export default connect((state: AppState) => ({\nonScreenThreadInfos: onScreenEntryEditableThreadInfos(state),\n}))(ThreadPicker);\n" }, { "change_type": "MODIFY", "old_path": "web/modals/history/history-revision.react.js", "new_path": "web/modals/history/history-revision.react.js", "diff": "@@ -10,12 +10,12 @@ import * as React from 'react';\nimport classNames from 'classnames';\nimport invariant from 'invariant';\nimport dateFormat from 'dateformat';\n-import { connect } from 'react-redux';\nimport PropTypes from 'prop-types';\nimport TimeAgo from 'react-timeago';\nimport { colorIsDark } from 'lib/shared/thread-utils';\nimport { threadInfoSelector } from 'lib/selectors/thread-selectors';\n+import { connect } from 'lib/utils/redux-utils';\nimport css from '../../style.css';\n@@ -81,6 +81,6 @@ HistoryRevision.propTypes = {\n};\ntype OwnProps = { revisionInfo: HistoryRevisionInfo };\n-export default connect((state: AppState, ownProps: OwnProps): * => ({\n+export default connect((state: AppState, ownProps: OwnProps) => ({\nthreadInfo: threadInfoSelector(state)[ownProps.revisionInfo.threadID],\n}))(HistoryRevision);\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Use redux-utils everywhere instead of react-redux directly
129,187
14.05.2018 14:47:28
14,400
5a82b7678d412a7369d5e69f77ea792f31fc3cbd
[native] Fix some lodash uses and update libdef with my own changes
[ { "change_type": "MODIFY", "old_path": "lib/flow-typed/npm/lodash_v4.x.x.js", "new_path": "lib/flow-typed/npm/lodash_v4.x.x.js", "diff": "@@ -1636,17 +1636,17 @@ declare module \"lodash/fp\" {\narray: $ReadOnlyArray<T>\n): T[];\ndifferenceWith<T>(\n- values: $ReadOnly<T>\n- ): ((comparator: Comparator<T>) => (array: $ReadOnly<T>) => T[]) &\n- ((comparator: Comparator<T>, array: $ReadOnly<T>) => T[]);\n+ comparator: Comparator<T>,\n+ ): ((first: $ReadOnly<T>) => (second: $ReadOnly<T>) => T[]) &\n+ ((first: $ReadOnly<T>, second: $ReadOnly<T>) => T[]);\ndifferenceWith<T>(\n- values: $ReadOnly<T>,\n- comparator: Comparator<T>\n- ): (array: $ReadOnly<T>) => T[];\n+ comparator: Comparator<T>,\n+ first: $ReadOnly<T>,\n+ ): (second: $ReadOnly<T>) => T[];\ndifferenceWith<T>(\n- values: $ReadOnly<T>,\ncomparator: Comparator<T>,\n- array: $ReadOnly<T>\n+ first: $ReadOnly<T>,\n+ second: $ReadOnly<T>\n): T[];\ndrop<T>(n: number): (array: Array<T>) => Array<T>;\ndrop<T>(n: number, array: Array<T>): Array<T>;\n@@ -2017,10 +2017,10 @@ declare module \"lodash/fp\" {\n): boolean;\nfilter<T>(\npredicate: Predicate<T> | OPredicate<T>\n- ): (collection: Array<T> | { [id: any]: T }) => Array<T>;\n+ ): (collection: $ReadOnlyArray<T> | { [id: any]: T }) => Array<T>;\nfilter<T>(\npredicate: Predicate<T> | OPredicate<T>,\n- collection: Array<T> | { [id: any]: T }\n+ collection: $ReadOnlyArray<T> | { [id: any]: T }\n): Array<T>;\nfind<T>(\npredicate: Predicate<T> | OPredicate<T>\n@@ -2186,10 +2186,10 @@ declare module \"lodash/fp\" {\n): { [key: V]: T };\nmap<T, U>(\niteratee: MapIterator<T, U> | OMapIterator<T, U>\n- ): (collection: Array<T> | { [id: any]: T }) => Array<U>;\n+ ): (collection: $ReadOnlyArray<T> | { [id: any]: T }) => Array<U>;\nmap<T, U>(\niteratee: MapIterator<T, U> | OMapIterator<T, U>,\n- collection: Array<T> | { [id: any]: T }\n+ collection: $ReadOnlyArray<T> | { [id: any]: T }\n): Array<U>;\nmap(iteratee: (char: string) => any): (str: string) => string;\nmap(iteratee: (char: string) => any, str: string): string;\n" }, { "change_type": "MODIFY", "old_path": "native/calendar/calendar.react.js", "new_path": "native/calendar/calendar.react.js", "diff": "@@ -555,9 +555,9 @@ class InnerCalendar extends React.PureComponent<Props, State> {\nif (animated === undefined) {\nanimated = this.props.tabActive;\n}\n- invariant(this.state.listDataWithHeights, \"should be set\");\n- const todayIndex = _findIndex(['dateString', dateString(new Date())])\n- (this.state.listDataWithHeights);\n+ const ldwh = this.state.listDataWithHeights;\n+ invariant(ldwh, \"should be set\");\n+ const todayIndex = _findIndex(['dateString', dateString(new Date())])(ldwh);\ninvariant(this.flatList, \"flatList should be set\");\nthis.flatList.scrollToIndex({\nindex: todayIndex,\n@@ -921,6 +921,14 @@ class InnerCalendar extends React.PureComponent<Props, State> {\nviewableItems: ViewToken[],\nchanged: ViewToken[],\n}) => {\n+ const ldwh = this.state.listDataWithHeights;\n+ if (!ldwh) {\n+ // This indicates the listData was cleared (set to null) right before this\n+ // callback was called. Since this leads to the FlatList getting cleared,\n+ // we'll just ignore this callback.\n+ return;\n+ }\n+\nconst visibleEntries = {};\nfor (let token of info.viewableItems) {\nif (token.item.itemType === \"entryInfo\") {\n@@ -930,10 +938,13 @@ class InnerCalendar extends React.PureComponent<Props, State> {\nthis.latestExtraData = {\nactiveEntries: _pickBy(\n(_, key: string) => {\n+ if (visibleEntries[key]) {\n+ return true;\n+ }\nconst item = _find\n(item => item.entryInfo && entryKey(item.entryInfo) === key)\n- (this.state.listDataWithHeights);\n- return visibleEntries[key] || (item && !item.id);\n+ (ldwh);\n+ return item && !item.id && true;\n},\n)(this.latestExtraData.activeEntries),\nvisibleEntries,\n" }, { "change_type": "MODIFY", "old_path": "native/flow-typed/npm/lodash_v4.x.x.js", "new_path": "native/flow-typed/npm/lodash_v4.x.x.js", "diff": "@@ -1646,14 +1646,18 @@ declare module \"lodash/fp\" {\narray: $ReadOnlyArray<T>\n): T[];\ndifferenceWith<T>(\n- values: $ReadOnlyArray<T>\n- ): ((comparator: Comparator<T>) => (array: $ReadOnlyArray<T>) => T[]) &\n- ((comparator: Comparator<T>, array: $ReadOnlyArray<T>) => T[]);\n+ comparator: Comparator<T>,\n+ ): ((first: $ReadOnly<T>) => (second: $ReadOnly<T>) => T[]) &\n+ ((first: $ReadOnly<T>, second: $ReadOnly<T>) => T[]);\ndifferenceWith<T>(\n- values: $ReadOnlyArray<T>,\n- comparator: Comparator<T>\n- ): (array: $ReadOnlyArray<T>) => T[];\n- differenceWith<T>(values: $ReadOnlyArray<T>, comparator: Comparator<T>, array: $ReadOnlyArray<T>): T[];\n+ comparator: Comparator<T>,\n+ first: $ReadOnly<T>,\n+ ): (second: $ReadOnly<T>) => T[];\n+ differenceWith<T>(\n+ comparator: Comparator<T>,\n+ first: $ReadOnly<T>,\n+ second: $ReadOnly<T>\n+ ): T[];\ndrop<T>(n: number): (array: Array<T>) => Array<T>;\ndrop<T>(n: number, array: Array<T>): Array<T>;\ndropLast<T>(n: number): (array: Array<T>) => Array<T>;\n@@ -2023,10 +2027,10 @@ declare module \"lodash/fp\" {\n): boolean;\nfilter<T>(\npredicate: Predicate<T> | OPredicate<T>\n- ): (collection: Array<T> | { [id: any]: T }) => Array<T>;\n+ ): (collection: $ReadOnlyArray<T> | { [id: any]: T }) => Array<T>;\nfilter<T>(\npredicate: Predicate<T> | OPredicate<T>,\n- collection: Array<T> | { [id: any]: T }\n+ collection: $ReadOnlyArray<T> | { [id: any]: T }\n): Array<T>;\nfind<T>(\npredicate: Predicate<T> | OPredicate<T>\n@@ -2194,10 +2198,10 @@ declare module \"lodash/fp\" {\n): { [key: V]: T };\nmap<T, U>(\niteratee: MapIterator<T, U> | OMapIterator<T, U>\n- ): (collection: Array<T> | { [id: any]: T }) => Array<U>;\n+ ): (collection: $ReadOnlyArray<T> | { [id: any]: T }) => Array<U>;\nmap<T, U>(\niteratee: MapIterator<T, U> | OMapIterator<T, U>,\n- collection: Array<T> | { [id: any]: T }\n+ collection: $ReadOnlyArray<T> | { [id: any]: T }\n): Array<U>;\nmap(iteratee: (char: string) => any): (str: string) => string;\nmap(iteratee: (char: string) => any, str: string): string;\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Fix some lodash uses and update libdef with my own changes
129,187
14.05.2018 14:52:39
14,400
c9336f696bd6b78471caa305ed41ec20473b8b9f
[native] Fix up navigation param types
[ { "change_type": "MODIFY", "old_path": "native/account/verification-modal.react.js", "new_path": "native/account/verification-modal.react.js", "diff": "@@ -62,8 +62,9 @@ const forceInset = { top: 'always', bottom: 'always' };\ntype VerificationModalMode = \"simple-text\" | \"reset-password\";\ntype Props = {\n- navigation: NavigationScreenProp<NavigationLeafRoute>\n- & { state: { params: { verifyCode: string } } },\n+ navigation:\n+ & { state: { params: { verifyCode: string } } }\n+ & NavigationScreenProp<NavigationLeafRoute>,\n// Redux state\nisForeground: bool,\n// Redux dispatch functions\n" }, { "change_type": "MODIFY", "old_path": "native/chat/compose-thread.react.js", "new_path": "native/chat/compose-thread.react.js", "diff": "@@ -69,12 +69,17 @@ const tagInputProps = {\n};\ntype NavProp =\n- & NavigationScreenProp<NavigationRoute>\n- & { state: { params: {\n+ & {\n+ state: {\n+ params: {\nthreadType?: ThreadType,\nparentThreadID?: string,\ncreateButtonDisabled?: bool,\n- } } };\n+ },\n+ key: string,\n+ },\n+ }\n+ & NavigationScreenProp<NavigationRoute>;\nlet queuedPress = false;\nfunction setQueuedPress() {\n" }, { "change_type": "MODIFY", "old_path": "native/chat/message-list.react.js", "new_path": "native/chat/message-list.react.js", "diff": "@@ -58,8 +58,14 @@ import { registerChatScreen } from './chat-screen-registry';\nimport ThreadSettingsButton from './thread-settings-button.react';\nimport KeyboardAvoidingView from '../components/keyboard-avoiding-view.react';\n-type NavProp = NavigationScreenProp<NavigationRoute>\n- & { state: { params: { threadInfo: ThreadInfo } } };\n+type NavProp =\n+ & {\n+ state: {\n+ params: { threadInfo: ThreadInfo },\n+ key: string,\n+ },\n+ }\n+ & NavigationScreenProp<NavigationRoute>;\nexport type RobotextChatMessageInfoItemWithHeight = {|\nitemType: \"message\",\n" }, { "change_type": "MODIFY", "old_path": "native/chat/settings/delete-thread.react.js", "new_path": "native/chat/settings/delete-thread.react.js", "diff": "@@ -38,8 +38,9 @@ import { threadInfoSelector } from 'lib/selectors/thread-selectors';\nimport Button from '../../components/button.react';\nimport OnePasswordButton from '../../components/one-password-button.react';\n-type NavProp = NavigationScreenProp<NavigationRoute>\n- & { state: { params: { threadInfo: ThreadInfo } } };\n+type NavProp =\n+ & { state: { params: { threadInfo: ThreadInfo } } }\n+ & NavigationScreenProp<NavigationRoute>;\ntype Props = {|\nnavigation: NavProp,\n" }, { "change_type": "MODIFY", "old_path": "native/chat/settings/thread-settings.react.js", "new_path": "native/chat/settings/thread-settings.react.js", "diff": "@@ -69,8 +69,14 @@ import ThreadSettingsDeleteThread from './thread-settings-delete-thread.react';\nconst itemPageLength = 5;\n-type NavProp = NavigationScreenProp<NavigationRoute>\n- & { state: { params: { threadInfo: ThreadInfo } } };\n+type NavProp =\n+ & {\n+ state: {\n+ params: { threadInfo: ThreadInfo },\n+ key: string,\n+ },\n+ }\n+ & NavigationScreenProp<NavigationRoute>;\ntype ChatSettingsItem =\n| {|\nitemType: \"header\",\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Fix up navigation param types
129,187
14.05.2018 15:17:08
14,400
357c3dd9c579ca0c316251d42780009818d2b910
[native] Fix up CalendarItem -> CalendarItemWithHeight logic
[ { "change_type": "MODIFY", "old_path": "lib/shared/entry-utils.js", "new_path": "lib/shared/entry-utils.js", "diff": "@@ -17,15 +17,15 @@ import {\nfilterExists,\n} from '../selectors/calendar-filter-selectors';\n-function entryKey(entryInfo: EntryInfo | RawEntryInfo): string {\n+type HasEntryIDs = { localID?: string, id?: string };\n+function entryKey(entryInfo: HasEntryIDs): string {\nif (entryInfo.localID) {\nreturn entryInfo.localID;\n}\ninvariant(entryInfo.id, \"localID should exist if ID does not\");\nreturn entryInfo.id;\n}\n-\n-function entryID(entryInfo: EntryInfo | RawEntryInfo): string {\n+function entryID(entryInfo: HasEntryIDs): string {\nif (entryInfo.id) {\nreturn entryInfo.id;\n}\n" }, { "change_type": "MODIFY", "old_path": "native/calendar/calendar.react.js", "new_path": "native/calendar/calendar.react.js", "diff": "@@ -7,7 +7,12 @@ import {\ntype CalendarResult,\n} from 'lib/types/entry-types';\nimport type { AppState } from '../redux-setup';\n-import type { CalendarItem } from '../selectors/calendar-selectors';\n+import type {\n+ CalendarItem,\n+ SectionHeaderItem,\n+ SectionFooterItem,\n+ LoaderItem,\n+} from '../selectors/calendar-selectors';\nimport type { ViewToken } from 'react-native/Libraries/Lists/ViewabilityHelper';\nimport type { DispatchActionPromise } from 'lib/utils/action-utils';\nimport type { KeyboardEvent } from '../keyboard';\n@@ -72,23 +77,18 @@ import {\n} from '../keyboard';\nimport KeyboardAvoidingView from '../components/keyboard-avoiding-view.react';\n-export type EntryInfoWithHeight = EntryInfo & { textHeight: number };\n-type SectionHeaderItem = {|\n- itemType: \"header\",\n- dateString: string,\n-|};\n-type SectionFooterItem = {|\n- itemType: \"footer\",\n- dateString: string,\n+export type EntryInfoWithHeight = {|\n+ ...EntryInfo,\n+ textHeight: number,\n|};\ntype CalendarItemWithHeight =\n- {|\n- itemType: \"loader\",\n- key: string,\n- |} | SectionHeaderItem | {|\n+ | LoaderItem\n+ | SectionHeaderItem\n+ | SectionFooterItem\n+ | {|\nitemType: \"entryInfo\",\nentryInfo: EntryInfoWithHeight,\n- |} | SectionFooterItem;\n+ |};\ntype ExtraData = {\nactiveEntries: {[key: string]: bool},\nvisibleEntries: {[key: string]: bool},\n@@ -516,6 +516,54 @@ class InnerCalendar extends React.PureComponent<Props, State> {\n}\n}\n+ static entryInfoWithHeight(\n+ entryInfo: EntryInfo,\n+ textHeight: number,\n+ ): EntryInfoWithHeight {\n+ // Blame Flow for not accepting object spread on exact types\n+ if (entryInfo.id && entryInfo.localID) {\n+ return {\n+ id: entryInfo.id,\n+ localID: entryInfo.localID,\n+ threadID: entryInfo.threadID,\n+ text: entryInfo.text,\n+ year: entryInfo.year,\n+ month: entryInfo.month,\n+ day: entryInfo.day,\n+ creationTime: entryInfo.creationTime,\n+ creator: entryInfo.creator,\n+ deleted: entryInfo.deleted,\n+ textHeight: Math.ceil(textHeight),\n+ };\n+ } else if (entryInfo.id) {\n+ return {\n+ id: entryInfo.id,\n+ threadID: entryInfo.threadID,\n+ text: entryInfo.text,\n+ year: entryInfo.year,\n+ month: entryInfo.month,\n+ day: entryInfo.day,\n+ creationTime: entryInfo.creationTime,\n+ creator: entryInfo.creator,\n+ deleted: entryInfo.deleted,\n+ textHeight: Math.ceil(textHeight),\n+ };\n+ } else {\n+ return {\n+ localID: entryInfo.localID,\n+ threadID: entryInfo.threadID,\n+ text: entryInfo.text,\n+ year: entryInfo.year,\n+ month: entryInfo.month,\n+ day: entryInfo.day,\n+ creationTime: entryInfo.creationTime,\n+ creator: entryInfo.creator,\n+ deleted: entryInfo.deleted,\n+ textHeight: Math.ceil(textHeight),\n+ };\n+ }\n+ }\n+\nmergeHeightsIntoListData(listData: $ReadOnlyArray<CalendarItem>) {\nconst textHeights = this.textHeights;\ninvariant(textHeights, \"textHeights should be set\");\n@@ -530,11 +578,11 @@ class InnerCalendar extends React.PureComponent<Props, State> {\n`height for ${entryKey(entryInfo)} should be set`,\n);\nreturn {\n- ...item,\n- entryInfo: {\n- ...item.entryInfo,\n- textHeight: Math.ceil(textHeight),\n- },\n+ itemType: \"entryInfo\",\n+ entryInfo: InnerCalendar.entryInfoWithHeight(\n+ item.entryInfo,\n+ textHeight,\n+ ),\n};\n})(listData);\nif (\n" }, { "change_type": "MODIFY", "old_path": "native/selectors/calendar-selectors.js", "new_path": "native/selectors/calendar-selectors.js", "diff": "@@ -11,20 +11,26 @@ import invariant from 'invariant';\nimport { currentDaysToEntries } from 'lib/selectors/thread-selectors';\nimport { dateString } from 'lib/utils/date-utils';\n-export type CalendarItem =\n- {\n- itemType: \"loader\",\n- key: string,\n- } | {\n+export type SectionHeaderItem = {|\nitemType: \"header\",\ndateString: string,\n- } | {\n- itemType: \"entryInfo\",\n- entryInfo: EntryInfo,\n- } | {\n+|};\n+export type SectionFooterItem = {|\nitemType: \"footer\",\ndateString: string,\n- };\n+|};\n+export type LoaderItem = {|\n+ itemType: \"loader\",\n+ key: string,\n+|};\n+export type CalendarItem =\n+ | LoaderItem\n+ | SectionHeaderItem\n+ | SectionFooterItem\n+ | {|\n+ itemType: \"entryInfo\",\n+ entryInfo: EntryInfo,\n+ |};\nconst calendarListData = createSelector(\n(state: AppState) => !!(state.currentUserInfo &&\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Fix up CalendarItem -> CalendarItemWithHeight logic
129,187
15.05.2018 14:11:17
14,400
8aba5cd3d48183b3faebcad50fa1ff9c9cdc1aa1
Finish updating react-native metro got weird, and now we need to use more packages to make things work. Sigh.
[ { "change_type": "MODIFY", "old_path": "lib/package.json", "new_path": "lib/package.json", "diff": "\"flow-bin\": \"^0.64.0\"\n},\n\"scripts\": {\n- \"postinstall\": \"cd ../; npx flow-mono create-symlinks lib/.flowconfig\",\n\"flow\": \"flow; test $? -eq 0 -o $? -eq 2\"\n},\n\"dependencies\": {\n" }, { "change_type": "MODIFY", "old_path": "native/components/keyboard-avoiding-view.react.js", "new_path": "native/components/keyboard-avoiding-view.react.js", "diff": "@@ -38,8 +38,6 @@ type KeyboardChangeEvent = {\neasing?: string,\n};\n-const viewRef = 'VIEW';\n-\ntype Props = {|\nchildren?: React.Node,\nstyle?: ViewStyle,\n@@ -150,7 +148,6 @@ class KeyboardAvoidingView extends React.PureComponent<Props, State> {\nconst paddingStyle = { paddingBottom: this.state.bottom };\nreturn (\n<View\n- ref={viewRef}\nstyle={[style, paddingStyle]}\nonLayout={this.onLayout}\n{...props}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "native/link-workspaces.js", "diff": "+require('crna-make-symlinks-for-yarn-workspaces')(__dirname);\n" }, { "change_type": "MODIFY", "old_path": "native/package.json", "new_path": "native/package.json", "diff": "\"version\": \"0.0.1\",\n\"private\": true,\n\"scripts\": {\n- \"postinstall\": \"cd ../; npx flow-mono create-symlinks native/.flowconfig\",\n+ \"postinstall\": \"node link-workspaces.js && cd ../; npx flow-mono create-symlinks native/.flowconfig\",\n\"start\": \"node node_modules/react-native/local-cli/cli.js start\",\n\"test\": \"jest\",\n\"devtools\": \"react-devtools\",\n\"babel-plugin-transform-remove-console\": \"^6.8.5\",\n\"babel-plugin-transform-remove-strict-mode\": \"0.0.2\",\n\"babel-preset-react-native\": \"^4.0.0\",\n+ \"crna-make-symlinks-for-yarn-workspaces\": \"^1.0.1\",\n\"flow-bin\": \"^0.67.1\",\n\"jest\": \"^20.0.4\",\n+ \"metro-bundler-config-yarn-workspaces\": \"^1.0.3\",\n\"react-devtools\": \"^3.0.0\",\n\"react-test-renderer\": \"^15.6.1\"\n},\n" }, { "change_type": "ADD", "old_path": null, "new_path": "native/rn-cli.config.js", "diff": "+const getConfig = require('metro-bundler-config-yarn-workspaces');\n+module.exports = getConfig(__dirname);\n" }, { "change_type": "MODIFY", "old_path": "server/package.json", "new_path": "server/package.json", "diff": "\"description\": \"\",\n\"main\": \"dist/server\",\n\"scripts\": {\n- \"postinstall\": \"cd ../; npx flow-mono create-symlinks server/.flowconfig\",\n\"babel\": \"babel src/ --out-dir dist/ --ignore 'lib/flow-typed','lib/node_modules','lib/package.json','web/flow-typed','web/node_modules','web/package.json','web/dist/hot','web/dist/dev.build.js','web/dist/prod.build.js','web/dist/prod.build.css','web/webpack.config.js' --copy-files\",\n\"prod\": \"node --experimental-modules --loader ./loader.mjs dist/server\",\n\"dev\": \"NODE_ENV=dev concurrently \\\"npm run babel -- --watch\\\" \\\"nodemon -e js,json --watch dist --experimental-modules --loader ./loader.mjs dist/server\\\"\"\n" }, { "change_type": "MODIFY", "old_path": "web/package.json", "new_path": "web/package.json", "diff": "\"webpack-dev-server\": \"^2.5.0\"\n},\n\"scripts\": {\n- \"postinstall\": \"cd ../; npx flow-mono create-symlinks web/.flowconfig\",\n\"dev\": \"concurrently \\\"webpack --env dev --progress --watch\\\" \\\"webpack-dev-server\\\"\",\n\"prod\": \"webpack --env prod --progress\",\n\"flow\": \"flow; test $? -eq 0 -o $? -eq 2\"\n" }, { "change_type": "MODIFY", "old_path": "yarn.lock", "new_path": "yarn.lock", "diff": "@@ -2707,6 +2707,13 @@ create-react-class@^15.6.3:\nloose-envify \"^1.3.1\"\nobject-assign \"^4.1.1\"\n+crna-make-symlinks-for-yarn-workspaces@^1.0.1:\n+ version \"1.0.1\"\n+ resolved \"https://registry.yarnpkg.com/crna-make-symlinks-for-yarn-workspaces/-/crna-make-symlinks-for-yarn-workspaces-1.0.1.tgz#5ad86caac2389daceec22978a0e30c969d55e3c6\"\n+ dependencies:\n+ find-root \"^1.1.0\"\n+ fs-extra \"^5.0.0\"\n+\ncron-parser@^2.4.0:\nversion \"2.4.5\"\nresolved \"https://registry.yarnpkg.com/cron-parser/-/cron-parser-2.4.5.tgz#33629810a4b491004c363f4b6996133bbc22e16f\"\n@@ -3806,6 +3813,10 @@ find-config-up@1.1.0:\nfind-up \"^2.1.0\"\nlodash \"^4.17.4\"\n+find-root@^1.1.0:\n+ version \"1.1.0\"\n+ resolved \"https://registry.yarnpkg.com/find-root/-/find-root-1.1.0.tgz#abcfc8ba76f708c42a97b3d685b7e9450bfb9ce4\"\n+\nfind-up@2.1.0, find-up@^2.0.0, find-up@^2.1.0:\nversion \"2.1.0\"\nresolved \"https://registry.yarnpkg.com/find-up/-/find-up-2.1.0.tgz#45d1b7e506c717ddd482775a2b77920a3c0c57a7\"\n@@ -4067,6 +4078,14 @@ get-value@^2.0.3, get-value@^2.0.6:\nversion \"2.0.6\"\nresolved \"https://registry.yarnpkg.com/get-value/-/get-value-2.0.6.tgz#dc15ca1c672387ca76bd37ac0a395ba2042a2c28\"\n+get-yarn-workspaces@^1.0.0:\n+ version \"1.0.2\"\n+ resolved \"https://registry.yarnpkg.com/get-yarn-workspaces/-/get-yarn-workspaces-1.0.2.tgz#81591bdb392f1c6bac09cdc8491a6d275781aa44\"\n+ dependencies:\n+ find-root \"^1.1.0\"\n+ flatten \"^1.0.2\"\n+ glob \"^7.1.2\"\n+\ngetpass@^0.1.1:\nversion \"0.1.7\"\nresolved \"https://registry.yarnpkg.com/getpass/-/getpass-0.1.7.tgz#5eff8e3e684d569ae4cb2b1282604e8ba62149fa\"\n@@ -6078,6 +6097,12 @@ metro-babylon7@0.30.2:\ndependencies:\nbabylon \"^7.0.0-beta\"\n+metro-bundler-config-yarn-workspaces@^1.0.3:\n+ version \"1.0.3\"\n+ resolved \"https://registry.yarnpkg.com/metro-bundler-config-yarn-workspaces/-/metro-bundler-config-yarn-workspaces-1.0.3.tgz#160ba7db8856fe218b866e5e4d2b2c9ac51203bd\"\n+ dependencies:\n+ get-yarn-workspaces \"^1.0.0\"\n+\nmetro-cache@0.30.2:\nversion \"0.30.2\"\nresolved \"https://registry.yarnpkg.com/metro-cache/-/metro-cache-0.30.2.tgz#1fb1ff92d3d8c596fd8cddc1635a9cb1c26e4cba\"\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Finish updating react-native metro got weird, and now we need to use more packages to make things work. Sigh.
129,187
16.05.2018 11:44:14
14,400
189f76840ba5fbfe06f31c2619f27a44cb7718bc
[native] Use react-navigation@2.0's new "less pushy" navigate We no longer have to check if the current route is active before `navigate`, as `react-navigation` will handle duplicates as long as we specify the correct `key`.
[ { "change_type": "MODIFY", "old_path": "native/calendar/entry.react.js", "new_path": "native/calendar/entry.react.js", "diff": "@@ -16,7 +16,10 @@ import type {\nDispatchActionPromise,\n} from 'lib/utils/action-utils';\nimport type { LoadingStatus } from 'lib/types/loading-types';\n-import type { NavigationParams, NavigationAction } from 'react-navigation';\n+import type {\n+ NavigationParams,\n+ NavigationNavigateAction,\n+} from 'react-navigation';\nimport * as React from 'react';\nimport {\n@@ -65,10 +68,6 @@ import { dateString } from 'lib/utils/date-utils';\nimport Button from '../components/button.react';\nimport { ChatRouteName } from '../chat/chat.react';\nimport { MessageListRouteName } from '../chat/message-list.react';\n-import {\n- assertNavigationRouteNotLeafNode,\n- getThreadIDFromParams,\n-} from '../utils/navigation-utils';\ntype Props = {\nentryInfo: EntryInfoWithHeight,\n@@ -76,11 +75,12 @@ type Props = {\nactive: bool,\nmakeActive: (entryKey: string, active: bool) => void,\nonEnterEditMode: (entryInfo: EntryInfoWithHeight) => void,\n- navigate: (\n+ navigate: ({\nrouteName: string,\nparams?: NavigationParams,\n- action?: NavigationAction,\n- ) => bool,\n+ action?: NavigationNavigateAction,\n+ key?: string,\n+ }) => bool,\nonPressWhitespace: () => void,\nentryRef: (entryKey: string, entry: ?InternalEntry) => void,\n// Redux state\n@@ -88,7 +88,6 @@ type Props = {\nsessionStartingPayload: () => { newSessionID?: string },\nsessionID: () => string,\nnextSessionID: () => ?string,\n- currentChatThreadID: ?string,\n// Redux dispatch functions\ndispatchActionPayload: DispatchActionPayload,\ndispatchActionPromise: DispatchActionPromise,\n@@ -123,7 +122,6 @@ class InternalEntry extends React.Component<Props, State> {\nsessionStartingPayload: PropTypes.func.isRequired,\nsessionID: PropTypes.func.isRequired,\nnextSessionID: PropTypes.func.isRequired,\n- currentChatThreadID: PropTypes.string,\ndispatchActionPayload: PropTypes.func.isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\ncreateEntry: PropTypes.func.isRequired,\n@@ -594,20 +592,16 @@ class InternalEntry extends React.Component<Props, State> {\nonPressThreadName = () => {\nKeyboard.dismiss();\n- if (this.props.currentChatThreadID === this.props.threadInfo.id) {\n- this.props.navigate(ChatRouteName);\n- return;\n- }\n- this.props.navigate(\n- ChatRouteName,\n- {},\n- NavigationActions.navigate({\n+ const threadInfo = this.props.threadInfo;\n+ this.props.navigate({\n+ routeName: ChatRouteName,\n+ params: {},\n+ action: NavigationActions.navigate({\nrouteName: MessageListRouteName,\n- params: {\n- threadInfo: this.props.threadInfo,\n- },\n- })\n- );\n+ params: { threadInfo },\n+ key: `${MessageListRouteName}${threadInfo.id}`,\n+ }),\n+ });\n}\n}\n@@ -693,23 +687,12 @@ registerFetchKey(saveEntryActionTypes);\nregisterFetchKey(deleteEntryActionTypes);\nconst Entry = connect(\n- (state: AppState, ownProps: { entryInfo: EntryInfoWithHeight }) => {\n- const appRoute =\n- assertNavigationRouteNotLeafNode(state.navInfo.navigationState.routes[0]);\n- const chatRoute = assertNavigationRouteNotLeafNode(appRoute.routes[1]);\n- const currentChatSubroute = chatRoute.routes[chatRoute.index];\n- const currentChatThreadID =\n- currentChatSubroute.routeName === MessageListRouteName\n- ? getThreadIDFromParams(currentChatSubroute)\n- : null;\n- return {\n+ (state: AppState, ownProps: { entryInfo: EntryInfoWithHeight }) => ({\nthreadInfo: threadInfoSelector(state)[ownProps.entryInfo.threadID],\nsessionStartingPayload: sessionStartingPayload(state),\nsessionID: currentSessionID(state),\nnextSessionID: nextSessionID(state),\n- currentChatThreadID,\n- };\n- },\n+ }),\n{ createEntry, saveEntry, deleteEntry },\n)(InternalEntry);\n" }, { "change_type": "MODIFY", "old_path": "native/chat/chat-thread-list.react.js", "new_path": "native/chat/chat-thread-list.react.js", "diff": "@@ -35,7 +35,6 @@ import ComposeThreadButton from './compose-thread-button.react';\nimport { registerChatScreen } from './chat-screen-registry';\nimport { ComposeThreadRouteName } from './compose-thread.react';\nimport KeyboardAvoidingView from '../components/keyboard-avoiding-view.react';\n-import { assertNavigationRouteNotLeafNode } from '../utils/navigation-utils';\nconst floatingActions = [{\ntext: 'Compose',\n@@ -52,7 +51,6 @@ type Props = {|\nchatListData: $ReadOnlyArray<ChatThreadItem>,\nviewerID: ?string,\nthreadSearchIndex: SearchIndex,\n- active: bool,\n|};\ntype State = {|\nlistData: $ReadOnlyArray<Item>,\n@@ -71,7 +69,6 @@ class InnerChatThreadList extends React.PureComponent<Props, State> {\nchatListData: PropTypes.arrayOf(chatThreadItemPropType).isRequired,\nviewerID: PropTypes.string,\nthreadSearchIndex: PropTypes.instanceOf(SearchIndex).isRequired,\n- active: PropTypes.bool.isRequired,\n};\nstatic navigationOptions = ({ navigation }) => ({\ntitle: 'Threads',\n@@ -269,23 +266,22 @@ class InnerChatThreadList extends React.PureComponent<Props, State> {\n}\nonPressItem = (threadInfo: ThreadInfo) => {\n- if (!this.props.active) {\n- return;\n- }\nthis.clearSearch();\nif (this.searchInput) {\nthis.searchInput.blur();\n}\n- this.props.navigation.navigate(\n- MessageListRouteName,\n- { threadInfo },\n- );\n+ this.props.navigation.navigate({\n+ routeName: MessageListRouteName,\n+ params: { threadInfo },\n+ key: `${MessageListRouteName}${threadInfo.id}`,\n+ });\n}\ncomposeThread = () => {\n- if (this.props.active) {\n- this.props.navigation.navigate(ComposeThreadRouteName, {});\n- }\n+ this.props.navigation.navigate({\n+ routeName: ComposeThreadRouteName,\n+ params: {},\n+ });\n}\n}\n@@ -333,18 +329,11 @@ const styles = StyleSheet.create({\n});\nconst ChatThreadListRouteName = 'ChatThreadList';\n-const ChatThreadList = connect((state: AppState) => {\n- const appRoute =\n- assertNavigationRouteNotLeafNode(state.navInfo.navigationState.routes[0]);\n- const chatRoute = assertNavigationRouteNotLeafNode(appRoute.routes[1]);\n- const currentChatSubroute = chatRoute.routes[chatRoute.index];\n- return {\n+const ChatThreadList = connect((state: AppState) => ({\nchatListData: chatListData(state),\nviewerID: state.currentUserInfo && state.currentUserInfo.id,\nthreadSearchIndex: threadSearchIndex(state),\n- active: currentChatSubroute.routeName === ChatThreadListRouteName,\n- };\n-})(InnerChatThreadList);\n+}))(InnerChatThreadList);\nexport {\nChatThreadList,\n" }, { "change_type": "MODIFY", "old_path": "native/chat/compose-thread-button.react.js", "new_path": "native/chat/compose-thread-button.react.js", "diff": "// @flow\nimport type { NavigationParams } from 'react-navigation';\n-import type { AppState } from '../redux-setup';\nimport React from 'react';\nimport { StyleSheet } from 'react-native';\nimport Icon from 'react-native-vector-icons/Ionicons';\nimport PropTypes from 'prop-types';\n-import { connect } from 'lib/utils/redux-utils';\n-\nimport { ComposeThreadRouteName } from './compose-thread.react';\nimport Button from '../components/button.react';\n-import { assertNavigationRouteNotLeafNode } from '../utils/navigation-utils';\n-import { ChatThreadListRouteName } from './chat-thread-list.react';\ntype Props = {\n- navigate: (\n+ navigate: ({\nrouteName: string,\nparams?: NavigationParams,\n- ) => bool,\n- // Redux state\n- chatThreadListActive: bool,\n+ key?: string,\n+ }) => bool,\n};\nclass ComposeThreadButton extends React.PureComponent<Props> {\nstatic propTypes = {\nnavigate: PropTypes.func.isRequired,\n- chatThreadListActive: PropTypes.bool.isRequired,\n};\nrender() {\n@@ -44,9 +37,10 @@ class ComposeThreadButton extends React.PureComponent<Props> {\n}\nonPress = () => {\n- if (this.props.chatThreadListActive) {\n- this.props.navigate(ComposeThreadRouteName, {});\n- }\n+ this.props.navigate({\n+ routeName: ComposeThreadRouteName,\n+ params: {},\n+ });\n}\n}\n@@ -57,13 +51,4 @@ const styles = StyleSheet.create({\n},\n});\n-export default connect((state: AppState) => {\n- const appRoute =\n- assertNavigationRouteNotLeafNode(state.navInfo.navigationState.routes[0]);\n- const chatRoute = assertNavigationRouteNotLeafNode(appRoute.routes[1]);\n- const currentChatSubroute = chatRoute.routes[chatRoute.index];\n- return {\n- chatThreadListActive:\n- currentChatSubroute.routeName === ChatThreadListRouteName,\n- };\n-})(ComposeThreadButton);\n+export default ComposeThreadButton;\n" }, { "change_type": "MODIFY", "old_path": "native/chat/compose-thread.react.js", "new_path": "native/chat/compose-thread.react.js", "diff": "@@ -60,7 +60,6 @@ import { MessageListRouteName } from './message-list.react';\nimport { registerChatScreen } from './chat-screen-registry';\nimport ThreadVisibility from '../components/thread-visibility.react';\nimport KeyboardAvoidingView from '../components/keyboard-avoiding-view.react';\n-import { assertNavigationRouteNotLeafNode } from '../utils/navigation-utils';\nconst tagInputProps = {\nplaceholder: \"username\",\n@@ -109,7 +108,6 @@ type Props = {\notherUserInfos: {[id: string]: AccountUserInfo},\nuserSearchIndex: SearchIndex,\nthreadInfos: {[id: string]: ThreadInfo},\n- active: bool,\n// Redux dispatch functions\ndispatchActionPromise: DispatchActionPromise,\n// async functions that hit server APIs\n@@ -142,7 +140,6 @@ class InnerComposeThread extends React.PureComponent<Props, State> {\notherUserInfos: PropTypes.objectOf(accountUserInfoPropType).isRequired,\nuserSearchIndex: PropTypes.instanceOf(SearchIndex).isRequired,\nthreadInfos: PropTypes.objectOf(threadInfoPropType).isRequired,\n- active: PropTypes.bool.isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\nnewThread: PropTypes.func.isRequired,\nsearchUsers: PropTypes.func.isRequired,\n@@ -488,13 +485,12 @@ class InnerComposeThread extends React.PureComponent<Props, State> {\n}\nonSelectExistingThread = (threadID: string) => {\n- if (!this.props.active) {\n- return;\n- }\n- this.props.navigation.navigate(\n- MessageListRouteName,\n- { threadInfo: this.props.threadInfos[threadID] },\n- );\n+ const threadInfo = this.props.threadInfos[threadID];\n+ this.props.navigation.navigate({\n+ routeName: MessageListRouteName,\n+ params: { threadInfo },\n+ key: `${MessageListRouteName}${threadInfo.id}`,\n+ });\n}\n}\n@@ -581,17 +577,12 @@ const ComposeThread = connect(\nparentThreadInfo = threadInfoSelector(state)[parentThreadID];\ninvariant(parentThreadInfo, \"parent thread should exist\");\n}\n- const appRoute =\n- assertNavigationRouteNotLeafNode(state.navInfo.navigationState.routes[0]);\n- const chatRoute = assertNavigationRouteNotLeafNode(appRoute.routes[1]);\n- const currentChatSubroute = chatRoute.routes[chatRoute.index];\nreturn {\nparentThreadInfo,\nloadingStatus: loadingStatusSelector(state),\notherUserInfos: userInfoSelectorForOtherMembersOfThread(null)(state),\nuserSearchIndex: userSearchIndexForOtherMembersOfThread(null)(state),\nthreadInfos: threadInfoSelector(state),\n- active: currentChatSubroute.routeName === ComposeThreadRouteName,\n};\n},\n{ newThread, searchUsers },\n" }, { "change_type": "MODIFY", "old_path": "native/chat/message-list-header-title.react.js", "new_path": "native/chat/message-list-header-title.react.js", "diff": "import type { NavigationParams } from 'react-navigation';\nimport type { ThreadInfo } from 'lib/types/thread-types';\nimport { threadInfoPropType } from 'lib/types/thread-types';\n-import type { AppState } from '../redux-setup';\nimport React from 'react';\nimport { View, Text, StyleSheet, Platform } from 'react-native';\n@@ -11,28 +10,22 @@ import PropTypes from 'prop-types';\nimport Icon from 'react-native-vector-icons/Ionicons';\nimport { HeaderTitle } from 'react-navigation';\n-import { connect } from 'lib/utils/redux-utils';\n-\nimport Button from '../components/button.react';\nimport { ThreadSettingsRouteName } from './settings/thread-settings.react';\n-import { MessageListRouteName } from './message-list.react';\n-import { assertNavigationRouteNotLeafNode } from '../utils/navigation-utils';\ntype Props = {\nthreadInfo: ThreadInfo,\n- navigate: (\n+ navigate: ({\nrouteName: string,\nparams?: NavigationParams,\n- ) => bool,\n- // Redux state\n- messageListActive: bool,\n+ key?: string,\n+ }) => bool,\n};\nclass MessageListHeaderTitle extends React.PureComponent<Props> {\nstatic propTypes = {\nthreadInfo: threadInfoPropType.isRequired,\nnavigate: PropTypes.func.isRequired,\n- messageListActive: PropTypes.bool.isRequired,\n};\nrender() {\n@@ -73,13 +66,12 @@ class MessageListHeaderTitle extends React.PureComponent<Props> {\n}\nonPress = () => {\n- if (!this.props.messageListActive) {\n- return;\n- }\n- this.props.navigate(\n- ThreadSettingsRouteName,\n- { threadInfo: this.props.threadInfo },\n- );\n+ const threadInfo = this.props.threadInfo;\n+ this.props.navigate({\n+ routeName: ThreadSettingsRouteName,\n+ params: { threadInfo },\n+ key: `${ThreadSettingsRouteName}${threadInfo.id}`,\n+ });\n}\n}\n@@ -109,12 +101,4 @@ const styles = StyleSheet.create({\n},\n});\n-export default connect((state: AppState) => {\n- const appRoute =\n- assertNavigationRouteNotLeafNode(state.navInfo.navigationState.routes[0]);\n- const chatRoute = assertNavigationRouteNotLeafNode(appRoute.routes[1]);\n- const currentChatSubroute = chatRoute.routes[chatRoute.index];\n- return {\n- messageListActive: currentChatSubroute.routeName === MessageListRouteName,\n- };\n-})(MessageListHeaderTitle);\n+export default MessageListHeaderTitle;\n" }, { "change_type": "MODIFY", "old_path": "native/chat/settings/compose-subthread-modal.react.js", "new_path": "native/chat/settings/compose-subthread-modal.react.js", "diff": "@@ -5,8 +5,10 @@ import {\nthreadInfoPropType,\nthreadTypes,\n} from 'lib/types/thread-types';\n-import type { NavigationParams } from 'react-navigation';\n-import type { AppState } from '../../redux-setup';\n+import type {\n+ NavigationParams,\n+ NavigationNavigateAction,\n+} from 'react-navigation';\nimport React from 'react';\nimport PropTypes from 'prop-types';\n@@ -15,27 +17,21 @@ import Icon from 'react-native-vector-icons/MaterialIcons';\nimport IonIcon from 'react-native-vector-icons/Ionicons';\nimport { threadTypeDescriptions } from 'lib/shared/thread-utils';\n-import { connect } from 'lib/utils/redux-utils';\nimport Button from '../../components/button.react';\nimport { ComposeThreadRouteName } from '../compose-thread.react';\nimport KeyboardAvoidingView\nfrom '../../components/keyboard-avoiding-view.react';\n-import { ThreadSettingsRouteName } from './thread-settings.react';\n-import {\n- assertNavigationRouteNotLeafNode,\n- getThreadIDFromParams,\n-} from '../../utils/navigation-utils';\ntype Props = {|\nthreadInfo: ThreadInfo,\n- navigate: (\n+ navigate: ({\nrouteName: string,\n- params?: NavigationParams\n- ) => bool,\n+ params?: NavigationParams,\n+ action?: NavigationNavigateAction,\n+ key?: string,\n+ }) => bool,\ncloseModal: () => void,\n- // Redux state\n- threadSettingsActive: bool,\n|};\nclass ComposeSubthreadModal extends React.PureComponent<Props> {\n@@ -43,7 +39,6 @@ class ComposeSubthreadModal extends React.PureComponent<Props> {\nthreadInfo: threadInfoPropType.isRequired,\nnavigate: PropTypes.func.isRequired,\ncloseModal: PropTypes.func.isRequired,\n- threadSettingsActive: PropTypes.bool.isRequired,\n};\nwaitingToNavigate = false;\n@@ -87,36 +82,40 @@ class ComposeSubthreadModal extends React.PureComponent<Props> {\n}\nonPressOpen = () => {\n- if (!this.props.threadSettingsActive || this.waitingToNavigate) {\n+ if (this.waitingToNavigate) {\nreturn;\n}\nthis.waitingToNavigate = true;\nInteractionManager.runAfterInteractions(() => {\n- this.props.navigate(\n- ComposeThreadRouteName,\n- {\n+ this.props.navigate({\n+ routeName: ComposeThreadRouteName,\n+ params: {\nthreadType: threadTypes.CHAT_NESTED_OPEN,\nparentThreadID: this.props.threadInfo.id,\n},\n- );\n+ key: ComposeThreadRouteName +\n+ `${this.props.threadInfo.id}|${threadTypes.CHAT_NESTED_OPEN}`,\n+ });\nthis.waitingToNavigate = false;\n});\nthis.props.closeModal();\n}\nonPressSecret = () => {\n- if (!this.props.threadSettingsActive || this.waitingToNavigate) {\n+ if (this.waitingToNavigate) {\nreturn;\n}\nthis.waitingToNavigate = true;\nInteractionManager.runAfterInteractions(() => {\n- this.props.navigate(\n- ComposeThreadRouteName,\n- {\n+ this.props.navigate({\n+ routeName: ComposeThreadRouteName,\n+ params: {\nthreadType: threadTypes.CHAT_SECRET,\nparentThreadID: this.props.threadInfo.id,\n},\n- );\n+ key: ComposeThreadRouteName +\n+ `${this.props.threadInfo.id}|${threadTypes.CHAT_NESTED_OPEN}`,\n+ });\nthis.waitingToNavigate = false;\n});\nthis.props.closeModal();\n@@ -161,16 +160,4 @@ const styles = StyleSheet.create({\n},\n});\n-export default connect(\n- (state: AppState, ownProps: { threadInfo: ThreadInfo }) => {\n- const appRoute =\n- assertNavigationRouteNotLeafNode(state.navInfo.navigationState.routes[0]);\n- const chatRoute = assertNavigationRouteNotLeafNode(appRoute.routes[1]);\n- const currentChatSubroute = chatRoute.routes[chatRoute.index];\n- return {\n- threadSettingsActive:\n- currentChatSubroute.routeName === ThreadSettingsRouteName &&\n- getThreadIDFromParams(currentChatSubroute) === ownProps.threadInfo.id,\n- };\n- },\n-)(ComposeSubthreadModal);\n+export default ComposeSubthreadModal;\n" }, { "change_type": "MODIFY", "old_path": "native/chat/settings/thread-settings-child-thread.react.js", "new_path": "native/chat/settings/thread-settings-child-thread.react.js", "diff": "// @flow\nimport { type ThreadInfo, threadInfoPropType } from 'lib/types/thread-types';\n-import type { NavigationParams } from 'react-navigation';\n-import type { AppState } from '../../redux-setup';\n+import type {\n+ NavigationParams,\n+ NavigationNavigateAction,\n+} from 'react-navigation';\nimport React from 'react';\nimport { Text, StyleSheet, View, Platform } from 'react-native';\nimport PropTypes from 'prop-types';\n-import { connect } from 'lib/utils/redux-utils';\n-\nimport { MessageListRouteName } from '../message-list.react';\nimport Button from '../../components/button.react';\nimport ColorSplotch from '../../components/color-splotch.react';\nimport ThreadVisibility from '../../components/thread-visibility.react';\n-import { ThreadSettingsRouteName } from './thread-settings.react';\n-import { assertNavigationRouteNotLeafNode } from '../../utils/navigation-utils';\ntype Props = {|\nthreadInfo: ThreadInfo,\n- navigate: (\n+ navigate: ({\nrouteName: string,\nparams?: NavigationParams,\n- ) => bool,\n+ action?: NavigationNavigateAction,\n+ key?: string,\n+ }) => bool,\nlastListItem: bool,\n- // Redux state\n- threadSettingsActive: bool,\n|};\nclass ThreadSettingsChildThread extends React.PureComponent<Props> {\n@@ -33,7 +31,6 @@ class ThreadSettingsChildThread extends React.PureComponent<Props> {\nthreadInfo: threadInfoPropType.isRequired,\nnavigate: PropTypes.func.isRequired,\nlastListItem: PropTypes.bool.isRequired,\n- threadSettingsActive: PropTypes.bool.isRequired,\n};\nrender() {\n@@ -58,13 +55,12 @@ class ThreadSettingsChildThread extends React.PureComponent<Props> {\n}\nonPress = () => {\n- if (!this.props.threadSettingsActive) {\n- return;\n- }\n- this.props.navigate(\n- MessageListRouteName,\n- { threadInfo: this.props.threadInfo },\n- );\n+ const threadInfo = this.props.threadInfo;\n+ this.props.navigate({\n+ routeName: MessageListRouteName,\n+ params: { threadInfo },\n+ key: `${MessageListRouteName}${threadInfo.id}`,\n+ });\n}\n}\n@@ -101,15 +97,4 @@ const styles = StyleSheet.create({\n},\n});\n-export default connect(\n- (state: AppState, ownProps: { threadInfo: ThreadInfo }) => {\n- const appRoute =\n- assertNavigationRouteNotLeafNode(state.navInfo.navigationState.routes[0]);\n- const chatRoute = assertNavigationRouteNotLeafNode(appRoute.routes[1]);\n- const currentChatSubroute = chatRoute.routes[chatRoute.index];\n- return {\n- threadSettingsActive:\n- currentChatSubroute.routeName === ThreadSettingsRouteName,\n- };\n- },\n-)(ThreadSettingsChildThread);\n+export default ThreadSettingsChildThread;\n" }, { "change_type": "MODIFY", "old_path": "native/chat/settings/thread-settings-delete-thread.react.js", "new_path": "native/chat/settings/thread-settings-delete-thread.react.js", "diff": "@@ -4,32 +4,27 @@ import {\ntype ThreadInfo,\nthreadInfoPropType,\n} from 'lib/types/thread-types';\n-import type { NavigationParams } from 'react-navigation';\n-import type { AppState } from '../../redux-setup';\n+import type {\n+ NavigationParams,\n+ NavigationNavigateAction,\n+} from 'react-navigation';\nimport React from 'react';\nimport { Text, StyleSheet, View, Platform } from 'react-native';\nimport PropTypes from 'prop-types';\n-import { connect } from 'lib/utils/redux-utils';\n-\nimport Button from '../../components/button.react';\nimport { DeleteThreadRouteName } from './delete-thread.react';\n-import { ThreadSettingsRouteName } from './thread-settings.react';\n-import {\n- assertNavigationRouteNotLeafNode,\n- getThreadIDFromParams,\n-} from '../../utils/navigation-utils';\ntype Props = {|\nthreadInfo: ThreadInfo,\n- navigate: (\n+ navigate: ({\nrouteName: string,\nparams?: NavigationParams,\n- ) => bool,\n+ action?: NavigationNavigateAction,\n+ key?: string,\n+ }) => bool,\ncanLeaveThread: bool,\n- // Redux state\n- threadSettingsActive: bool,\n|};\nclass ThreadSettingsDeleteThread extends React.PureComponent<Props> {\n@@ -37,7 +32,6 @@ class ThreadSettingsDeleteThread extends React.PureComponent<Props> {\nthreadInfo: threadInfoPropType.isRequired,\nnavigate: PropTypes.func.isRequired,\ncanLeaveThread: PropTypes.bool.isRequired,\n- threadSettingsActive: PropTypes.bool.isRequired,\n};\nrender() {\n@@ -57,13 +51,12 @@ class ThreadSettingsDeleteThread extends React.PureComponent<Props> {\n}\nonPress = () => {\n- if (!this.props.threadSettingsActive) {\n- return;\n- }\n- this.props.navigate(\n- DeleteThreadRouteName,\n- { threadInfo: this.props.threadInfo },\n- );\n+ const threadInfo = this.props.threadInfo;\n+ this.props.navigate({\n+ routeName: DeleteThreadRouteName,\n+ params: { threadInfo },\n+ key: `${DeleteThreadRouteName}${threadInfo.id}`,\n+ });\n}\n}\n@@ -90,16 +83,4 @@ const styles = StyleSheet.create({\n},\n});\n-export default connect(\n- (state: AppState, ownProps: { threadInfo: ThreadInfo }) => {\n- const appRoute =\n- assertNavigationRouteNotLeafNode(state.navInfo.navigationState.routes[0]);\n- const chatRoute = assertNavigationRouteNotLeafNode(appRoute.routes[1]);\n- const currentChatSubroute = chatRoute.routes[chatRoute.index];\n- return {\n- threadSettingsActive:\n- currentChatSubroute.routeName === ThreadSettingsRouteName &&\n- getThreadIDFromParams(currentChatSubroute) === ownProps.threadInfo.id,\n- };\n- },\n-)(ThreadSettingsDeleteThread);\n+export default ThreadSettingsDeleteThread;\n" }, { "change_type": "MODIFY", "old_path": "native/chat/settings/thread-settings-parent.react.js", "new_path": "native/chat/settings/thread-settings-parent.react.js", "diff": "@@ -8,6 +8,7 @@ import type { NavigationParams } from 'react-navigation';\nimport React from 'react';\nimport { Text, StyleSheet, View, Platform } from 'react-native';\nimport PropTypes from 'prop-types';\n+import invariant from 'invariant';\nimport { threadInfoSelector } from 'lib/selectors/thread-selectors';\nimport { connect } from 'lib/utils/redux-utils';\n@@ -15,20 +16,16 @@ import { connect } from 'lib/utils/redux-utils';\nimport Button from '../../components/button.react';\nimport { MessageListRouteName } from '../message-list.react';\nimport { ThreadSettingsRouteName } from './thread-settings.react';\n-import {\n- assertNavigationRouteNotLeafNode,\n- getThreadIDFromParams,\n-} from '../../utils/navigation-utils';\ntype Props = {|\nthreadInfo: ThreadInfo,\n- navigate: (\n+ navigate: ({\nrouteName: string,\nparams?: NavigationParams,\n- ) => bool,\n+ key?: string,\n+ }) => bool,\n// Redux state\nparentThreadInfo?: ?ThreadInfo,\n- threadSettingsActive: bool,\n|};\nclass ThreadSettingsParent extends React.PureComponent<Props> {\n@@ -36,7 +33,6 @@ class ThreadSettingsParent extends React.PureComponent<Props> {\nthreadInfo: threadInfoPropType.isRequired,\nnavigate: PropTypes.func.isRequired,\nparentThreadInfo: threadInfoPropType,\n- threadSettingsActive: PropTypes.bool.isRequired,\n};\nrender() {\n@@ -84,13 +80,13 @@ class ThreadSettingsParent extends React.PureComponent<Props> {\n}\nonPressParentThread = () => {\n- if (!this.props.threadSettingsActive) {\n- return;\n- }\n- this.props.navigate(\n- MessageListRouteName,\n- { threadInfo: this.props.parentThreadInfo },\n- );\n+ const threadInfo = this.props.parentThreadInfo;\n+ invariant(threadInfo, \"should be set\");\n+ this.props.navigate({\n+ routeName: MessageListRouteName,\n+ params: { threadInfo },\n+ key: `${MessageListRouteName}${threadInfo.id}`,\n+ });\n}\n}\n@@ -134,15 +130,8 @@ export default connect(\nconst parentThreadInfo: ?ThreadInfo = ownProps.threadInfo.parentThreadID\n? parsedThreadInfos[ownProps.threadInfo.parentThreadID]\n: null;\n- const appRoute =\n- assertNavigationRouteNotLeafNode(state.navInfo.navigationState.routes[0]);\n- const chatRoute = assertNavigationRouteNotLeafNode(appRoute.routes[1]);\n- const currentChatSubroute = chatRoute.routes[chatRoute.index];\nreturn {\nparentThreadInfo,\n- threadSettingsActive:\n- currentChatSubroute.routeName === ThreadSettingsRouteName &&\n- getThreadIDFromParams(currentChatSubroute) === ownProps.threadInfo.id,\n};\n},\n)(ThreadSettingsParent);\n" }, { "change_type": "MODIFY", "old_path": "native/chat/settings/thread-settings.react.js", "new_path": "native/chat/settings/thread-settings.react.js", "diff": "@@ -4,6 +4,7 @@ import type {\nNavigationScreenProp,\nNavigationRoute,\nNavigationParams,\n+ NavigationNavigateAction,\n} from 'react-navigation';\nimport {\ntype ThreadInfo,\n@@ -117,7 +118,12 @@ type ChatSettingsItem =\nitemType: \"parent\",\nkey: string,\nthreadInfo: ThreadInfo,\n- navigate: (routeName: string, params?: NavigationParams) => bool,\n+ navigate: ({\n+ routeName: string,\n+ params?: NavigationParams,\n+ action?: NavigationNavigateAction,\n+ key?: string,\n+ }) => bool,\n|}\n| {|\nitemType: \"visibility\",\n@@ -138,7 +144,12 @@ type ChatSettingsItem =\nitemType: \"childThread\",\nkey: string,\nthreadInfo: ThreadInfo,\n- navigate: (routeName: string, params?: NavigationParams) => bool,\n+ navigate: ({\n+ routeName: string,\n+ params?: NavigationParams,\n+ action?: NavigationNavigateAction,\n+ key?: string,\n+ }) => bool,\nlastListItem: bool,\n|}\n| {|\n@@ -167,7 +178,12 @@ type ChatSettingsItem =\nitemType: \"deleteThread\",\nkey: string,\nthreadInfo: ThreadInfo,\n- navigate: (routeName: string, params?: NavigationParams) => bool,\n+ navigate: ({\n+ routeName: string,\n+ params?: NavigationParams,\n+ action?: NavigationNavigateAction,\n+ key?: string,\n+ }) => bool,\ncanLeaveThread: bool,\n|};\n" }, { "change_type": "MODIFY", "old_path": "native/chat/thread-settings-button.react.js", "new_path": "native/chat/thread-settings-button.react.js", "diff": "import type { NavigationParams } from 'react-navigation';\nimport { type ThreadInfo, threadInfoPropType } from 'lib/types/thread-types';\n-import type { AppState } from '../redux-setup';\nimport React from 'react';\nimport { StyleSheet } from 'react-native';\nimport Icon from 'react-native-vector-icons/Ionicons';\nimport PropTypes from 'prop-types';\n-import { connect } from 'lib/utils/redux-utils';\n-\nimport { ThreadSettingsRouteName } from './settings/thread-settings.react';\nimport Button from '../components/button.react';\n-import { MessageListRouteName } from './message-list.react';\n-import { assertNavigationRouteNotLeafNode } from '../utils/navigation-utils';\ntype Props = {\nthreadInfo: ThreadInfo,\n- navigate: (\n+ navigate: ({\nrouteName: string,\nparams?: NavigationParams,\n- ) => bool,\n- // Redux state\n- messageListActive: bool,\n+ key?: string,\n+ }) => bool,\n};\nclass ThreadSettingsButton extends React.PureComponent<Props> {\nstatic propTypes = {\nthreadInfo: threadInfoPropType.isRequired,\nnavigate: PropTypes.func.isRequired,\n- messageListActive: PropTypes.bool.isRequired,\n};\nrender() {\n@@ -47,13 +40,12 @@ class ThreadSettingsButton extends React.PureComponent<Props> {\n}\nonPress = () => {\n- if (!this.props.messageListActive) {\n- return;\n- }\n- this.props.navigate(\n- ThreadSettingsRouteName,\n- { threadInfo: this.props.threadInfo },\n- );\n+ const threadInfo = this.props.threadInfo;\n+ this.props.navigate({\n+ routeName: ThreadSettingsRouteName,\n+ params: { threadInfo },\n+ key: `${ThreadSettingsRouteName}${threadInfo.id}`,\n+ });\n}\n}\n@@ -64,12 +56,4 @@ const styles = StyleSheet.create({\n},\n});\n-export default connect((state: AppState) => {\n- const appRoute =\n- assertNavigationRouteNotLeafNode(state.navInfo.navigationState.routes[0]);\n- const chatRoute = assertNavigationRouteNotLeafNode(appRoute.routes[1]);\n- const currentChatSubroute = chatRoute.routes[chatRoute.index];\n- return {\n- messageListActive: currentChatSubroute.routeName === MessageListRouteName,\n- };\n-})(ThreadSettingsButton);\n+export default ThreadSettingsButton;\n" }, { "change_type": "MODIFY", "old_path": "native/more/more-screen.react.js", "new_path": "native/more/more-screen.react.js", "diff": "@@ -44,7 +44,6 @@ import { EditPasswordRouteName } from './edit-password.react';\nimport { DeleteAccountRouteName } from './delete-account.react';\nimport { BuildInfoRouteName} from './build-info.react';\nimport { DevToolsRouteName} from './dev-tools.react';\n-import { assertNavigationRouteNotLeafNode } from '../utils/navigation-utils';\ntype Props = {\nnavigation: NavigationScreenProp<*>,\n@@ -53,7 +52,6 @@ type Props = {\nemail: ?string,\nemailVerified: ?bool,\nresendVerificationLoadingStatus: LoadingStatus,\n- active: bool,\n// Redux dispatch functions\ndispatchActionPromise: DispatchActionPromise,\n// async functions that hit server APIs\n@@ -70,7 +68,6 @@ class InnerMoreScreen extends React.PureComponent<Props> {\nemail: PropTypes.string,\nemailVerified: PropTypes.bool,\nresendVerificationLoadingStatus: loadingStatusPropType.isRequired,\n- active: PropTypes.bool.isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\nlogOut: PropTypes.func.isRequired,\nresendVerificationEmail: PropTypes.func.isRequired,\n@@ -273,9 +270,7 @@ class InnerMoreScreen extends React.PureComponent<Props> {\n}\nnavigateIfActive(routeName: string) {\n- if (this.props.active) {\n- this.props.navigation.navigate(routeName);\n- }\n+ this.props.navigation.navigate({ routeName });\n}\nonPressEditEmail = () => {\n@@ -425,11 +420,7 @@ const resendVerificationLoadingStatusSelector = createLoadingStatusSelector(\nconst MoreScreenRouteName = 'MoreScreen';\nconst MoreScreen = connect(\n- (state: AppState) => {\n- const appRoute =\n- assertNavigationRouteNotLeafNode(state.navInfo.navigationState.routes[0]);\n- const moreRoute = assertNavigationRouteNotLeafNode(appRoute.routes[2]);\n- return {\n+ (state: AppState) => ({\nusername: state.currentUserInfo && !state.currentUserInfo.anonymous\n? state.currentUserInfo.username\n: undefined,\n@@ -441,9 +432,7 @@ const MoreScreen = connect(\n: undefined,\nresendVerificationLoadingStatus:\nresendVerificationLoadingStatusSelector(state),\n- active: moreRoute.index === 0,\n- };\n- },\n+ }),\n{ logOut, resendVerificationEmail },\n)(InnerMoreScreen);\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Use react-navigation@2.0's new "less pushy" navigate We no longer have to check if the current route is active before `navigate`, as `react-navigation` will handle duplicates as long as we specify the correct `key`.
129,187
16.05.2018 21:54:49
14,400
7dd934599445bc04d0e8faed2b3079ba51e1beed
[native] Use createNavigationPropConstructor and initializeListeners from react-navigation-redux-helpers
[ { "change_type": "MODIFY", "old_path": "native/app.react.js", "new_path": "native/app.react.js", "diff": "import type {\nNavigationState,\nNavigationAction,\n- NavigationScreenProp,\n} from 'react-navigation';\nimport type { Dispatch } from 'lib/types/redux-types';\nimport type { AppState } from './redux-setup';\n@@ -51,15 +50,16 @@ import {\nAlert,\nDeviceInfo,\n} from 'react-native';\n-import { createReduxBoundAddListener } from 'react-navigation-redux-helpers';\n+import {\n+ createNavigationPropConstructor,\n+ initializeListeners,\n+} from 'react-navigation-redux-helpers';\nimport invariant from 'invariant';\nimport PropTypes from 'prop-types';\nimport NotificationsIOS from 'react-native-notifications';\nimport InAppNotification from 'react-native-in-app-notification';\nimport FCM, { FCMEvent } from 'react-native-fcm';\nimport SplashScreen from 'react-native-splash-screen';\n-import getNavigationActionCreators\n- from 'react-navigation/src/routers/getNavigationActionCreators';\nimport { registerConfig } from 'lib/utils/config';\nimport { connect } from 'lib/utils/redux-utils';\n@@ -122,7 +122,7 @@ registerConfig({\nplatform: Platform.OS,\n});\n-const reactNavigationAddListener = createReduxBoundAddListener(\"root\");\n+const reactNavigationPropConstructor = createNavigationPropConstructor(\"root\");\nconst msInDay = 24 * 60 * 60 * 1000;\ntype NativeDispatch = Dispatch & ((action: NavigationAction) => boolean);\n@@ -203,6 +203,7 @@ class AppWithNavigationState extends React.PureComponent<Props> {\nNativeAppState.addEventListener('change', this.handleAppStateChange);\nthis.handleInitialURL();\nLinking.addEventListener('url', this.handleURLChange);\n+ initializeListeners(\"root\", this.props.navigationState);\nif (this.props.loggedIn) {\nthis.startTimeouts(this.props, \"active\");\n}\n@@ -837,18 +838,10 @@ class AppWithNavigationState extends React.PureComponent<Props> {\n}\nrender() {\n- const state = this.props.navigationState;\n- const navigation: NavigationScreenProp<any> = {\n- dispatch: this.props.dispatch,\n- state,\n- addListener: reactNavigationAddListener,\n- };\n- const actionCreators = getNavigationActionCreators(state);\n- Object.keys(actionCreators).forEach(actionName => {\n- navigation[actionName] = (...args) =>\n- this.props.dispatch(actionCreators[actionName](...args));\n- });\n-\n+ const navigation = reactNavigationPropConstructor(\n+ this.props.dispatch,\n+ this.props.navigationState,\n+ );\nconst inAppNotificationHeight = DeviceInfo.isIPhoneX_deprecated ? 104 : 80;\nreturn (\n<View style={styles.app}>\n" }, { "change_type": "MODIFY", "old_path": "native/flow-typed/npm/react-navigation_v2.x.x.js", "new_path": "native/flow-typed/npm/react-navigation_v2.x.x.js", "diff": "-// flow-typed signature: 202ef1dbc567dacdc6871e8e6910e7cc\n-// flow-typed version: 85a49fd1e5/react-navigation_v2.x.x/flow_>=v0.60.x\n-\n// @flow\ndeclare module 'react-navigation' {\n@@ -272,26 +269,21 @@ declare module 'react-navigation' {\ndeclare export type NavigationComponent =\n| NavigationScreenComponent<NavigationRoute, *, *>\n- | NavigationContainer<*, *, *>;\n+ | NavigationContainer<*, *, *>\n+ | any;\ndeclare export type NavigationScreenComponent<\nRoute: NavigationRoute,\nOptions: {},\nProps: {}\n- > = React$ComponentType<{\n- ...Props,\n- ...NavigationNavigatorProps<Options, Route>,\n- }> &\n+ > = React$ComponentType<NavigationNavigatorProps<Options, Route> & Props> &\n({} | { navigationOptions: NavigationScreenConfig<Options> });\ndeclare export type NavigationNavigator<\nState: NavigationState,\nOptions: {},\nProps: {}\n- > = React$ComponentType<{\n- ...Props,\n- ...NavigationNavigatorProps<Options, State>,\n- }> & {\n+ > = React$ComponentType<NavigationNavigatorProps<Options, State> & Props> & {\nrouter: NavigationRouter<State, Options>,\nnavigationOptions?: ?NavigationScreenConfig<Options>,\n};\n@@ -491,23 +483,13 @@ declare module 'react-navigation' {\n};\ndeclare export type NavigationScreenProp<+S> = {\n+ ...$ObjMap<\n+ _DefaultActionCreators,\n+ <Args>((...args: Args) => *) => (...args: Args) => boolean,\n+ >,\n+state: S,\ndispatch: NavigationDispatch,\n- goBack: (routeKey?: ?string) => boolean,\ndismiss: () => boolean,\n- navigate: (\n- routeName:\n- | string\n- | {\n- routeName: string,\n- params?: NavigationParams,\n- action?: NavigationNavigateAction,\n- key?: string,\n- },\n- params?: NavigationParams,\n- action?: NavigationNavigateAction\n- ) => boolean,\n- setParams: (newParams: NavigationParams) => boolean,\ngetParam: (paramName: string, fallback?: any) => any,\naddListener: (\neventName: string,\n@@ -542,10 +524,7 @@ declare module 'react-navigation' {\nState: NavigationState,\nOptions: {},\nProps: {}\n- > = React$ComponentType<{\n- ...Props,\n- ...NavigationContainerProps<State, Options>,\n- }> & {\n+ > = React$ComponentType<NavigationContainerProps<State, Options> & Props> & {\nrouter: NavigationRouter<State, Options>,\nnavigationOptions?: ?NavigationScreenConfig<Options>,\n};\n@@ -757,6 +736,26 @@ declare module 'react-navigation' {\n},\n};\n+ declare type _DefaultActionCreators = {|\n+ goBack: (routeKey?: ?string) => NavigationBackAction,\n+ navigate: (\n+ routeName:\n+ | string\n+ | {\n+ routeName: string,\n+ params?: NavigationParams,\n+ action?: NavigationNavigateAction,\n+ key?: string,\n+ },\n+ params?: NavigationParams,\n+ action?: NavigationNavigateAction\n+ ) => NavigationNavigateAction,\n+ setParams: (newParams: NavigationParams) => NavigationSetParamsAction,\n+ |};\n+ declare export function getNavigationActionCreators(\n+ route: NavigationRoute | NavigationState\n+ ): _DefaultActionCreators;\n+\ndeclare type _RouterProp<S: NavigationState, O: {}> = {\nrouter: NavigationRouter<S, O>,\n};\n@@ -777,7 +776,7 @@ declare module 'react-navigation' {\nview: NavigationView<O, S>,\nrouter: NavigationRouter<S, O>,\nnavigatorConfig?: NavigatorConfig\n- ): NavigationNavigator<S, O, *>;\n+ ): any;\ndeclare export function StackNavigator(\nrouteConfigMap: NavigationRouteConfigMap,\n" }, { "change_type": "MODIFY", "old_path": "native/package.json", "new_path": "native/package.json", "diff": "\"react-native-splash-screen\": \"^3.0.6\",\n\"react-native-vector-icons\": \"^4.5.0\",\n\"react-navigation\": \"^2.0.1\",\n- \"react-navigation-redux-helpers\": \"^1.0.7\",\n+ \"react-navigation-redux-helpers\": \"^1.1.0\",\n\"react-redux\": \"^5.0.6\",\n\"redux\": \"^3.7.2\",\n\"redux-devtools-extension\": \"^2.13.2\",\n" }, { "change_type": "MODIFY", "old_path": "yarn.lock", "new_path": "yarn.lock", "diff": "@@ -7832,9 +7832,9 @@ react-navigation-deprecated-tab-navigator@1.2.0:\ndependencies:\nreact-native-tab-view \"^0.0.74\"\n-react-navigation-redux-helpers@^1.0.7:\n- version \"1.0.7\"\n- resolved \"https://registry.yarnpkg.com/react-navigation-redux-helpers/-/react-navigation-redux-helpers-1.0.7.tgz#ed292fcdf1eb35292f997ae9fab8ced2e3f8f3ae\"\n+react-navigation-redux-helpers@^1.1.0:\n+ version \"1.1.0\"\n+ resolved \"https://registry.yarnpkg.com/react-navigation-redux-helpers/-/react-navigation-redux-helpers-1.1.0.tgz#b003cb993193e78ad109563f93faadbc3c62c1e1\"\ndependencies:\ninvariant \"^2.2.2\"\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Use createNavigationPropConstructor and initializeListeners from react-navigation-redux-helpers
129,187
21.05.2018 22:42:13
14,400
bdae8f6365724e0f1bd29b9e0a17bc1a0c70e057
[server] Include nav-selectors in server
[ { "change_type": "MODIFY", "old_path": "server/package.json", "new_path": "server/package.json", "diff": "\"description\": \"\",\n\"main\": \"dist/server\",\n\"scripts\": {\n- \"babel\": \"babel src/ --out-dir dist/ --ignore 'lib/flow-typed','lib/node_modules','lib/package.json','web/flow-typed','web/node_modules','web/package.json','web/dist/hot','web/dist/dev.build.js','web/dist/prod.build.js','web/dist/prod.build.css','web/webpack.config.js','web/account-bar.react.js','web/app.react.js','web/calendar','web/chat','web/flow','web/loading-indicator.react.js','web/modals','web/router-history.js','web/script.js','web/selectors','web/server-rendering.js','web/splash','web/style.css','web/vector-utils.js','web/vectors.react.js' --copy-files\",\n+ \"babel\": \"babel src/ --out-dir dist/ --ignore 'lib/flow-typed','lib/node_modules','lib/package.json','web/flow-typed','web/node_modules','web/package.json','web/dist/hot','web/dist/dev.build.js','web/dist/prod.build.js','web/dist/prod.build.css','web/webpack.config.js','web/account-bar.react.js','web/app.react.js','web/calendar','web/chat','web/flow','web/loading-indicator.react.js','web/modals','web/router-history.js','web/script.js','web/selectors/chat-selectors.js','web/selectors/entry-selectors.js','web/server-rendering.js','web/splash','web/style.css','web/vector-utils.js','web/vectors.react.js' --copy-files\",\n\"prod\": \"node --experimental-modules --loader ./loader.mjs dist/server\",\n\"dev\": \"NODE_ENV=dev concurrently \\\"npm run babel -- --watch\\\" \\\"nodemon -e js,json --watch dist --experimental-modules --loader ./loader.mjs dist/server\\\"\"\n},\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Include nav-selectors in server
129,187
09.06.2018 15:31:29
-25,200
d2a4024f86341bd072727034eeb44dc1e6c9a562
Version bumps and bugfixes
[ { "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.0.6\",\n\"react-native-vector-icons\": \"^4.5.0\",\n- \"react-navigation\": \"^2.0.1\",\n+ \"react-navigation\": \"^2.0.4\",\n\"react-navigation-redux-helpers\": \"^1.1.0\",\n\"react-redux\": \"^5.0.6\",\n\"redux\": \"^3.7.2\",\n" }, { "change_type": "MODIFY", "old_path": "server/flow-typed/npm/lib_vx.x.x.js", "new_path": "server/flow-typed/npm/lib_vx.x.x.js", "diff": "-// flow-typed signature: 9ac7223eaefc14df2b4a5c0c349a1434\n+// flow-typed signature: 66ca233bbd897ba07ebd9fd0fdfe88f9\n// flow-typed version: <<STUB>>/lib_v0.0.1/flow_v0.64.0\n/**\n@@ -190,6 +190,10 @@ declare module 'lib/selectors/calendar-selectors' {\ndeclare module.exports: any;\n}\n+declare module 'lib/selectors/chat-selectors' {\n+ declare module.exports: any;\n+}\n+\ndeclare module 'lib/selectors/loading-selectors' {\ndeclare module.exports: any;\n}\n@@ -517,6 +521,9 @@ declare module 'lib/selectors/calendar-filter-selectors.js' {\ndeclare module 'lib/selectors/calendar-selectors.js' {\ndeclare module.exports: $Exports<'lib/selectors/calendar-selectors'>;\n}\n+declare module 'lib/selectors/chat-selectors.js' {\n+ declare module.exports: $Exports<'lib/selectors/chat-selectors'>;\n+}\ndeclare module 'lib/selectors/loading-selectors.js' {\ndeclare module.exports: $Exports<'lib/selectors/loading-selectors'>;\n}\n" }, { "change_type": "MODIFY", "old_path": "server/flow-typed/npm/nodemon_vx.x.x.js", "new_path": "server/flow-typed/npm/nodemon_vx.x.x.js", "diff": "-// flow-typed signature: af2e57be054a5a7e0e92399b099b42c1\n+// flow-typed signature: dc6dcfd067d6e6c924edf15a8870f53c\n// flow-typed version: <<STUB>>/nodemon_v^1.14.3/flow_v0.64.0\n/**\n@@ -26,6 +26,10 @@ declare module 'nodemon/bin/nodemon' {\ndeclare module.exports: any;\n}\n+declare module 'nodemon/bin/postinstall' {\n+ declare module.exports: any;\n+}\n+\ndeclare module 'nodemon/commitlint.config' {\ndeclare module.exports: any;\n}\n@@ -138,6 +142,9 @@ declare module 'nodemon/lib/version' {\ndeclare module 'nodemon/bin/nodemon.js' {\ndeclare module.exports: $Exports<'nodemon/bin/nodemon'>;\n}\n+declare module 'nodemon/bin/postinstall.js' {\n+ declare module.exports: $Exports<'nodemon/bin/postinstall'>;\n+}\ndeclare module 'nodemon/commitlint.config.js' {\ndeclare module.exports: $Exports<'nodemon/commitlint.config'>;\n}\n" }, { "change_type": "DELETE", "old_path": "server/flow-typed/npm/react-hot-loader_v3.x.x.js", "new_path": null, "diff": "-// flow-typed signature: 9d0d7b4cee70d8ca16304fe8c1b4bbed\n-// flow-typed version: 23646d2d0e/react-hot-loader_v3.x.x/flow_>=v0.53.0\n-\n-// @flow\n-declare module \"react-hot-loader\" {\n- declare class AppContainer<S, A> extends React$Component<{\n- errorReporter?: React$Element<any> | (() => React$Element<any>),\n- children: React$Element<any>\n- }> {}\n-}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "server/flow-typed/npm/react-hot-loader_vx.x.x.js", "diff": "+// flow-typed signature: 36c08f9233068a94d4f3c2363de463d9\n+// flow-typed version: <<STUB>>/react-hot-loader_v^4.2.0/flow_v0.64.0\n+\n+/**\n+ * This is an autogenerated libdef stub for:\n+ *\n+ * 'react-hot-loader'\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-hot-loader' {\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-hot-loader/babel' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'react-hot-loader/dist/babel.development' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'react-hot-loader/dist/babel.production.min' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'react-hot-loader/dist/react-hot-loader.development' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'react-hot-loader/dist/react-hot-loader.production.min' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'react-hot-loader/patch' {\n+ declare module.exports: any;\n+}\n+\n+// Filename aliases\n+declare module 'react-hot-loader/babel.js' {\n+ declare module.exports: $Exports<'react-hot-loader/babel'>;\n+}\n+declare module 'react-hot-loader/dist/babel.development.js' {\n+ declare module.exports: $Exports<'react-hot-loader/dist/babel.development'>;\n+}\n+declare module 'react-hot-loader/dist/babel.production.min.js' {\n+ declare module.exports: $Exports<'react-hot-loader/dist/babel.production.min'>;\n+}\n+declare module 'react-hot-loader/dist/react-hot-loader.development.js' {\n+ declare module.exports: $Exports<'react-hot-loader/dist/react-hot-loader.development'>;\n+}\n+declare module 'react-hot-loader/dist/react-hot-loader.production.min.js' {\n+ declare module.exports: $Exports<'react-hot-loader/dist/react-hot-loader.production.min'>;\n+}\n+declare module 'react-hot-loader/index' {\n+ declare module.exports: $Exports<'react-hot-loader'>;\n+}\n+declare module 'react-hot-loader/index.js' {\n+ declare module.exports: $Exports<'react-hot-loader'>;\n+}\n+declare module 'react-hot-loader/patch.js' {\n+ declare module.exports: $Exports<'react-hot-loader/patch'>;\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "server/flow-typed/npm/stream-cache_vx.x.x.js", "diff": "+// flow-typed signature: 044bcbad2760cfb80755448804516dc9\n+// flow-typed version: <<STUB>>/stream-cache_v^0.0.2/flow_v0.64.0\n+\n+/**\n+ * This is an autogenerated libdef stub for:\n+ *\n+ * 'stream-cache'\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 'stream-cache' {\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 'stream-cache/lib/StreamCache' {\n+ declare module.exports: any;\n+}\n+\n+declare module 'stream-cache/test/test-with-child-processes' {\n+ declare module.exports: any;\n+}\n+\n+// Filename aliases\n+declare module 'stream-cache/index' {\n+ declare module.exports: $Exports<'stream-cache'>;\n+}\n+declare module 'stream-cache/index.js' {\n+ declare module.exports: $Exports<'stream-cache'>;\n+}\n+declare module 'stream-cache/lib/StreamCache.js' {\n+ declare module.exports: $Exports<'stream-cache/lib/StreamCache'>;\n+}\n+declare module 'stream-cache/test/test-with-child-processes.js' {\n+ declare module.exports: $Exports<'stream-cache/test/test-with-child-processes'>;\n+}\n" }, { "change_type": "MODIFY", "old_path": "server/package.json", "new_path": "server/package.json", "diff": "\"babel-plugin-transform-object-rest-spread\": \"^6.26.0\",\n\"babel-preset-react\": \"^6.24.1\",\n\"concurrently\": \"^3.5.1\",\n- \"flow-bin\": \"^0.64.0\",\n+ \"flow-bin\": \"^0.72.0\",\n\"flow-typed\": \"^2.2.3\",\n\"nodemon\": \"^1.14.3\"\n},\n" }, { "change_type": "MODIFY", "old_path": "server/src/creators/thread-creator.js", "new_path": "server/src/creators/thread-creator.js", "diff": "@@ -35,7 +35,7 @@ async function createThread(\n}\nconst threadType = request.type;\n- if (threadType === threadTypes.NESTED_OPEN && !request.parentThreadID) {\n+ if (threadType === threadTypes.CHAT_NESTED_OPEN && !request.parentThreadID) {\nthrow new ServerError('invalid_parameters');\n}\nlet parentThreadID = null;\n" }, { "change_type": "MODIFY", "old_path": "server/src/responders/handlers.js", "new_path": "server/src/responders/handlers.js", "diff": "@@ -48,8 +48,8 @@ function downloadHandler(responder: DownloadResponder) {\n};\n}\n-function getMessageForException(error: Error) {\n- return error.sqlMessage ? \"database error\" : error.message;\n+function getMessageForException(error: Error & { sqlMessage?: string }) {\n+ return error.sqlMessage !== null ? \"database error\" : error.message;\n}\nfunction handleException(error: Error, res: $Response) {\n" }, { "change_type": "MODIFY", "old_path": "server/src/updaters/thread-updaters.js", "new_path": "server/src/updaters/thread-updaters.js", "diff": "@@ -410,8 +410,8 @@ async function updateThread(\n// If the thread is being switched to nested, a parent must be specified\nif (\n- oldThreadType !== threadTypes.NESTED_OPEN &&\n- threadType === threadTypes.NESTED_OPEN &&\n+ oldThreadType !== threadTypes.CHAT_NESTED_OPEN &&\n+ threadType === threadTypes.CHAT_NESTED_OPEN &&\noldParentThreadID === null &&\nparentThreadID === null\n) {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Version bumps and bugfixes
129,187
09.06.2018 15:32:32
-25,200
8409744515c8ea7ce7038f399209a928efb9a3db
[server] Buffer mysqldump results in memory mysqldump shouldn't hang when the file write stream runs out of space anymore, and we won't call mysqldump twice in that scenario anymore.
[ { "change_type": "MODIFY", "old_path": "server/package.json", "new_path": "server/package.json", "diff": "\"react-router\": \"^4.2.0\",\n\"redux\": \"^3.7.2\",\n\"sql-template-strings\": \"^2.2.2\",\n+ \"stream-cache\": \"^0.0.2\",\n\"tcomb\": \"^3.2.24\",\n\"twin-bcrypt\": \"^2.1.1\",\n\"uuid\": \"^3.1.0\",\n" }, { "change_type": "MODIFY", "old_path": "server/src/backups.js", "new_path": "server/src/backups.js", "diff": "@@ -5,6 +5,7 @@ import childProcess from 'child_process';\nimport zlib from 'zlib';\nimport dateFormat from 'dateformat';\nimport denodeify from 'denodeify';\n+import StreamCache from 'stream-cache';\nimport dbConfig from '../secrets/db_config';\nimport backupConfig from '../facts/backups';\n@@ -17,10 +18,38 @@ async function backupDB(retries: number = 2) {\nif (!backupConfig || !backupConfig.enabled) {\nreturn;\n}\n+\n+ const mysqlDump = childProcess.spawn(\n+ 'mysqldump',\n+ [\n+ '-u',\n+ dbConfig.user,\n+ `-p${dbConfig.password}`,\n+ dbConfig.database,\n+ ],\n+ {\n+ stdio: ['ignore', 'pipe', 'ignore'],\n+ },\n+ );\n+ const cache = new StreamCache();\n+ mysqlDump\n+ .stdout\n+ .pipe(zlib.createGzip())\n+ .pipe(cache);\n+\nconst dateString = dateFormat(\"yyyy-mm-dd-HH:MM\");\nconst filename = `${backupConfig.directory}/squadcal.${dateString}.sql.gz`;\n+\n+ await saveBackup(filename, cache);\n+}\n+\n+async function saveBackup(\n+ filePath: string,\n+ cache: StreamCache,\n+ retries: number = 2,\n+): Promise<void> {\ntry {\n- await backupDBToFile(filename);\n+ await trySaveBackup(filePath, cache);\n} catch (e) {\nif (e.code !== \"ENOSPC\") {\nthrow e;\n@@ -29,25 +58,14 @@ async function backupDB(retries: number = 2) {\nthrow e;\n}\nawait deleteOldestBackup();\n- await backupDB(retries - 1);\n+ await saveBackup(filePath, cache, retries - 1);\n}\n}\n-function backupDBToFile(filePath: string): Promise<void> {\n+function trySaveBackup(filePath: string, cache: StreamCache): Promise<void> {\nconst writeStream = fs.createWriteStream(filePath);\n- const mysqlDump = childProcess.spawn(\n- 'mysqldump',\n- [\n- '-u',\n- dbConfig.user,\n- `-p${dbConfig.password}`,\n- dbConfig.database,\n- ],\n- );\nreturn new Promise((resolve, reject) => {\n- mysqlDump\n- .stdout\n- .pipe(zlib.createGzip())\n+ cache\n.pipe(writeStream)\n.on('finish', resolve)\n.on('error', reject);\n@@ -69,8 +87,16 @@ async function deleteOldestBackup() {\noldestFile = { file, mtime: stat.mtime };\n}\n}\n- if (oldestFile) {\n+ if (!oldestFile) {\n+ return;\n+ }\n+ try {\nawait unlink(`${backupConfig.directory}/${oldestFile.file}`);\n+ } catch (e) {\n+ // Check if it's already been deleted\n+ if (e.code !== \"ENOENT\") {\n+ throw e;\n+ }\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "yarn.lock", "new_path": "yarn.lock", "diff": "@@ -3891,10 +3891,6 @@ flatten@^1.0.2:\nversion \"1.0.2\"\nresolved \"https://registry.yarnpkg.com/flatten/-/flatten-1.0.2.tgz#dae46a9d78fbe25292258cc1e780a41d95c03782\"\n-flow-bin@^0.64.0:\n- version \"0.64.0\"\n- resolved \"https://registry.yarnpkg.com/flow-bin/-/flow-bin-0.64.0.tgz#ddd3fb3b183ab1ab35a5d5dec9caf5ebbcded167\"\n-\nflow-bin@^0.67.1:\nversion \"0.67.1\"\nresolved \"https://registry.yarnpkg.com/flow-bin/-/flow-bin-0.67.1.tgz#eabb7197cce870ac9442cfd04251c7ddc30377db\"\n@@ -7664,10 +7660,6 @@ react-html-email@^3.0.0:\ndependencies:\nprop-types \"^15.5.10\"\n-react-lifecycles-compat@^1.0.2:\n- version \"1.1.4\"\n- resolved \"https://registry.yarnpkg.com/react-lifecycles-compat/-/react-lifecycles-compat-1.1.4.tgz#fc005c72849b7ed364de20a0f64ff58ebdc2009a\"\n-\nreact-lifecycles-compat@^3, 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\"\n@@ -7757,6 +7749,12 @@ react-native-safe-area-view@^0.7.0:\ndependencies:\nhoist-non-react-statics \"^2.3.1\"\n+react-native-safe-area-view@^0.8.0:\n+ version \"0.8.0\"\n+ resolved \"https://registry.yarnpkg.com/react-native-safe-area-view/-/react-native-safe-area-view-0.8.0.tgz#22d78cb8e8658d04a10cd53c1546e0bc86cb7aea\"\n+ dependencies:\n+ hoist-non-react-statics \"^2.3.1\"\n+\nreact-native-segmented-control-tab@^3.2.1:\nversion \"3.2.2\"\nresolved \"https://registry.yarnpkg.com/react-native-segmented-control-tab/-/react-native-segmented-control-tab-3.2.2.tgz#251ce94acdc655e04063b9813bb1ef595bf11f2d\"\n@@ -7771,13 +7769,13 @@ react-native-swipe-gestures@^1.0.2:\nversion \"1.0.2\"\nresolved \"https://registry.yarnpkg.com/react-native-swipe-gestures/-/react-native-swipe-gestures-1.0.2.tgz#914e1a72a94bc55b322b4622a01103ab879296dd\"\n-react-native-tab-view@^0.0.74:\n- version \"0.0.74\"\n- resolved \"https://registry.yarnpkg.com/react-native-tab-view/-/react-native-tab-view-0.0.74.tgz#62c0c882d9232b461ce181d440d683b4f99d1bd8\"\n+react-native-tab-view@^0.0.77:\n+ version \"0.0.77\"\n+ resolved \"https://registry.yarnpkg.com/react-native-tab-view/-/react-native-tab-view-0.0.77.tgz#11ceb8e7c23100d07e628dc151b57797524d00d4\"\ndependencies:\nprop-types \"^15.6.0\"\n-react-native-tab-view@~0.0.77:\n+react-native-tab-view@~0.0.78:\nversion \"0.0.78\"\nresolved \"https://registry.yarnpkg.com/react-native-tab-view/-/react-native-tab-view-0.0.78.tgz#9b90730d89cbd34a03f0e0ab10e74ca7af945560\"\ndependencies:\n@@ -7855,11 +7853,11 @@ react-native@^0.55.3:\nxmldoc \"^0.4.0\"\nyargs \"^9.0.0\"\n-react-navigation-deprecated-tab-navigator@1.2.0:\n- version \"1.2.0\"\n- resolved \"https://registry.yarnpkg.com/react-navigation-deprecated-tab-navigator/-/react-navigation-deprecated-tab-navigator-1.2.0.tgz#e0d969c196dcd3a4a440770a7bd97fa058eb4aaf\"\n+react-navigation-deprecated-tab-navigator@1.3.0:\n+ version \"1.3.0\"\n+ resolved \"https://registry.yarnpkg.com/react-navigation-deprecated-tab-navigator/-/react-navigation-deprecated-tab-navigator-1.3.0.tgz#015dcae1e977b984ca7e99245261c15439026bb7\"\ndependencies:\n- react-native-tab-view \"^0.0.74\"\n+ react-native-tab-view \"^0.0.77\"\nreact-navigation-redux-helpers@^1.1.0:\nversion \"1.1.0\"\n@@ -7867,19 +7865,19 @@ react-navigation-redux-helpers@^1.1.0:\ndependencies:\ninvariant \"^2.2.2\"\n-react-navigation-tabs@0.2.0:\n- version \"0.2.0\"\n- resolved \"https://registry.yarnpkg.com/react-navigation-tabs/-/react-navigation-tabs-0.2.0.tgz#d25be64e01a728c893a93cfeee6b176ab74d67de\"\n+react-navigation-tabs@0.3.0:\n+ version \"0.3.0\"\n+ resolved \"https://registry.yarnpkg.com/react-navigation-tabs/-/react-navigation-tabs-0.3.0.tgz#b1fe7ef1c665dd8928fafcc8622616e220ae5efa\"\ndependencies:\nhoist-non-react-statics \"^2.5.0\"\nprop-types \"^15.6.0\"\n- react-lifecycles-compat \"^1.0.2\"\n+ react-lifecycles-compat \"^3.0.4\"\nreact-native-safe-area-view \"^0.7.0\"\n- react-native-tab-view \"~0.0.77\"\n+ react-native-tab-view \"~0.0.78\"\n-react-navigation@^2.0.1:\n- version \"2.0.1\"\n- resolved \"https://registry.yarnpkg.com/react-navigation/-/react-navigation-2.0.1.tgz#adeba4eb16307c0f740c6c9efafd0c0aa6d47002\"\n+react-navigation@^2.0.4:\n+ version \"2.0.4\"\n+ resolved \"https://registry.yarnpkg.com/react-navigation/-/react-navigation-2.0.4.tgz#efc09de09799c2117a54002a6ea0e9b80e92828d\"\ndependencies:\nclamp \"^1.0.1\"\ncreate-react-context \"^0.2.1\"\n@@ -7888,9 +7886,9 @@ react-navigation@^2.0.1:\nprop-types \"^15.5.10\"\nreact-lifecycles-compat \"^3\"\nreact-native-drawer-layout-polyfill \"^1.3.2\"\n- react-native-safe-area-view \"^0.7.0\"\n- react-navigation-deprecated-tab-navigator \"1.2.0\"\n- react-navigation-tabs \"0.2.0\"\n+ react-native-safe-area-view \"^0.8.0\"\n+ react-navigation-deprecated-tab-navigator \"1.3.0\"\n+ react-navigation-tabs \"0.3.0\"\nreact-proxy@^1.1.7:\nversion \"1.1.8\"\n@@ -8881,6 +8879,10 @@ stream-buffers@~2.2.0:\nversion \"2.2.0\"\nresolved \"https://registry.yarnpkg.com/stream-buffers/-/stream-buffers-2.2.0.tgz#91d5f5130d1cef96dcfa7f726945188741d09ee4\"\n+stream-cache@^0.0.2:\n+ version \"0.0.2\"\n+ resolved \"https://registry.yarnpkg.com/stream-cache/-/stream-cache-0.0.2.tgz#1ac5ad6832428ca55667dbdee395dad4e6db118f\"\n+\nstream-combiner@~0.0.4:\nversion \"0.0.4\"\nresolved \"https://registry.yarnpkg.com/stream-combiner/-/stream-combiner-0.0.4.tgz#4d5e433c185261dde623ca3f44c586bcf5c4ad14\"\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Buffer mysqldump results in memory mysqldump shouldn't hang when the file write stream runs out of space anymore, and we won't call mysqldump twice in that scenario anymore.
129,187
15.06.2018 08:36:20
-28,800
bb9f3542a152e4667fb960f4b7850d2e5ccb6002
[native] Update to the latest react-navigation and redux-helpers versions
[ { "change_type": "MODIFY", "old_path": "native/app.react.js", "new_path": "native/app.react.js", "diff": "@@ -50,10 +50,7 @@ import {\nAlert,\nDeviceInfo,\n} from 'react-native';\n-import {\n- createNavigationPropConstructor,\n- initializeListeners,\n-} from 'react-navigation-redux-helpers';\n+import { reduxifyNavigator } from 'react-navigation-redux-helpers';\nimport invariant from 'invariant';\nimport PropTypes from 'prop-types';\nimport NotificationsIOS from 'react-native-notifications';\n@@ -122,8 +119,8 @@ registerConfig({\nplatform: Platform.OS,\n});\n-const reactNavigationPropConstructor = createNavigationPropConstructor(\"root\");\nconst msInDay = 24 * 60 * 60 * 1000;\n+const ReduxifiedRootNavigator = reduxifyNavigator(RootNavigator, \"root\");\ntype NativeDispatch = Dispatch & ((action: NavigationAction) => boolean);\n@@ -203,7 +200,6 @@ class AppWithNavigationState extends React.PureComponent<Props> {\nNativeAppState.addEventListener('change', this.handleAppStateChange);\nthis.handleInitialURL();\nLinking.addEventListener('url', this.handleURLChange);\n- initializeListeners(\"root\", this.props.navigationState);\nif (this.props.loggedIn) {\nthis.startTimeouts(this.props, \"active\");\n}\n@@ -823,14 +819,13 @@ class AppWithNavigationState extends React.PureComponent<Props> {\n}\nrender() {\n- const navigation = reactNavigationPropConstructor(\n- this.props.dispatch,\n- this.props.navigationState,\n- );\nconst inAppNotificationHeight = DeviceInfo.isIPhoneX_deprecated ? 104 : 80;\nreturn (\n<View style={styles.app}>\n- <RootNavigator navigation={navigation} />\n+ <ReduxifiedRootNavigator\n+ state={this.props.navigationState}\n+ dispatch={this.props.dispatch}\n+ />\n<ConnectedStatusBar />\n<InAppNotification\nheight={inAppNotificationHeight}\n" }, { "change_type": "MODIFY", "old_path": "native/calendar/calendar.react.js", "new_path": "native/calendar/calendar.react.js", "diff": "@@ -172,10 +172,14 @@ class InnerCalendar extends React.PureComponent<Props, State> {\nstyle={[styles.icon, { color: tintColor }]}\n/>\n),\n- tabBarOnPress: ({ navigation }: {\n+ tabBarOnPress: ({ navigation, defaultHandler }: {\nnavigation: NavigationScreenProp<NavigationRoute>,\n+ defaultHandler: () => void,\n}) => {\n- if (navigation.isFocused() && currentCalendarRef) {\n+ if (!navigation.isFocused()) {\n+ defaultHandler();\n+ }\n+ if (currentCalendarRef) {\ncurrentCalendarRef.scrollToToday();\n}\n},\n" }, { "change_type": "MODIFY", "old_path": "native/chat/chat.react.js", "new_path": "native/chat/chat.react.js", "diff": "@@ -39,10 +39,12 @@ Chat.navigationOptions = ({ navigation }) => ({\n? ({ tintColor }) => <ChatLabel color={tintColor} />\n: \"Chat\",\ntabBarIcon: ({ tintColor }) => <ChatIcon color={tintColor} />,\n- tabBarOnPress: ({ navigation }: {\n+ tabBarOnPress: ({ navigation, defaultHandler }: {\nnavigation: NavigationScreenProp<NavigationStateRoute>,\n+ defaultHandler: () => void,\n}) => {\nif (!navigation.isFocused()) {\n+ defaultHandler();\nreturn;\n}\nconst state = navigation.state;\n" }, { "change_type": "MODIFY", "old_path": "native/flow-typed/npm/react-navigation_v2.x.x.js", "new_path": "native/flow-typed/npm/react-navigation_v2.x.x.js", "diff": "+// flow-typed signature: f11177b9fec0950067d1c26bb2d3e44c\n+// flow-typed version: cd88cfb433/react-navigation_v2.x.x/flow_>=v0.60.x\n+\n// @flow\ndeclare module 'react-navigation' {\n@@ -69,6 +72,14 @@ declare module 'react-navigation' {\n[key: string]: mixed,\n};\n+ declare export type NavigationBackAction = {|\n+ type: 'Navigation/BACK',\n+ key?: ?string,\n+ |};\n+ declare export type NavigationInitAction = {|\n+ type: 'Navigation/INIT',\n+ params?: NavigationParams,\n+ |};\ndeclare export type NavigationNavigateAction = {|\ntype: 'Navigation/NAVIGATE',\nrouteName: string,\n@@ -79,12 +90,6 @@ declare module 'react-navigation' {\nkey?: string,\n|};\n-\n- declare export type NavigationBackAction = {|\n- type: 'Navigation/BACK',\n- key?: ?string,\n- |};\n-\ndeclare export type NavigationSetParamsAction = {|\ntype: 'Navigation/SET_PARAMS',\n@@ -95,23 +100,28 @@ declare module 'react-navigation' {\nparams: NavigationParams,\n|};\n- declare export type NavigationInitAction = {|\n- type: 'Navigation/INIT',\n- params?: NavigationParams,\n+ declare export type NavigationPopAction = {|\n+ +type: 'Navigation/POP',\n+ +n?: number,\n+ +immediate?: boolean,\n+ |};\n+ declare export type NavigationPopToTopAction = {|\n+ +type: 'Navigation/POP_TO_TOP',\n+ +immediate?: boolean,\n+ |};\n+ declare export type NavigationPushAction = {|\n+ +type: 'Navigation/PUSH',\n+ +routeName: string,\n+ +params?: NavigationParams,\n+ +action?: NavigationNavigateAction,\n+ +key?: string,\n|};\n-\ndeclare export type NavigationResetAction = {|\ntype: 'Navigation/RESET',\nindex: number,\nkey?: ?string,\nactions: Array<NavigationNavigateAction>,\n|};\n-\n- declare export type NavigationUriAction = {|\n- type: 'Navigation/URI',\n- uri: string,\n- |};\n-\ndeclare export type NavigationReplaceAction = {|\n+type: 'Navigation/REPLACE',\n+key: string,\n@@ -119,33 +129,38 @@ declare module 'react-navigation' {\n+params?: NavigationParams,\n+action?: NavigationNavigateAction,\n|};\n- declare export type NavigationPopAction = {|\n- +type: 'Navigation/POP',\n- +n?: number,\n- +immediate?: boolean,\n+ declare export type NavigationCompleteTransitionAction = {|\n+ +type: 'Navigation/COMPLETE_TRANSITION',\n+ +key?: string,\n|};\n- declare export type NavigationPopToTopAction = {|\n- +type: 'Navigation/POP_TO_TOP',\n- +immediate?: boolean,\n+\n+ declare export type NavigationOpenDrawerAction = {|\n+ +type: 'Navigation/OPEN_DRAWER',\n+ +key?: string,\n|};\n- declare export type NavigationPushAction = {|\n- +type: 'Navigation/PUSH',\n- +routeName: string,\n- +params?: NavigationParams,\n- +action?: NavigationNavigateAction,\n+ declare export type NavigationCloseDrawerAction = {|\n+ +type: 'Navigation/CLOSE_DRAWER',\n+ +key?: string,\n+ |};\n+ declare export type NavigationToggleDrawerAction = {|\n+ +type: 'Navigation/TOGGLE_DRAWER',\n+key?: string,\n|};\ndeclare export type NavigationAction =\n+ | NavigationBackAction\n| NavigationInitAction\n| NavigationNavigateAction\n- | NavigationReplaceAction\n+ | NavigationSetParamsAction\n| NavigationPopAction\n| NavigationPopToTopAction\n| NavigationPushAction\n- | NavigationBackAction\n- | NavigationSetParamsAction\n- | NavigationResetAction;\n+ | NavigationResetAction\n+ | NavigationReplaceAction\n+ | NavigationCompleteTransitionAction\n+ | NavigationOpenDrawerAction\n+ | NavigationCloseDrawerAction\n+ | NavigationToggleDrawerAction;\n/**\n* NavigationState is a tree of routes for a single navigator, where each\n@@ -269,24 +284,36 @@ declare module 'react-navigation' {\ndeclare export type NavigationComponent =\n| NavigationScreenComponent<NavigationRoute, *, *>\n- | NavigationContainer<*, *, *>\n- | any;\n+ | NavigationContainer<*, *, *>;\n+\n+ declare interface withOptionalNavigationOptions<Options> {\n+ navigationOptions?: NavigationScreenConfig<Options>;\n+ }\ndeclare export type NavigationScreenComponent<\nRoute: NavigationRoute,\nOptions: {},\nProps: {}\n- > = React$ComponentType<NavigationNavigatorProps<Options, Route> & Props> &\n- ({} | { navigationOptions: NavigationScreenConfig<Options> });\n+ > = React$ComponentType<{\n+ ...Props,\n+ ...NavigationNavigatorProps<Options, Route>,\n+ }> &\n+ withOptionalNavigationOptions<Options>;\n+\n+ declare interface withRouter<State, Options> {\n+ router: NavigationRouter<State, Options>;\n+ }\ndeclare export type NavigationNavigator<\nState: NavigationState,\nOptions: {},\nProps: {}\n- > = React$ComponentType<NavigationNavigatorProps<Options, State> & Props> & {\n- router: NavigationRouter<State, Options>,\n- navigationOptions?: ?NavigationScreenConfig<Options>,\n- };\n+ > = React$ComponentType<{\n+ ...Props,\n+ ...NavigationNavigatorProps<Options, State>,\n+ }> &\n+ withRouter<State, Options> &\n+ withOptionalNavigationOptions<Options>;\ndeclare export type NavigationRouteConfig =\n| NavigationComponent\n@@ -426,10 +453,10 @@ declare module 'react-navigation' {\n| ((options: { tintColor: ?string, focused: boolean }) => ?React$Node),\ntabBarVisible?: boolean,\ntabBarTestIDProps?: { testID?: string, accessibilityLabel?: string },\n- tabBarOnPress?: (\n- scene: TabScene,\n- jumpToIndex: (index: number) => void\n- ) => void,\n+ tabBarOnPress?: ({\n+ navigation: NavigationScreenProp<NavigationRoute>,\n+ defaultHandler: () => void,\n+ }) => void,\n|};\n/**\n@@ -483,31 +510,48 @@ declare module 'react-navigation' {\n};\ndeclare export type NavigationScreenProp<+S> = {\n- ...$ObjMap<\n- _DefaultActionCreators,\n- <Args>((...args: Args) => *) => (...args: Args) => boolean,\n- >,\n+state: S,\ndispatch: NavigationDispatch,\n- dismiss: () => boolean,\n- getParam: (paramName: string, fallback?: any) => any,\naddListener: (\neventName: string,\ncallback: NavigationEventCallback\n) => NavigationEventSubscription,\n- push: (\n+ getParam: (paramName: string, fallback?: any) => any,\n+ isFocused: () => boolean,\n+ // Shared action creators that exist for all routers\n+ goBack: (routeKey?: ?string) => boolean,\n+ navigate: (\n+ routeName:\n+ | string\n+ | {\nrouteName: string,\nparams?: NavigationParams,\n+ action?: NavigationNavigateAction,\n+ key?: string,\n+ },\n+ params?: NavigationParams,\naction?: NavigationNavigateAction\n) => boolean,\n- replace: (\n+ setParams: (newParams: NavigationParams) => boolean,\n+ // StackRouter action creators\n+ pop?: (n?: number, params?: { immediate?: boolean }) => boolean,\n+ popToTop?: (params?: { immediate?: boolean }) => boolean,\n+ push?: (\nrouteName: string,\nparams?: NavigationParams,\naction?: NavigationNavigateAction\n) => boolean,\n- pop: (n?: number, params?: { immediate?: boolean }) => boolean,\n- popToTop: (params?: { immediate?: boolean }) => boolean,\n- isFocused: () => boolean,\n+ replace?: (\n+ routeName: string,\n+ params?: NavigationParams,\n+ action?: NavigationNavigateAction\n+ ) => boolean,\n+ reset?: (actions: NavigationAction[], index: number) => boolean,\n+ dismiss?: () => boolean,\n+ // DrawerRouter action creators\n+ openDrawer?: () => boolean,\n+ closeDrawer?: () => boolean,\n+ toggleDrawer?: () => boolean,\n};\ndeclare export type NavigationNavigatorProps<O: {}, S: {}> = $Shape<{\n@@ -524,10 +568,12 @@ declare module 'react-navigation' {\nState: NavigationState,\nOptions: {},\nProps: {}\n- > = React$ComponentType<NavigationContainerProps<State, Options> & Props> & {\n- router: NavigationRouter<State, Options>,\n- navigationOptions?: ?NavigationScreenConfig<Options>,\n- };\n+ > = React$ComponentType<{\n+ ...Props,\n+ ...NavigationContainerProps<State, Options>,\n+ }> &\n+ withRouter<State, Options> &\n+ withOptionalNavigationOptions<Options>;\ndeclare export type NavigationContainerProps<S: {}, O: {}> = $Shape<{\nuriPrefix?: string | RegExp,\n@@ -696,65 +742,74 @@ declare module 'react-navigation' {\nBACK: 'Navigation/BACK',\nINIT: 'Navigation/INIT',\nNAVIGATE: 'Navigation/NAVIGATE',\n- RESET: 'Navigation/RESET',\nSET_PARAMS: 'Navigation/SET_PARAMS',\n- URI: 'Navigation/URI',\n- back: {\n- (payload?: { key?: ?string }): NavigationBackAction,\n- toString: () => string,\n- },\n- init: {\n- (payload?: { params?: NavigationParams }): NavigationInitAction,\n- toString: () => string,\n- },\n- navigate: {\n- (payload: {\n+\n+ back: (payload?: { key?: ?string }) => NavigationBackAction,\n+ init: (payload?: { params?: NavigationParams }) => NavigationInitAction,\n+ navigate: (payload: {\nrouteName: string,\nparams?: ?NavigationParams,\naction?: ?NavigationNavigateAction,\n- }): NavigationNavigateAction,\n- toString: () => string,\n- },\n- reset: {\n- (payload: {\n- index: number,\n- key?: ?string,\n- actions: Array<NavigationNavigateAction>,\n- }): NavigationResetAction,\n- toString: () => string,\n- },\n- setParams: {\n- (payload: {\n+ key?: string,\n+ }) => NavigationNavigateAction,\n+ setParams: (payload: {\nkey: string,\nparams: NavigationParams,\n- }): NavigationSetParamsAction,\n- toString: () => string,\n- },\n- uri: {\n- (payload: { uri: string }): NavigationUriAction,\n- toString: () => string,\n- },\n+ }) => NavigationSetParamsAction,\n};\n- declare type _DefaultActionCreators = {|\n- goBack: (routeKey?: ?string) => NavigationBackAction,\n- navigate: (\n- routeName:\n- | string\n- | {\n+ declare export var StackActions: {\n+ POP: 'Navigation/POP',\n+ POP_TO_TOP: 'Navigation/POP_TO_TOP',\n+ PUSH: 'Navigation/PUSH',\n+ RESET: 'Navigation/RESET',\n+ REPLACE: 'Navigation/REPLACE',\n+ COMPLETE_TRANSITION: 'Navigation/COMPLETE_TRANSITION',\n+\n+ pop: (payload: {\n+ n?: number,\n+ immediate?: boolean,\n+ }) => NavigationPopAction,\n+ popToTop: (payload: {\n+ immediate?: boolean,\n+ }) => NavigationPopToTopAction,\n+ push: (payload: {\nrouteName: string,\nparams?: NavigationParams,\naction?: NavigationNavigateAction,\nkey?: string,\n- },\n+ }) => NavigationPushAction,\n+ reset: (payload: {\n+ index: number,\n+ key?: ?string,\n+ actions: Array<NavigationNavigateAction>,\n+ }) => NavigationResetAction,\n+ replace: (payload: {\n+ key: string,\n+ routeName: string,\nparams?: NavigationParams,\n- action?: NavigationNavigateAction\n- ) => NavigationNavigateAction,\n- setParams: (newParams: NavigationParams) => NavigationSetParamsAction,\n- |};\n- declare export function getNavigationActionCreators(\n- route: NavigationRoute | NavigationState\n- ): _DefaultActionCreators;\n+ action?: NavigationNavigateAction,\n+ }) => NavigationReplaceAction,\n+ completeTransition: (payload: {\n+ key?: string,\n+ }) => NavigationCompleteTransitionAction,\n+ };\n+\n+ declare export var DrawerActions: {\n+ OPEN_DRAWER: 'Navigation/OPEN_DRAWER',\n+ CLOSE_DRAWER: 'Navigation/CLOSE_DRAWER',\n+ TOGGLE_DRAWER: 'Navigation/TOGGLE_DRAWER',\n+\n+ openDrawer: (payload: {\n+ key?: string,\n+ }) => NavigationOpenDrawerAction,\n+ closeDrawer: (payload: {\n+ key?: string,\n+ }) => NavigationCloseDrawerAction,\n+ toggleDrawer: (payload: {\n+ key?: string,\n+ }) => NavigationToggleDrawerAction,\n+ };\ndeclare type _RouterProp<S: NavigationState, O: {}> = {\nrouter: NavigationRouter<S, O>,\n@@ -776,7 +831,7 @@ declare module 'react-navigation' {\nview: NavigationView<O, S>,\nrouter: NavigationRouter<S, O>,\nnavigatorConfig?: NavigatorConfig\n- ): any;\n+ ): NavigationNavigator<S, O, *>;\ndeclare export function StackNavigator(\nrouteConfigMap: NavigationRouteConfigMap,\n@@ -1107,4 +1162,13 @@ declare module 'react-navigation' {\ndeclare export function withNavigationFocus<Props: {}>(\nComponent: React$ComponentType<Props>\n): React$ComponentType<$Diff<Props, { isFocused: boolean | void }>>;\n+\n+ declare export function getNavigation<State: NavigationState, Options: {}>(\n+ router: NavigationRouter<State, Options>,\n+ state: State,\n+ dispatch: NavigationDispatch,\n+ actionSubscribers: Set<NavigationEventCallback>,\n+ getScreenProps: () => {},\n+ getCurrentNavigation: () => NavigationScreenProp<State>\n+ ): NavigationScreenProp<State>;\n}\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.0.6\",\n\"react-native-vector-icons\": \"^4.5.0\",\n- \"react-navigation\": \"^2.0.4\",\n- \"react-navigation-redux-helpers\": \"^1.1.0\",\n+ \"react-navigation\": \"^2.3.1\",\n+ \"react-navigation-redux-helpers\": \"^2.0.1\",\n\"react-redux\": \"^5.0.6\",\n\"redux\": \"^3.7.2\",\n\"redux-devtools-extension\": \"^2.13.2\",\n" }, { "change_type": "MODIFY", "old_path": "native/redux-setup.js", "new_path": "native/redux-setup.js", "diff": "@@ -30,7 +30,7 @@ import { createStore, applyMiddleware } from 'redux';\nimport { composeWithDevTools } from 'redux-devtools-extension';\nimport { persistStore, persistReducer } from 'redux-persist';\nimport PropTypes from 'prop-types';\n-import { NavigationActions } from 'react-navigation';\n+import { NavigationActions, StackActions } from 'react-navigation';\nimport {\ncreateReactNavigationReduxMiddleware,\n} from 'react-navigation-redux-helpers';\n@@ -300,7 +300,12 @@ function reducer(state: AppState = defaultState, action: *) {\naction.type === NavigationActions.NAVIGATE ||\naction.type === NavigationActions.BACK ||\naction.type === NavigationActions.SET_PARAMS ||\n- action.type === NavigationActions.RESET\n+ action.type === StackActions.POP ||\n+ action.type === StackActions.POP_TO_TOP ||\n+ action.type === StackActions.PUSH ||\n+ action.type === StackActions.RESET ||\n+ action.type === StackActions.REPLACE ||\n+ action.type === StackActions.COMPLETE_TRANSITION\n) {\nreturn validateState(oldState, state);\n}\n" }, { "change_type": "MODIFY", "old_path": "server/src/backups.js", "new_path": "server/src/backups.js", "diff": "@@ -14,7 +14,7 @@ const readdir = denodeify(fs.readdir);\nconst lstat = denodeify(fs.lstat);\nconst unlink = denodeify(fs.unlink);\n-async function backupDB(retries: number = 2) {\n+async function backupDB() {\nif (!backupConfig || !backupConfig.enabled) {\nreturn;\n}\n" }, { "change_type": "MODIFY", "old_path": "yarn.lock", "new_path": "yarn.lock", "diff": "@@ -7775,11 +7775,11 @@ react-native-tab-view@^0.0.77:\ndependencies:\nprop-types \"^15.6.0\"\n-react-native-tab-view@~0.0.78:\n- version \"0.0.78\"\n- resolved \"https://registry.yarnpkg.com/react-native-tab-view/-/react-native-tab-view-0.0.78.tgz#9b90730d89cbd34a03f0e0ab10e74ca7af945560\"\n+react-native-tab-view@^1.0.0:\n+ version \"1.0.2\"\n+ resolved \"https://registry.yarnpkg.com/react-native-tab-view/-/react-native-tab-view-1.0.2.tgz#66e0bc6d38a227ed2b212e3a256b7902f6ce02ed\"\ndependencies:\n- prop-types \"^15.6.0\"\n+ prop-types \"^15.6.1\"\nreact-native-vector-icons@^4.5.0:\nversion \"4.6.0\"\n@@ -7859,25 +7859,31 @@ react-navigation-deprecated-tab-navigator@1.3.0:\ndependencies:\nreact-native-tab-view \"^0.0.77\"\n-react-navigation-redux-helpers@^1.1.0:\n- version \"1.1.0\"\n- resolved \"https://registry.yarnpkg.com/react-navigation-redux-helpers/-/react-navigation-redux-helpers-1.1.0.tgz#b003cb993193e78ad109563f93faadbc3c62c1e1\"\n+react-navigation-drawer@0.3.0:\n+ version \"0.3.0\"\n+ resolved \"https://registry.yarnpkg.com/react-navigation-drawer/-/react-navigation-drawer-0.3.0.tgz#641007213f0f1e1b55a0a4bb64d71df07b3e7208\"\n+ dependencies:\n+ react-native-drawer-layout-polyfill \"^1.3.2\"\n+\n+react-navigation-redux-helpers@^2.0.1:\n+ version \"2.0.1\"\n+ resolved \"https://registry.yarnpkg.com/react-navigation-redux-helpers/-/react-navigation-redux-helpers-2.0.1.tgz#2af99d372557a632d3eacd1878a1d6ca41dcfdcf\"\ndependencies:\ninvariant \"^2.2.2\"\n-react-navigation-tabs@0.3.0:\n- version \"0.3.0\"\n- resolved \"https://registry.yarnpkg.com/react-navigation-tabs/-/react-navigation-tabs-0.3.0.tgz#b1fe7ef1c665dd8928fafcc8622616e220ae5efa\"\n+react-navigation-tabs@0.5.1:\n+ version \"0.5.1\"\n+ resolved \"https://registry.yarnpkg.com/react-navigation-tabs/-/react-navigation-tabs-0.5.1.tgz#ed33bce3a3e21b92646700de25bd94b8fc570371\"\ndependencies:\nhoist-non-react-statics \"^2.5.0\"\n- prop-types \"^15.6.0\"\n+ prop-types \"^15.6.1\"\nreact-lifecycles-compat \"^3.0.4\"\nreact-native-safe-area-view \"^0.7.0\"\n- react-native-tab-view \"~0.0.78\"\n+ react-native-tab-view \"^1.0.0\"\n-react-navigation@^2.0.4:\n- version \"2.0.4\"\n- resolved \"https://registry.yarnpkg.com/react-navigation/-/react-navigation-2.0.4.tgz#efc09de09799c2117a54002a6ea0e9b80e92828d\"\n+react-navigation@^2.3.1:\n+ version \"2.3.1\"\n+ resolved \"https://registry.yarnpkg.com/react-navigation/-/react-navigation-2.3.1.tgz#f0734ecc64a0af70395f889d9ffa8f610642eed5\"\ndependencies:\nclamp \"^1.0.1\"\ncreate-react-context \"^0.2.1\"\n@@ -7885,10 +7891,10 @@ react-navigation@^2.0.4:\npath-to-regexp \"^1.7.0\"\nprop-types \"^15.5.10\"\nreact-lifecycles-compat \"^3\"\n- react-native-drawer-layout-polyfill \"^1.3.2\"\nreact-native-safe-area-view \"^0.8.0\"\nreact-navigation-deprecated-tab-navigator \"1.3.0\"\n- react-navigation-tabs \"0.3.0\"\n+ react-navigation-drawer \"0.3.0\"\n+ react-navigation-tabs \"0.5.1\"\nreact-proxy@^1.1.7:\nversion \"1.1.8\"\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Update to the latest react-navigation and redux-helpers versions
129,187
18.06.2018 17:55:40
-28,800
6cfb7481a4d730e3938e226d4206787ff7643361
Move member filtering hack from ServerThreadInfo to RawThreadInfo
[ { "change_type": "MODIFY", "old_path": "lib/shared/thread-utils.js", "new_path": "lib/shared/thread-utils.js", "diff": "@@ -95,6 +95,17 @@ function rawThreadInfoFromServerThreadInfo(\nconst members = [];\nlet currentUser;\nfor (let serverMember of serverThreadInfo.members) {\n+ // This is a hack, similar to what we have in ThreadSettingsMember.\n+ // Basically we only want to return users that are either a member of this\n+ // thread, or are a \"parent admin\". We approximate \"parent admin\" by\n+ // looking for the PERMISSION_CHANGE_ROLE permission.\n+ if (\n+ serverMember.id !== viewerID &&\n+ !serverMember.role &&\n+ !serverMember.permissions[threadPermissions.CHANGE_ROLE].value\n+ ) {\n+ continue;\n+ }\nmembers.push({\nid: serverMember.id,\nrole: serverMember.role,\n" }, { "change_type": "MODIFY", "old_path": "server/src/fetchers/thread-fetchers.js", "new_path": "server/src/fetchers/thread-fetchers.js", "diff": "@@ -24,7 +24,6 @@ type FetchServerThreadInfosResult = {|\n|};\nasync function fetchServerThreadInfos(\n- viewer: Viewer,\ncondition?: SQLStatement,\n): Promise<FetchServerThreadInfosResult> {\nconst whereClause = condition ? SQL`WHERE `.append(condition) : \"\";\n@@ -78,23 +77,13 @@ async function fetchServerThreadInfos(\nif (row.user) {\nconst userID = row.user.toString();\nconst allPermissions = getAllThreadPermissions(row.permissions, threadID);\n- const member = {\n+ threadInfos[threadID].members.push({\nid: userID,\npermissions: allPermissions,\nrole: row.role ? role : null,\nsubscription: row.subscription,\nunread: row.role ? !!row.unread : null,\n- };\n- // This is a hack, similar to what we have in ThreadSettingsMember.\n- // Basically we only want to return users that are either a member of this\n- // thread, or are a \"parent admin\". We approximate \"parent admin\" by\n- // looking for the PERMISSION_CHANGE_ROLE permission.\n- if (\n- userID === viewer.id ||\n- row.role ||\n- allPermissions[threadPermissions.CHANGE_ROLE].value\n- ) {\n- threadInfos[threadID].members.push(member);\n+ });\nif (row.username) {\nuserInfos[userID] = {\nid: userID,\n@@ -103,7 +92,6 @@ async function fetchServerThreadInfos(\n}\n}\n}\n- }\nreturn { threadInfos, userInfos };\n}\n@@ -116,7 +104,7 @@ async function fetchThreadInfos(\nviewer: Viewer,\ncondition?: SQLStatement,\n): Promise<FetchThreadInfosResult> {\n- const serverResult = await fetchServerThreadInfos(viewer, condition);\n+ const serverResult = await fetchServerThreadInfos(condition);\nconst viewerID = viewer.id;\nconst threadInfos = {};\nconst userInfos = {};\n" }, { "change_type": "MODIFY", "old_path": "server/src/updaters/thread-updaters.js", "new_path": "server/src/updaters/thread-updaters.js", "diff": "@@ -211,7 +211,7 @@ async function leaveThread(\n): Promise<LeaveThreadResult> {\nconst [ isMember, { threadInfos: serverThreadInfos } ] = await Promise.all([\nviewerIsMember(viewer, request.threadID),\n- fetchServerThreadInfos(viewer, SQL`t.id = ${request.threadID}`),\n+ fetchServerThreadInfos(SQL`t.id = ${request.threadID}`),\n]);\nif (!isMember) {\nthrow new ServerError('invalid_parameters');\n" }, { "change_type": "MODIFY", "old_path": "web/dist/app.build.js", "new_path": "web/dist/app.build.js", "diff": "@@ -1498,6 +1498,13 @@ function rawThreadInfoFromServerThreadInfo(serverThreadInfo, viewerID) {\nconst members = [];\nlet currentUser;\nfor (let serverMember of serverThreadInfo.members) {\n+ // This is a hack, similar to what we have in ThreadSettingsMember.\n+ // Basically we only want to return users that are either a member of this\n+ // thread, or are a \"parent admin\". We approximate \"parent admin\" by\n+ // looking for the PERMISSION_CHANGE_ROLE permission.\n+ if (serverMember.id !== viewerID && !serverMember.role && !serverMember.permissions[__WEBPACK_IMPORTED_MODULE_0__types_thread_types__[\"e\" /* threadPermissions */].CHANGE_ROLE].value) {\n+ continue;\n+ }\nmembers.push({\nid: serverMember.id,\nrole: serverMember.role,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Move member filtering hack from ServerThreadInfo to RawThreadInfo
129,187
18.06.2018 19:03:04
-28,800
42807825142cbc2ffd5a2fc1789444f702a8bede
[server] Add updater_cookie column to updates table
[ { "change_type": "MODIFY", "old_path": "server/src/creators/update-creator.js", "new_path": "server/src/creators/update-creator.js", "diff": "@@ -12,6 +12,7 @@ import { dbQuery, SQL } from '../database';\nimport createIDs from './id-creator';\nasync function createUpdates(\n+ cookieID: string,\nupdateDatas: $ReadOnlyArray<UpdateData>,\n): Promise<UpdateInfo[]> {\nif (updateDatas.length === 0) {\n@@ -35,13 +36,14 @@ async function createUpdates(\nids[i],\nupdateData.userID,\nupdateData.type,\n+ cookieID,\ncontent,\nupdateData.time,\n]);\n}\nconst insertQuery = SQL`\n- INSERT INTO updates(id, user, type, content, time)\n+ INSERT INTO updates(id, user, type, updater_cookie, content, time)\nVALUES ${insertRows}\n`;\nawait dbQuery(insertQuery);\n" }, { "change_type": "MODIFY", "old_path": "server/src/deleters/account-deleters.js", "new_path": "server/src/deleters/account-deleters.js", "diff": "@@ -54,9 +54,10 @@ async function deleteAccount(\ncreateNewAnonymousCookie(viewer.platform),\ndbQuery(deletionQuery),\n]);\n+ const oldCookieID = viewer.cookieID;\nviewer.setNewCookie(anonymousViewerData);\n- createAccountDeletionUpdates(deletedUserID);\n+ createAccountDeletionUpdates(oldCookieID, deletedUserID);\nreturn {\ncurrentUserInfo: {\n@@ -67,6 +68,7 @@ async function deleteAccount(\n}\nasync function createAccountDeletionUpdates(\n+ oldCookieID: string,\ndeletedUserID: string,\n): Promise<void> {\nconst allUserIDs = await fetchAllUserIDs();\n@@ -77,7 +79,7 @@ async function createAccountDeletionUpdates(\ntime,\ndeletedUserID,\n}));\n- await createUpdates(updateDatas);\n+ await createUpdates(oldCookieID, updateDatas);\n}\nexport {\n" }, { "change_type": "MODIFY", "old_path": "server/src/deleters/update-deleters.js", "new_path": "server/src/deleters/update-deleters.js", "diff": "@@ -14,7 +14,7 @@ async function deleteExpiredUpdates(): Promise<void> {\nRIGHT JOIN users u ON u.id = c.user\nGROUP BY u.id\n) o ON o.user = u.user\n- WHERE u.time < o.oldest_last_update\n+ WHERE o.user IS NULL OR u.time < o.oldest_last_update\n`);\n}\n" }, { "change_type": "MODIFY", "old_path": "server/src/fetchers/update-fetchers.js", "new_path": "server/src/fetchers/update-fetchers.js", "diff": "@@ -42,6 +42,8 @@ async function fetchUpdateInfos(\nSELECT id, type, content, time\nFROM updates\nWHERE user = ${viewer.id} AND time > ${currentAsOf}\n+ AND updater_cookie != ${viewer.cookieID}\n+ ORDER BY time ASC\n`;\nconst [ result ] = await dbQuery(query);\n" }, { "change_type": "MODIFY", "old_path": "server/src/updaters/thread-updaters.js", "new_path": "server/src/updaters/thread-updaters.js", "diff": "@@ -116,7 +116,7 @@ async function updateRole(\nawait fetchServerThreadInfos(SQL`t.id = ${request.threadID}`);\nconst serverThreadInfo = serverThreadInfos[request.threadID];\n- createThreadUpdates(serverThreadInfo);\n+ createThreadUpdates(viewer, serverThreadInfo);\nconst threadInfo = rawThreadInfoFromServerThreadInfo(\nserverThreadInfo,\n@@ -130,6 +130,7 @@ async function updateRole(\n}\nasync function createThreadUpdates(\n+ viewer: Viewer,\nserverThreadInfo: ServerThreadInfo,\n): Promise<void> {\nconst time = Date.now();\n@@ -149,7 +150,7 @@ async function createThreadUpdates(\nthreadInfo,\n});\n}\n- await createUpdates(updateDatas);\n+ await createUpdates(viewer.cookieID, updateDatas);\n}\nasync function removeMembers(\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Add updater_cookie column to updates table
129,187
18.06.2018 20:19:09
-28,800
6b73310d73dbabe4e6e0a2412d9b72e4cc0d4cf8
[server] Do permission check before any mutations in createEntry
[ { "change_type": "MODIFY", "old_path": "server/src/creators/entry-creator.js", "new_path": "server/src/creators/entry-creator.js", "diff": "@@ -20,17 +20,20 @@ async function createEntry(\nviewer: Viewer,\nrequest: CreateEntryRequest,\n): Promise<SaveEntryResult> {\n+ const hasPermission = await checkThreadPermission(\n+ viewer,\n+ request.threadID,\n+ threadPermissions.EDIT_ENTRIES,\n+ );\n+ if (!hasPermission) {\n+ throw new ServerError('invalid_credentials');\n+ }\n+\nconst [\n- hasPermission,\ndayID,\n[ entryID ],\n[ revisionID ],\n] = await Promise.all([\n- checkThreadPermission(\n- viewer,\n- request.threadID,\n- threadPermissions.EDIT_ENTRIES,\n- ),\nfetchOrCreateDayID(\nrequest.threadID,\nrequest.date,\n@@ -38,9 +41,6 @@ async function createEntry(\ncreateIDs(\"entries\", 1),\ncreateIDs(\"revisions\", 1),\n]);\n- if (!hasPermission) {\n- throw new ServerError('invalid_credentials');\n- }\nconst viewerID = viewer.id;\nconst entryRow = [\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Do permission check before any mutations in createEntry
129,187
18.06.2018 11:55:46
25,200
eee60fcf2938aa343207439dd51d7bc4a0084118
[server] Make update_cookier column optional
[ { "change_type": "MODIFY", "old_path": "server/src/creators/update-creator.js", "new_path": "server/src/creators/update-creator.js", "diff": "@@ -12,8 +12,8 @@ import { dbQuery, SQL } from '../database';\nimport createIDs from './id-creator';\nasync function createUpdates(\n- cookieID: string,\nupdateDatas: $ReadOnlyArray<UpdateData>,\n+ cookieID?: ?string,\n): Promise<UpdateInfo[]> {\nif (updateDatas.length === 0) {\nreturn [];\n@@ -32,20 +32,23 @@ async function createUpdates(\n} else if (updateData.type === updateTypes.UPDATE_THREAD) {\ncontent = JSON.stringify(updateData.threadInfo);\n}\n- insertRows.push([\n+ const insertRow = [\nids[i],\nupdateData.userID,\nupdateData.type,\n- cookieID,\ncontent,\nupdateData.time,\n- ]);\n+ ];\n+ if (cookieID) {\n+ insertRow.push(cookieID);\n+ }\n+ insertRows.push(insertRow);\n}\n- const insertQuery = SQL`\n- INSERT INTO updates(id, user, type, updater_cookie, content, time)\n- VALUES ${insertRows}\n- `;\n+ const insertQuery = cookieID\n+ ? SQL`INSERT INTO updates(id, user, type, content, time, updater_cookie) `\n+ : SQL`INSERT INTO updates(id, user, type, content, time) `;\n+ insertQuery.append(SQL`VALUES ${insertRows}`);\nawait dbQuery(insertQuery);\nreturn updateInfos;\n" }, { "change_type": "MODIFY", "old_path": "server/src/deleters/account-deleters.js", "new_path": "server/src/deleters/account-deleters.js", "diff": "@@ -57,7 +57,7 @@ async function deleteAccount(\nconst oldCookieID = viewer.cookieID;\nviewer.setNewCookie(anonymousViewerData);\n- createAccountDeletionUpdates(oldCookieID, deletedUserID);\n+ createAccountDeletionUpdates(deletedUserID, oldCookieID);\nreturn {\ncurrentUserInfo: {\n@@ -68,8 +68,8 @@ async function deleteAccount(\n}\nasync function createAccountDeletionUpdates(\n- oldCookieID: string,\ndeletedUserID: string,\n+ oldCookieID: string,\n): Promise<void> {\nconst allUserIDs = await fetchAllUserIDs();\nconst time = Date.now();\n@@ -79,7 +79,7 @@ async function createAccountDeletionUpdates(\ntime,\ndeletedUserID,\n}));\n- await createUpdates(oldCookieID, updateDatas);\n+ await createUpdates(updateDatas, oldCookieID);\n}\nexport {\n" }, { "change_type": "MODIFY", "old_path": "server/src/fetchers/update-fetchers.js", "new_path": "server/src/fetchers/update-fetchers.js", "diff": "@@ -42,7 +42,7 @@ async function fetchUpdateInfos(\nSELECT id, type, content, time\nFROM updates\nWHERE user = ${viewer.id} AND time > ${currentAsOf}\n- AND updater_cookie != ${viewer.cookieID}\n+ AND (updater_cookie IS NULL OR updater_cookie != ${viewer.cookieID})\nORDER BY time ASC\n`;\nconst [ result ] = await dbQuery(query);\n" }, { "change_type": "MODIFY", "old_path": "server/src/updaters/thread-updaters.js", "new_path": "server/src/updaters/thread-updaters.js", "diff": "@@ -150,7 +150,7 @@ async function createThreadUpdates(\nthreadInfo,\n});\n}\n- await createUpdates(viewer.cookieID, updateDatas);\n+ await createUpdates(updateDatas, viewer.cookieID);\n}\nasync function removeMembers(\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Make update_cookier column optional
129,187
18.06.2018 15:01:59
25,200
53a8003e6aa03de25f686deeeb676c42785d260b
[server] Introduce keys for merging updates
[ { "change_type": "MODIFY", "old_path": "server/src/creators/update-creator.js", "new_path": "server/src/creators/update-creator.js", "diff": "@@ -10,6 +10,7 @@ import { updateInfoFromUpdateData } from 'lib/shared/update-utils';\nimport { dbQuery, SQL } from '../database';\nimport createIDs from './id-creator';\n+import { deleteUpdatesByConditions } from '../deleters/update-deleters';\nasync function createUpdates(\nupdateDatas: $ReadOnlyArray<UpdateData>,\n@@ -22,23 +23,46 @@ async function createUpdates(\nconst updateInfos: UpdateInfo[] = [];\nconst insertRows = [];\n+ const deleteConditions = [];\nfor (let i = 0; i < updateDatas.length; i++) {\nconst updateData = updateDatas[i];\nupdateInfos.push(updateInfoFromUpdateData(updateData, ids[i]));\n- let content;\n+ let content, key;\nif (updateData.type === updateTypes.DELETE_ACCOUNT) {\ncontent = JSON.stringify({ deletedUserID: updateData.deletedUserID });\n+ key = null;\n} else if (updateData.type === updateTypes.UPDATE_THREAD) {\ncontent = JSON.stringify(updateData.threadInfo);\n+ key = updateData.threadInfo.id;\n+ const deleteTypes = [\n+ updateTypes.UPDATE_THREAD,\n+ updateTypes.UPDATE_THREAD_READ_STATUS,\n+ ];\n+ deleteConditions.push(\n+ SQL`(\n+ u.user = ${updateData.userID} AND\n+ u.key = ${key} AND\n+ u.type IN (${deleteTypes})\n+ )`\n+ );\n} else if (updateData.type === updateTypes.UPDATE_THREAD_READ_STATUS) {\nconst { threadID, unread } = updateData;\ncontent = JSON.stringify({ threadID, unread });\n+ key = threadID;\n+ deleteConditions.push(\n+ SQL`(\n+ u.user = ${updateData.userID} AND\n+ u.key = ${key} AND\n+ u.type = ${updateData.type}\n+ )`\n+ );\n}\nconst insertRow = [\nids[i],\nupdateData.userID,\nupdateData.type,\n+ key,\ncontent,\nupdateData.time,\n];\n@@ -48,11 +72,21 @@ async function createUpdates(\ninsertRows.push(insertRow);\n}\n+ const promises = [];\n+\nconst insertQuery = cookieID\n- ? SQL`INSERT INTO updates(id, user, type, content, time, updater_cookie) `\n- : SQL`INSERT INTO updates(id, user, type, content, time) `;\n+ ? SQL`\n+ INSERT INTO updates(id, user, type, key, content, time, updater_cookie)\n+ `\n+ : SQL`INSERT INTO updates(id, user, type, key, content, time) `;\ninsertQuery.append(SQL`VALUES ${insertRows}`);\n- await dbQuery(insertQuery);\n+ promises.push(dbQuery(insertQuery));\n+\n+ if (deleteConditions.length > 0) {\n+ promises.push(deleteUpdatesByConditions(deleteConditions));\n+ }\n+\n+ await Promise.all(promises);\nreturn updateInfos;\n}\n" }, { "change_type": "MODIFY", "old_path": "server/src/database.js", "new_path": "server/src/database.js", "diff": "@@ -21,7 +21,7 @@ const pool = mysqlPromise.createPool({\ntype SQLOrString = SQLStatement | string;\nfunction appendSQLArray(\nsql: SQLStatement,\n- sqlArray: SQLStatement[],\n+ sqlArray: $ReadOnlyArray<SQLStatement>,\ndelimeter: SQLOrString,\n) {\nif (sqlArray.length === 0) {\n@@ -39,18 +39,21 @@ function appendSQLArray(\n);\n}\n-function mergeConditions(conditions: SQLStatement[], delimiter: SQLStatement) {\n+function mergeConditions(\n+ conditions: $ReadOnlyArray<SQLStatement>,\n+ delimiter: SQLStatement,\n+) {\nconst sql = SQL` (`;\nappendSQLArray(sql, conditions, delimiter);\nsql.append(SQL`) `);\nreturn sql;\n}\n-function mergeAndConditions(andConditions: SQLStatement[]) {\n+function mergeAndConditions(andConditions: $ReadOnlyArray<SQLStatement>) {\nreturn mergeConditions(andConditions, SQL` AND `);\n}\n-function mergeOrConditions(andConditions: SQLStatement[]) {\n+function mergeOrConditions(andConditions: $ReadOnlyArray<SQLStatement>) {\nreturn mergeConditions(andConditions, SQL` OR `);\n}\n" }, { "change_type": "MODIFY", "old_path": "server/src/deleters/update-deleters.js", "new_path": "server/src/deleters/update-deleters.js", "diff": "// @flow\n-import { dbQuery, SQL } from '../database';\n+import invariant from 'invariant';\n+\n+import { dbQuery, SQL, SQLStatement, mergeOrConditions } from '../database';\n+\n+async function deleteUpdatesByConditions(\n+ conditions: $ReadOnlyArray<SQLStatement>,\n+) {\n+ invariant(conditions.length > 0, \"no conditions specified\");\n+ const conditionClause = mergeOrConditions(conditions);\n+ const query = SQL`\n+ DELETE u, i\n+ FROM updates u\n+ LEFT JOIN ids i ON i.id = u.id\n+ WHERE\n+ `;\n+ query.append(conditionClause);\n+ await dbQuery(query);\n+}\nasync function deleteExpiredUpdates(): Promise<void> {\nawait dbQuery(SQL`\n@@ -20,4 +37,5 @@ async function deleteExpiredUpdates(): Promise<void> {\nexport {\ndeleteExpiredUpdates,\n+ deleteUpdatesByConditions,\n};\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Introduce keys for merging updates
129,187
18.06.2018 16:20:31
25,200
9e485d36878e9c72dbcca70e8fcfe00b00169dc6
[server] Remaining updateTypes.UPDATE_THREAD update sites
[ { "change_type": "MODIFY", "old_path": "server/src/creators/thread-creator.js", "new_path": "server/src/creators/thread-creator.js", "diff": "@@ -21,8 +21,7 @@ import { verifyUserIDs } from '../fetchers/user-fetchers';\nimport {\nchangeRole,\nrecalculateAllPermissions,\n- saveMemberships,\n- deleteMemberships,\n+ commitMembershipChangeset,\n} from '../updaters/thread-permission-updaters';\nimport createMessages from './message-creator';\n@@ -181,8 +180,7 @@ async function createThread(\nconst [ newMessageInfos ] = await Promise.all([\ncreateMessages(messageDatas),\n- saveMemberships(toSave),\n- deleteMemberships(toDelete),\n+ commitMembershipChangeset(viewer, { toSave, toDelete }),\n]);\nconst roles = { [newRoles.default.id]: newRoles.default };\n" }, { "change_type": "MODIFY", "old_path": "server/src/fetchers/thread-fetchers.js", "new_path": "server/src/fetchers/thread-fetchers.js", "diff": "@@ -95,7 +95,7 @@ async function fetchServerThreadInfos(\nreturn { threadInfos, userInfos };\n}\n-type FetchThreadInfosResult = {|\n+export type FetchThreadInfosResult = {|\nthreadInfos: {[id: string]: RawThreadInfo},\nuserInfos: {[id: string]: AccountUserInfo},\n|};\n@@ -105,6 +105,13 @@ async function fetchThreadInfos(\ncondition?: SQLStatement,\n): Promise<FetchThreadInfosResult> {\nconst serverResult = await fetchServerThreadInfos(condition);\n+ return rawThreadInfosFromServerThreadInfos(viewer, serverResult);\n+}\n+\n+function rawThreadInfosFromServerThreadInfos(\n+ viewer: Viewer,\n+ serverResult: FetchServerThreadInfosResult,\n+): FetchThreadInfosResult {\nconst viewerID = viewer.id;\nconst threadInfos = {};\nconst userInfos = {};\n@@ -198,6 +205,7 @@ async function viewerIsMember(\nexport {\nfetchServerThreadInfos,\nfetchThreadInfos,\n+ rawThreadInfosFromServerThreadInfos,\nverifyThreadIDs,\nverifyThreadID,\nfetchThreadPermissionsBlob,\n" }, { "change_type": "MODIFY", "old_path": "server/src/updaters/thread-permission-updaters.js", "new_path": "server/src/updaters/thread-permission-updaters.js", "diff": "@@ -8,6 +8,8 @@ import {\nassertThreadType,\n} from 'lib/types/thread-types';\nimport type { ThreadSubscription } from 'lib/types/subscription-types';\n+import type { Viewer } from '../session/viewer';\n+import { updateTypes } from 'lib/types/update-types';\nimport invariant from 'invariant';\nimport _isEqual from 'lodash/fp/isEqual';\n@@ -16,10 +18,18 @@ import {\nmakePermissionsBlob,\nmakePermissionsForChildrenBlob,\n} from 'lib/permissions/thread-permissions';\n+import { rawThreadInfoFromServerThreadInfo } from 'lib/shared/thread-utils';\n+\n+import {\n+ fetchServerThreadInfos,\n+ rawThreadInfosFromServerThreadInfos,\n+ type FetchThreadInfosResult,\n+} from '../fetchers/thread-fetchers';\n+import { createUpdates } from '../creators/update-creator';\nimport { dbQuery, SQL, mergeOrConditions } from '../database';\n-type RowToSave = {|\n+export type RowToSave = {|\nuserID: string,\nthreadID: string,\npermissions: ThreadPermissionsBlob,\n@@ -29,7 +39,7 @@ type RowToSave = {|\nsubscription?: ThreadSubscription,\nunread?: bool,\n|};\n-type RowToDelete = {|\n+export type RowToDelete = {|\nuserID: string,\nthreadID: string,\n|};\n@@ -457,9 +467,69 @@ async function deleteMemberships(toDelete: $ReadOnlyArray<RowToDelete>) {\nawait dbQuery(query);\n}\n+async function commitMembershipChangeset(\n+ viewer: Viewer,\n+ changeset: MembershipChangeset,\n+ changedThreadIDs?: Set<string> = new Set(),\n+): Promise<FetchThreadInfosResult> {\n+ await Promise.all([\n+ saveMemberships(changeset.toSave),\n+ deleteMemberships(changeset.toDelete),\n+ ]);\n+\n+ const threadInfoFetchResult = await fetchServerThreadInfos();\n+ const { threadInfos: serverThreadInfos } = threadInfoFetchResult;\n+\n+ const threadMembershipDeletionPairs = [];\n+ for (let rowToSave of changeset.toSave) {\n+ const { threadID } = rowToSave;\n+ changedThreadIDs.add(threadID);\n+ }\n+ for (let rowToDelete of changeset.toDelete) {\n+ const { userID, threadID } = rowToDelete;\n+ changedThreadIDs.add(threadID);\n+ threadMembershipDeletionPairs.push({ userID, threadID });\n+ }\n+\n+ const time = Date.now();\n+ const updateDatas = [];\n+ for (let changedThreadID of changedThreadIDs) {\n+ const serverThreadInfo = serverThreadInfos[changedThreadID];\n+ for (let memberInfo of serverThreadInfo.members) {\n+ const threadInfo = rawThreadInfoFromServerThreadInfo(\n+ serverThreadInfo,\n+ memberInfo.id,\n+ );\n+ if (!threadInfo) {\n+ continue;\n+ }\n+ updateDatas.push({\n+ type: updateTypes.UPDATE_THREAD,\n+ userID: memberInfo.id,\n+ time,\n+ threadInfo,\n+ });\n+ }\n+ }\n+ for (let pair of threadMembershipDeletionPairs) {\n+ //updateDatas.push({\n+ // type: updateTypes.DELETE_THREAD,\n+ // userID: pair.userID,\n+ // time,\n+ // threadID: pair.threadID,\n+ //});\n+ }\n+\n+ createUpdates(updateDatas, viewer.cookieID);\n+\n+ return rawThreadInfosFromServerThreadInfos(\n+ viewer,\n+ threadInfoFetchResult,\n+ );\n+}\n+\nexport {\nchangeRole,\nrecalculateAllPermissions,\n- saveMemberships,\n- deleteMemberships,\n+ commitMembershipChangeset,\n};\n" }, { "change_type": "MODIFY", "old_path": "server/src/updaters/thread-updaters.js", "new_path": "server/src/updaters/thread-updaters.js", "diff": "@@ -16,7 +16,6 @@ import {\n} from 'lib/types/thread-types';\nimport type { Viewer } from '../session/viewer';\nimport { messageTypes, defaultNumberPerThread } from 'lib/types/message-types';\n-import { updateTypes } from 'lib/types/update-types';\nimport bcrypt from 'twin-bcrypt';\nimport _find from 'lodash/fp/find';\n@@ -25,7 +24,6 @@ import { ServerError } from 'lib/utils/errors';\nimport { promiseAll } from 'lib/utils/promises';\nimport { permissionLookup } from 'lib/permissions/thread-permissions';\nimport { filteredThreadIDs } from 'lib/selectors/calendar-filter-selectors';\n-import { rawThreadInfoFromServerThreadInfo } from 'lib/shared/thread-utils';\nimport { dbQuery, SQL } from '../database';\nimport {\n@@ -35,20 +33,17 @@ import {\nimport {\ncheckThreadPermission,\nfetchServerThreadInfos,\n- fetchThreadInfos,\nviewerIsMember,\nfetchThreadPermissionsBlob,\n} from '../fetchers/thread-fetchers';\nimport {\nchangeRole,\nrecalculateAllPermissions,\n- saveMemberships,\n- deleteMemberships,\n+ commitMembershipChangeset,\n} from './thread-permission-updaters';\nimport createMessages from '../creators/message-creator';\nimport { fetchMessageInfos } from '../fetchers/message-fetchers';\nimport { fetchEntryInfos } from '../fetchers/entry-fetchers';\n-import { createUpdates } from '../creators/update-creator';\nasync function updateRole(\nviewer: Viewer,\n@@ -106,51 +101,15 @@ async function updateRole(\nuserIDs: memberIDs,\nnewRole: request.role,\n};\n- const [ newMessageInfos ] = await Promise.all([\n+ const [ newMessageInfos, { threadInfos } ] = await Promise.all([\ncreateMessages([messageData]),\n- saveMemberships(changeset.toSave),\n- deleteMemberships(changeset.toDelete),\n+ commitMembershipChangeset(viewer, changeset),\n]);\n- const { threadInfos: serverThreadInfos } =\n- await fetchServerThreadInfos(SQL`t.id = ${request.threadID}`);\n- const serverThreadInfo = serverThreadInfos[request.threadID];\n-\n- createThreadUpdates(viewer, serverThreadInfo);\n-\n- const threadInfo = rawThreadInfoFromServerThreadInfo(\n- serverThreadInfo,\n- viewer.id,\n- );\n- if (!threadInfo) {\n- throw new ServerError('unknown_error');\n- }\n-\n- return { threadInfo, newMessageInfos };\n-}\n-\n-async function createThreadUpdates(\n- viewer: Viewer,\n- serverThreadInfo: ServerThreadInfo,\n-): Promise<void> {\n- const time = Date.now();\n- const updateDatas = [];\n- for (let memberInfo of serverThreadInfo.members) {\n- const threadInfo = rawThreadInfoFromServerThreadInfo(\n- serverThreadInfo,\n- memberInfo.id,\n- );\n- if (!threadInfo) {\n- continue;\n- }\n- updateDatas.push({\n- type: updateTypes.UPDATE_THREAD,\n- userID: memberInfo.id,\n- time,\n- threadInfo,\n- });\n- }\n- await createUpdates(updateDatas, viewer.cookieID);\n+ return {\n+ threadInfo: threadInfos[request.threadID],\n+ newMessageInfos,\n+ };\n}\nasync function removeMembers(\n@@ -224,15 +183,10 @@ async function removeMembers(\ntime: Date.now(),\nremovedUserIDs: actualMemberIDs,\n};\n- const [ newMessageInfos ] = await Promise.all([\n+ const [ newMessageInfos, { threadInfos } ] = await Promise.all([\ncreateMessages([messageData]),\n- saveMemberships(changeset.toSave),\n- deleteMemberships(changeset.toDelete),\n+ commitMembershipChangeset(viewer, changeset),\n]);\n- const { threadInfos } = await fetchThreadInfos(\n- viewer,\n- SQL`t.id = ${request.threadID}`,\n- );\nreturn {\nthreadInfo: threadInfos[request.threadID],\n@@ -292,13 +246,11 @@ async function leaveThread(\ncreatorID: viewerID,\ntime: Date.now(),\n};\n- await Promise.all([\n+ const [ { threadInfos } ] = await Promise.all([\n+ commitMembershipChangeset(viewer, changeset),\ncreateMessages([messageData]),\n- saveMemberships(toSave),\n- deleteMemberships(changeset.toDelete),\n]);\n- const { threadInfos } = await fetchThreadInfos(viewer);\nreturn { threadInfos };\n}\n@@ -531,16 +483,18 @@ async function updateThread(\n});\n}\n- const [ newMessageInfos ] = await Promise.all([\n+ const [ newMessageInfos, { threadInfos } ] = await Promise.all([\ncreateMessages(messageDatas),\n- saveMemberships(toSave),\n- deleteMemberships(toDelete),\n- ]);\n-\n- const { threadInfos } = await fetchThreadInfos(\n+ commitMembershipChangeset(\nviewer,\n- SQL`t.id = ${request.threadID}`,\n- );\n+ { toSave, toDelete },\n+ // This forces an update for this thread,\n+ // regardless of whether any membership rows are changed\n+ Object.keys(sqlUpdate).length > 0\n+ ? new Set(request.threadID)\n+ : new Set(),\n+ ),\n+ ]);\nreturn {\nthreadInfo: threadInfos[request.threadID],\n@@ -595,10 +549,9 @@ async function joinThread(\ncreatorID: viewer.id,\ntime: Date.now(),\n};\n- await Promise.all([\n+ const [ fetchThreadsResult ] = await Promise.all([\n+ commitMembershipChangeset(viewer, { toSave, toDelete: changeset.toDelete }),\ncreateMessages([messageData]),\n- saveMemberships(toSave),\n- deleteMemberships(changeset.toDelete),\n]);\nconst threadSelectionCriteria = {\n@@ -606,7 +559,6 @@ async function joinThread(\n};\nconst [\nfetchMessagesResult,\n- fetchThreadsResult,\nfetchEntriesResult,\n] = await Promise.all([\nfetchMessageInfos(\n@@ -614,7 +566,6 @@ async function joinThread(\nthreadSelectionCriteria,\ndefaultNumberPerThread,\n),\n- fetchThreadInfos(viewer),\ncalendarQuery ? fetchEntryInfos(viewer, calendarQuery) : undefined,\n]);\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Remaining updateTypes.UPDATE_THREAD update sites
129,187
19.06.2018 16:00:49
25,200
578a26abe4b538976ae797499ddca87e5cd8a0bc
[lib] Filter out relevant MemberInfos in reducer on updateTypes.DELETE_ACCOUNT
[ { "change_type": "MODIFY", "old_path": "lib/reducers/thread-reducer.js", "new_path": "lib/reducers/thread-reducer.js", "diff": "@@ -108,6 +108,7 @@ function pingPull(\nreturn newThreadInfos;\n}\n+// ... PUSH.\nfunction pingPush(\nstate: {[id: string]: RawThreadInfo},\npayload: PingResult,\n@@ -143,6 +144,20 @@ function pingPush(\n) {\nsomeThreadUpdated = true;\ndelete newState[update.threadID];\n+ } else if (update.type === updateTypes.DELETE_ACCOUNT) {\n+ for (let threadID in state) {\n+ const threadInfo = state[threadID];\n+ const newMembers = threadInfo.members.filter(\n+ member => member.id !== update.deletedUserID,\n+ );\n+ if (newMembers.length < threadInfo.members.length) {\n+ someThreadUpdated = true;\n+ newState[threadID] = {\n+ ...threadInfo,\n+ members: newMembers,\n+ };\n+ }\n+ }\n}\n}\nif (!someThreadUpdated) {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[lib] Filter out relevant MemberInfos in reducer on updateTypes.DELETE_ACCOUNT
129,187
19.06.2018 16:16:34
25,200
e059dba3d657e3a7dbb88afdd104b5e2a1be2ce5
[lib] Update subscription in reducer for updateSubscriptionActionTypes.success
[ { "change_type": "MODIFY", "old_path": "lib/actions/user-actions.js", "new_path": "lib/actions/user-actions.js", "diff": "@@ -18,7 +18,7 @@ import type {\n} from '../types/account-types';\nimport type {\nSubscriptionUpdateRequest,\n- ThreadSubscription,\n+ SubscriptionUpdateResult,\n} from '../types/subscription-types';\nimport type { UserSearchResult } from '../types/search-types';\n@@ -273,12 +273,15 @@ const updateSubscriptionActionTypes = Object.freeze({\nasync function updateSubscription(\nfetchJSON: FetchJSON,\nsubscriptionUpdate: SubscriptionUpdateRequest,\n-): Promise<ThreadSubscription> {\n+): Promise<SubscriptionUpdateResult> {\nconst response = await fetchJSON(\n'update_user_subscription',\nsubscriptionUpdate,\n);\n- return response.threadSubscription;\n+ return {\n+ threadID: subscriptionUpdate.threadID,\n+ subscription: response.threadSubscription,\n+ };\n}\nconst requestAccessActionTypes = Object.freeze({\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/thread-reducer.js", "new_path": "lib/reducers/thread-reducer.js", "diff": "@@ -15,6 +15,7 @@ import {\nlogInActionTypes,\nresetPasswordActionTypes,\nregisterActionTypes,\n+ updateSubscriptionActionTypes,\n} from '../actions/user-actions';\nimport {\nchangeThreadSettingsActionTypes,\n@@ -221,6 +222,17 @@ export default function reduceThreadInfos(\n}\n}\nreturn newState;\n+ } else if (action.type === updateSubscriptionActionTypes.success) {\n+ return {\n+ ...state,\n+ [action.payload.threadID]: {\n+ ...state[action.payload.threadID],\n+ currentUser: {\n+ ...state[action.payload.threadID].currentUser,\n+ subscription: action.payload.subscription,\n+ },\n+ },\n+ };\n}\nreturn state;\n}\n" }, { "change_type": "MODIFY", "old_path": "lib/types/redux-types.js", "new_path": "lib/types/redux-types.js", "diff": "@@ -53,6 +53,7 @@ import type {\nCalendarThreadFilter,\nSetCalendarDeletedFilterPayload,\n} from './filter-types';\n+import type { SubscriptionUpdateResult } from '../types/subscription-types';\nexport type BaseAppState<NavInfo: BaseNavInfo> = {\nnavInfo: NavInfo,\n@@ -522,6 +523,18 @@ export type BaseAction =\n|} | {|\ntype: \"SET_CALENDAR_DELETED_FILTER\",\npayload: SetCalendarDeletedFilterPayload,\n+ |} | {|\n+ type: \"UPDATE_SUBSCRIPTION_STARTED\",\n+ loadingInfo: LoadingInfo,\n+ |} | {|\n+ type: \"UPDATE_SUBSCRIPTION_FAILED\",\n+ error: true,\n+ payload: Error,\n+ loadingInfo: LoadingInfo,\n+ |} | {|\n+ type: \"UPDATE_SUBSCRIPTION_SUCCESS\",\n+ payload: SubscriptionUpdateResult,\n+ loadingInfo: LoadingInfo,\n|};\nexport type ActionPayload\n" }, { "change_type": "MODIFY", "old_path": "lib/types/subscription-types.js", "new_path": "lib/types/subscription-types.js", "diff": "@@ -13,3 +13,8 @@ export type SubscriptionUpdateRequest = {|\nexport type SubscriptionUpdateResponse = {|\nthreadSubscription: ThreadSubscription,\n|};\n+\n+export type SubscriptionUpdateResult = {|\n+ threadID: string,\n+ subscription: ThreadSubscription,\n+|};\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[lib] Update subscription in reducer for updateSubscriptionActionTypes.success
129,187
19.06.2018 16:34:50
25,200
66e67456a774de9fe61e4c95cea96d93c6b609ea
[server] Send updateTypes.UPDATE_THREAD to user's other devices when ThreadSubscription changed
[ { "change_type": "MODIFY", "old_path": "server/src/updaters/user-subscription-updaters.js", "new_path": "server/src/updaters/user-subscription-updaters.js", "diff": "@@ -5,28 +5,32 @@ import type {\nSubscriptionUpdateRequest,\n} from 'lib/types/subscription-types';\nimport type { Viewer } from '../session/viewer';\n+import { updateTypes } from 'lib/types/update-types';\nimport { ServerError } from 'lib/utils/errors';\n+import { viewerIsMember } from 'lib/shared/thread-utils';\nimport { dbQuery, SQL } from '../database';\n+import { createUpdates } from '../creators/update-creator';\n+import { fetchThreadInfos } from '../fetchers/thread-fetchers';\nasync function userSubscriptionUpdater(\nviewer: Viewer,\nupdate: SubscriptionUpdateRequest,\n): Promise<ThreadSubscription> {\n- const query = SQL`\n- SELECT subscription\n- FROM memberships\n- WHERE user = ${viewer.id} AND thread = ${update.threadID} AND role != 0\n- `;\n- const [ result ] = await dbQuery(query);\n- if (result.length === 0) {\n+ const threadInfos = await fetchThreadInfos(\n+ viewer,\n+ SQL`t.id = ${update.threadID}`,\n+ );\n+ const threadInfo = threadInfos[update.threadID];\n+ if (!viewerIsMember(threadInfo)) {\nthrow new ServerError('not_member');\n}\n- const row = result[0];\n+\n+ const promises = [];\nconst newSubscription = {\n- ...row.subscription,\n+ ...threadInfo.currentUser.subscription,\n...update.updatedFields,\n};\nconst saveQuery = SQL`\n@@ -34,8 +38,24 @@ async function userSubscriptionUpdater(\nSET subscription = ${JSON.stringify(newSubscription)}\nWHERE user = ${viewer.id} AND thread = ${update.threadID}\n`;\n- await dbQuery(saveQuery);\n+ promises.push(dbQuery(saveQuery));\n+\n+ const time = Date.now();\n+ const updateDatas = [{\n+ type: updateTypes.UPDATE_THREAD,\n+ userID: viewer.id,\n+ time,\n+ threadInfo: {\n+ ...threadInfo,\n+ currentUser: {\n+ ...threadInfo.currentUser,\n+ subscription: newSubscription,\n+ },\n+ },\n+ }];\n+ promises.push(createUpdates(updateDatas, viewer.cookieID));\n+ await Promise.all(promises);\nreturn newSubscription;\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Send updateTypes.UPDATE_THREAD to user's other devices when ThreadSubscription changed
129,187
19.06.2018 18:09:17
25,200
430fd52f3fc204fdabb47fc50fdd0cf78395af5b
Synchronously return list of updates for viewer from thread mutators Lists of updates returned on ping don't include updates created by the same cookie doing the ping. Instead, those updates will be returned synchronously by the server call that triggered the update.
[ { "change_type": "MODIFY", "old_path": "lib/actions/thread-actions.js", "new_path": "lib/actions/thread-actions.js", "diff": "@@ -34,7 +34,11 @@ async function deleteThread(\nthreadID,\naccountPassword: currentAccountPassword,\n});\n- return { threadID, threadInfos: response.threadInfos };\n+ return {\n+ threadID,\n+ threadInfos: response.threadInfos,\n+ updatesResult: response.updatesResult,\n+ };\n}\nconst changeThreadSettingsActionTypes = Object.freeze({\n@@ -53,6 +57,8 @@ async function changeThreadSettings(\n);\nreturn {\nthreadInfo: response.threadInfo,\n+ threadInfos: response.threadInfos,\n+ updatesResult: response.updatesResult,\nnewMessageInfos: response.newMessageInfos,\n};\n}\n@@ -73,6 +79,8 @@ async function removeUsersFromThread(\n});\nreturn {\nthreadInfo: response.threadInfo,\n+ threadInfos: response.threadInfos,\n+ updatesResult: response.updatesResult,\nnewMessageInfos: response.newMessageInfos,\n};\n}\n@@ -95,6 +103,8 @@ async function changeThreadMemberRoles(\n});\nreturn {\nthreadInfo: response.threadInfo,\n+ threadInfos: response.threadInfos,\n+ updatesResult: response.updatesResult,\nnewMessageInfos: response.newMessageInfos,\n};\n}\n@@ -111,6 +121,7 @@ async function newThread(\nconst response = await fetchJSON('create_thread', request);\nreturn {\nnewThreadInfo: response.newThreadInfo,\n+ updatesResult: response.updatesResult,\nnewMessageInfos: response.newMessageInfos,\n};\n}\n@@ -141,6 +152,7 @@ async function joinThread(\nreturn {\nthreadID: request.threadID,\nthreadInfos: response.threadInfos,\n+ updatesResult: response.updatesResult,\nrawMessageInfos: response.rawMessageInfos,\ntruncationStatuses: response.truncationStatuses,\nuserInfos,\n@@ -158,7 +170,11 @@ async function leaveThread(\nthreadID: string,\n): Promise<LeaveThreadPayload> {\nconst response = await fetchJSON('leave_thread', { threadID });\n- return { threadID, threadInfos: response.threadInfos };\n+ return {\n+ threadID,\n+ threadInfos: response.threadInfos,\n+ updatesResult: response.updatesResult,\n+ };\n}\nexport {\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/thread-reducer.js", "new_path": "lib/reducers/thread-reducer.js", "diff": "import type { BaseAction } from '../types/redux-types';\nimport type { RawThreadInfo } from '../types/thread-types';\nimport type { PingResult } from '../types/ping-types';\n-import { updateTypes } from '../types/update-types';\n+import { updateTypes, type UpdateInfo } from '../types/update-types';\nimport invariant from 'invariant';\nimport _isEqual from 'lodash/fp/isEqual';\n@@ -112,7 +112,7 @@ function pingPull(\n// ... PUSH.\nfunction pingPush(\nstate: {[id: string]: RawThreadInfo},\n- payload: PingResult,\n+ payload: { +updatesResult: ?{ newUpdates: $ReadOnlyArray<UpdateInfo> } },\n): {[id: string]: RawThreadInfo} {\nif (!payload.updatesResult) {\nreturn state;\n@@ -177,42 +177,48 @@ export default function reduceThreadInfos(\naction.type === logInActionTypes.success ||\naction.type === registerActionTypes.success ||\naction.type === resetPasswordActionTypes.success ||\n- action.type === joinThreadActionTypes.success ||\n- action.type === leaveThreadActionTypes.success ||\n- action.type === deleteThreadActionTypes.success ||\naction.type === setCookieActionType\n) {\nif (_isEqual(state)(action.payload.threadInfos)) {\nreturn state;\n}\nreturn action.payload.threadInfos;\n- } else if (action.type === pingActionTypes.success) {\n- const payload = action.payload;\n- const pullResult = pingPull(state, payload);\n- //const pushResult = pingPush(state, payload);\n- return pullResult;\n} else if (\n+ action.type === joinThreadActionTypes.success ||\n+ action.type === leaveThreadActionTypes.success ||\n+ action.type === deleteThreadActionTypes.success ||\naction.type === changeThreadSettingsActionTypes.success ||\naction.type === removeUsersFromThreadActionTypes.success ||\naction.type === changeThreadMemberRolesActionTypes.success\n) {\n- const newThreadInfo = action.payload.threadInfo;\n- if (_isEqual(state[newThreadInfo.id])(newThreadInfo)) {\n+ if (\n+ _isEqual(state)(action.payload.threadInfos) &&\n+ action.payload.updatesResult.newUpdates.length === 0\n+ ) {\nreturn state;\n}\n- return {\n- ...state,\n- [newThreadInfo.id]: newThreadInfo,\n- };\n+ const pullResult = action.payload.threadInfos;\n+ //const pushResult = pingPush(state, action.payload);\n+ return pullResult;\n+ } else if (action.type === pingActionTypes.success) {\n+ const payload = action.payload;\n+ const pullResult = pingPull(state, payload);\n+ //const pushResult = pingPush(state, payload);\n+ return pullResult;\n} else if (action.type === newThreadActionTypes.success) {\nconst newThreadInfo = action.payload.newThreadInfo;\n- if (_isEqual(state[newThreadInfo.id])(newThreadInfo)) {\n+ if (\n+ _isEqual(state[newThreadInfo.id])(newThreadInfo) &&\n+ action.payload.updatesResult.newUpdates.length === 0\n+ ) {\nreturn state;\n}\n- return {\n+ const pullResult = {\n...state,\n[newThreadInfo.id]: newThreadInfo,\n};\n+ //const pushResult = pingPush(state, action.payload);\n+ return pullResult;\n} else if (action.type === updateActivityActionTypes.success) {\nconst newState = { ...state };\nfor (let setToUnread of action.payload.unfocusedToUnread) {\n" }, { "change_type": "MODIFY", "old_path": "lib/types/thread-types.js", "new_path": "lib/types/thread-types.js", "diff": "@@ -11,6 +11,7 @@ import type {\nCalendarResult,\nRawEntryInfo,\n} from './entry-types';\n+import type { UpdateInfo } from './update-types';\nimport PropTypes from 'prop-types';\nimport invariant from 'invariant';\n@@ -254,6 +255,10 @@ export type RoleChangeRequest = {|\nexport type ChangeThreadSettingsResult = {|\nthreadInfo: RawThreadInfo,\n+ threadInfos: {[id: string]: RawThreadInfo},\n+ updatesResult: {\n+ newUpdates: $ReadOnlyArray<UpdateInfo>,\n+ },\nnewMessageInfos: $ReadOnlyArray<RawMessageInfo>,\n|};\n@@ -262,6 +267,9 @@ export type LeaveThreadRequest = {|\n|};\nexport type LeaveThreadResult = {|\nthreadInfos: {[id: string]: RawThreadInfo},\n+ updatesResult: {\n+ newUpdates: $ReadOnlyArray<UpdateInfo>,\n+ },\n|};\nexport type LeaveThreadPayload = {|\n@@ -298,6 +306,9 @@ export type NewThreadRequest = {|\n|};\nexport type NewThreadResult = {|\nnewThreadInfo: RawThreadInfo,\n+ updatesResult: {\n+ newUpdates: $ReadOnlyArray<UpdateInfo>,\n+ },\nnewMessageInfos: $ReadOnlyArray<RawMessageInfo>,\n|};\n@@ -307,6 +318,9 @@ export type ThreadJoinRequest = {|\n|};\nexport type ThreadJoinResult = {|\nthreadInfos: {[id: string]: RawThreadInfo},\n+ updatesResult: {\n+ newUpdates: $ReadOnlyArray<UpdateInfo>,\n+ },\nrawMessageInfos: $ReadOnlyArray<RawMessageInfo>,\ntruncationStatuses: MessageTruncationStatuses,\nuserInfos: UserInfos,\n@@ -315,6 +329,9 @@ export type ThreadJoinResult = {|\nexport type ThreadJoinPayload = {|\nthreadID: string,\nthreadInfos: {[id: string]: RawThreadInfo},\n+ updatesResult: {\n+ newUpdates: $ReadOnlyArray<UpdateInfo>,\n+ },\nrawMessageInfos: RawMessageInfo[],\ntruncationStatuses: MessageTruncationStatuses,\nuserInfos: $ReadOnlyArray<UserInfo>,\n" }, { "change_type": "MODIFY", "old_path": "server/src/creators/thread-creator.js", "new_path": "server/src/creators/thread-creator.js", "diff": "@@ -119,9 +119,6 @@ async function createThread(\ntoSave = [...toSave, ...initialMembersChangeset.toSave];\ntoDelete = [...toDelete, ...initialMembersChangeset.toDelete];\n}\n-\n- const members = [];\n- let currentUserInfo = null;\nfor (let rowToSave of toSave) {\nif (\nrowToSave.role !== \"0\" &&\n@@ -133,27 +130,8 @@ async function createThread(\nif (rowToSave.threadID === id && rowToSave.role !== \"0\") {\nconst subscription = { home: true, pushNotifs: true };\nrowToSave.subscription = subscription;\n- const member = {\n- id: rowToSave.userID,\n- permissions: getAllThreadPermissions(rowToSave.permissions, id),\n- role: rowToSave.role && rowToSave.role !== \"0\"\n- ? rowToSave.role\n- : null,\n- };\n- members.unshift(member);\n- if (rowToSave.userID === viewer.userID) {\n- currentUserInfo = {\n- role: member.role,\n- permissions: member.permissions,\n- subscription,\n- unread: false,\n- };\n- }\n}\n}\n- if (!currentUserInfo) {\n- throw new ServerError('unknown_error');\n- }\nconst messageDatas = [{\ntype: messageTypes.CREATE_THREAD,\n@@ -178,28 +156,16 @@ async function createThread(\n});\n}\n- const [ newMessageInfos ] = await Promise.all([\n+ const [ newMessageInfos, commitResult ] = await Promise.all([\ncreateMessages(messageDatas),\ncommitMembershipChangeset(viewer, { toSave, toDelete }),\n]);\n+ const { threadInfos, viewerUpdates } = commitResult;\n- const roles = { [newRoles.default.id]: newRoles.default };\n- if (newRoles.creator.id !== newRoles.default.id) {\n- roles[newRoles.creator.id] = newRoles.creator;\n- }\nreturn {\n- newThreadInfo: {\n- id,\n- type: threadType,\n- visibilityRules: threadType,\n- name,\n- description,\n- color,\n- creationTime: time,\n- parentThreadID,\n- members,\n- roles,\n- currentUser: currentUserInfo,\n+ newThreadInfo: threadInfos[id],\n+ updatesResult: {\n+ newUpdates: viewerUpdates,\n},\nnewMessageInfos,\n};\n" }, { "change_type": "MODIFY", "old_path": "server/src/creators/update-creator.js", "new_path": "server/src/creators/update-creator.js", "diff": "@@ -5,6 +5,7 @@ import {\ntype UpdateData,\nupdateTypes,\n} from 'lib/types/update-types';\n+import type { Viewer } from '../session/viewer';\nimport { updateInfoFromUpdateData } from 'lib/shared/update-utils';\n@@ -12,21 +13,26 @@ import { dbQuery, SQL } from '../database';\nimport createIDs from './id-creator';\nimport { deleteUpdatesByConditions } from '../deleters/update-deleters';\n+// If the viewer is not passed in, the returned array will be empty, and the\n+// update won't have an updater_cookie. This should only be done when we are\n+// sure none of the updates are destined for the viewer.\nasync function createUpdates(\nupdateDatas: $ReadOnlyArray<UpdateData>,\n- cookieID?: ?string,\n+ viewer?: Viewer,\n): Promise<UpdateInfo[]> {\nif (updateDatas.length === 0) {\nreturn [];\n}\nconst ids = await createIDs(\"updates\", updateDatas.length);\n- const updateInfos: UpdateInfo[] = [];\n+ const viewerUpdates = [];\nconst insertRows = [];\nconst deleteConditions = [];\nfor (let i = 0; i < updateDatas.length; i++) {\nconst updateData = updateDatas[i];\n- updateInfos.push(updateInfoFromUpdateData(updateData, ids[i]));\n+ if (viewer && updateData.userID === viewer.id) {\n+ viewerUpdates.push(updateInfoFromUpdateData(updateData, ids[i]));\n+ }\nlet content, key;\nif (updateData.type === updateTypes.DELETE_ACCOUNT) {\n@@ -73,15 +79,15 @@ async function createUpdates(\ncontent,\nupdateData.time,\n];\n- if (cookieID) {\n- insertRow.push(cookieID);\n+ if (viewer) {\n+ insertRow.push(viewer.cookieID);\n}\ninsertRows.push(insertRow);\n}\nconst promises = [];\n- const insertQuery = cookieID\n+ const insertQuery = viewer\n? SQL`\nINSERT INTO updates(id, user, type, key, content, time, updater_cookie)\n`\n@@ -95,7 +101,7 @@ async function createUpdates(\nawait Promise.all(promises);\n- return updateInfos;\n+ return viewerUpdates;\n}\nexport {\n" }, { "change_type": "MODIFY", "old_path": "server/src/deleters/account-deleters.js", "new_path": "server/src/deleters/account-deleters.js", "diff": "@@ -54,10 +54,9 @@ async function deleteAccount(\ncreateNewAnonymousCookie(viewer.platform),\ndbQuery(deletionQuery),\n]);\n- const oldCookieID = viewer.cookieID;\nviewer.setNewCookie(anonymousViewerData);\n- createAccountDeletionUpdates(deletedUserID, oldCookieID);\n+ createAccountDeletionUpdates(deletedUserID);\nreturn {\ncurrentUserInfo: {\n@@ -69,7 +68,6 @@ async function deleteAccount(\nasync function createAccountDeletionUpdates(\ndeletedUserID: string,\n- oldCookieID: string,\n): Promise<void> {\nconst allUserIDs = await fetchAllUserIDs();\nconst time = Date.now();\n@@ -79,7 +77,7 @@ async function createAccountDeletionUpdates(\ntime,\ndeletedUserID,\n}));\n- await createUpdates(updateDatas, oldCookieID);\n+ await createUpdates(updateDatas);\n}\nexport {\n" }, { "change_type": "MODIFY", "old_path": "server/src/deleters/thread-deleters.js", "new_path": "server/src/deleters/thread-deleters.js", "diff": "@@ -81,7 +81,6 @@ async function deleteThread(\nLEFT JOIN ids ino ON ino.id = n.id\nWHERE t.id = ${threadDeletionRequest.threadID}\n`;\n- await dbQuery(query);\nconst serverThreadInfo = serverThreadInfos[threadDeletionRequest.threadID];\nconst time = Date.now();\n@@ -94,10 +93,19 @@ async function deleteThread(\nthreadID: threadDeletionRequest.threadID,\n});\n}\n- createUpdates(updateDatas, viewer.cookieID);\n+\n+ const [ viewerUpdates ] = await Promise.all([\n+ createUpdates(updateDatas, viewer),\n+ dbQuery(query),\n+ ]);\nconst { threadInfos } = await fetchThreadInfos(viewer);\n- return { threadInfos };\n+ return {\n+ threadInfos,\n+ updatesResult: {\n+ newUpdates: viewerUpdates,\n+ },\n+ };\n}\nasync function deleteInaccessibleThreads(): Promise<void> {\n" }, { "change_type": "MODIFY", "old_path": "server/src/updaters/activity-updaters.js", "new_path": "server/src/updaters/activity-updaters.js", "diff": "@@ -103,7 +103,7 @@ async function activityUpdater(\nthreadID,\nunread: false,\n})),\n- localViewer.cookieID,\n+ localViewer,\n));\nconst rescindCondition = SQL`\nn.user = ${localViewer.userID} AND n.thread IN (${focusedThreadIDs})\n@@ -223,7 +223,7 @@ async function possiblyResetThreadsToUnread(\nthreadID,\nunread: true,\n})),\n- viewer.cookieID,\n+ viewer,\n));\nawait Promise.all(promises);\n" }, { "change_type": "MODIFY", "old_path": "server/src/updaters/thread-permission-updaters.js", "new_path": "server/src/updaters/thread-permission-updaters.js", "diff": "@@ -9,7 +9,7 @@ import {\n} from 'lib/types/thread-types';\nimport type { ThreadSubscription } from 'lib/types/subscription-types';\nimport type { Viewer } from '../session/viewer';\n-import { updateTypes } from 'lib/types/update-types';\n+import { updateTypes, type UpdateInfo } from 'lib/types/update-types';\nimport invariant from 'invariant';\nimport _isEqual from 'lodash/fp/isEqual';\n@@ -467,11 +467,15 @@ async function deleteMemberships(toDelete: $ReadOnlyArray<RowToDelete>) {\nawait dbQuery(query);\n}\n+type MembershipChangesetCommitResult = {|\n+ ...FetchThreadInfosResult,\n+ viewerUpdates: $ReadOnlyArray<UpdateInfo>,\n+|};\nasync function commitMembershipChangeset(\nviewer: Viewer,\nchangeset: MembershipChangeset,\nchangedThreadIDs?: Set<string> = new Set(),\n-): Promise<FetchThreadInfosResult> {\n+): Promise<MembershipChangesetCommitResult> {\nawait Promise.all([\nsaveMemberships(changeset.toSave),\ndeleteMemberships(changeset.toDelete),\n@@ -525,12 +529,15 @@ async function commitMembershipChangeset(\n});\n}\n- createUpdates(updateDatas, viewer.cookieID);\n+ const viewerUpdates = await createUpdates(updateDatas, viewer);\n- return rawThreadInfosFromServerThreadInfos(\n+ return {\n+ ...rawThreadInfosFromServerThreadInfos(\nviewer,\nthreadInfoFetchResult,\n- );\n+ ),\n+ viewerUpdates,\n+ };\n}\nexport {\n" }, { "change_type": "MODIFY", "old_path": "server/src/updaters/thread-updaters.js", "new_path": "server/src/updaters/thread-updaters.js", "diff": "@@ -101,13 +101,20 @@ async function updateRole(\nuserIDs: memberIDs,\nnewRole: request.role,\n};\n- const [ newMessageInfos, { threadInfos } ] = await Promise.all([\n+ const [\n+ newMessageInfos,\n+ { threadInfos, viewerUpdates },\n+ ] = await Promise.all([\ncreateMessages([messageData]),\ncommitMembershipChangeset(viewer, changeset),\n]);\nreturn {\nthreadInfo: threadInfos[request.threadID],\n+ threadInfos,\n+ updatesResult: {\n+ newUpdates: viewerUpdates,\n+ },\nnewMessageInfos,\n};\n}\n@@ -183,13 +190,20 @@ async function removeMembers(\ntime: Date.now(),\nremovedUserIDs: actualMemberIDs,\n};\n- const [ newMessageInfos, { threadInfos } ] = await Promise.all([\n+ const [\n+ newMessageInfos,\n+ { threadInfos, viewerUpdates },\n+ ] = await Promise.all([\ncreateMessages([messageData]),\ncommitMembershipChangeset(viewer, changeset),\n]);\nreturn {\nthreadInfo: threadInfos[request.threadID],\n+ threadInfos,\n+ updatesResult: {\n+ newUpdates: viewerUpdates,\n+ },\nnewMessageInfos,\n};\n}\n@@ -246,12 +260,17 @@ async function leaveThread(\ncreatorID: viewerID,\ntime: Date.now(),\n};\n- const [ { threadInfos } ] = await Promise.all([\n+ const [ { threadInfos, viewerUpdates } ] = await Promise.all([\ncommitMembershipChangeset(viewer, changeset),\ncreateMessages([messageData]),\n]);\n- return { threadInfos };\n+ return {\n+ threadInfos,\n+ updatesResult: {\n+ newUpdates: viewerUpdates,\n+ },\n+ };\n}\nasync function updateThread(\n@@ -483,7 +502,10 @@ async function updateThread(\n});\n}\n- const [ newMessageInfos, { threadInfos } ] = await Promise.all([\n+ const [\n+ newMessageInfos,\n+ { threadInfos, viewerUpdates },\n+ ] = await Promise.all([\ncreateMessages(messageDatas),\ncommitMembershipChangeset(\nviewer,\n@@ -498,6 +520,10 @@ async function updateThread(\nreturn {\nthreadInfo: threadInfos[request.threadID],\n+ threadInfos,\n+ updatesResult: {\n+ newUpdates: viewerUpdates,\n+ },\nnewMessageInfos,\n};\n}\n@@ -587,6 +613,9 @@ async function joinThread(\nrawMessageInfos: fetchMessagesResult.rawMessageInfos,\ntruncationStatuses: fetchMessagesResult.truncationStatuses,\nuserInfos,\n+ updatesResult: {\n+ newUpdates: fetchThreadsResult.viewerUpdates,\n+ },\n};\nif (rawEntryInfos) {\nresponse.rawEntryInfos = rawEntryInfos;\n" }, { "change_type": "MODIFY", "old_path": "server/src/updaters/user-subscription-updaters.js", "new_path": "server/src/updaters/user-subscription-updaters.js", "diff": "@@ -53,7 +53,7 @@ async function userSubscriptionUpdater(\n},\n},\n}];\n- promises.push(createUpdates(updateDatas, viewer.cookieID));\n+ promises.push(createUpdates(updateDatas, viewer));\nawait Promise.all(promises);\nreturn newSubscription;\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Synchronously return list of updates for viewer from thread mutators Lists of updates returned on ping don't include updates created by the same cookie doing the ping. Instead, those updates will be returned synchronously by the server call that triggered the update.
129,187
20.06.2018 13:49:41
25,200
54db2f9a560940e4955e6639d202c67b095fcfe8
[server] Thread "join" operation to commitMembershipChangeset Having this info lets us be a bit smarter about subscription status on join/leave, and is necessary for deciding between `updateTypes.UPDATE_THREAD` and `updateTypes.JOIN_THREAD` (coming soon).
[ { "change_type": "MODIFY", "old_path": "server/.flowconfig", "new_path": "server/.flowconfig", "diff": "[options]\nmodule.name_mapper='^lib/(.*)$' -> '<PROJECT_ROOT>/../lib/\\1'\n+\n+module.file_ext=.js\n+module.file_ext=.json\n+module.file_ext=.build\n" }, { "change_type": "MODIFY", "old_path": "server/src/creators/thread-creator.js", "new_path": "server/src/creators/thread-creator.js", "diff": "@@ -100,37 +100,29 @@ async function createThread(\nconst initialMemberAndCreatorIDs = initialMemberIDs\n? [...initialMemberIDs, viewer.userID]\n: [viewer.userID];\n- let toSave = [\n- ...creatorChangeset.toSave,\n- ...recalculatePermissionsChangeset.toSave.filter(\n+ const changeset = [\n+ ...creatorChangeset,\n+ ...recalculatePermissionsChangeset.filter(\nrowToSave => !initialMemberAndCreatorIDs.includes(rowToSave.userID),\n),\n];\n- let toDelete = [\n- ...creatorChangeset.toDelete,\n- ...recalculatePermissionsChangeset.toDelete.filter(\n- rowToSave => !initialMemberAndCreatorIDs.includes(rowToSave.userID),\n- ),\n- ];\n- if (initialMemberIDs) {\n+ if (initialMemberIDs && initialMemberIDs.length > 0) {\nif (!initialMembersChangeset) {\nthrow new ServerError('unknown_error');\n}\n- toSave = [...toSave, ...initialMembersChangeset.toSave];\n- toDelete = [...toDelete, ...initialMembersChangeset.toDelete];\n+ changeset.push(...initialMembersChangeset);\n+ }\n+ for (let rowToSave of changeset) {\n+ if (rowToSave.operation === \"delete\") {\n+ continue;\n}\n- for (let rowToSave of toSave) {\nif (\n- rowToSave.role !== \"0\" &&\n+ rowToSave.operation === \"join\" &&\n(rowToSave.userID !== viewer.userID ||\nrowToSave.threadID !== id)\n) {\nrowToSave.unread = true;\n}\n- if (rowToSave.threadID === id && rowToSave.role !== \"0\") {\n- const subscription = { home: true, pushNotifs: true };\n- rowToSave.subscription = subscription;\n- }\n}\nconst messageDatas = [{\n@@ -158,7 +150,7 @@ async function createThread(\nconst [ newMessageInfos, commitResult ] = await Promise.all([\ncreateMessages(messageDatas),\n- commitMembershipChangeset(viewer, { toSave, toDelete }),\n+ commitMembershipChangeset(viewer, changeset),\n]);\nconst { threadInfos, viewerUpdates } = commitResult;\n" }, { "change_type": "MODIFY", "old_path": "server/src/updaters/thread-permission-updaters.js", "new_path": "server/src/updaters/thread-permission-updaters.js", "diff": "@@ -29,7 +29,8 @@ import { createUpdates } from '../creators/update-creator';\nimport { dbQuery, SQL, mergeOrConditions } from '../database';\n-export type RowToSave = {|\n+type RowToSave = {|\n+ operation: \"update\" | \"join\",\nuserID: string,\nthreadID: string,\npermissions: ThreadPermissionsBlob,\n@@ -39,14 +40,13 @@ export type RowToSave = {|\nsubscription?: ThreadSubscription,\nunread?: bool,\n|};\n-export type RowToDelete = {|\n+type RowToDelete = {|\n+ operation: \"delete\",\nuserID: string,\nthreadID: string,\n|};\n-type MembershipChangeset = {|\n- toSave: $ReadOnlyArray<RowToSave>,\n- toDelete: $ReadOnlyArray<RowToDelete>,\n-|};\n+type Row = RowToSave | RowToDelete;\n+type Changeset = Row[];\n// 0 role means to remove the user from the thread\n// null role means to set the user to the default role\n@@ -55,7 +55,7 @@ async function changeRole(\nthreadID: string,\nuserIDs: $ReadOnlyArray<string>,\nrole: string | 0 | null,\n-): Promise<?MembershipChangeset> {\n+): Promise<?Changeset> {\nconst membershipQuery = SQL`\nSELECT m.user, m.role, m.permissions_for_children,\npm.permissions_for_children AS permissions_from_parent\n@@ -88,8 +88,7 @@ async function changeRole(\n);\n}\n- const toSave = [];\n- const toDelete = [];\n+ const changeset = [];\nconst toUpdateDescendants = new Map();\nfor (let userID of userIDs) {\nlet oldPermissionsForChildren = null;\n@@ -121,7 +120,12 @@ async function changeRole(\n);\nif (permissions) {\n- toSave.push({\n+ changeset.push({\n+ operation:\n+ roleThreadResult.roleColumnValue !== \"0\" &&\n+ (!userRoleInfo || userRoleInfo.oldRole === \"0\")\n+ ? \"join\"\n+ : \"update\",\nuserID,\nthreadID,\npermissions,\n@@ -129,7 +133,11 @@ async function changeRole(\nrole: roleThreadResult.roleColumnValue,\n});\n} else {\n- toDelete.push({ userID, threadID });\n+ changeset.push({\n+ operation: \"delete\",\n+ userID,\n+ threadID,\n+ });\n}\nif (!_isEqual(permissionsForChildren)(oldPermissionsForChildren)) {\n@@ -142,13 +150,10 @@ async function changeRole(\nthreadID,\ntoUpdateDescendants,\n);\n- return {\n- toSave: [...toSave, ...descendantResults.toSave],\n- toDelete: [...toDelete, ...descendantResults.toDelete],\n- };\n+ changeset.push(...descendantResults);\n}\n- return { toSave, toDelete };\n+ return changeset;\n}\ntype RoleThreadResult = {|\n@@ -212,13 +217,12 @@ async function changeRoleThreadQuery(\nasync function updateDescendantPermissions(\ninitialParentThreadID: string,\ninitialUsersToPermissionsFromParent: Map<string, ?ThreadPermissionsBlob>,\n-): Promise<MembershipChangeset> {\n+): Promise<Changeset> {\nconst stack = [[\ninitialParentThreadID,\ninitialUsersToPermissionsFromParent,\n]];\n- const toSave = [];\n- const toDelete = [];\n+ const changeset = [];\nwhile (stack.length > 0) {\nconst [ parentThreadID, usersToPermissionsFromParent ] = stack.shift();\n@@ -289,7 +293,8 @@ async function updateDescendantPermissions(\npermissions,\n);\nif (permissions) {\n- toSave.push({\n+ changeset.push({\n+ operation: \"update\",\nuserID,\nthreadID,\npermissions,\n@@ -297,7 +302,11 @@ async function updateDescendantPermissions(\nrole,\n});\n} else {\n- toDelete.push({ userID, threadID });\n+ changeset.push({\n+ operation: \"delete\",\n+ userID,\n+ threadID,\n+ });\n}\nif (!_isEqual(permissionsForChildren)(oldPermissionsForChildren)) {\nusersForNextLayer.set(userID, permissionsForChildren);\n@@ -308,16 +317,16 @@ async function updateDescendantPermissions(\n}\n}\n}\n- return { toSave, toDelete };\n+ return changeset;\n}\n-// Unlike changeRole and others, this doesn't just create a MembershipChangeset.\n+// Unlike changeRole and others, this doesn't just create a Changeset.\n// It mutates the threads table by setting the type column.\n-// Caller still needs to save the resultant MembershipChangeset.\n+// Caller still needs to save the resultant Changeset.\nasync function recalculateAllPermissions(\nthreadID: string,\nnewThreadType: ThreadType,\n-): Promise<MembershipChangeset> {\n+): Promise<Changeset> {\nconst updateQuery = SQL`\nUPDATE threads SET type = ${newThreadType} WHERE id = ${threadID}\n`;\n@@ -344,8 +353,7 @@ async function recalculateAllPermissions(\ndbQuery(updateQuery),\n]);\n- const toSave = [];\n- const toDelete = [];\n+ const changeset = [];\nconst toUpdateDescendants = new Map();\nfor (let row of selectResult) {\nif (!row.user) {\n@@ -372,7 +380,8 @@ async function recalculateAllPermissions(\npermissions,\n);\nif (permissions) {\n- toSave.push({\n+ changeset.push({\n+ operation: \"update\",\nuserID,\nthreadID,\npermissions,\n@@ -380,7 +389,11 @@ async function recalculateAllPermissions(\nrole,\n});\n} else {\n- toDelete.push({ userID, threadID });\n+ changeset.push({\n+ operation: \"delete\",\n+ userID,\n+ threadID,\n+ });\n}\nif (!_isEqual(permissionsForChildren)(oldPermissionsForChildren)) {\ntoUpdateDescendants.set(userID, permissionsForChildren);\n@@ -392,17 +405,16 @@ async function recalculateAllPermissions(\nthreadID,\ntoUpdateDescendants,\n);\n- return {\n- toSave: [...toSave, ...descendantResults.toSave],\n- toDelete: [...toDelete, ...descendantResults.toDelete],\n- };\n+ changeset.push(...descendantResults);\n}\n- return { toSave, toDelete };\n+ return changeset;\n}\nconst defaultSubscriptionString =\nJSON.stringify({ home: false, pushNotifs: false });\n+const joinSubscriptionString =\n+ JSON.stringify({ home: true, pushNotifs: true });\nasync function saveMemberships(toSave: $ReadOnlyArray<RowToSave>) {\nif (toSave.length === 0) {\n@@ -410,8 +422,17 @@ async function saveMemberships(toSave: $ReadOnlyArray<RowToSave>) {\n}\nconst time = Date.now();\n- const insertRows = toSave.map(\n- rowToSave => [\n+ const insertRows = [];\n+ for (let rowToSave of toSave) {\n+ let subscription;\n+ if (rowToSave.subscription) {\n+ subscription = JSON.stringify(rowToSave.subscription);\n+ } else if (rowToSave.operation === \"join\") {\n+ subscription = joinSubscriptionString;\n+ } else {\n+ subscription = defaultSubscriptionString;\n+ }\n+ insertRows.push([\nrowToSave.userID,\nrowToSave.threadID,\nrowToSave.role,\n@@ -424,8 +445,8 @@ async function saveMemberships(toSave: $ReadOnlyArray<RowToSave>) {\n? JSON.stringify(rowToSave.permissionsForChildren)\n: null,\nrowToSave.unread ? \"1\" : \"0\",\n- ],\n- );\n+ ]);\n+ }\n// Logic below will only update an existing membership row's `subscription`\n// column if the user is either joining or leaving the thread. That means\n@@ -467,29 +488,46 @@ async function deleteMemberships(toDelete: $ReadOnlyArray<RowToDelete>) {\nawait dbQuery(query);\n}\n-type MembershipChangesetCommitResult = {|\n+type ChangesetCommitResult = {|\n...FetchThreadInfosResult,\nviewerUpdates: $ReadOnlyArray<UpdateInfo>,\n|};\nasync function commitMembershipChangeset(\nviewer: Viewer,\n- changeset: MembershipChangeset,\n+ changeset: Changeset,\nchangedThreadIDs?: Set<string> = new Set(),\n-): Promise<MembershipChangesetCommitResult> {\n+): Promise<ChangesetCommitResult> {\n+ const toJoin = [], toUpdate = [], toDelete = [];\n+ for (let row of changeset) {\n+ if (row.operation === \"join\") {\n+ toJoin.push(row);\n+ } else if (row.operation === \"update\") {\n+ toUpdate.push(row);\n+ } else if (row.operation === \"delete\") {\n+ toDelete.push(row);\n+ }\n+ }\n+\nawait Promise.all([\n- saveMemberships(changeset.toSave),\n- deleteMemberships(changeset.toDelete),\n+ saveMemberships([...toJoin, ...toUpdate]),\n+ deleteMemberships(toDelete),\n]);\nconst threadInfoFetchResult = await fetchServerThreadInfos();\nconst { threadInfos: serverThreadInfos } = threadInfoFetchResult;\n+ const threadMembershipCreationPairs = new Set();\nconst threadMembershipDeletionPairs = new Set();\n- for (let rowToSave of changeset.toSave) {\n- const { threadID } = rowToSave;\n+ for (let rowToJoin of toJoin) {\n+ const { userID, threadID } = rowToJoin;\n+ changedThreadIDs.add(threadID);\n+ threadMembershipCreationPairs.add(`${userID}|${threadID}`);\n+ }\n+ for (let rowToUpdate of toUpdate) {\n+ const { threadID } = rowToUpdate;\nchangedThreadIDs.add(threadID);\n}\n- for (let rowToDelete of changeset.toDelete) {\n+ for (let rowToDelete of toDelete) {\nconst { userID, threadID } = rowToDelete;\nchangedThreadIDs.add(threadID);\nthreadMembershipDeletionPairs.add(`${userID}|${threadID}`);\n" }, { "change_type": "MODIFY", "old_path": "server/src/updaters/thread-updaters.js", "new_path": "server/src/updaters/thread-updaters.js", "diff": "@@ -249,10 +249,6 @@ async function leaveThread(\nif (!changeset) {\nthrow new ServerError('unknown_error');\n}\n- const toSave = changeset.toSave.map(rowToSave => ({\n- ...rowToSave,\n- subscription: { home: false, pushNotifs: false },\n- }));\nconst messageData = {\ntype: messageTypes.LEAVE_THREAD,\n@@ -353,7 +349,7 @@ async function updateThread(\nthrow new ServerError('invalid_credentials');\n}\n- const newMemberIDs = verifiedNewMemberIDs\n+ const newMemberIDs = verifiedNewMemberIDs && verifiedNewMemberIDs.length > 0\n? verifiedNewMemberIDs\n: null;\nif (Object.keys(sqlUpdate).length === 0 && !newMemberIDs) {\n@@ -459,23 +455,28 @@ async function updateThread(\nrecalculatePermissionsChangeset,\n} = await promiseAll(savePromises);\n- let toSave = [];\n- let toDelete = [];\n- if (recalculatePermissionsChangeset) {\n- toSave = [...toSave, ...recalculatePermissionsChangeset.toSave];\n- toDelete = [...toDelete, ...recalculatePermissionsChangeset.toDelete];\n+ const changeset = [];\n+ if (recalculatePermissionsChangeset && newMemberIDs) {\n+ changeset.push(...recalculatePermissionsChangeset.filter(\n+ rowToSave => !newMemberIDs.includes(rowToSave.userID),\n+ ));\n+ } else if (recalculatePermissionsChangeset) {\n+ changeset.push(...recalculatePermissionsChangeset);\n}\nif (addMembersChangeset) {\n- toDelete = [...toDelete, ...addMembersChangeset.toDelete];\n- for (let rowToSave of addMembersChangeset.toSave) {\n- let newRowToSave = {...rowToSave};\n- if (rowToSave.role !== \"0\") {\n- newRowToSave.unread = true;\n+ for (let rowToSave of addMembersChangeset) {\n+ if (rowToSave.operation === \"delete\") {\n+ changeset.push(rowToSave);\n+ continue;\n}\n- if (rowToSave.threadID === request.threadID) {\n- newRowToSave.subscription = { home: true, pushNotifs: true };\n+ if (\n+ rowToSave.operation === \"join\" &&\n+ (rowToSave.userID !== viewer.userID ||\n+ rowToSave.threadID !== request.threadID)\n+ ) {\n+ rowToSave.unread = true;\n}\n- toSave.push(newRowToSave);\n+ changeset.push(rowToSave);\n}\n}\n@@ -509,7 +510,7 @@ async function updateThread(\ncreateMessages(messageDatas),\ncommitMembershipChangeset(\nviewer,\n- { toSave, toDelete },\n+ changeset,\n// This forces an update for this thread,\n// regardless of whether any membership rows are changed\nObject.keys(sqlUpdate).length > 0\n@@ -564,10 +565,18 @@ async function joinThread(\nif (!changeset) {\nthrow new ServerError('unknown_error');\n}\n- const toSave = changeset.toSave.map(rowToSave => ({\n- ...rowToSave,\n- subscription: { home: true, pushNotifs: true },\n- }));\n+ for (let rowToSave of changeset) {\n+ if (rowToSave.operation === \"delete\") {\n+ continue;\n+ }\n+ if (\n+ rowToSave.operation === \"join\" &&\n+ (rowToSave.userID !== viewer.userID ||\n+ rowToSave.threadID !== request.threadID)\n+ ) {\n+ rowToSave.unread = true;\n+ }\n+ }\nconst messageData = {\ntype: messageTypes.JOIN_THREAD,\n@@ -576,7 +585,7 @@ async function joinThread(\ntime: Date.now(),\n};\nconst [ fetchThreadsResult ] = await Promise.all([\n- commitMembershipChangeset(viewer, { toSave, toDelete: changeset.toDelete }),\n+ commitMembershipChangeset(viewer, changeset),\ncreateMessages([messageData]),\n]);\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Thread "join" operation to commitMembershipChangeset Having this info lets us be a bit smarter about subscription status on join/leave, and is necessary for deciding between `updateTypes.UPDATE_THREAD` and `updateTypes.JOIN_THREAD` (coming soon).
129,187
20.06.2018 16:09:30
25,200
45d775d980eb974a6e869ee6cf0d493830574162
Don't store ThreadInfo in updates table Just store `threadID`, and query for the `RawThreadInfo` when delivering to the client. We'll use the same technique for fetching `RawEntryInfo`s and `RawMessageInfo`s for the upcoming `updateTypes.JOIN_THREAD`.
[ { "change_type": "MODIFY", "old_path": "lib/shared/update-utils.js", "new_path": "lib/shared/update-utils.js", "diff": "@@ -19,45 +19,6 @@ function mostRecentUpdateTimestamp(\nreturn _maxBy('time')(updateInfos).time;\n}\n-function updateInfoFromUpdateData(\n- updateData: UpdateData,\n- id: string,\n-): UpdateInfo {\n- if (updateData.type === updateTypes.DELETE_ACCOUNT) {\n- return {\n- type: updateTypes.DELETE_ACCOUNT,\n- id,\n- time: updateData.time,\n- deletedUserID: updateData.deletedUserID,\n- };\n- } else if (updateData.type === updateTypes.UPDATE_THREAD) {\n- return {\n- type: updateTypes.UPDATE_THREAD,\n- id,\n- time: updateData.time,\n- threadInfo: updateData.threadInfo,\n- };\n- } else if (updateData.type === updateTypes.UPDATE_THREAD_READ_STATUS) {\n- return {\n- type: updateTypes.UPDATE_THREAD_READ_STATUS,\n- id,\n- time: updateData.time,\n- threadID: updateData.threadID,\n- unread: updateData.unread,\n- };\n- } else if (updateData.type === updateTypes.DELETE_THREAD) {\n- return {\n- type: updateTypes.DELETE_THREAD,\n- id,\n- time: updateData.time,\n- threadID: updateData.threadID,\n- };\n- } else {\n- invariant(false, `unrecognized updateType ${updateData.type}`);\n- }\n-}\n-\nexport {\nmostRecentUpdateTimestamp,\n- updateInfoFromUpdateData,\n};\n" }, { "change_type": "MODIFY", "old_path": "lib/types/update-types.js", "new_path": "lib/types/update-types.js", "diff": "@@ -34,7 +34,7 @@ type ThreadUpdateData = {|\ntype: 1,\nuserID: string,\ntime: number,\n- threadInfo: RawThreadInfo,\n+ threadID: string,\n|};\ntype ThreadReadStatusUpdateData = {|\ntype: 2,\n" }, { "change_type": "MODIFY", "old_path": "server/src/creators/update-creator.js", "new_path": "server/src/creators/update-creator.js", "diff": "@@ -6,32 +6,52 @@ import {\nupdateTypes,\n} from 'lib/types/update-types';\nimport type { Viewer } from '../session/viewer';\n+import type { RawThreadInfo } from 'lib/types/thread-types';\n+import type { AccountUserInfo } from 'lib/types/user-types';\n-import { updateInfoFromUpdateData } from 'lib/shared/update-utils';\n+import invariant from 'invariant';\n+\n+import { promiseAll } from 'lib/utils/promises';\nimport { dbQuery, SQL } from '../database';\nimport createIDs from './id-creator';\nimport { deleteUpdatesByConditions } from '../deleters/update-deleters';\n+import {\n+ fetchThreadInfos,\n+ type FetchThreadInfosResult,\n+} from '../fetchers/thread-fetchers';\n// If the viewer is not passed in, the returned array will be empty, and the\n// update won't have an updater_cookie. This should only be done when we are\n// sure none of the updates are destined for the viewer.\n+export type ViewerInfo =\n+ | {| viewer: Viewer |}\n+ | {|\n+ viewer: Viewer,\n+ threadInfos: {[id: string]: RawThreadInfo},\n+ userInfos: {[id: string]: AccountUserInfo},\n+ |};\n+type UpdatesResult = {|\n+ viewerUpdates: $ReadOnlyArray<UpdateInfo>,\n+ userInfos: {[id: string]: AccountUserInfo},\n+|};\n+const defaultResult = { viewerUpdates: [], userInfos: {} };\nasync function createUpdates(\nupdateDatas: $ReadOnlyArray<UpdateData>,\n- viewer?: Viewer,\n-): Promise<UpdateInfo[]> {\n+ viewerInfo?: ViewerInfo,\n+): Promise<UpdatesResult> {\nif (updateDatas.length === 0) {\n- return [];\n+ return defaultResult;\n}\nconst ids = await createIDs(\"updates\", updateDatas.length);\n- const viewerUpdates = [];\n+ const viewerUpdateDatas: ViewerUpdateData[] = [];\nconst insertRows = [];\nconst deleteConditions = [];\nfor (let i = 0; i < updateDatas.length; i++) {\nconst updateData = updateDatas[i];\n- if (viewer && updateData.userID === viewer.id) {\n- viewerUpdates.push(updateInfoFromUpdateData(updateData, ids[i]));\n+ if (viewerInfo && updateData.userID === viewerInfo.viewer.id) {\n+ viewerUpdateDatas.push({ data: updateData, id: ids[i] });\n}\nlet content, key;\n@@ -39,8 +59,8 @@ async function createUpdates(\ncontent = JSON.stringify({ deletedUserID: updateData.deletedUserID });\nkey = null;\n} else if (updateData.type === updateTypes.UPDATE_THREAD) {\n- content = JSON.stringify(updateData.threadInfo);\n- key = updateData.threadInfo.id;\n+ content = JSON.stringify({ threadID: updateData.threadID });\n+ key = updateData.threadID;\nconst deleteTypes = [\nupdateTypes.UPDATE_THREAD,\nupdateTypes.UPDATE_THREAD_READ_STATUS,\n@@ -79,31 +99,140 @@ async function createUpdates(\ncontent,\nupdateData.time,\n];\n- if (viewer) {\n- insertRow.push(viewer.cookieID);\n+ if (viewerInfo) {\n+ insertRow.push(viewerInfo.viewer.cookieID);\n}\ninsertRows.push(insertRow);\n}\n- const promises = [];\n+ const promises = {};\n- const insertQuery = viewer\n+ const insertQuery = viewerInfo\n? SQL`\nINSERT INTO updates(id, user, type, key, content, time, updater_cookie)\n`\n: SQL`INSERT INTO updates(id, user, type, key, content, time) `;\ninsertQuery.append(SQL`VALUES ${insertRows}`);\n- promises.push(dbQuery(insertQuery));\n+ promises.insert = dbQuery(insertQuery);\nif (deleteConditions.length > 0) {\n- promises.push(deleteUpdatesByConditions(deleteConditions));\n+ promises.delete = deleteUpdatesByConditions(deleteConditions);\n+ }\n+\n+ if (viewerUpdateDatas.length > 0) {\n+ invariant(viewerInfo, \"should be set\");\n+ promises.updatesResult = fetchUpdateInfosWithUpdateDatas(\n+ viewerUpdateDatas,\n+ viewerInfo,\n+ );\n+ }\n+\n+ const { updatesResult } = await promiseAll(promises);\n+ if (!updatesResult) {\n+ return defaultResult;\n+ }\n+ const { updateInfos, userInfos } = updatesResult;\n+ return { viewerUpdates: updateInfos, userInfos };\n+}\n+\n+export type ViewerUpdateData = {| data: UpdateData, id: string |};\n+export type FetchUpdatesResult = {|\n+ updateInfos: $ReadOnlyArray<UpdateInfo>,\n+ userInfos: {[id: string]: AccountUserInfo},\n+|};\n+async function fetchUpdateInfosWithUpdateDatas(\n+ updateDatas: $ReadOnlyArray<ViewerUpdateData>,\n+ viewerInfo: ViewerInfo,\n+): Promise<FetchUpdatesResult> {\n+ const threadIDsNeedingFetch = new Set();\n+ if (!viewerInfo.threadInfos) {\n+ for (let viewerUpdateData of updateDatas) {\n+ const updateData = viewerUpdateData.data;\n+ if (updateData.type === updateTypes.UPDATE_THREAD) {\n+ threadIDsNeedingFetch.add(updateData.threadID);\n+ }\n+ }\n+ }\n+\n+ let threadResult = undefined;\n+ if (threadIDsNeedingFetch.size > 0) {\n+ threadResult = await fetchThreadInfos(\n+ viewerInfo.viewer,\n+ SQL`t.id IN (${[...threadIDsNeedingFetch]})`,\n+ );\n}\n- await Promise.all(promises);\n+ if (viewerInfo.threadInfos) {\n+ const { threadInfos, userInfos } = viewerInfo;\n+ return updateInfosFromUpdateDatas(updateDatas, { threadInfos, userInfos });\n+ } else if (threadResult) {\n+ return updateInfosFromUpdateDatas(updateDatas, threadResult);\n+ } else {\n+ return updateInfosFromUpdateDatas(\n+ updateDatas,\n+ { threadInfos: {}, userInfos: {} },\n+ );\n+ }\n+}\n+\n+function updateInfosFromUpdateDatas(\n+ updateDatas: $ReadOnlyArray<ViewerUpdateData>,\n+ threadInfosResult: FetchThreadInfosResult,\n+): FetchUpdatesResult {\n+ const updateInfos = [];\n+ const userIDs = new Set();\n+ for (let viewerUpdateData of updateDatas) {\n+ const { data: updateData, id } = viewerUpdateData;\n+ if (updateData.type === updateTypes.DELETE_ACCOUNT) {\n+ updateInfos.push({\n+ type: updateTypes.DELETE_ACCOUNT,\n+ id,\n+ time: updateData.time,\n+ deletedUserID: updateData.deletedUserID,\n+ });\n+ } else if (updateData.type === updateTypes.UPDATE_THREAD) {\n+ const threadInfo = threadInfosResult.threadInfos[updateData.threadID];\n+ for (let member of threadInfo.members) {\n+ userIDs.add(member.id);\n+ }\n+ updateInfos.push({\n+ type: updateTypes.UPDATE_THREAD,\n+ id,\n+ time: updateData.time,\n+ threadInfo,\n+ });\n+ } else if (updateData.type === updateTypes.UPDATE_THREAD_READ_STATUS) {\n+ updateInfos.push({\n+ type: updateTypes.UPDATE_THREAD_READ_STATUS,\n+ id,\n+ time: updateData.time,\n+ threadID: updateData.threadID,\n+ unread: updateData.unread,\n+ });\n+ } else if (updateData.type === updateTypes.DELETE_THREAD) {\n+ updateInfos.push({\n+ type: updateTypes.DELETE_THREAD,\n+ id,\n+ time: updateData.time,\n+ threadID: updateData.threadID,\n+ });\n+ } else {\n+ invariant(false, `unrecognized updateType ${updateData.type}`);\n+ }\n+ }\n+\n+ const userInfos = {};\n+ for (let userID of userIDs) {\n+ const userInfo = threadInfosResult.userInfos[userID];\n+ if (userInfo) {\n+ userInfos[userID] = userInfo;\n+ }\n+ }\n- return viewerUpdates;\n+ return { updateInfos, userInfos };\n}\nexport {\ncreateUpdates,\n+ updateInfosFromUpdateDatas,\n};\n" }, { "change_type": "MODIFY", "old_path": "server/src/deleters/thread-deleters.js", "new_path": "server/src/deleters/thread-deleters.js", "diff": "@@ -94,8 +94,8 @@ async function deleteThread(\n});\n}\n- const [ viewerUpdates ] = await Promise.all([\n- createUpdates(updateDatas, viewer),\n+ const [ { viewerUpdates } ] = await Promise.all([\n+ createUpdates(updateDatas, { viewer }),\ndbQuery(query),\n]);\n" }, { "change_type": "MODIFY", "old_path": "server/src/fetchers/update-fetchers.js", "new_path": "server/src/fetchers/update-fetchers.js", "diff": "@@ -6,69 +6,83 @@ import {\nassertUpdateType,\n} from 'lib/types/update-types';\nimport type { Viewer } from '../session/viewer';\n+import type { FetchThreadInfosResult } from '../fetchers/thread-fetchers';\nimport invariant from 'invariant';\nimport { dbQuery, SQL } from '../database';\n+import {\n+ type ViewerUpdateData,\n+ type FetchUpdatesResult,\n+ updateInfosFromUpdateDatas,\n+} from '../creators/update-creator';\n-function updateInfoFromRow(row: Object): UpdateInfo {\n+async function fetchUpdateInfos(\n+ viewer: Viewer,\n+ currentAsOf: number,\n+ threadInfosResult: FetchThreadInfosResult,\n+): Promise<FetchUpdatesResult> {\n+ const query = SQL`\n+ SELECT id, type, content, time\n+ FROM updates\n+ WHERE user = ${viewer.id} AND time > ${currentAsOf}\n+ AND (updater_cookie IS NULL OR updater_cookie != ${viewer.cookieID})\n+ ORDER BY time ASC\n+ `;\n+ const [ result ] = await dbQuery(query);\n+\n+ const viewerUpdateDatas = [];\n+ for (let row of result) {\n+ viewerUpdateDatas.push(viewerUpdateDataFromRow(viewer, row));\n+ }\n+\n+ return updateInfosFromUpdateDatas(viewerUpdateDatas, threadInfosResult);\n+}\n+\n+function viewerUpdateDataFromRow(\n+ viewer: Viewer,\n+ row: Object,\n+): ViewerUpdateData {\nconst type = assertUpdateType(row.type);\n+ let data;\n+ const id = row.id;\nif (type === updateTypes.DELETE_ACCOUNT) {\nconst content = JSON.parse(row.content);\n- return {\n+ data = {\ntype: updateTypes.DELETE_ACCOUNT,\n- id: row.id,\n+ userID: viewer.id,\ntime: row.time,\ndeletedUserID: content.deletedUserID,\n};\n} else if (type === updateTypes.UPDATE_THREAD) {\n- const rawThreadInfo = JSON.parse(row.content);\n- return {\n+ const { threadID } = JSON.parse(row.content);\n+ data = {\ntype: updateTypes.UPDATE_THREAD,\n- id: row.id,\n+ userID: viewer.id,\ntime: row.time,\n- threadInfo: rawThreadInfo,\n+ threadID,\n};\n} else if (type === updateTypes.UPDATE_THREAD_READ_STATUS) {\nconst { threadID, unread } = JSON.parse(row.content);\n- return {\n+ data = {\ntype: updateTypes.UPDATE_THREAD_READ_STATUS,\n- id: row.id,\n+ userID: viewer.id,\ntime: row.time,\nthreadID,\nunread,\n};\n} else if (type === updateTypes.DELETE_THREAD) {\nconst { threadID } = JSON.parse(row.content);\n- return {\n+ data = {\ntype: updateTypes.DELETE_THREAD,\n- id: row.id,\n+ userID: viewer.id,\ntime: row.time,\nthreadID,\n};\n} else {\ninvariant(false, `unrecognized updateType ${type}`);\n}\n-}\n-\n-async function fetchUpdateInfos(\n- viewer: Viewer,\n- currentAsOf: number,\n-): Promise<UpdateInfo[]> {\n- const query = SQL`\n- SELECT id, type, content, time\n- FROM updates\n- WHERE user = ${viewer.id} AND time > ${currentAsOf}\n- AND (updater_cookie IS NULL OR updater_cookie != ${viewer.cookieID})\n- ORDER BY time ASC\n- `;\n- const [ result ] = await dbQuery(query);\n-\n- const updateInfos = [];\n- for (let row of result) {\n- updateInfos.push(updateInfoFromRow(row));\n- }\n- return updateInfos;\n+ return { data, id };\n}\nexport {\n" }, { "change_type": "MODIFY", "old_path": "server/src/responders/ping-responders.js", "new_path": "server/src/responders/ping-responders.js", "diff": "@@ -115,7 +115,6 @@ async function pingResponder(\nthreadsResult,\nentriesResult,\ncurrentUserInfo,\n- newUpdates,\n] = await Promise.all([\nfetchMessageInfosSince(\nviewer,\n@@ -126,35 +125,34 @@ async function pingResponder(\nfetchThreadInfos(viewer),\nfetchEntryInfos(viewer, request.calendarQuery),\nfetchCurrentUserInfo(viewer),\n- oldUpdatesCurrentAsOf !== null && oldUpdatesCurrentAsOf !== undefined\n- ? fetchUpdateInfos(viewer, oldUpdatesCurrentAsOf)\n- : null,\nclientResponsePromises.length > 0\n? Promise.all(clientResponsePromises)\n: null,\n]);\nlet updatesResult = null;\n- const timestampUpdatePromises = [ updateActivityTime(viewer) ];\n- if (newUpdates) {\n- invariant(\n- oldUpdatesCurrentAsOf !== null && oldUpdatesCurrentAsOf !== undefined,\n- \"should be set\",\n+ if (oldUpdatesCurrentAsOf !== null && oldUpdatesCurrentAsOf !== undefined) {\n+ const { updateInfos } = await fetchUpdateInfos(\n+ viewer,\n+ oldUpdatesCurrentAsOf,\n+ threadsResult,\n);\nconst newUpdatesCurrentAsOf = mostRecentUpdateTimestamp(\n- newUpdates,\n+ [...updateInfos],\noldUpdatesCurrentAsOf,\n);\n- if (newUpdates.length > 0) {\n- timestampUpdatePromises.push(\n- recordDeliveredUpdate(viewer.cookieID, newUpdatesCurrentAsOf),\n- );\n- }\nupdatesResult = {\n- newUpdates,\n+ newUpdates: updateInfos,\ncurrentAsOf: newUpdatesCurrentAsOf,\n};\n}\n+\n+ const timestampUpdatePromises = [ updateActivityTime(viewer) ];\n+ if (updatesResult && updatesResult.newUpdates.length > 0) {\n+ timestampUpdatePromises.push(\n+ recordDeliveredUpdate(viewer.cookieID, updatesResult.currentAsOf),\n+ );\n+ }\nawait Promise.all(timestampUpdatePromises);\nconst userInfos: any = Object.values({\n" }, { "change_type": "MODIFY", "old_path": "server/src/updaters/activity-updaters.js", "new_path": "server/src/updaters/activity-updaters.js", "diff": "@@ -103,7 +103,7 @@ async function activityUpdater(\nthreadID,\nunread: false,\n})),\n- localViewer,\n+ { viewer: localViewer },\n));\nconst rescindCondition = SQL`\nn.user = ${localViewer.userID} AND n.thread IN (${focusedThreadIDs})\n@@ -223,7 +223,7 @@ async function possiblyResetThreadsToUnread(\nthreadID,\nunread: true,\n})),\n- viewer,\n+ { viewer },\n));\nawait Promise.all(promises);\n" }, { "change_type": "MODIFY", "old_path": "server/src/updaters/thread-permission-updaters.js", "new_path": "server/src/updaters/thread-permission-updaters.js", "diff": "@@ -513,8 +513,8 @@ async function commitMembershipChangeset(\ndeleteMemberships(toDelete),\n]);\n- const threadInfoFetchResult = await fetchServerThreadInfos();\n- const { threadInfos: serverThreadInfos } = threadInfoFetchResult;\n+ const serverThreadInfoFetchResult = await fetchServerThreadInfos();\n+ const { threadInfos: serverThreadInfos } = serverThreadInfoFetchResult;\nconst threadMembershipCreationPairs = new Set();\nconst threadMembershipDeletionPairs = new Set();\n@@ -542,18 +542,11 @@ async function commitMembershipChangeset(\nif (threadMembershipDeletionPairs.has(pairString)) {\ncontinue;\n}\n- const threadInfo = rawThreadInfoFromServerThreadInfo(\n- serverThreadInfo,\n- memberInfo.id,\n- );\n- if (!threadInfo) {\n- continue;\n- }\nupdateDatas.push({\ntype: updateTypes.UPDATE_THREAD,\nuserID: memberInfo.id,\ntime,\n- threadInfo,\n+ threadID: changedThreadID,\n});\n}\n}\n@@ -567,13 +560,17 @@ async function commitMembershipChangeset(\n});\n}\n- const viewerUpdates = await createUpdates(updateDatas, viewer);\n+ const threadInfoFetchResult = rawThreadInfosFromServerThreadInfos(\n+ viewer,\n+ serverThreadInfoFetchResult,\n+ );\n+ const { viewerUpdates } = await createUpdates(\n+ updateDatas,\n+ { viewer, ...threadInfoFetchResult },\n+ );\nreturn {\n- ...rawThreadInfosFromServerThreadInfos(\n- viewer,\n- threadInfoFetchResult,\n- ),\n+ ...threadInfoFetchResult,\nviewerUpdates,\n};\n}\n" }, { "change_type": "MODIFY", "old_path": "server/src/updaters/user-subscription-updaters.js", "new_path": "server/src/updaters/user-subscription-updaters.js", "diff": "@@ -45,15 +45,9 @@ async function userSubscriptionUpdater(\ntype: updateTypes.UPDATE_THREAD,\nuserID: viewer.id,\ntime,\n- threadInfo: {\n- ...threadInfo,\n- currentUser: {\n- ...threadInfo.currentUser,\n- subscription: newSubscription,\n- },\n- },\n+ threadID: update.threadID,\n}];\n- promises.push(createUpdates(updateDatas, viewer));\n+ promises.push(createUpdates(updateDatas, { viewer }));\nawait Promise.all(promises);\nreturn newSubscription;\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Don't store ThreadInfo in updates table Just store `threadID`, and query for the `RawThreadInfo` when delivering to the client. We'll use the same technique for fetching `RawEntryInfo`s and `RawMessageInfo`s for the upcoming `updateTypes.JOIN_THREAD`.
129,187
21.06.2018 23:53:44
25,200
1c533611de45f5d86b0ee7afd2abdcf281d79fbf
[server] Use CalendarQuery from client for fetching EntryInfos for updates
[ { "change_type": "MODIFY", "old_path": "server/src/creators/update-creator.js", "new_path": "server/src/creators/update-creator.js", "diff": "@@ -49,6 +49,7 @@ export type ViewerInfo =\nviewer: Viewer,\nthreadInfos: {[id: string]: RawThreadInfo},\nuserInfos: {[id: string]: AccountUserInfo},\n+ calendarQuery: ?CalendarQuery,\n|};\ntype UpdatesResult = {|\nviewerUpdates: $ReadOnlyArray<UpdateInfo>,\n@@ -203,7 +204,13 @@ async function fetchUpdateInfosWithUpdateDatas(\nthreadSelectionCriteria,\ndefaultNumberPerThread,\n);\n- calendarQuery = defaultCalendarQuery();\n+ // defaultCalendarQuery will only ever get used in the case of a legacy\n+ // client calling join_thread without specifying a CalendarQuery. Those\n+ // legacy clients will be discarding the UpdateInfos anyways, so we don't\n+ // need to worry about the CalendarQuery correctness.\n+ calendarQuery = viewerInfo.calendarQuery\n+ ? viewerInfo.calendarQuery\n+ : defaultCalendarQuery();\ncalendarQuery.filters = [\n...nonThreadCalendarFilters(calendarQuery.filters),\n{ type: \"threads\", threadIDs: [...threadIDsNeedingDetailedFetch] },\n" }, { "change_type": "MODIFY", "old_path": "server/src/fetchers/update-fetchers.js", "new_path": "server/src/fetchers/update-fetchers.js", "diff": "@@ -5,6 +5,7 @@ import {\nupdateTypes,\nassertUpdateType,\n} from 'lib/types/update-types';\n+import type { CalendarQuery } from 'lib/types/entry-types';\nimport type { Viewer } from '../session/viewer';\nimport type { FetchThreadInfosResult } from '../fetchers/thread-fetchers';\n@@ -17,10 +18,14 @@ import {\nfetchUpdateInfosWithUpdateDatas,\n} from '../creators/update-creator';\n+type UpdateInfoQueryInput = {|\n+ ...FetchThreadInfosResult,\n+ calendarQuery: CalendarQuery,\n+|};\nasync function fetchUpdateInfos(\nviewer: Viewer,\ncurrentAsOf: number,\n- threadInfosResult: FetchThreadInfosResult,\n+ queryInput: UpdateInfoQueryInput,\n): Promise<FetchUpdatesResult> {\nconst query = SQL`\nSELECT id, type, content, time\n@@ -38,7 +43,7 @@ async function fetchUpdateInfos(\nreturn await fetchUpdateInfosWithUpdateDatas(\nviewerUpdateDatas,\n- { viewer, ...threadInfosResult },\n+ { viewer, ...queryInput },\n);\n}\n" }, { "change_type": "MODIFY", "old_path": "server/src/responders/ping-responders.js", "new_path": "server/src/responders/ping-responders.js", "diff": "@@ -135,7 +135,7 @@ async function pingResponder(\nconst { updateInfos } = await fetchUpdateInfos(\nviewer,\noldUpdatesCurrentAsOf,\n- threadsResult,\n+ { ...threadsResult, calendarQuery: request.calendarQuery },\n);\nconst newUpdatesCurrentAsOf = mostRecentUpdateTimestamp(\n[...updateInfos],\n" }, { "change_type": "MODIFY", "old_path": "server/src/updaters/thread-permission-updaters.js", "new_path": "server/src/updaters/thread-permission-updaters.js", "diff": "@@ -10,6 +10,7 @@ import {\nimport type { ThreadSubscription } from 'lib/types/subscription-types';\nimport type { Viewer } from '../session/viewer';\nimport { updateTypes, type UpdateInfo } from 'lib/types/update-types';\n+import type { CalendarQuery } from 'lib/types/entry-types';\nimport invariant from 'invariant';\nimport _isEqual from 'lodash/fp/isEqual';\n@@ -488,6 +489,10 @@ async function deleteMemberships(toDelete: $ReadOnlyArray<RowToDelete>) {\nawait dbQuery(query);\n}\n+// Specify non-empty changedThreadIDs to force updates to be generated for those\n+// threads, presumably for reasons not covered in the changeset. calendarQuery\n+// only needs to be specified if a JOIN_THREAD update will be generated for the\n+// viewer, in which case it's necessary for knowing the set of entries to fetch.\ntype ChangesetCommitResult = {|\n...FetchThreadInfosResult,\nviewerUpdates: $ReadOnlyArray<UpdateInfo>,\n@@ -496,6 +501,7 @@ async function commitMembershipChangeset(\nviewer: Viewer,\nchangeset: Changeset,\nchangedThreadIDs?: Set<string> = new Set(),\n+ calendarQuery?: ?CalendarQuery,\n): Promise<ChangesetCommitResult> {\nconst toJoin = [], toUpdate = [], toDelete = [];\nfor (let row of changeset) {\n@@ -513,9 +519,6 @@ async function commitMembershipChangeset(\ndeleteMemberships(toDelete),\n]);\n- const serverThreadInfoFetchResult = await fetchServerThreadInfos();\n- const { threadInfos: serverThreadInfos } = serverThreadInfoFetchResult;\n-\nconst threadMembershipCreationPairs = new Set();\nconst threadMembershipDeletionPairs = new Set();\nfor (let rowToJoin of toJoin) {\n@@ -533,6 +536,9 @@ async function commitMembershipChangeset(\nthreadMembershipDeletionPairs.add(`${userID}|${threadID}`);\n}\n+ const serverThreadInfoFetchResult = await fetchServerThreadInfos();\n+ const { threadInfos: serverThreadInfos } = serverThreadInfoFetchResult;\n+\nconst time = Date.now();\nconst updateDatas = [];\nfor (let changedThreadID of changedThreadIDs) {\n@@ -578,7 +584,7 @@ async function commitMembershipChangeset(\n);\nconst { viewerUpdates } = await createUpdates(\nupdateDatas,\n- { viewer, ...threadInfoFetchResult },\n+ { viewer, calendarQuery, ...threadInfoFetchResult },\n);\nreturn {\n" }, { "change_type": "MODIFY", "old_path": "server/src/updaters/thread-updaters.js", "new_path": "server/src/updaters/thread-updaters.js", "diff": "@@ -585,7 +585,7 @@ async function joinThread(\ntime: Date.now(),\n};\nconst [ fetchThreadsResult ] = await Promise.all([\n- commitMembershipChangeset(viewer, changeset),\n+ commitMembershipChangeset(viewer, changeset, new Set(), calendarQuery),\ncreateMessages([messageData]),\n]);\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Use CalendarQuery from client for fetching EntryInfos for updates
129,187
22.06.2018 12:55:12
25,200
77928b26a53dad1af6cee8324b209d1753a1f850
viewerCanSeeThread -> threadInChatList
[ { "change_type": "MODIFY", "old_path": "lib/reducers/message-reducer.js", "new_path": "lib/reducers/message-reducer.js", "diff": "@@ -32,7 +32,7 @@ import _uniq from 'lodash/fp/uniq';\nimport { messageID, combineTruncationStatuses } from '../shared/message-utils';\nimport { setHighestLocalID } from '../utils/local-ids';\n-import { viewerCanSeeThread } from '../shared/thread-utils';\n+import { threadInChatList } from '../shared/thread-utils';\nimport { setCookieActionType } from '../utils/action-utils';\nimport {\nlogOutActionTypes,\n@@ -87,7 +87,7 @@ function threadIsWatched(\nwatchedIDs: $ReadOnlyArray<string>,\n) {\nreturn threadInfo &&\n- (viewerCanSeeThread(threadInfo) || watchedIDs.includes(threadInfo.id));\n+ (threadInChatList(threadInfo) || watchedIDs.includes(threadInfo.id));\n}\nfunction freshMessageStore(\n" }, { "change_type": "MODIFY", "old_path": "lib/selectors/chat-selectors.js", "new_path": "lib/selectors/chat-selectors.js", "diff": "@@ -26,7 +26,7 @@ import {\ncreateMessageInfo,\n} from '../shared/message-utils';\nimport { threadInfoSelector } from './thread-selectors';\n-import { viewerCanSeeThread } from '../shared/thread-utils';\n+import { threadInChatList } from '../shared/thread-utils';\nexport type ChatThreadItem = {|\ntype: \"chatThreadItem\",\n@@ -95,9 +95,7 @@ const chatListData = createSelector(\nviewerID: ?string,\nuserInfos: {[id: string]: UserInfo},\n): ChatThreadItem[] => _flow(\n- // TODO change this to viewerIsMember once I figure out how to include\n- // non-visible threads in the ChatThreadList\n- _filter(viewerCanSeeThread),\n+ _filter(threadInChatList),\n_map((threadInfo: ThreadInfo): ChatThreadItem => createChatThreadItem(\nthreadInfo,\nthreadInfos,\n" }, { "change_type": "MODIFY", "old_path": "lib/shared/thread-utils.js", "new_path": "lib/shared/thread-utils.js", "diff": "@@ -52,7 +52,7 @@ function viewerIsMember(threadInfo: ?(ThreadInfo | RawThreadInfo)) {\nthreadInfo.currentUser.role !== undefined;\n}\n-function viewerCanSeeThread(threadInfo: ?(ThreadInfo | RawThreadInfo)) {\n+function threadInChatList(threadInfo: ?(ThreadInfo | RawThreadInfo)) {\nreturn viewerIsMember(threadInfo) &&\nthreadHasPermission(threadInfo, threadPermissions.VISIBLE);\n}\n@@ -245,7 +245,7 @@ export {\ngenerateRandomColor,\nthreadHasPermission,\nviewerIsMember,\n- viewerCanSeeThread,\n+ threadInChatList,\nuserIsMember,\nthreadActualMembers,\nthreadIsPersonalChat,\n" }, { "change_type": "MODIFY", "old_path": "native/chat/compose-thread.react.js", "new_path": "native/chat/compose-thread.react.js", "diff": "@@ -45,7 +45,7 @@ import {\n} from 'lib/selectors/user-selectors';\nimport SearchIndex from 'lib/shared/search-index';\nimport {\n- viewerCanSeeThread,\n+ threadInChatList,\nuserIsMember,\n} from 'lib/shared/thread-utils';\nimport { getUserSearchResults } from 'lib/shared/search-utils';\n@@ -255,7 +255,7 @@ class InnerComposeThread extends React.PureComponent<Props, State> {\nreturn _flow(\n_filter(\n(threadInfo: ThreadInfo) =>\n- viewerCanSeeThread(threadInfo) &&\n+ threadInChatList(threadInfo) &&\n(!props.parentThreadInfo ||\nthreadInfo.parentThreadID === props.parentThreadInfo.id) &&\nuserIDs.every(userID => userIsMember(threadInfo, userID)),\n" }, { "change_type": "MODIFY", "old_path": "native/chat/message-list.react.js", "new_path": "native/chat/message-list.react.js", "diff": "@@ -43,7 +43,7 @@ import {\nfetchMostRecentMessages,\n} from 'lib/actions/message-actions';\nimport threadWatcher from 'lib/shared/thread-watcher';\n-import { viewerCanSeeThread } from 'lib/shared/thread-utils';\n+import { threadInChatList } from 'lib/shared/thread-utils';\nimport { registerFetchKey } from 'lib/reducers/loading-reducer';\nimport { threadInfoSelector } from 'lib/selectors/thread-selectors';\nimport { onlyEmojiRegex } from 'lib/shared/emojis';\n@@ -176,7 +176,7 @@ class InnerMessageList extends React.PureComponent<Props, State> {\ncomponentDidMount() {\nconst threadInfo = InnerMessageList.getThreadInfo(this.props);\nregisterChatScreen(this.props.navigation.state.key, this);\n- if (!viewerCanSeeThread(threadInfo)) {\n+ if (!threadInChatList(threadInfo)) {\nthreadWatcher.watchID(threadInfo.id);\nthis.props.dispatchActionPromise(\nfetchMostRecentMessagesActionTypes,\n@@ -188,7 +188,7 @@ class InnerMessageList extends React.PureComponent<Props, State> {\ncomponentWillUnmount() {\nconst threadInfo = InnerMessageList.getThreadInfo(this.props);\nregisterChatScreen(this.props.navigation.state.key, null);\n- if (!viewerCanSeeThread(threadInfo)) {\n+ if (!threadInChatList(threadInfo)) {\nthreadWatcher.removeID(threadInfo.id);\n}\n}\n@@ -237,13 +237,13 @@ class InnerMessageList extends React.PureComponent<Props, State> {\n}\nif (\n- viewerCanSeeThread(oldThreadInfo) &&\n- !viewerCanSeeThread(newThreadInfo)\n+ threadInChatList(oldThreadInfo) &&\n+ !threadInChatList(newThreadInfo)\n) {\nthreadWatcher.watchID(oldThreadInfo.id);\n} else if (\n- !viewerCanSeeThread(oldThreadInfo) &&\n- viewerCanSeeThread(newThreadInfo)\n+ !threadInChatList(oldThreadInfo) &&\n+ threadInChatList(newThreadInfo)\n) {\nthreadWatcher.removeID(oldThreadInfo.id);\n}\n" }, { "change_type": "MODIFY", "old_path": "native/chat/settings/thread-settings.react.js", "new_path": "native/chat/settings/thread-settings.react.js", "diff": "@@ -40,7 +40,7 @@ import {\nimport {\nthreadHasPermission,\nviewerIsMember,\n- viewerCanSeeThread,\n+ threadInChatList,\n} from 'lib/shared/thread-utils';\nimport threadWatcher from 'lib/shared/thread-watcher';\nimport { connect } from 'lib/utils/redux-utils';\n@@ -261,7 +261,7 @@ class InnerThreadSettings extends React.PureComponent<Props, State> {\ncomponentDidMount() {\nregisterChatScreen(this.props.navigation.state.key, this);\nconst threadInfo = InnerThreadSettings.getThreadInfo(this.props);\n- if (!viewerCanSeeThread(threadInfo)) {\n+ if (!threadInChatList(threadInfo)) {\nthreadWatcher.watchID(threadInfo.id);\n}\n}\n@@ -269,7 +269,7 @@ class InnerThreadSettings extends React.PureComponent<Props, State> {\ncomponentWillUnmount() {\nregisterChatScreen(this.props.navigation.state.key, null);\nconst threadInfo = InnerThreadSettings.getThreadInfo(this.props);\n- if (!viewerCanSeeThread(threadInfo)) {\n+ if (!threadInChatList(threadInfo)) {\nthreadWatcher.removeID(threadInfo.id);\n}\n}\n@@ -279,13 +279,13 @@ class InnerThreadSettings extends React.PureComponent<Props, State> {\nconst newThreadInfo = nextProps.threadInfo;\nif (\n- viewerCanSeeThread(oldThreadInfo) &&\n- !viewerCanSeeThread(newThreadInfo)\n+ threadInChatList(oldThreadInfo) &&\n+ !threadInChatList(newThreadInfo)\n) {\nthreadWatcher.watchID(oldThreadInfo.id);\n} else if (\n- !viewerCanSeeThread(oldThreadInfo) &&\n- viewerCanSeeThread(newThreadInfo)\n+ !threadInChatList(oldThreadInfo) &&\n+ threadInChatList(newThreadInfo)\n) {\nthreadWatcher.removeID(oldThreadInfo.id);\n}\n" }, { "change_type": "MODIFY", "old_path": "web/chat/chat-message-list.react.js", "new_path": "web/chat/chat-message-list.react.js", "diff": "@@ -15,7 +15,7 @@ import invariant from 'invariant';\nimport { connect } from 'lib/utils/redux-utils';\nimport { messageKey } from 'lib/shared/message-utils';\n-import { viewerCanSeeThread } from 'lib/shared/thread-utils';\n+import { threadInChatList } from 'lib/shared/thread-utils';\nimport threadWatcher from 'lib/shared/thread-watcher';\nimport { threadInfoSelector } from 'lib/selectors/thread-selectors';\nimport {\n@@ -71,7 +71,7 @@ class ChatMessageList extends React.PureComponent<Props, State> {\ncomponentDidMount() {\nconst { threadInfo } = this.props;\n- if (!threadInfo || viewerCanSeeThread(threadInfo)) {\n+ if (!threadInfo || threadInChatList(threadInfo)) {\nreturn;\n}\nthreadWatcher.watchID(threadInfo.id);\n@@ -83,7 +83,7 @@ class ChatMessageList extends React.PureComponent<Props, State> {\ncomponentWillUnmount() {\nconst { threadInfo } = this.props;\n- if (!threadInfo || viewerCanSeeThread(threadInfo)) {\n+ if (!threadInfo || threadInChatList(threadInfo)) {\nreturn;\n}\nthreadWatcher.removeID(threadInfo.id);\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
viewerCanSeeThread -> threadInChatList
129,187
22.06.2018 12:59:26
25,200
0c47730c34fa24cc35ce305f12b10c81a477c796
[server] Default fetchMessageInfosSince to messageTruncationStatus.UNCHANGED This fixes a bug where a ping result that doesn't have any updated messages for a "watched" thread would make the client think that the start of that thread had been reached.
[ { "change_type": "MODIFY", "old_path": "server/src/fetchers/message-fetchers.js", "new_path": "server/src/fetchers/message-fetchers.js", "diff": "@@ -421,7 +421,7 @@ async function fetchMessageInfosSince(\nconst threadSelectionClause = threadSelectionCriteriaToSQLClause(criteria);\nconst truncationStatuses = threadSelectionCriteriaToInitialTruncationStatuses(\ncriteria,\n- messageTruncationStatus.EXHAUSTIVE,\n+ messageTruncationStatus.UNCHANGED,\n);\nconst viewerID = viewer.id;\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Default fetchMessageInfosSince to messageTruncationStatus.UNCHANGED This fixes a bug where a ping result that doesn't have any updated messages for a "watched" thread would make the client think that the start of that thread had been reached.
129,187
22.06.2018 13:36:56
25,200
4146e76bf0c1cd0ca3bb5efac08159b9a9adcabd
[server] Update thread-responder to accept CalendarQuery for joinThread
[ { "change_type": "MODIFY", "old_path": "server/src/responders/thread-responders.js", "new_path": "server/src/responders/thread-responders.js", "diff": "@@ -35,6 +35,10 @@ import {\njoinThread,\n} from '../updaters/thread-updaters';\nimport createThread from '../creators/thread-creator';\n+import {\n+ entryQueryInputValidator,\n+ verifyCalendarQueryThreadIDs,\n+} from './entry-responders';\nconst threadDeletionRequestInputValidator = tShape({\nthreadID: t.String,\n@@ -194,6 +198,7 @@ async function threadCreationResponder(\nconst joinThreadRequestInputValidator = tShape({\nthreadID: t.String,\n+ calendarQuery: t.maybe(entryQueryInputValidator),\n});\nasync function threadJoinResponder(\nviewer: Viewer,\n@@ -201,6 +206,11 @@ async function threadJoinResponder(\n): Promise<ThreadJoinResult> {\nconst request: ThreadJoinRequest = input;\nvalidateInput(joinThreadRequestInputValidator, request);\n+\n+ if (request.calendarQuery) {\n+ await verifyCalendarQueryThreadIDs(request.calendarQuery);\n+ }\n+\nreturn await joinThread(viewer, request);\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Update thread-responder to accept CalendarQuery for joinThread
129,187
22.06.2018 13:40:00
25,200
c65a6c78d6fbed32c965e7891383bf56aa1c9884
Separate ClientThreadJoinRequest from ServerThreadJoinRequest
[ { "change_type": "MODIFY", "old_path": "lib/actions/thread-actions.js", "new_path": "lib/actions/thread-actions.js", "diff": "@@ -8,7 +8,7 @@ import type {\nUpdateThreadRequest,\nNewThreadRequest,\nNewThreadResult,\n- ThreadJoinRequest,\n+ ClientThreadJoinRequest,\nThreadJoinPayload,\n} from '../types/thread-types';\nimport type { FetchJSON } from '../utils/fetch-json';\n@@ -133,22 +133,13 @@ const joinThreadActionTypes = Object.freeze({\n});\nasync function joinThread(\nfetchJSON: FetchJSON,\n- request: ThreadJoinRequest,\n+ request: ClientThreadJoinRequest,\n): Promise<ThreadJoinPayload> {\nconst response = await fetchJSON('join_thread', request);\n// https://github.com/facebook/flow/issues/2221\nconst userInfos: any = Object.values(response.userInfos);\n- let calendarResult = null;\n- if (request.calendarQuery) {\n- calendarResult = {\n- calendarQuery: request.calendarQuery,\n- rawEntryInfos: response.rawEntryInfos,\n- userInfos,\n- };\n- }\n-\nreturn {\nthreadID: request.threadID,\nthreadInfos: response.threadInfos,\n@@ -156,7 +147,11 @@ async function joinThread(\nrawMessageInfos: response.rawMessageInfos,\ntruncationStatuses: response.truncationStatuses,\nuserInfos,\n- calendarResult,\n+ calendarResult: {\n+ calendarQuery: request.calendarQuery,\n+ rawEntryInfos: response.rawEntryInfos,\n+ userInfos,\n+ },\n};\n}\n" }, { "change_type": "MODIFY", "old_path": "lib/types/thread-types.js", "new_path": "lib/types/thread-types.js", "diff": "@@ -312,10 +312,14 @@ export type NewThreadResult = {|\nnewMessageInfos: $ReadOnlyArray<RawMessageInfo>,\n|};\n-export type ThreadJoinRequest = {|\n+export type ServerThreadJoinRequest = {|\nthreadID: string,\ncalendarQuery?: ?CalendarQuery,\n|};\n+export type ClientThreadJoinRequest = {|\n+ threadID: string,\n+ calendarQuery: CalendarQuery,\n+|};\nexport type ThreadJoinResult = {|\nthreadInfos: {[id: string]: RawThreadInfo},\nupdatesResult: {\n@@ -335,5 +339,5 @@ export type ThreadJoinPayload = {|\nrawMessageInfos: RawMessageInfo[],\ntruncationStatuses: MessageTruncationStatuses,\nuserInfos: $ReadOnlyArray<UserInfo>,\n- calendarResult?: ?CalendarResult,\n+ calendarResult: CalendarResult,\n|};\n" }, { "change_type": "MODIFY", "old_path": "native/chat/chat-input-bar.react.js", "new_path": "native/chat/chat-input-bar.react.js", "diff": "@@ -14,7 +14,7 @@ import {\ntype ThreadInfo,\nthreadInfoPropType,\nthreadPermissions,\n- type ThreadJoinRequest,\n+ type ClientThreadJoinRequest,\ntype ThreadJoinPayload,\n} from 'lib/types/thread-types';\nimport type { LoadingStatus } from 'lib/types/loading-types';\n@@ -71,7 +71,7 @@ type Props = {\nthreadID: string,\ntext: string,\n) => Promise<SendTextMessageResult>,\n- joinThread: (request: ThreadJoinRequest) => Promise<ThreadJoinPayload>,\n+ joinThread: (request: ClientThreadJoinRequest) => Promise<ThreadJoinPayload>,\n};\ntype State = {\ntext: string,\n" }, { "change_type": "MODIFY", "old_path": "server/src/responders/thread-responders.js", "new_path": "server/src/responders/thread-responders.js", "diff": "@@ -10,7 +10,7 @@ import {\ntype UpdateThreadRequest,\ntype NewThreadRequest,\ntype NewThreadResult,\n- type ThreadJoinRequest,\n+ type ServerThreadJoinRequest,\ntype ThreadJoinResult,\nassertThreadType,\n} from 'lib/types/thread-types';\n@@ -204,7 +204,7 @@ async function threadJoinResponder(\nviewer: Viewer,\ninput: any,\n): Promise<ThreadJoinResult> {\n- const request: ThreadJoinRequest = input;\n+ const request: ServerThreadJoinRequest = input;\nvalidateInput(joinThreadRequestInputValidator, request);\nif (request.calendarQuery) {\n" }, { "change_type": "MODIFY", "old_path": "server/src/updaters/thread-updaters.js", "new_path": "server/src/updaters/thread-updaters.js", "diff": "@@ -7,7 +7,7 @@ import {\ntype LeaveThreadRequest,\ntype LeaveThreadResult,\ntype UpdateThreadRequest,\n- type ThreadJoinRequest,\n+ type ServerThreadJoinRequest,\ntype ThreadJoinResult,\ntype ServerThreadInfo,\nthreadPermissions,\n@@ -531,7 +531,7 @@ async function updateThread(\nasync function joinThread(\nviewer: Viewer,\n- request: ThreadJoinRequest,\n+ request: ServerThreadJoinRequest,\n): Promise<ThreadJoinResult> {\nconst [ isMember, hasPermission ] = await Promise.all([\nviewerIsMember(viewer, request.threadID),\n" }, { "change_type": "MODIFY", "old_path": "web/chat/chat-input-bar.react.js", "new_path": "web/chat/chat-input-bar.react.js", "diff": "@@ -9,7 +9,7 @@ import {\ntype ThreadInfo,\nthreadInfoPropType,\nthreadPermissions,\n- type ThreadJoinRequest,\n+ type ClientThreadJoinRequest,\ntype ThreadJoinPayload,\n} from 'lib/types/thread-types';\nimport {\n@@ -54,7 +54,7 @@ type Props = {|\nthreadID: string,\ntext: string,\n) => Promise<SendTextMessageResult>,\n- joinThread: (request: ThreadJoinRequest) => Promise<ThreadJoinPayload>,\n+ joinThread: (request: ClientThreadJoinRequest) => Promise<ThreadJoinPayload>,\n|};\ntype State = {|\nmessageText: string,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Separate ClientThreadJoinRequest from ServerThreadJoinRequest
129,187
22.06.2018 16:57:05
25,200
a5e5af7c70cc4c0228d37bd65750ec9451c59716
Fix some edge cases regarding MessageTruncationStatus Also simplifies and refactor `message-reducer` a little bit.
[ { "change_type": "MODIFY", "old_path": "lib/reducers/message-reducer.js", "new_path": "lib/reducers/message-reducer.js", "diff": "@@ -11,7 +11,7 @@ import {\ndefaultNumberPerThread,\n} from '../types/message-types';\nimport type { BaseAction } from '../types/redux-types';\n-import type { RawThreadInfo } from '../types/thread-types';\n+import { type RawThreadInfo, threadPermissions } from '../types/thread-types';\nimport { type UpdateInfo, updateTypes } from '../types/update-types';\nimport invariant from 'invariant';\n@@ -29,10 +29,11 @@ import _pickBy from 'lodash/fp/pickBy';\nimport _omitBy from 'lodash/fp/omitBy';\nimport _mapKeys from 'lodash/fp/mapKeys';\nimport _uniq from 'lodash/fp/uniq';\n+import _intersection from 'lodash/fp/intersection';\nimport { messageID, combineTruncationStatuses } from '../shared/message-utils';\nimport { setHighestLocalID } from '../utils/local-ids';\n-import { threadInChatList } from '../shared/thread-utils';\n+import { threadHasPermission, threadInChatList } from '../shared/thread-utils';\nimport { setCookieActionType } from '../utils/action-utils';\nimport {\nlogOutActionTypes,\n@@ -87,6 +88,7 @@ function threadIsWatched(\nwatchedIDs: $ReadOnlyArray<string>,\n) {\nreturn threadInfo &&\n+ threadHasPermission(threadInfo, threadPermissions.VISIBLE) &&\n(threadInChatList(threadInfo) || watchedIDs.includes(threadInfo.id));\n}\n@@ -130,16 +132,12 @@ function freshMessageStore(\n// oldMessageStore is from the old state\n// newMessageInfos, truncationStatus come from server\n-// replaceUnlessUnchanged refers to how we should treat threads that have a\n-// MessageTruncationStatus that isn't unchanged. if it's true, we will\n-// completely replace what's in the store with what came from the server, but if\n-// it's false we will attempt to merge\nfunction mergeNewMessages(\noldMessageStore: MessageStore,\nnewMessageInfos: $ReadOnlyArray<RawMessageInfo>,\ntruncationStatus: {[threadID: string]: MessageTruncationStatus},\n- threadInfos: ?{[threadID: string]: RawThreadInfo},\n- replaceUnlessUnchanged: bool,\n+ threadInfos: {[threadID: string]: RawThreadInfo},\n+ actionType: *,\n): MessageStore {\nconst orderedNewMessageInfos = _flow(\n_map((messageInfo: RawMessageInfo) => {\n@@ -183,12 +181,22 @@ function mergeNewMessages(\nconst threads = _flow(\n_pickBy(\n(messageIDs: string[], threadID: string) =>\n- !threadInfos || threadIsWatched(threadInfos[threadID], watchedIDs),\n+ threadIsWatched(threadInfos[threadID], watchedIDs),\n),\n_mapValuesWithKeys((messageIDs: string[], threadID: string) => {\nconst oldThread = oldMessageStore.threads[threadID];\nconst truncate = truncationStatus[threadID];\nif (!oldThread) {\n+ if (actionType === fetchMessagesBeforeCursorActionTypes.success) {\n+ // Well, this is weird. Somehow fetchMessagesBeforeCursor got called\n+ // for a thread that doesn't exist in the messageStore. How did this\n+ // happen? How do we even know what cursor to use if we didn't have\n+ // any messages? Anyways, the messageStore is predicated on the\n+ // principle that it is current. We can't create a ThreadMessageInfo\n+ // for a thread if we can't guarantee this, as the client has no UX\n+ // for endReached, only for startReached. We'll have to bail out here.\n+ return null;\n+ }\nreturn {\nmessageIDs,\nstartReached: truncate === messageTruncationStatus.EXHAUSTIVE,\n@@ -196,50 +204,63 @@ function mergeNewMessages(\nlastPruned,\n};\n}\n- const expectedTruncationStatus = oldThread.startReached\n- ? messageTruncationStatus.EXHAUSTIVE\n- : messageTruncationStatus.TRUNCATED;\n- if (\n- _isEqual(messageIDs)(oldThread.messageIDs) &&\n- (truncate === messageTruncationStatus.UNCHANGED ||\n- truncate === expectedTruncationStatus)\n- ) {\n+ if (!isContiguous(truncate, oldThread.messageIDs, 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+ // messageStore: currentness and contiguousness.\n+ return {\n+ messageIDs,\n+ startReached: false,\n+ lastNavigatedTo: oldThread.lastNavigatedTo,\n+ lastPruned: oldThread.lastPruned,\n+ };\n+ }\n+ const startReached = oldThread.startReached ||\n+ truncate === 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) {\nreturn oldThread;\n}\n- let mergedMessageIDs = messageIDs;\n- if (\n- !replaceUnlessUnchanged ||\n- truncate === messageTruncationStatus.UNCHANGED\n- ) {\n+ return {\n+ messageIDs: oldThread.messageIDs,\n+ startReached,\n+ lastNavigatedTo: oldThread.lastNavigatedTo,\n+ lastPruned: oldThread.lastPruned,\n+ };\n+ }\nconst oldNotInNew = _difference(oldThread.messageIDs)(messageIDs);\nfor (let messageID of oldNotInNew) {\noldMessageInfosToCombine.push(oldMessageStore.messages[messageID]);\n}\n- mergedMessageIDs = [ ...messageIDs, ...oldNotInNew ];\n+ const mergedMessageIDs = [ ...messageIDs, ...oldNotInNew ];\nmustResortThreadMessageIDs.push(threadID);\n- }\nreturn {\nmessageIDs: mergedMessageIDs,\n- startReached: truncate === messageTruncationStatus.EXHAUSTIVE ||\n- (truncate === messageTruncationStatus.UNCHANGED &&\n- oldThread.startReached),\n+ startReached,\nlastNavigatedTo: oldThread.lastNavigatedTo,\nlastPruned: oldThread.lastPruned,\n};\n}),\n+ _pickBy(thread => !!thread),\n)(threadsToMessageIDs);\nfor (let threadID in oldMessageStore.threads) {\nif (\nthreads[threadID] ||\n- (threadInfos && !threadIsWatched(threadInfos[threadID], watchedIDs))\n+ !threadIsWatched(threadInfos[threadID], watchedIDs)\n) {\ncontinue;\n}\n- const thread = oldMessageStore.threads[threadID];\n+ let thread = oldMessageStore.threads[threadID];\nconst truncate = truncationStatus[threadID];\nif (truncate === messageTruncationStatus.EXHAUSTIVE) {\n- thread.startReached = true;\n+ thread = {\n+ ...thread,\n+ startReached: true,\n+ };\n}\nthreads[threadID] = thread;\nfor (let messageID of thread.messageIDs) {\n@@ -278,6 +299,20 @@ function mergeNewMessages(\nreturn { messages, threads, currentAsOf: oldMessageStore.currentAsOf };\n}\n+function isContiguous(\n+ truncate: MessageTruncationStatus,\n+ oldMessageIDs: string[],\n+ newMessageIDs: string[],\n+): bool {\n+ if (truncate !== messageTruncationStatus.TRUNCATED) {\n+ return true;\n+ }\n+ if (_intersection(oldMessageIDs)(newMessageIDs).length > 0) {\n+ return true;\n+ }\n+ return false;\n+}\n+\nfunction filterByNewThreadInfos(\nmessageStore: MessageStore,\nthreadInfos: {[id: string]: RawThreadInfo},\n@@ -331,7 +366,7 @@ function reduceMessageStore(\nmessagesResult.messageInfos,\nmessagesResult.truncationStatus,\nnewThreadInfos,\n- true,\n+ action.type,\n);\nconst oldWatchedIDs = action.payload.messagesResult.watchedIDsAtRequestTime;\nconst currentWatchedIDs = threadWatcher.getWatchedIDs();\n@@ -356,8 +391,8 @@ function reduceMessageStore(\nmessageStore,\naction.payload.rawMessageInfos,\n{ [action.payload.threadID]: action.payload.truncationStatus },\n- null,\n- false,\n+ newThreadInfos,\n+ action.type,\n);\n} else if (\naction.type === logOutActionTypes.success ||\n@@ -380,8 +415,8 @@ function reduceMessageStore(\nmessageStore,\naction.payload.newMessageInfos,\ntruncationStatuses,\n- null,\n- false,\n+ newThreadInfos,\n+ action.type,\n);\n} else if (action.type === registerActionTypes.success) {\nconst truncationStatuses = {};\n@@ -393,8 +428,8 @@ function reduceMessageStore(\nmessageStore,\naction.payload.rawMessageInfos,\ntruncationStatuses,\n- null,\n- false,\n+ newThreadInfos,\n+ action.type,\n);\n} else if (\naction.type === changeThreadSettingsActionTypes.success ||\n@@ -405,8 +440,8 @@ function reduceMessageStore(\nmessageStore,\naction.payload.newMessageInfos,\n{ [action.payload.threadInfo.id]: messageTruncationStatus.UNCHANGED },\n- null,\n- false,\n+ newThreadInfos,\n+ action.type,\n);\n} else if (\naction.type === createEntryActionTypes.success ||\n@@ -416,8 +451,8 @@ function reduceMessageStore(\nmessageStore,\naction.payload.newMessageInfos,\n{ [action.payload.threadID]: messageTruncationStatus.UNCHANGED },\n- null,\n- false,\n+ newThreadInfos,\n+ action.type,\n);\n} else if (action.type === deleteEntryActionTypes.success) {\nconst payload = action.payload;\n@@ -426,8 +461,8 @@ function reduceMessageStore(\nmessageStore,\npayload.newMessageInfos,\n{ [payload.threadID]: messageTruncationStatus.UNCHANGED },\n- null,\n- false,\n+ newThreadInfos,\n+ action.type,\n);\n}\n} else if (action.type === restoreEntryActionTypes.success) {\n@@ -436,8 +471,8 @@ function reduceMessageStore(\nmessageStore,\naction.payload.newMessageInfos,\n{ [threadID]: messageTruncationStatus.UNCHANGED },\n- null,\n- false,\n+ newThreadInfos,\n+ action.type,\n);\n} else if (action.type === joinThreadActionTypes.success) {\nreturn mergeNewMessages(\n@@ -445,7 +480,7 @@ function reduceMessageStore(\naction.payload.rawMessageInfos,\naction.payload.truncationStatuses,\nnewThreadInfos,\n- true,\n+ action.type,\n);\n} else if (action.type === sendMessageActionTypes.started) {\nconst payload = action.payload;\n@@ -592,8 +627,8 @@ function reduceMessageStore(\nmessageStore,\naction.payload.rawMessageInfos,\ntruncationStatuses,\n- null,\n- false,\n+ newThreadInfos,\n+ action.type,\n);\n}\nreturn messageStore;\n" }, { "change_type": "MODIFY", "old_path": "lib/types/message-types.js", "new_path": "lib/types/message-types.js", "diff": "@@ -471,9 +471,32 @@ export type MessageStore = {|\n|};\nexport const messageTruncationStatus = Object.freeze({\n+ // EXHAUSTIVE means we've reached the start of the thread. Either the result\n+ // set includes the very first message for that thread, or there is nothing\n+ // behind the cursor you queried for. Given that the client only ever issues\n+ // ranged queries whose range, when unioned with what is in state, represent\n+ // the set of all messages for a given thread, we can guarantee that getting\n+ // EXHAUSTIVE means the start has been reached.\n+ EXHAUSTIVE: \"exhaustive\",\n+ // TRUNCATED is rare, and means that the server can't guarantee that the\n+ // result set for a given thread is contiguous with what the client has in its\n+ // state. If the client can't verify the contiguousness itself, it needs to\n+ // replace its Redux store's contents with what it is in this payload.\n+ // 1) getMessageInfosSince: Sesult set for thread is equal to max, and the\n+ // truncation status isn't EXHAUSTIVE (ie. doesn't include the very first\n+ // message).\n+ // 2) getMessageInfos: ThreadSelectionCriteria does not specify cursors, the\n+ // result set for thread is equal to max, and the truncation status isn't\n+ // EXHAUSTIVE. If cursors are specified, we never return truncated, since\n+ // the cursor given us guarantees the contiguousness of the result set.\n+ // Note that in the reducer, we can guarantee contiguousness if there is any\n+ // intersection between messageIDs in the result set and the set currently in\n+ // the Redux store.\nTRUNCATED: \"truncated\",\n+ // UNCHANGED means the result set is guaranteed to be contiguous with what the\n+ // client has in its state, but is not EXHAUSTIVE. Basically, it's anything\n+ // that isn't either EXHAUSTIVE or TRUNCATED.\nUNCHANGED: \"unchanged\",\n- EXHAUSTIVE: \"exhaustive\",\n});\nexport type MessageTruncationStatus = $Values<typeof messageTruncationStatus>;\nexport function assertMessageTruncationStatus(\n" }, { "change_type": "MODIFY", "old_path": "server/src/fetchers/message-fetchers.js", "new_path": "server/src/fetchers/message-fetchers.js", "diff": "@@ -281,10 +281,7 @@ async function fetchMessageInfos(\nnumberPerThread: number,\n): Promise<FetchMessageInfosResult> {\nconst threadSelectionClause = threadSelectionCriteriaToSQLClause(criteria);\n- const truncationStatuses = threadSelectionCriteriaToInitialTruncationStatuses(\n- criteria,\n- messageTruncationStatus.EXHAUSTIVE,\n- );\n+ const truncationStatuses = {};\nconst viewerID = viewer.id;\nconst visibleExtractString = `$.${threadPermissions.VISIBLE}.value`;\n@@ -335,11 +332,40 @@ async function fetchMessageInfos(\n}\nfor (let [ threadID, messageCount ] of threadToMessageCount) {\n+ // If there are fewer messages returned than the max for a given thread,\n+ // then our result set includes all messages in the query range for that\n+ // thread\ntruncationStatuses[threadID] = messageCount < numberPerThread\n? messageTruncationStatus.EXHAUSTIVE\n: messageTruncationStatus.TRUNCATED;\n}\n+ for (let rawMessageInfo of rawMessageInfos) {\n+ if (rawMessageInfo.type === messageTypes.CREATE_THREAD) {\n+ // If a CREATE_THREAD message for a given thread is in the result set,\n+ // then our result set includes all messages in the query range for that\n+ // thread\n+ truncationStatuses[rawMessageInfo.threadID] =\n+ messageTruncationStatus.EXHAUSTIVE;\n+ }\n+ }\n+\n+ for (let threadID in criteria.threadCursors) {\n+ const cursor = criteria.threadCursors[threadID];\n+ const truncationStatus = truncationStatuses[threadID];\n+ if (truncationStatus === null || truncationStatus === undefined) {\n+ // If nothing was returned for a thread that was explicitly queried for,\n+ // then our result set includes all messages in the query range for that\n+ // thread\n+ truncationStatuses[threadID] = messageTruncationStatus.EXHAUSTIVE;\n+ } else if (truncationStatus === messageTruncationStatus.TRUNCATED) {\n+ // If a cursor was specified for a given thread, then the result is\n+ // guaranteed to be contiguous with what the client has, and as such the\n+ // result should never be TRUNCATED\n+ truncationStatuses[threadID] = messageTruncationStatus.UNCHANGED;\n+ }\n+ }\n+\nconst allUserInfos = await fetchAllUsers(rawMessageInfos, userInfos);\nreturn {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Fix some edge cases regarding MessageTruncationStatus Also simplifies and refactor `message-reducer` a little bit.
129,187
22.06.2018 18:35:26
25,200
09fdd83b08a0a61f6bf96e6e6dc37f64f3db4362
[lib] Other reducers filter when ThreadInfo are removed from the Redux store Update other reducers (and related selector updates) for handling situations where a `RawThreadInfo` is removed from the store, and other related objects need to be removed as well.
[ { "change_type": "MODIFY", "old_path": "lib/reducers/calendar-filters-reducer.js", "new_path": "lib/reducers/calendar-filters-reducer.js", "diff": "@@ -18,18 +18,13 @@ import {\nresetPasswordActionTypes,\nregisterActionTypes,\n} from '../actions/user-actions';\n+import { setCookieActionType } from '../utils/action-utils';\nimport {\nfilteredThreadIDs,\nnonThreadCalendarFilters,\nnonExcludeDeletedCalendarFilters,\n} from '../selectors/calendar-filter-selectors';\n-import {\n- joinThreadActionTypes,\n- deleteThreadActionTypes,\n- leaveThreadActionTypes,\n- newThreadActionTypes,\n-} from '../actions/thread-actions';\n-import { viewerIsMember } from '../shared/thread-utils';\n+import { threadInFilterList } from '../shared/thread-utils';\nexport default function reduceCalendarFilters(\nstate: $ReadOnlyArray<CalendarFilter>,\n@@ -42,14 +37,21 @@ export default function reduceCalendarFilters(\naction.type === deleteAccountActionTypes.success ||\naction.type === logInActionTypes.success ||\naction.type === registerActionTypes.success ||\n- action.type === resetPasswordActionTypes.success\n+ action.type === resetPasswordActionTypes.success ||\n+ (action.type === setCookieActionType &&\n+ action.payload.cookieInvalidated)\n) {\nreturn defaultCalendarFilters;\n} else if (action.type === updateCalendarThreadFilter) {\nconst nonThreadFilters = nonThreadCalendarFilters(state);\nreturn [\n...nonThreadFilters,\n- action.payload,\n+ {\n+ type: calendarThreadFilterTypes.THREAD_LIST,\n+ threadIDs: action.payload.threadIDs.filter(\n+ threadID => threadInFilterList(newThreadInfos[threadID]),\n+ ),\n+ },\n];\n} else if (action.type === clearCalendarThreadFilter) {\nreturn nonThreadCalendarFilters(state);\n@@ -76,17 +78,20 @@ export default function reduceCalendarFilters(\n// - pingActionTypes.success\n// - deleteThreadActionTypes.success\n// - leaveThreadActionTypes.success\n+ // - changeThreadMemberRolesActionTypes.success\n+ // - changeThreadSettingsActionTypes.success\n+ // - removeUsersFromThreadActionTypes.success\nconst currentlyFilteredIDs = filteredThreadIDs(state);\nif (!currentlyFilteredIDs) {\nreturn state;\n}\nconst validCurrentFilteredIDs = [...currentlyFilteredIDs].filter(\n- threadID => !!newThreadInfos[threadID],\n+ threadID => threadInFilterList(newThreadInfos[threadID]),\n);\nconst joinedThreadIDs = [];\nfor (let threadID in newThreadInfos) {\nconst newThreadInfo = newThreadInfos[threadID];\n- if (!oldThreadInfos[threadID] && viewerIsMember(newThreadInfo)) {\n+ if (!oldThreadInfos[threadID] && threadInFilterList(newThreadInfo)) {\njoinedThreadIDs.push(threadID);\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/entry-reducer.js", "new_path": "lib/reducers/entry-reducer.js", "diff": "@@ -7,7 +7,7 @@ import type {\nCalendarQuery,\nCalendarResult,\n} from '../types/entry-types';\n-import { threadPermissions, type RawThreadInfo } from '../types/thread-types';\n+import { type RawThreadInfo } from '../types/thread-types';\nimport { updateTypes, type UpdateInfo } from '../types/update-types';\nimport _flow from 'lodash/fp/flow';\n@@ -50,6 +50,9 @@ import {\ndeleteThreadActionTypes,\nleaveThreadActionTypes,\njoinThreadActionTypes,\n+ changeThreadSettingsActionTypes,\n+ removeUsersFromThreadActionTypes,\n+ changeThreadMemberRolesActionTypes,\n} from '../actions/thread-actions';\nimport { pingActionTypes } from '../actions/ping-actions';\nimport { rehydrateActionType } from '../types/redux-types';\n@@ -57,6 +60,7 @@ import {\nentryID,\nrawEntryInfoWithinCalendarQuery,\n} from '../shared/entry-utils';\n+import { threadInFilterList } from '../shared/thread-utils';\nfunction daysToEntriesFromEntryInfos(entryInfos: $ReadOnlyArray<RawEntryInfo>) {\nreturn _flow(\n@@ -85,10 +89,10 @@ function mergeNewEntryInfos(\ncurrentEntryInfos: {[id: string]: RawEntryInfo},\noldDaysToEntries: {[id: string]: string[]},\nnewEntryInfos: $ReadOnlyArray<RawEntryInfo>,\n+ threadInfos: {[id: string]: RawThreadInfo},\npingInfo?: {|\nprevEntryInfos: {[id: string]: RawEntryInfo},\ncalendarQuery: CalendarQuery,\n- threadInfos: {[id: string]: RawThreadInfo},\n|},\n) {\nconst mergedEntryInfos = {};\n@@ -178,9 +182,15 @@ function mergeNewEntryInfos(\nmergedEntryInfos[id] = currentEntryInfo;\n}\n- const addedDaysToEntries =\n- daysToEntriesFromEntryInfos(_values(mergedEntryInfos));\n- return [mergedEntryInfos, addedDaysToEntries];\n+ for (let entryID in mergedEntryInfos) {\n+ const entryInfo = mergedEntryInfos[entryID];\n+ if (!threadInFilterList(threadInfos[entryInfo.threadID])) {\n+ delete mergedEntryInfos[entryID];\n+ }\n+ }\n+\n+ const daysToEntries = daysToEntriesFromEntryInfos(_values(mergedEntryInfos));\n+ return [mergedEntryInfos, daysToEntries];\n}\nfunction reduceEntryInfos(\n@@ -188,21 +198,24 @@ function reduceEntryInfos(\naction: BaseAction,\nnewThreadInfos: {[id: string]: RawThreadInfo},\n): EntryStore {\n- const entryInfos = entryStore.entryInfos;\n- const daysToEntries = entryStore.daysToEntries;\n- const lastUserInteractionCalendar = entryStore.lastUserInteractionCalendar;\n+ const { entryInfos, daysToEntries, lastUserInteractionCalendar } = entryStore;\nif (\naction.type === logOutActionTypes.success ||\naction.type === deleteAccountActionTypes.success ||\naction.type === deleteThreadActionTypes.success ||\naction.type === leaveThreadActionTypes.success\n) {\n- const authorizedThreadInfos = _pickBy(\n- `currentUser.permissions.${threadPermissions.VISIBLE}`,\n- )(newThreadInfos);\n+ const authorizedThreadInfos = _pickBy(threadInFilterList)(newThreadInfos);\nconst newEntryInfos = _pickBy(\n(entry: RawEntryInfo) => authorizedThreadInfos[entry.threadID],\n)(entryInfos);\n+ if (Object.keys(newEntryInfos).length === Object.keys(entryInfos).length) {\n+ return {\n+ entryInfos,\n+ daysToEntries,\n+ lastUserInteractionCalendar: 0,\n+ };\n+ }\nconst newDaysToEntries = filterExistingDaysToEntriesWithNewEntryInfos(\ndaysToEntries,\nnewEntryInfos,\n@@ -213,9 +226,7 @@ function reduceEntryInfos(\nlastUserInteractionCalendar: 0,\n};\n} else if (action.type === setCookieActionType) {\n- const authorizedThreadInfos = _pickBy(\n- `currentUser.permissions.${threadPermissions.VISIBLE}`,\n- )(newThreadInfos);\n+ const authorizedThreadInfos = _pickBy(threadInFilterList)(newThreadInfos);\nconst newEntryInfos = _pickBy(\n(entry: RawEntryInfo) => authorizedThreadInfos[entry.threadID],\n)(entryInfos);\n@@ -226,6 +237,13 @@ function reduceEntryInfos(\nconst newLastUserInteractionCalendar = action.payload.cookieInvalidated\n? 0\n: lastUserInteractionCalendar;\n+ if (Object.keys(newEntryInfos).length === Object.keys(entryInfos).length) {\n+ return {\n+ entryInfos,\n+ daysToEntries,\n+ lastUserInteractionCalendar: newLastUserInteractionCalendar,\n+ };\n+ }\nreturn {\nentryInfos: newEntryInfos,\ndaysToEntries: newDaysToEntries,\n@@ -239,6 +257,7 @@ function reduceEntryInfos(\nentryInfos,\ndaysToEntries,\naction.payload.rawEntryInfos,\n+ newThreadInfos,\n);\nreturn {\nentryInfos: updatedEntryInfos,\n@@ -250,6 +269,7 @@ function reduceEntryInfos(\nentryInfos,\ndaysToEntries,\naction.payload.rawEntryInfos,\n+ newThreadInfos,\n);\nreturn {\nentryInfos: updatedEntryInfos,\n@@ -322,7 +342,10 @@ function reduceEntryInfos(\n};\n} else if (action.type === saveEntryActionTypes.success) {\nconst serverID = action.payload.entryID;\n- if (!entryInfos[serverID]) {\n+ if (\n+ !entryInfos[serverID] ||\n+ !threadInFilterList(newThreadInfos[entryInfos[serverID].threadID])\n+ ) {\n// This happens if the entry is deauthorized before it's saved\nreturn entryStore;\n}\n@@ -340,7 +363,10 @@ function reduceEntryInfos(\n};\n} else if (action.type === concurrentModificationResetActionType) {\nconst payload = action.payload;\n- if (!entryInfos[payload.id]) {\n+ if (\n+ !entryInfos[payload.id] ||\n+ !threadInFilterList(newThreadInfos[entryInfos[payload.id].threadID])\n+ ) {\n// This happens if the entry is deauthorized before it's restored\nreturn entryStore;\n}\n@@ -375,11 +401,19 @@ function reduceEntryInfos(\nlastUserInteractionCalendar: Date.now(),\n};\n} else if (action.type === fetchRevisionsForEntryActionTypes.success) {\n+ const id = action.payload.entryID;\n+ if (\n+ !entryInfos[id] ||\n+ !threadInFilterList(newThreadInfos[entryInfos[id].threadID])\n+ ) {\n+ // This happens if the entry is deauthorized before it's restored\n+ return entryStore;\n+ }\n// Make sure the entry is in sync with its latest revision\nconst newEntryInfos = {\n...entryInfos,\n- [action.payload.entryID]: {\n- ...entryInfos[action.payload.entryID],\n+ [id]: {\n+ ...entryInfos[id],\ntext: action.payload.text,\ndeleted: action.payload.deleted,\n},\n@@ -412,6 +446,7 @@ function reduceEntryInfos(\nentryInfos,\ndaysToEntries,\ncalendarResult.rawEntryInfos,\n+ newThreadInfos,\n);\nreturn {\nentryInfos: updatedEntryInfos,\n@@ -432,10 +467,10 @@ function reduceEntryInfos(\nentryInfos,\ndaysToEntries,\nrawEntryInfos,\n+ newThreadInfos,\n{\nprevEntryInfos: action.payload.prevState.entryInfos,\ncalendarQuery: action.payload.calendarResult.calendarQuery,\n- threadInfos: newThreadInfos,\n},\n);\nreturn {\n@@ -443,6 +478,27 @@ function reduceEntryInfos(\ndaysToEntries: updatedDaysToEntries,\nlastUserInteractionCalendar,\n};\n+ } else if (\n+ action.type === changeThreadSettingsActionTypes.success ||\n+ action.type === removeUsersFromThreadActionTypes.success ||\n+ action.type === changeThreadMemberRolesActionTypes.success\n+ ) {\n+ const authorizedThreadInfos = _pickBy(threadInFilterList)(newThreadInfos);\n+ const newEntryInfos = _pickBy(\n+ (entry: RawEntryInfo) => authorizedThreadInfos[entry.threadID],\n+ )(entryInfos);\n+ if (Object.keys(newEntryInfos).length === Object.keys(entryInfos).length) {\n+ return entryStore;\n+ }\n+ const newDaysToEntries = filterExistingDaysToEntriesWithNewEntryInfos(\n+ daysToEntries,\n+ newEntryInfos,\n+ );\n+ return {\n+ entryInfos: newEntryInfos,\n+ daysToEntries: newDaysToEntries,\n+ lastUserInteractionCalendar,\n+ };\n} else if (action.type === rehydrateActionType) {\nif (!action.payload || !action.payload.entryStore) {\nreturn entryStore;\n" }, { "change_type": "MODIFY", "old_path": "lib/selectors/calendar-selectors.js", "new_path": "lib/selectors/calendar-selectors.js", "diff": "@@ -10,7 +10,7 @@ import { createSelector } from 'reselect';\nimport { threadInfoSelector } from './thread-selectors';\nimport { currentCalendarQuery } from './nav-selectors';\nimport { rawEntryInfoWithinActiveRange } from '../shared/entry-utils';\n-import { viewerIsMember } from '../shared/thread-utils';\n+import { threadInFilterList } from '../shared/thread-utils';\nimport SearchIndex from '../shared/search-index';\nconst filterThreadInfos = createSelector(\n@@ -31,7 +31,7 @@ const filterThreadInfos = createSelector(\n}\nconst threadID = rawEntryInfo.threadID;\nconst threadInfo = threadInfos[rawEntryInfo.threadID];\n- if (!threadInfo || !viewerIsMember(threadInfo)) {\n+ if (!threadInFilterList(threadInfo)) {\ncontinue;\n}\nif (result[threadID]) {\n@@ -45,7 +45,7 @@ const filterThreadInfos = createSelector(\n}\nfor (let threadID in threadInfos) {\nconst threadInfo = threadInfos[threadID];\n- if (!result[threadID] && viewerIsMember(threadInfo)) {\n+ if (!result[threadID] && threadInFilterList(threadInfo)) {\nresult[threadID] = {\nthreadInfo,\nnumVisibleEntries: 0,\n" }, { "change_type": "MODIFY", "old_path": "lib/selectors/thread-selectors.js", "new_path": "lib/selectors/thread-selectors.js", "diff": "@@ -28,6 +28,7 @@ import { dateString, dateFromString } from '../utils/date-utils';\nimport { createEntryInfo } from '../shared/entry-utils';\nimport {\nviewerIsMember,\n+ threadInFilterList,\nthreadInfoFromRawThreadInfo,\nthreadHasPermission,\n} from '../shared/thread-utils';\n@@ -58,13 +59,14 @@ const threadInfoSelector: ThreadInfoSelectorType = createSelector(\nrawThreadInfosToThreadInfos,\n);\n-const memberThreadInfos = createSelector(\n+\n+const canBeOnScreenThreadInfos = createSelector(\nthreadInfoSelector,\n(threadInfos: {[id: string]: ThreadInfo}) => {\nconst result = [];\nfor (let threadID in threadInfos) {\nconst threadInfo = threadInfos[threadID];\n- if (!viewerIsMember(threadInfo)) {\n+ if (!threadInFilterList(threadInfo)) {\ncontinue;\n}\nresult.push(threadInfo);\n@@ -75,7 +77,7 @@ const memberThreadInfos = createSelector(\nconst onScreenThreadInfos = createSelector(\nfilteredThreadIDsSelector,\n- memberThreadInfos,\n+ canBeOnScreenThreadInfos,\n(\ninputThreadIDs: ?Set<string>,\nthreadInfos: ThreadInfo[],\n@@ -238,7 +240,6 @@ const mostRecentReadThreadSelector = createSelector(\nexport {\nrawThreadInfosToThreadInfos,\nthreadInfoSelector,\n- memberThreadInfos,\nonScreenThreadInfos,\nonScreenEntryEditableThreadInfos,\ncurrentDaysToEntries,\n" }, { "change_type": "MODIFY", "old_path": "lib/shared/thread-utils.js", "new_path": "lib/shared/thread-utils.js", "diff": "@@ -57,6 +57,10 @@ function threadInChatList(threadInfo: ?(ThreadInfo | RawThreadInfo)) {\nthreadHasPermission(threadInfo, threadPermissions.VISIBLE);\n}\n+function threadInFilterList(threadInfo: ?(ThreadInfo | RawThreadInfo)) {\n+ return threadInChatList(threadInfo);\n+}\n+\nfunction userIsMember(\nthreadInfo: ?(ThreadInfo | RawThreadInfo),\nuserID: string,\n@@ -246,6 +250,7 @@ export {\nthreadHasPermission,\nviewerIsMember,\nthreadInChatList,\n+ threadInFilterList,\nuserIsMember,\nthreadActualMembers,\nthreadIsPersonalChat,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[lib] Other reducers filter when ThreadInfo are removed from the Redux store Update other reducers (and related selector updates) for handling situations where a `RawThreadInfo` is removed from the store, and other related objects need to be removed as well.
129,187
22.06.2018 18:43:02
25,200
1b3e6d0c17d34fa656f4e357bfaf0509e56102f0
Only include threadInChatList threads in notif badge count
[ { "change_type": "MODIFY", "old_path": "lib/selectors/thread-selectors.js", "new_path": "lib/selectors/thread-selectors.js", "diff": "@@ -27,7 +27,7 @@ const _mapValuesWithKeys = _mapValues.convert({ cap: false });\nimport { dateString, dateFromString } from '../utils/date-utils';\nimport { createEntryInfo } from '../shared/entry-utils';\nimport {\n- viewerIsMember,\n+ threadInChatList,\nthreadInFilterList,\nthreadInfoFromRawThreadInfo,\nthreadHasPermission,\n@@ -172,7 +172,7 @@ const childThreadInfos = createSelector(\nconst unreadCount = createSelector(\n(state: BaseAppState<*>) => state.threadInfos,\n(threadInfos: {[id: string]: RawThreadInfo}): number => _flow(\n- _filter(viewerIsMember),\n+ _filter(threadInChatList),\n_filter('currentUser.unread'),\n_size,\n)(threadInfos),\n" }, { "change_type": "MODIFY", "old_path": "server/src/push/utils.js", "new_path": "server/src/push/utils.js", "diff": "// @flow\n+import { threadPermissions } from 'lib/types/thread-types';\n+\nimport apn from 'apn';\nimport fcmAdmin from 'firebase-admin';\n@@ -134,10 +136,12 @@ async function fcmSinglePush(\nasync function getUnreadCounts(\nuserIDs: string[],\n): Promise<{ [userID: string]: number }> {\n+ const visPermissionExtractString = `$.${threadPermissions.VISIBLE}.value`;\nconst query = SQL`\nSELECT user, COUNT(thread) AS unread_count\nFROM memberships\nWHERE user IN (${userIDs}) AND unread = 1 AND role != 0\n+ AND JSON_EXTRACT(permissions, ${visPermissionExtractString})\nGROUP BY user\n`;\nconst [ result ] = await dbQuery(query);\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Only include threadInChatList threads in notif badge count
129,187
23.06.2018 15:23:15
25,200
e909bcd4a56c210fb031426b7a29c3964de15822
Dedup MessageInfos/EntryInfos for main payload vs. UpdateInfos When parsing an action payload to get the full list of `MessageInfo`s/`EntryInfo`s to merge, make sure to dedup the ones we get from `UpdateInfo`s from the ones we get from the main payload.
[ { "change_type": "MODIFY", "old_path": "lib/reducers/entry-reducer.js", "new_path": "lib/reducers/entry-reducer.js", "diff": "@@ -527,10 +527,18 @@ function mergeUpdateEntryInfos(\nentryInfos: $ReadOnlyArray<RawEntryInfo>,\nnewUpdates: $ReadOnlyArray<UpdateInfo>,\n): RawEntryInfo[] {\n+ const entryIDs = new Set(entryInfos.map(entryInfo => entryInfo.id));\nconst mergedEntryInfos = [...entryInfos];\nfor (let updateInfo of newUpdates) {\n- if (updateInfo.type === updateTypes.JOIN_THREAD) {\n- mergedEntryInfos.push(...updateInfo.rawEntryInfos);\n+ if (updateInfo.type !== updateTypes.JOIN_THREAD) {\n+ continue;\n+ }\n+ for (let entryInfo of updateInfo.rawEntryInfos) {\n+ if (entryIDs.has(entryInfo.id)) {\n+ continue;\n+ }\n+ mergedEntryInfos.push(entryInfo);\n+ entryIDs.add(entryInfo.id);\n}\n}\nreturn mergedEntryInfos;\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/message-reducer.js", "new_path": "lib/reducers/message-reducer.js", "diff": "@@ -638,18 +638,28 @@ function mergeUpdatesIntoMessagesResult(\nmessagesResult: GenericMessagesResult,\nnewUpdates: $ReadOnlyArray<UpdateInfo>,\n): GenericMessagesResult {\n+ const messageIDs = new Set(messagesResult.messageInfos.map(\n+ messageInfo => messageInfo.id,\n+ ));\nconst mergedMessageInfos = [...messagesResult.messageInfos];\nconst mergedTruncationStatuses = {...messagesResult.truncationStatus};\nfor (let updateInfo of newUpdates) {\n- if (updateInfo.type === updateTypes.JOIN_THREAD) {\n- mergedMessageInfos.push(...updateInfo.rawMessageInfos);\n+ if (updateInfo.type !== updateTypes.JOIN_THREAD) {\n+ continue;\n+ }\n+ for (let messageInfo of updateInfo.rawMessageInfos) {\n+ if (messageIDs.has(messageInfo.id)) {\n+ continue;\n+ }\n+ mergedMessageInfos.push(messageInfo);\n+ messageIDs.add(messageInfo.id);\n+ }\nmergedTruncationStatuses[updateInfo.threadInfo.id] =\ncombineTruncationStatuses(\n- mergedTruncationStatuses[updateInfo.threadInfo.id],\nupdateInfo.truncationStatus,\n+ mergedTruncationStatuses[updateInfo.threadInfo.id],\n);\n}\n- }\nreturn {\n...messagesResult,\nmessageInfos: mergedMessageInfos,\n" }, { "change_type": "MODIFY", "old_path": "lib/shared/message-utils.js", "new_path": "lib/shared/message-utils.js", "diff": "@@ -586,14 +586,17 @@ function usersInMessageInfos(\nfunction combineTruncationStatuses(\nfirst: MessageTruncationStatus,\n- second: MessageTruncationStatus,\n+ second: ?MessageTruncationStatus,\n): MessageTruncationStatus {\nif (\nfirst === messageTruncationStatus.EXHAUSTIVE ||\nsecond === messageTruncationStatus.EXHAUSTIVE\n) {\n- return first;\n- } else if (first === messageTruncationStatus.UNCHANGED) {\n+ return messageTruncationStatus.EXHAUSTIVE;\n+ } else if (\n+ first === messageTruncationStatus.UNCHANGED &&\n+ second !== null && second !== undefined\n+ ) {\nreturn second;\n} else {\nreturn first;\n" }, { "change_type": "MODIFY", "old_path": "server/src/updaters/activity-updaters.js", "new_path": "server/src/updaters/activity-updaters.js", "diff": "@@ -134,7 +134,7 @@ async function updateFocusedRows(\n}\nawait dbQuery(SQL`\nDELETE FROM focused\n- WHERE user = ${localViewer.userID} AND cookie = ${localViewer.cookieID}\n+ WHERE user = ${viewer.userID} AND cookie = ${viewer.cookieID}\nAND time < ${time}\n`);\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Dedup MessageInfos/EntryInfos for main payload vs. UpdateInfos When parsing an action payload to get the full list of `MessageInfo`s/`EntryInfo`s to merge, make sure to dedup the ones we get from `UpdateInfo`s from the ones we get from the main payload.
129,187
23.06.2018 18:29:01
25,200
99e53948d7d4e445690a3d3521bda7041775fdfe
[server] Refine createUpdates to avoid unnecessary updates Filter them out before they even get created. Also refines the deletion of existing updates due to new ones.
[ { "change_type": "MODIFY", "old_path": "server/src/creators/update-creator.js", "new_path": "server/src/creators/update-creator.js", "diff": "@@ -18,6 +18,8 @@ import type {\n} from 'lib/types/entry-types';\nimport invariant from 'invariant';\n+import _uniq from 'lodash/fp/uniq';\n+import _intersection from 'lodash/fp/intersection';\nimport { promiseAll } from 'lib/utils/promises';\nimport {\n@@ -55,7 +57,8 @@ type UpdatesResult = {|\nviewerUpdates: $ReadOnlyArray<UpdateInfo>,\nuserInfos: {[id: string]: AccountUserInfo},\n|};\n-const defaultResult = { viewerUpdates: [], userInfos: {} };\n+const emptyArray = [];\n+const defaultResult = { viewerUpdates: emptyArray, userInfos: {} };\nasync function createUpdates(\nupdateDatas: $ReadOnlyArray<UpdateData>,\nviewerInfo?: ViewerInfo,\n@@ -63,13 +66,108 @@ async function createUpdates(\nif (updateDatas.length === 0) {\nreturn defaultResult;\n}\n- const ids = await createIDs(\"updates\", updateDatas.length);\n+ const sortedUpdateDatas = [...updateDatas].sort(\n+ (a: UpdateData, b: UpdateData) => a.time - b.time,\n+ );\n+\n+ const filteredUpdateDatas: UpdateData[] = [];\n+ const keyedUpdateDatas: Map<string, UpdateData[]> = new Map();\n+ const deleteConditions: Map<string, number[]> = new Map();\n+ for (let updateData of sortedUpdateDatas) {\n+ let types;\n+ if (updateData.type === updateTypes.UPDATE_THREAD) {\n+ types = [\n+ updateTypes.UPDATE_THREAD,\n+ updateTypes.UPDATE_THREAD_READ_STATUS,\n+ ];\n+ } else if (updateData.type === updateTypes.UPDATE_THREAD_READ_STATUS) {\n+ types = [ updateTypes.UPDATE_THREAD_READ_STATUS ];\n+ } else if (\n+ updateData.type === updateTypes.DELETE_THREAD ||\n+ updateData.type === updateTypes.JOIN_THREAD\n+ ) {\n+ types = [];\n+ } else {\n+ filteredUpdateDatas.push(updateData);\n+ continue;\n+ }\n+\n+ const key = updateData.threadID;\n+ const conditionKey = `${updateData.userID}|${key}`;\n+\n+ // Possibly filter any existing UpdateDatas based on this one\n+ let keyUpdateDatas = keyedUpdateDatas.get(conditionKey);\n+ let keyUpdateDatasChanged = false;\n+ if (!keyUpdateDatas) {\n+ keyUpdateDatas = [];\n+ } else if (types.length === 0) {\n+ keyUpdateDatas = [];\n+ keyUpdateDatasChanged = true;\n+ } else {\n+ const filteredKeyUpdateDatas = existingUpdateDatas.filter(\n+ updateData => types.indexOf(updateData.type) === -1,\n+ );\n+ if (filteredKeyUpdateDatas.length === 0) {\n+ keyUpdateDatas = [];\n+ keyUpdateDatasChanged = true;\n+ } else if (filteredKeyUpdateDatas.length !== existingUpdateDatas.length) {\n+ keyUpdateDatas = filteredKeyUpdateDatas;\n+ keyUpdateDatasChanged = true;\n+ }\n+ }\n+\n+ // Update the deleteConditions and add our UpdateData to keyedUpdateDatas\n+ const existingTypes = deleteConditions.get(conditionKey);\n+ if (types.length === 0) {\n+ // If this UpdateData says to delete all the others, then include it, and\n+ // update the deleteConditions (if they don't already say to delete)\n+ if (!existingTypes || existingTypes.length !== 0) {\n+ deleteConditions.set(conditionKey, emptyArray);\n+ }\n+ keyUpdateDatas.push(updateData);\n+ keyUpdateDatasChanged = true;\n+ } else if (!existingTypes) {\n+ // If there were no existing conditions, then set the deleteConditions and\n+ // include this UpdateData\n+ deleteConditions.set(conditionKey, types);\n+ keyUpdateDatas.push(updateData);\n+ keyUpdateDatasChanged = true;\n+ } else {\n+ // Finally, if we have a list of types to delete, both existing and new,\n+ // then merge the list for the deleteConditions, and include this\n+ // UpdateData as long as its list of types isn't a strict subset of the\n+ // existing one.\n+ const newTypes = _uniq([...existingTypes, ...types]);\n+ deleteConditions.set(conditionKey, newTypes);\n+ const intersection = _intersection(existingTypes)(types);\n+ if (\n+ intersection.length !== types.length ||\n+ intersection.length === existingTypes.length\n+ ) {\n+ keyUpdateDatas.push(updateData);\n+ keyUpdateDatasChanged = true;\n+ }\n+ }\n- const viewerUpdateDatas: ViewerUpdateData[] = [];\n- const insertRows = [];\n- const deleteConditions = [];\n- for (let i = 0; i < updateDatas.length; i++) {\n- const updateData = updateDatas[i];\n+ if (!keyUpdateDatasChanged) {\n+ continue;\n+ }\n+ if (keyUpdateDatas.length === 0) {\n+ keyedUpdateDatas.delete(conditionKey);\n+ } else {\n+ keyedUpdateDatas.set(conditionKey, keyUpdateDatas);\n+ }\n+ }\n+\n+ for (let [ conditionKey, updateDatas ] of keyedUpdateDatas) {\n+ filteredUpdateDatas.push(...updateDatas);\n+ }\n+ const ids = await createIDs(\"updates\", filteredUpdateDatas.length);\n+\n+ const viewerUpdateDatas: Map<string, ViewerUpdateData[]> = [];\n+ const insertRows: Map<string, (number | string)[][]> = [];\n+ for (let i = 0; i < filteredUpdateDatas.length; i++) {\n+ const updateData = filteredUpdateDatas[i];\nif (viewerInfo && updateData.userID === viewerInfo.viewer.id) {\nviewerUpdateDatas.push({ data: updateData, id: ids[i] });\n}\n@@ -81,28 +179,10 @@ async function createUpdates(\n} else if (updateData.type === updateTypes.UPDATE_THREAD) {\ncontent = JSON.stringify({ threadID: updateData.threadID });\nkey = updateData.threadID;\n- const deleteTypes = [\n- updateTypes.UPDATE_THREAD,\n- updateTypes.UPDATE_THREAD_READ_STATUS,\n- ];\n- deleteConditions.push(\n- SQL`(\n- u.user = ${updateData.userID} AND\n- u.key = ${key} AND\n- u.type IN (${deleteTypes})\n- )`\n- );\n} else if (updateData.type === updateTypes.UPDATE_THREAD_READ_STATUS) {\nconst { threadID, unread } = updateData;\ncontent = JSON.stringify({ threadID, unread });\nkey = threadID;\n- deleteConditions.push(\n- SQL`(\n- u.user = ${updateData.userID} AND\n- u.key = ${key} AND\n- u.type = ${updateData.type}\n- )`\n- );\n} else if (\nupdateData.type === updateTypes.DELETE_THREAD ||\nupdateData.type === updateTypes.JOIN_THREAD\n@@ -110,10 +190,10 @@ async function createUpdates(\nconst { threadID } = updateData;\ncontent = JSON.stringify({ threadID });\nkey = threadID;\n- deleteConditions.push(\n- SQL`(u.user = ${updateData.userID} AND u.key = ${key})`\n- );\n+ } else {\n+ invariant(false, `unrecognized updateType ${updateData.type}`);\n}\n+\nconst insertRow = [\nids[i],\nupdateData.userID,\n@@ -128,8 +208,27 @@ async function createUpdates(\ninsertRows.push(insertRow);\n}\n+ const deleteSQLConditions: SQLStatement[] = deleteConditions.map(\n+ ([ conditionKey, types ]) => {\n+ const [ userID, key ] = conditionKey.split('|');\n+ if (types.length === 0) {\n+ return SQL`(\n+ u.user = ${userID} AND\n+ u.key = ${key}\n+ )`;\n+ } else {\n+ return SQL`(\n+ u.user = ${userID} AND\n+ u.key = ${key} AND\n+ u.type IN (${types})\n+ )`;\n+ }\n+ },\n+ );\n+\nconst promises = {};\n+ if (insertRows.length > 0) {\nconst insertQuery = viewerInfo\n? SQL`\nINSERT INTO updates(id, user, type, key, content, time, updater_cookie)\n@@ -137,9 +236,10 @@ async function createUpdates(\n: SQL`INSERT INTO updates(id, user, type, key, content, time) `;\ninsertQuery.append(SQL`VALUES ${insertRows}`);\npromises.insert = dbQuery(insertQuery);\n+ }\n- if (deleteConditions.length > 0) {\n- promises.delete = deleteUpdatesByConditions(deleteConditions);\n+ if (deleteSQLConditions.length > 0) {\n+ promises.delete = deleteUpdatesByConditions(deleteSQLConditions);\n}\nif (viewerUpdateDatas.length > 0) {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Refine createUpdates to avoid unnecessary updates Filter them out before they even get created. Also refines the deletion of existing updates due to new ones.
129,187
24.06.2018 15:25:55
25,200
b38c28e6ae62db38bb7a289b46d531e5acbc9831
[server] Scope createUpdates deletions to timestamps before earliest new update
[ { "change_type": "MODIFY", "old_path": "server/src/creators/update-creator.js", "new_path": "server/src/creators/update-creator.js", "diff": "@@ -32,7 +32,7 @@ import {\nnonThreadCalendarFilters,\n} from 'lib/selectors/calendar-filter-selectors';\n-import { dbQuery, SQL } from '../database';\n+import { dbQuery, SQL, SQLStatement, mergeAndConditions } from '../database';\nimport createIDs from './id-creator';\nimport { deleteUpdatesByConditions } from '../deleters/update-deleters';\nimport {\n@@ -58,7 +58,7 @@ type UpdatesResult = {|\nuserInfos: {[id: string]: AccountUserInfo},\n|};\nconst emptyArray = [];\n-const defaultResult = { viewerUpdates: emptyArray, userInfos: {} };\n+const defaultResult = { viewerUpdates: [], userInfos: {} };\nasync function createUpdates(\nupdateDatas: $ReadOnlyArray<UpdateData>,\nviewerInfo?: ViewerInfo,\n@@ -74,26 +74,27 @@ async function createUpdates(\nconst keyedUpdateDatas: Map<string, UpdateData[]> = new Map();\nconst deleteConditions: Map<string, number[]> = new Map();\nfor (let updateData of sortedUpdateDatas) {\n- let types;\n+ let conditionKey, types;\nif (updateData.type === updateTypes.UPDATE_THREAD) {\n+ conditionKey = `${updateData.userID}|${updateData.threadID}`;\ntypes = [\nupdateTypes.UPDATE_THREAD,\nupdateTypes.UPDATE_THREAD_READ_STATUS,\n];\n} else if (updateData.type === updateTypes.UPDATE_THREAD_READ_STATUS) {\n+ conditionKey = `${updateData.userID}|${updateData.threadID}`;\ntypes = [ updateTypes.UPDATE_THREAD_READ_STATUS ];\n} else if (\nupdateData.type === updateTypes.DELETE_THREAD ||\nupdateData.type === updateTypes.JOIN_THREAD\n) {\n+ conditionKey = `${updateData.userID}|${updateData.threadID}`;\ntypes = [];\n} else {\nfilteredUpdateDatas.push(updateData);\ncontinue;\n}\n-\n- const key = updateData.threadID;\n- const conditionKey = `${updateData.userID}|${key}`;\n+ invariant(conditionKey && types, \"should be set\");\n// Possibly filter any existing UpdateDatas based on this one\nlet keyUpdateDatas = keyedUpdateDatas.get(conditionKey);\n@@ -104,13 +105,13 @@ async function createUpdates(\nkeyUpdateDatas = [];\nkeyUpdateDatasChanged = true;\n} else {\n- const filteredKeyUpdateDatas = existingUpdateDatas.filter(\n+ const filteredKeyUpdateDatas = keyUpdateDatas.filter(\nupdateData => types.indexOf(updateData.type) === -1,\n);\nif (filteredKeyUpdateDatas.length === 0) {\nkeyUpdateDatas = [];\nkeyUpdateDatasChanged = true;\n- } else if (filteredKeyUpdateDatas.length !== existingUpdateDatas.length) {\n+ } else if (filteredKeyUpdateDatas.length !== keyUpdateDatas.length) {\nkeyUpdateDatas = filteredKeyUpdateDatas;\nkeyUpdateDatasChanged = true;\n}\n@@ -164,8 +165,9 @@ async function createUpdates(\n}\nconst ids = await createIDs(\"updates\", filteredUpdateDatas.length);\n- const viewerUpdateDatas: Map<string, ViewerUpdateData[]> = [];\n- const insertRows: Map<string, (number | string)[][]> = [];\n+ const viewerUpdateDatas: ViewerUpdateData[] = [];\n+ const insertRows: (number | string | null)[][] = [];\n+ const earliestTime: Map<string, number> = new Map();\nfor (let i = 0; i < filteredUpdateDatas.length; i++) {\nconst updateData = filteredUpdateDatas[i];\nif (viewerInfo && updateData.userID === viewerInfo.viewer.id) {\n@@ -194,6 +196,14 @@ async function createUpdates(\ninvariant(false, `unrecognized updateType ${updateData.type}`);\n}\n+ if (key) {\n+ const conditionKey = `${updateData.userID}|${key}`;\n+ const currentEarliestTime = earliestTime.get(conditionKey);\n+ if (!currentEarliestTime || updateData.time < currentEarliestTime) {\n+ earliestTime.set(conditionKey, updateData.time);\n+ }\n+ }\n+\nconst insertRow = [\nids[i],\nupdateData.userID,\n@@ -208,21 +218,18 @@ async function createUpdates(\ninsertRows.push(insertRow);\n}\n- const deleteSQLConditions: SQLStatement[] = deleteConditions.map(\n- ([ conditionKey, types ]) => {\n+ const deleteSQLConditions: SQLStatement[] = [...deleteConditions].map(\n+ ([ conditionKey: string, types: number[] ]) => {\nconst [ userID, key ] = conditionKey.split('|');\n- if (types.length === 0) {\n- return SQL`(\n- u.user = ${userID} AND\n- u.key = ${key}\n- )`;\n- } else {\n- return SQL`(\n- u.user = ${userID} AND\n- u.key = ${key} AND\n- u.type IN (${types})\n- )`;\n+ const conditions = [ SQL`u.user = ${userID}`, SQL`u.key = ${key}` ];\n+ if (types.length > 0) {\n+ conditions.push(SQL`u.type IN (${types})`);\n}\n+ const earliestTimeForCondition = earliestTime.get(conditionKey);\n+ if (earliestTimeForCondition) {\n+ conditions.push(SQL`u.time < ${earliestTimeForCondition}`);\n+ }\n+ return mergeAndConditions(conditions);\n},\n);\n@@ -443,6 +450,8 @@ function updateInfosFromUpdateDatas(\n}\n}\n+ updateInfos.sort((a: UpdateInfo, b: UpdateInfo) => a.time - b.time);\n+\nreturn { updateInfos, userInfos };\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Scope createUpdates deletions to timestamps before earliest new update
129,187
24.06.2018 19:52:11
25,200
0c094cb655c574dd511f7ae7e183a06f535c014a
Introduce threadStore
[ { "change_type": "MODIFY", "old_path": "lib/reducers/master-reducer.js", "new_path": "lib/reducers/master-reducer.js", "diff": "@@ -26,7 +26,8 @@ export default function baseReducer<N: BaseNavInfo, T: BaseAppState<N>>(\nstate: T,\naction: BaseAction,\n): T {\n- const threadInfos = reduceThreadInfos(state.threadInfos, action);\n+ const threadStore = reduceThreadInfos(state.threadStore, action);\n+ const { threadInfos } = threadStore;\n// NavInfo has to be handled differently because of the covariance\n// (see comment about \"+\" in redux-types.js)\n@@ -74,7 +75,7 @@ export default function baseReducer<N: BaseNavInfo, T: BaseAppState<N>>(\n},\nloadingStatuses: reduceLoadingStatuses(state.loadingStatuses, action),\ncurrentUserInfo: reduceCurrentUserInfo(state.currentUserInfo, action),\n- threadInfos,\n+ threadStore,\nuserInfos: reduceUserInfos(state.userInfos, action),\nmessageStore: reduceMessageStore(state.messageStore, action, threadInfos),\ndrafts: reduceDrafts(state.drafts, action),\n@@ -95,7 +96,7 @@ export default function baseReducer<N: BaseNavInfo, T: BaseAppState<N>>(\nstate.calendarFilters,\naction,\nthreadInfos,\n- state.threadInfos,\n+ state.threadStore.threadInfos,\n),\n};\n}\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/message-reducer.js", "new_path": "lib/reducers/message-reducer.js", "diff": "@@ -661,9 +661,10 @@ function mergeUpdatesIntoMessagesResult(\n);\n}\nreturn {\n- ...messagesResult,\nmessageInfos: mergedMessageInfos,\ntruncationStatus: mergedTruncationStatuses,\n+ watchedIDsAtRequestTime: messagesResult.watchedIDsAtRequestTime,\n+ currentAsOf: messagesResult.currentAsOf,\n};\n}\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/thread-reducer.js", "new_path": "lib/reducers/thread-reducer.js", "diff": "// @flow\nimport type { BaseAction } from '../types/redux-types';\n-import type { RawThreadInfo } from '../types/thread-types';\n+import type { RawThreadInfo, ThreadStore } from '../types/thread-types';\nimport type { PingResult } from '../types/ping-types';\nimport { updateTypes, type UpdateInfo } from '../types/update-types';\n@@ -32,11 +32,11 @@ import {\n} from '../actions/ping-actions';\nfunction pingPull(\n- state: {[id: string]: RawThreadInfo},\n+ threadInfos: {[id: string]: RawThreadInfo},\npayload: PingResult,\n): {[id: string]: RawThreadInfo} {\n- if (_isEqual(state)(payload.threadInfos)) {\n- return state;\n+ if (_isEqual(threadInfos)(payload.threadInfos)) {\n+ return threadInfos;\n}\nconst newThreadInfos = {};\nlet threadIDsWithNewMessages: ?Set<string> = null;\n@@ -52,7 +52,7 @@ function pingPull(\n};\nfor (let threadID in payload.threadInfos) {\nconst newThreadInfo = payload.threadInfos[threadID];\n- const currentThreadInfo = state[threadID];\n+ const currentThreadInfo = threadInfos[threadID];\nconst prevThreadInfo = payload.prevState.threadInfos[threadID];\nif (_isEqual(currentThreadInfo)(newThreadInfo)) {\nnewThreadInfos[threadID] = currentThreadInfo;\n@@ -89,7 +89,7 @@ function pingPull(\nnewThreadInfos[threadID] = newThreadInfo;\n}\n}\n- for (let threadID in state) {\n+ for (let threadID in threadInfos) {\nconst newThreadInfo = payload.threadInfos[threadID];\nif (newThreadInfo) {\ncontinue;\n@@ -100,55 +100,55 @@ function pingPull(\n}\n// If a thread was not present at the start of the ping, it's possible\n// that an action added it in between the start and the end of the ping.\n- const currentThreadInfo = state[threadID];\n+ const currentThreadInfo = threadInfos[threadID];\nnewThreadInfos[threadID] = currentThreadInfo;\n}\n- if (_isEqual(state)(newThreadInfos)) {\n- return state;\n+ if (_isEqual(threadInfos)(newThreadInfos)) {\n+ return threadInfos;\n}\nreturn newThreadInfos;\n}\n// ... PUSH.\nfunction pingPush(\n- state: {[id: string]: RawThreadInfo},\n+ threadInfos: {[id: string]: RawThreadInfo},\npayload: { +updatesResult: ?{ newUpdates: $ReadOnlyArray<UpdateInfo> } },\n): {[id: string]: RawThreadInfo} {\nif (!payload.updatesResult) {\n- return state;\n+ return threadInfos;\n}\n- const newState = { ...state };\n+ const newState = { ...threadInfos };\nlet someThreadUpdated = false;\nfor (let update of payload.updatesResult.newUpdates) {\nif (\n(update.type === updateTypes.UPDATE_THREAD ||\nupdate.type === updateTypes.JOIN_THREAD) &&\n- !_isEqual(state[update.threadInfo.id])(update.threadInfo)\n+ !_isEqual(threadInfos[update.threadInfo.id])(update.threadInfo)\n) {\nsomeThreadUpdated = true;\nnewState[update.threadInfo.id] = update.threadInfo;\n} else if (\nupdate.type === updateTypes.UPDATE_THREAD_READ_STATUS &&\n- state[update.threadID] &&\n- state[update.threadID].currentUser.unread !== update.unread\n+ threadInfos[update.threadID] &&\n+ threadInfos[update.threadID].currentUser.unread !== update.unread\n) {\nsomeThreadUpdated = true;\nnewState[update.threadID] = {\n- ...state[update.threadID],\n+ ...threadInfos[update.threadID],\ncurrentUser: {\n- ...state[update.threadID].currentUser,\n+ ...threadInfos[update.threadID].currentUser,\nunread: update.unread,\n},\n};\n} else if (\nupdate.type === updateTypes.DELETE_THREAD &&\n- state[update.threadID]\n+ threadInfos[update.threadID]\n) {\nsomeThreadUpdated = true;\ndelete newState[update.threadID];\n} else if (update.type === updateTypes.DELETE_ACCOUNT) {\n- for (let threadID in state) {\n- const threadInfo = state[threadID];\n+ for (let threadID in threadInfos) {\n+ const threadInfo = threadInfos[threadID];\nconst newMembers = threadInfo.members.filter(\nmember => member.id !== update.deletedUserID,\n);\n@@ -163,15 +163,15 @@ function pingPush(\n}\n}\nif (!someThreadUpdated) {\n- return state;\n+ return threadInfos;\n}\nreturn newState;\n}\nexport default function reduceThreadInfos(\n- state: {[id: string]: RawThreadInfo},\n+ state: ThreadStore,\naction: BaseAction,\n-): {[id: string]: RawThreadInfo} {\n+): ThreadStore {\nif (\naction.type === logOutActionTypes.success ||\naction.type === deleteAccountActionTypes.success ||\n@@ -180,10 +180,13 @@ export default function reduceThreadInfos(\naction.type === resetPasswordActionTypes.success ||\naction.type === setCookieActionType\n) {\n- if (_isEqual(state)(action.payload.threadInfos)) {\n+ if (_isEqual(state.threadInfos)(action.payload.threadInfos)) {\nreturn state;\n}\n- return action.payload.threadInfos;\n+ return {\n+ threadInfos: action.payload.threadInfos,\n+ inconsistencyResponses: state.inconsistencyResponses,\n+ };\n} else if (\naction.type === joinThreadActionTypes.success ||\naction.type === leaveThreadActionTypes.success ||\n@@ -193,53 +196,69 @@ export default function reduceThreadInfos(\naction.type === changeThreadMemberRolesActionTypes.success\n) {\nif (\n- _isEqual(state)(action.payload.threadInfos) &&\n+ _isEqual(state.threadInfos)(action.payload.threadInfos) &&\naction.payload.updatesResult.newUpdates.length === 0\n) {\nreturn state;\n}\nconst pullResult = action.payload.threadInfos;\n- //const pushResult = pingPush(state, action.payload);\n- return pullResult;\n+ //const pushResult = pingPush(state.threadInfos, action.payload);\n+ return {\n+ threadInfos: pullResult,\n+ inconsistencyResponses: state.inconsistencyResponses,\n+ };\n} else if (action.type === pingActionTypes.success) {\nconst payload = action.payload;\n- const pullResult = pingPull(state, payload);\n- //const pushResult = pingPush(state, payload);\n- return pullResult;\n+ const pullResult = pingPull(state.threadInfos, payload);\n+ //const pushResult = pingPush(state.threadInfos, payload);\n+ return {\n+ threadInfos: pullResult,\n+ inconsistencyResponses: state.inconsistencyResponses,\n+ };\n} else if (action.type === newThreadActionTypes.success) {\nconst newThreadInfo = action.payload.newThreadInfo;\nif (\n- _isEqual(state[newThreadInfo.id])(newThreadInfo) &&\n+ _isEqual(state.threadInfos[newThreadInfo.id])(newThreadInfo) &&\naction.payload.updatesResult.newUpdates.length === 0\n) {\nreturn state;\n}\nconst pullResult = {\n- ...state,\n+ ...state.threadInfos,\n[newThreadInfo.id]: newThreadInfo,\n};\n//const pushResult = pingPush(state, action.payload);\n- return pullResult;\n+ return {\n+ threadInfos: pullResult,\n+ inconsistencyResponses: state.inconsistencyResponses,\n+ };\n} else if (action.type === updateActivityActionTypes.success) {\n- const newState = { ...state };\n+ const newThreadInfos = { ...state.threadInfos };\nfor (let setToUnread of action.payload.unfocusedToUnread) {\n- const threadInfo = newState[setToUnread];\n+ const threadInfo = newThreadInfos[setToUnread];\nif (threadInfo) {\nthreadInfo.currentUser.unread = true;\n}\n}\n- return newState;\n- } else if (action.type === updateSubscriptionActionTypes.success) {\nreturn {\n- ...state,\n+ threadInfos: newThreadInfos,\n+ inconsistencyResponses: state.inconsistencyResponses,\n+ };\n+ } else if (action.type === updateSubscriptionActionTypes.success) {\n+ const newThreadInfos = {\n+ ...state.threadInfos,\n[action.payload.threadID]: {\n- ...state[action.payload.threadID],\n+ ...state.threadInfos[action.payload.threadID],\ncurrentUser: {\n- ...state[action.payload.threadID].currentUser,\n+ ...state.threadInfos[action.payload.threadID].currentUser,\nsubscription: action.payload.subscription,\n},\n},\n};\n+ return {\n+ threadInfos: newThreadInfos,\n+ inconsistencyResponses: state.inconsistencyResponses,\n+ };\n}\nreturn state;\n}\n" }, { "change_type": "MODIFY", "old_path": "lib/selectors/nav-selectors.js", "new_path": "lib/selectors/nav-selectors.js", "diff": "@@ -95,7 +95,7 @@ const threadSearchText = (\n}\nconst threadSearchIndex = createSelector(\n- (state: BaseAppState<*>) => state.threadInfos,\n+ (state: BaseAppState<*>) => state.threadStore.threadInfos,\n(state: BaseAppState<*>) => state.userInfos,\n(\nthreadInfos: {[id: string]: RawThreadInfo},\n" }, { "change_type": "MODIFY", "old_path": "lib/selectors/ping-selectors.js", "new_path": "lib/selectors/ping-selectors.js", "diff": "@@ -39,7 +39,7 @@ const pingStartingPayload = createSelector(\n// This gets generated and passed in to the action function, which then passes\n// it on in the PING_SUCCESS payload\nconst pingActionInput = createSelector(\n- (state: BaseAppState<*>) => state.threadInfos,\n+ (state: BaseAppState<*>) => state.threadStore.threadInfos,\n(state: BaseAppState<*>) => state.entryStore.entryInfos,\n(state: BaseAppState<*>) => state.currentUserInfo,\n(state: BaseAppState<*>) => state.messageStore.currentAsOf,\n" }, { "change_type": "MODIFY", "old_path": "lib/selectors/thread-selectors.js", "new_path": "lib/selectors/thread-selectors.js", "diff": "@@ -53,7 +53,7 @@ const rawThreadInfosToThreadInfos = (\ntype ThreadInfoSelectorType =\n(state: BaseAppState<*>) => {[id: string]: ThreadInfo};\nconst threadInfoSelector: ThreadInfoSelectorType = createSelector(\n- (state: BaseAppState<*>) => state.threadInfos,\n+ (state: BaseAppState<*>) => state.threadStore.threadInfos,\n(state: BaseAppState<*>) => state.currentUserInfo && state.currentUserInfo.id,\n(state: BaseAppState<*>) => state.userInfos,\nrawThreadInfosToThreadInfos,\n@@ -170,7 +170,7 @@ const childThreadInfos = createSelector(\n);\nconst unreadCount = createSelector(\n- (state: BaseAppState<*>) => state.threadInfos,\n+ (state: BaseAppState<*>) => state.threadStore.threadInfos,\n(threadInfos: {[id: string]: RawThreadInfo}): number => _flow(\n_filter(threadInChatList),\n_filter('currentUser.unread'),\n@@ -179,7 +179,7 @@ const unreadCount = createSelector(\n);\nconst baseOtherUsersButNoOtherAdmins = (threadID: string) => createSelector(\n- (state: BaseAppState<*>) => state.threadInfos[threadID],\n+ (state: BaseAppState<*>) => state.threadStore.threadInfos[threadID],\nrelativeMemberInfoSelectorForMembersOfThread(threadID),\n(threadInfo: ?RawThreadInfo, members: RelativeMemberInfo[]): bool => {\nif (!threadInfo) {\n@@ -233,7 +233,7 @@ function mostRecentReadThread(\nconst mostRecentReadThreadSelector = createSelector(\n(state: BaseAppState<*>) => state.messageStore,\n- (state: BaseAppState<*>) => state.threadInfos,\n+ (state: BaseAppState<*>) => state.threadStore.threadInfos,\nmostRecentReadThread,\n);\n" }, { "change_type": "MODIFY", "old_path": "lib/selectors/user-selectors.js", "new_path": "lib/selectors/user-selectors.js", "diff": "@@ -51,7 +51,7 @@ function userIDsToRelativeUserInfos(\n// Includes current user at the start\nconst baseRelativeMemberInfoSelectorForMembersOfThread = (threadID: string) =>\ncreateSelector(\n- (state: BaseAppState<*>) => state.threadInfos[threadID],\n+ (state: BaseAppState<*>) => state.threadStore.threadInfos[threadID],\n(state: BaseAppState<*>) => state.currentUserInfo && state.currentUserInfo.id,\n(state: BaseAppState<*>) => state.userInfos,\n(\n@@ -99,8 +99,9 @@ const baseUserInfoSelectorForOtherMembersOfThread = (threadID: ?string) =>\ncreateSelector(\n(state: BaseAppState<*>) => state.userInfos,\n(state: BaseAppState<*>) => state.currentUserInfo && state.currentUserInfo.id,\n- (state: BaseAppState<*>) => threadID && state.threadInfos[threadID]\n- ? state.threadInfos[threadID].members\n+ (state: BaseAppState<*>) =>\n+ threadID && state.threadStore.threadInfos[threadID]\n+ ? state.threadStore.threadInfos[threadID].members\n: null,\n(\nuserInfos: {[id: string]: UserInfo},\n" }, { "change_type": "MODIFY", "old_path": "lib/types/redux-types.js", "new_path": "lib/types/redux-types.js", "diff": "// @flow\nimport type {\n- RawThreadInfo,\n+ ThreadStore,\nChangeThreadSettingsResult,\nLeaveThreadPayload,\nNewThreadResult,\n@@ -35,7 +35,7 @@ import type {\nPingStartingPayload,\nPingResult,\nPingTimestamps,\n-} from '../types/ping-types';\n+} from './ping-types';\nimport type {\nMessageStore,\nRawTextMessageInfo,\n@@ -61,7 +61,7 @@ export type BaseAppState<NavInfo: BaseNavInfo> = {\nsessionID: string,\nentryStore: EntryStore,\nlastUserInteraction: {[section: string]: number},\n- threadInfos: {[id: string]: RawThreadInfo},\n+ threadStore: ThreadStore,\nuserInfos: {[id: string]: UserInfo},\nmessageStore: MessageStore,\ndrafts: {[key: string]: string},\n" }, { "change_type": "MODIFY", "old_path": "lib/types/request-types.js", "new_path": "lib/types/request-types.js", "diff": "// @flow\nimport type { Platform } from './device-types';\n+import type { RawThreadInfo } from './thread-types';\n+import type { BaseAction } from './redux-types';\nimport invariant from 'invariant';\nimport PropTypes from 'prop-types';\n@@ -10,35 +12,45 @@ import PropTypes from 'prop-types';\nexport const serverRequestTypes = Object.freeze({\nPLATFORM: 0,\nDEVICE_TOKEN: 1,\n+ THREAD_POLL_PUSH_INCONSISTENCY: 2,\n});\n-export type ServerRequestType = $Values<typeof serverRequestTypes>;\n-export function assertServerRequestType(\n+type ServerRequestType = $Values<typeof serverRequestTypes>;\n+function assertServerRequestType(\nserverRequestType: number,\n): ServerRequestType {\ninvariant(\nserverRequestType === 0 ||\n- serverRequestType === 1,\n+ serverRequestType === 1 ||\n+ serverRequestType === 2,\n\"number is not ServerRequestType enum\",\n);\nreturn serverRequestType;\n}\n-export type PlatformServerRequest = {|\n+type PlatformServerRequest = {|\ntype: 0,\n|};\n-export type PlatformClientResponse = {|\n+type PlatformClientResponse = {|\ntype: 0,\nplatform: Platform,\n|};\n-export type DeviceTokenServerRequest = {|\n+type DeviceTokenServerRequest = {|\ntype: 1,\n|};\n-export type DeviceTokenClientResponse = {|\n+type DeviceTokenClientResponse = {|\ntype: 1,\ndeviceToken: string,\n|};\n+export type ThreadPollPushInconsistencyClientResponse = {|\n+ type: 2,\n+ beforeAction: {[id: string]: RawThreadInfo},\n+ action: BaseAction,\n+ pollResult: {[id: string]: RawThreadInfo},\n+ pushResult: {[id: string]: RawThreadInfo},\n+|};\n+\nexport const serverRequestPropType = PropTypes.oneOfType([\nPropTypes.shape({\ntype: PropTypes.oneOf([ serverRequestTypes.PLATFORM ]).isRequired,\n@@ -53,4 +65,5 @@ export type ServerRequest =\n| DeviceTokenServerRequest;\nexport type ClientResponse =\n| PlatformClientResponse\n- | DeviceTokenClientResponse;\n+ | DeviceTokenClientResponse\n+ | ThreadPollPushInconsistencyClientResponse;\n" }, { "change_type": "MODIFY", "old_path": "lib/types/thread-types.js", "new_path": "lib/types/thread-types.js", "diff": "@@ -12,6 +12,9 @@ import type {\nRawEntryInfo,\n} from './entry-types';\nimport type { UpdateInfo } from './update-types';\n+import type {\n+ ThreadPollPushInconsistencyClientResponse,\n+} from './request-types';\nimport PropTypes from 'prop-types';\nimport invariant from 'invariant';\n@@ -237,6 +240,12 @@ export type ServerThreadInfo = {|\nroles: {[id: string]: RoleInfo},\n|};\n+export type ThreadStore = {|\n+ threadInfos: {[id: string]: RawThreadInfo},\n+ inconsistencyResponses:\n+ $ReadOnlyArray<ThreadPollPushInconsistencyClientResponse>,\n+|};\n+\nexport type ThreadDeletionRequest = {|\nthreadID: string,\naccountPassword: string,\n" }, { "change_type": "MODIFY", "old_path": "native/app.react.js", "new_path": "native/app.react.js", "diff": "@@ -867,7 +867,7 @@ const ConnectedAppWithNavigationState = connect(\n: null,\ndeviceToken: state.deviceToken,\nunreadCount: unreadCount(state),\n- rawThreadInfos: state.threadInfos,\n+ rawThreadInfos: state.threadStore.threadInfos,\nnotifPermissionAlertInfo: state.notifPermissionAlertInfo,\npingTimestamps: state.pingTimestamps,\nsessionTimeLeft: sessionTimeLeft(state),\n" }, { "change_type": "MODIFY", "old_path": "native/persist.js", "new_path": "native/persist.js", "diff": "@@ -32,7 +32,7 @@ const migrations = {\n...state,\nmessageSentFromRoute: [],\n}),\n- [3]: (state: Object) => ({\n+ [3]: (state) => ({\ncurrentUserInfo: state.currentUserInfo,\nentryStore: state.entryStore,\nthreadInfos: state.threadInfos,\n@@ -61,6 +61,14 @@ const migrations = {\n...state,\ncalendarFilters: defaultCalendarFilters,\n}),\n+ [6]: (state) => ({\n+ ...state,\n+ threadInfos: undefined,\n+ threadStore: {\n+ threadInfos: state.threadInfos,\n+ inconsistencyResponses: [],\n+ },\n+ }),\n};\nconst persistConfig = {\n@@ -68,7 +76,7 @@ const persistConfig = {\nstorage,\nblacklist,\ndebug: __DEV__,\n- version: 5,\n+ version: 6,\nmigrate: createMigrate(migrations, { debug: __DEV__ }),\n};\n" }, { "change_type": "MODIFY", "old_path": "native/redux-setup.js", "new_path": "native/redux-setup.js", "diff": "// @flow\n-import type { RawThreadInfo } from 'lib/types/thread-types';\n+import type { ThreadStore } from 'lib/types/thread-types';\nimport type { EntryStore } from 'lib/types/entry-types';\nimport type { LoadingStatus } from 'lib/types/loading-types';\nimport type { CurrentUserInfo, UserInfo } from 'lib/types/user-types';\n@@ -75,7 +75,7 @@ export type AppState = {|\nsessionID: string,\nentryStore: EntryStore,\nlastUserInteraction: {[section: string]: number},\n- threadInfos: {[id: string]: RawThreadInfo},\n+ threadStore: ThreadStore,\nuserInfos: {[id: string]: UserInfo},\nmessageStore: MessageStore,\ndrafts: {[key: string]: string},\n@@ -104,7 +104,10 @@ const defaultState = ({\nlastUserInteractionCalendar: 0,\n},\nlastUserInteraction: { sessionReset: Date.now() },\n+ threadStore: {\nthreadInfos: {},\n+ inconsistencyResponses: [],\n+ },\nuserInfos: {},\nmessageStore: {\nmessages: {},\n@@ -187,7 +190,7 @@ function reducer(state: AppState = defaultState, action: *) {\nsessionID: state.sessionID,\nentryStore: state.entryStore,\nlastUserInteraction: state.lastUserInteraction,\n- threadInfos: state.threadInfos,\n+ threadStore: state.threadStore,\nuserInfos: state.userInfos,\nmessageStore: state.messageStore,\ndrafts: state.drafts,\n@@ -216,7 +219,7 @@ function reducer(state: AppState = defaultState, action: *) {\nsessionID: state.sessionID,\nentryStore: state.entryStore,\nlastUserInteraction: state.lastUserInteraction,\n- threadInfos: state.threadInfos,\n+ threadStore: state.threadStore,\nuserInfos: state.userInfos,\nmessageStore: state.messageStore,\ndrafts: state.drafts,\n@@ -244,7 +247,7 @@ function reducer(state: AppState = defaultState, action: *) {\nsessionID: state.sessionID,\nentryStore: state.entryStore,\nlastUserInteraction: state.lastUserInteraction,\n- threadInfos: state.threadInfos,\n+ threadStore: state.threadStore,\nuserInfos: state.userInfos,\nmessageStore: state.messageStore,\ndrafts: state.drafts,\n@@ -269,7 +272,7 @@ function reducer(state: AppState = defaultState, action: *) {\nsessionID: state.sessionID,\nentryStore: state.entryStore,\nlastUserInteraction: state.lastUserInteraction,\n- threadInfos: state.threadInfos,\n+ threadStore: state.threadStore,\nuserInfos: state.userInfos,\nmessageStore: state.messageStore,\ndrafts: state.drafts,\n@@ -322,7 +325,7 @@ function reducer(state: AppState = defaultState, action: *) {\nsessionID: state.sessionID,\nentryStore: state.entryStore,\nlastUserInteraction: state.lastUserInteraction,\n- threadInfos: state.threadInfos,\n+ threadStore: state.threadStore,\nuserInfos: state.userInfos,\nmessageStore: state.messageStore,\ndrafts: state.drafts,\n@@ -347,7 +350,10 @@ function reducer(state: AppState = defaultState, action: *) {\nfunction validateState(oldState: AppState, state: AppState): AppState {\nconst oldActiveThread = activeThreadSelector(oldState);\nconst activeThread = activeThreadSelector(state);\n- if (activeThread && state.threadInfos[activeThread].currentUser.unread) {\n+ if (\n+ activeThread &&\n+ state.threadStore.threadInfos[activeThread].currentUser.unread\n+ ) {\n// Makes sure a currently focused thread is never unread\nstate = {\nnavInfo: state.navInfo,\n@@ -355,16 +361,19 @@ function validateState(oldState: AppState, state: AppState): AppState {\nsessionID: state.sessionID,\nentryStore: state.entryStore,\nlastUserInteraction: state.lastUserInteraction,\n+ threadStore: {\nthreadInfos: {\n- ...state.threadInfos,\n+ ...state.threadStore.threadInfos,\n[activeThread]: {\n- ...state.threadInfos[activeThread],\n+ ...state.threadStore.threadInfos[activeThread],\ncurrentUser: {\n- ...state.threadInfos[activeThread].currentUser,\n+ ...state.threadStore.threadInfos[activeThread].currentUser,\nunread: false,\n},\n},\n},\n+ inconsistencyResponses: state.threadStore.inconsistencyResponses,\n+ },\nuserInfos: state.userInfos,\nmessageStore: state.messageStore,\ndrafts: state.drafts,\n@@ -395,7 +404,7 @@ function validateState(oldState: AppState, state: AppState): AppState {\nsessionID: state.sessionID,\nentryStore: state.entryStore,\nlastUserInteraction: state.lastUserInteraction,\n- threadInfos: state.threadInfos,\n+ threadStore: state.threadStore,\nuserInfos: state.userInfos,\nmessageStore: {\nmessages: state.messageStore.messages,\n@@ -437,7 +446,7 @@ function validateState(oldState: AppState, state: AppState): AppState {\nsessionID: state.sessionID,\nentryStore: state.entryStore,\nlastUserInteraction: state.lastUserInteraction,\n- threadInfos: state.threadInfos,\n+ threadStore: state.threadStore,\nuserInfos: state.userInfos,\nmessageStore: state.messageStore,\ndrafts: state.drafts,\n" }, { "change_type": "MODIFY", "old_path": "server/src/responders/website-responders.js", "new_path": "server/src/responders/website-responders.js", "diff": "@@ -121,7 +121,10 @@ async function websiteResponder(viewer: Viewer, url: string): Promise<string> {\nlastUserInteractionCalendar: time,\n},\nlastUserInteraction: { sessionReset: time },\n+ threadStore: {\nthreadInfos,\n+ inconsistencyResponses: [],\n+ },\nuserInfos: {\n...messageUserInfos,\n...entryUserInfos,\n" }, { "change_type": "MODIFY", "old_path": "web/app.react.js", "new_path": "web/app.react.js", "diff": "@@ -577,7 +577,7 @@ export default connect(\nmostRecentReadThread: mostRecentReadThreadSelector(state),\nactiveThread: activeThreadSelector(state),\nactiveThreadCurrentlyUnread: !activeChatThreadID ||\n- state.threadInfos[activeChatThreadID].currentUser.unread,\n+ state.threadStore.threadInfos[activeChatThreadID].currentUser.unread,\nactiveThreadLatestMessage:\nactiveChatThreadID && state.messageStore.threads[activeChatThreadID]\n? state.messageStore.threads[activeChatThreadID].messageIDs[0]\n" }, { "change_type": "MODIFY", "old_path": "web/redux-setup.js", "new_path": "web/redux-setup.js", "diff": "// @flow\nimport type { BaseNavInfo } from 'lib/types/nav-types';\n-import type { RawThreadInfo } from 'lib/types/thread-types';\n+import type { ThreadStore } from 'lib/types/thread-types';\nimport type { EntryStore } from 'lib/types/entry-types';\nimport type { BaseAction } from 'lib/types/redux-types';\nimport type { LoadingStatus } from 'lib/types/loading-types';\n@@ -48,7 +48,7 @@ export type AppState = {|\nresetPasswordUsername: string,\nentryStore: EntryStore,\nlastUserInteraction: {[section: string]: number},\n- threadInfos: {[id: string]: RawThreadInfo},\n+ threadStore: ThreadStore,\nuserInfos: {[id: string]: UserInfo},\nmessageStore: MessageStore,\ndrafts: {[key: string]: string},\n@@ -87,7 +87,7 @@ export function reducer(inputState: AppState | void, action: Action) {\nresetPasswordUsername: state.resetPasswordUsername,\nentryStore: state.entryStore,\nlastUserInteraction: state.lastUserInteraction,\n- threadInfos: state.threadInfos,\n+ threadStore: state.threadStore,\nuserInfos: state.userInfos,\nmessageStore: state.messageStore,\ndrafts: state.drafts,\n@@ -110,7 +110,7 @@ export function reducer(inputState: AppState | void, action: Action) {\nresetPasswordUsername: state.resetPasswordUsername,\nentryStore: state.entryStore,\nlastUserInteraction: state.lastUserInteraction,\n- threadInfos: state.threadInfos,\n+ threadStore: state.threadStore,\nuserInfos: state.userInfos,\nmessageStore: state.messageStore,\ndrafts: state.drafts,\n@@ -133,7 +133,10 @@ export function reducer(inputState: AppState | void, action: Action) {\nfunction validateState(oldState: AppState, state: AppState): AppState {\nconst oldActiveThread = activeThreadSelector(oldState);\nconst activeThread = activeThreadSelector(state);\n- if (activeThread && state.threadInfos[activeThread].currentUser.unread) {\n+ if (\n+ activeThread &&\n+ state.threadStore.threadInfos[activeThread].currentUser.unread\n+ ) {\n// Makes sure a currently focused thread is never unread\nstate = {\nnavInfo: state.navInfo,\n@@ -143,16 +146,19 @@ function validateState(oldState: AppState, state: AppState): AppState {\nresetPasswordUsername: state.resetPasswordUsername,\nentryStore: state.entryStore,\nlastUserInteraction: state.lastUserInteraction,\n+ threadStore: {\n+ ...state.threadStore,\nthreadInfos: {\n- ...state.threadInfos,\n+ ...state.threadStore.threadInfos,\n[activeThread]: {\n- ...state.threadInfos[activeThread],\n+ ...state.threadStore.threadInfos[activeThread],\ncurrentUser: {\n- ...state.threadInfos[activeThread].currentUser,\n+ ...state.threadStore.threadInfos[activeThread].currentUser,\nunread: false,\n},\n},\n},\n+ },\nuserInfos: state.userInfos,\nmessageStore: state.messageStore,\ndrafts: state.drafts,\n@@ -181,7 +187,7 @@ function validateState(oldState: AppState, state: AppState): AppState {\nresetPasswordUsername: state.resetPasswordUsername,\nentryStore: state.entryStore,\nlastUserInteraction: state.lastUserInteraction,\n- threadInfos: state.threadInfos,\n+ threadStore: state.threadStore,\nuserInfos: state.userInfos,\nmessageStore: {\nmessages: state.messageStore.messages,\n@@ -209,7 +215,7 @@ function validateState(oldState: AppState, state: AppState): AppState {\nif (\nstate.navInfo.activeChatThreadID &&\n- !state.threadInfos[state.navInfo.activeChatThreadID]\n+ !state.threadStore.threadInfos[state.navInfo.activeChatThreadID]\n) {\n// Makes sure the active thread always exists\nstate = {\n@@ -226,7 +232,7 @@ function validateState(oldState: AppState, state: AppState): AppState {\nresetPasswordUsername: state.resetPasswordUsername,\nentryStore: state.entryStore,\nlastUserInteraction: state.lastUserInteraction,\n- threadInfos: state.threadInfos,\n+ threadStore: state.threadStore,\nuserInfos: state.userInfos,\nmessageStore: state.messageStore,\ndrafts: state.drafts,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Introduce threadStore
129,187
25.06.2018 11:22:55
14,400
2f0862587a5ba6609e4bb5214eba7008f407d30f
serverRequestTypes.THREAD_POLL_PUSH_INCONSISTENCY Inform the server when there is inconsistency between poll and push results for the `ThreadStore`.
[ { "change_type": "MODIFY", "old_path": "lib/actions/ping-actions.js", "new_path": "lib/actions/ping-actions.js", "diff": "@@ -27,7 +27,7 @@ async function ping(\nclientResponses: actionInput.clientResponses,\nwatchedIDs,\n});\n- const result: PingResult = {\n+ return {\nthreadInfos: response.threadInfos,\ncurrentUserInfo: response.currentUserInfo,\ncalendarResult: {\n@@ -45,11 +45,11 @@ async function ping(\nloggedIn: actionInput.loggedIn,\nprevState: actionInput.prevState,\nupdatesResult: response.updatesResult,\n+ requests: {\n+ serverRequests: response.serverRequests,\n+ deliveredClientResponses: actionInput.clientResponses,\n+ },\n};\n- if (response.serverRequests) {\n- result.serverRequests = response.serverRequests;\n- }\n- return result;\n}\nconst updateActivityActionTypes = Object.freeze({\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/server-requests-reducer.js", "new_path": "lib/reducers/server-requests-reducer.js", "diff": "@@ -9,18 +9,16 @@ export default function reduceServerRequests(\nstate: $ReadOnlyArray<ServerRequest>,\naction: BaseAction,\n): $ReadOnlyArray<ServerRequest> {\n- if (\n- action.type === pingActionTypes.success &&\n- action.payload.serverRequests\n- ) {\n+ if (action.type === pingActionTypes.success) {\n+ const { requests } = action.payload;\nreturn [\n- ...state,\n- ...action.payload.serverRequests,\n- ];\n- } else if (action.type === pingActionTypes.started && state.length > 0) {\n// For now, we assume that each ping responds to every server request\n- // present at the time\n- return [];\n+ // present at the time. Note that we're relying on reference comparisons.\n+ ...state.filter(\n+ request => !requests.deliveredClientResponses.includes(request),\n+ ),\n+ ...requests.serverRequests,\n+ ];\n}\nreturn state;\n}\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/thread-reducer.js", "new_path": "lib/reducers/thread-reducer.js", "diff": "@@ -4,6 +4,10 @@ import type { BaseAction } from '../types/redux-types';\nimport type { RawThreadInfo, ThreadStore } from '../types/thread-types';\nimport type { PingResult } from '../types/ping-types';\nimport { updateTypes, type UpdateInfo } from '../types/update-types';\n+import {\n+ type ThreadPollPushInconsistencyClientResponse,\n+ serverRequestTypes,\n+} from '../types/request-types';\nimport invariant from 'invariant';\nimport _isEqual from 'lodash/fp/isEqual';\n@@ -31,7 +35,7 @@ import {\nupdateActivityActionTypes,\n} from '../actions/ping-actions';\n-function pingPull(\n+function pingPoll(\nthreadInfos: {[id: string]: RawThreadInfo},\npayload: PingResult,\n): {[id: string]: RawThreadInfo} {\n@@ -168,6 +172,25 @@ function pingPush(\nreturn newState;\n}\n+const emptyArray = [];\n+function findInconsistencies(\n+ beforeAction: {[id: string]: RawThreadInfo},\n+ action: BaseAction,\n+ pollResult: {[id: string]: RawThreadInfo},\n+ pushResult: {[id: string]: RawThreadInfo},\n+): ThreadPollPushInconsistencyClientResponse[] {\n+ if (_isEqual(pollResult)(pushResult)) {\n+ return emptyArray;\n+ }\n+ return [{\n+ type: serverRequestTypes.THREAD_POLL_PUSH_INCONSISTENCY,\n+ beforeAction,\n+ action,\n+ pollResult,\n+ pushResult,\n+ }];\n+}\n+\nexport default function reduceThreadInfos(\nstate: ThreadStore,\naction: BaseAction,\n@@ -201,19 +224,38 @@ export default function reduceThreadInfos(\n) {\nreturn state;\n}\n- const pullResult = action.payload.threadInfos;\n- //const pushResult = pingPush(state.threadInfos, action.payload);\n+ const pollResult = action.payload.threadInfos;\n+ const pushResult = pingPush(state.threadInfos, action.payload);\nreturn {\n- threadInfos: pullResult,\n- inconsistencyResponses: state.inconsistencyResponses,\n+ threadInfos: pollResult,\n+ inconsistencyResponses: [\n+ ...state.inconsistencyResponses,\n+ ...findInconsistencies(\n+ state.threadInfos,\n+ action,\n+ pollResult,\n+ pushResult,\n+ ),\n+ ],\n};\n} else if (action.type === pingActionTypes.success) {\nconst payload = action.payload;\n- const pullResult = pingPull(state.threadInfos, payload);\n- //const pushResult = pingPush(state.threadInfos, payload);\n+ const pollResult = pingPoll(state.threadInfos, payload);\n+ const pushResult = pingPush(state.threadInfos, payload);\nreturn {\n- threadInfos: pullResult,\n- inconsistencyResponses: state.inconsistencyResponses,\n+ threadInfos: pollResult,\n+ inconsistencyResponses: [\n+ ...state.inconsistencyResponses.filter(\n+ request =>\n+ !payload.requests.deliveredClientResponses.includes(request),\n+ ),\n+ ...findInconsistencies(\n+ state.threadInfos,\n+ action,\n+ pollResult,\n+ pushResult,\n+ ),\n+ ],\n};\n} else if (action.type === newThreadActionTypes.success) {\nconst newThreadInfo = action.payload.newThreadInfo;\n@@ -223,14 +265,22 @@ export default function reduceThreadInfos(\n) {\nreturn state;\n}\n- const pullResult = {\n+ const pollResult = {\n...state.threadInfos,\n[newThreadInfo.id]: newThreadInfo,\n};\n- //const pushResult = pingPush(state, action.payload);\n+ const pushResult = pingPush(state.threadInfos, action.payload);\nreturn {\n- threadInfos: pullResult,\n- inconsistencyResponses: state.inconsistencyResponses,\n+ threadInfos: pollResult,\n+ inconsistencyResponses: [\n+ ...state.inconsistencyResponses,\n+ ...findInconsistencies(\n+ state.threadInfos,\n+ action,\n+ pollResult,\n+ pushResult,\n+ ),\n+ ],\n};\n} else if (action.type === updateActivityActionTypes.success) {\nconst newThreadInfos = { ...state.threadInfos };\n" }, { "change_type": "MODIFY", "old_path": "lib/selectors/ping-selectors.js", "new_path": "lib/selectors/ping-selectors.js", "diff": "@@ -5,7 +5,11 @@ import type { CalendarQuery, RawEntryInfo } from '../types/entry-types';\nimport type { CurrentUserInfo } from '../types/user-types';\nimport type { PingStartingPayload, PingActionInput } from '../types/ping-types';\nimport type { RawThreadInfo } from '../types/thread-types';\n-import { serverRequestTypes, type ServerRequest } from '../types/request-types';\n+import {\n+ serverRequestTypes,\n+ type ServerRequest,\n+ type ThreadPollPushInconsistencyClientResponse,\n+} from '../types/request-types';\nimport { createSelector } from 'reselect';\n@@ -46,6 +50,7 @@ const pingActionInput = createSelector(\n(state: BaseAppState<*>) => state.updatesCurrentAsOf,\n(state: BaseAppState<*>) => state.activeServerRequests,\n(state: BaseAppState<*>) => state.deviceToken,\n+ (state: BaseAppState<*>) => state.threadStore.inconsistencyResponses,\n(\nthreadInfos: {[id: string]: RawThreadInfo},\nentryInfos: {[id: string]: RawEntryInfo},\n@@ -54,8 +59,10 @@ const pingActionInput = createSelector(\nupdatesCurrentAsOf: number,\nactiveServerRequests: $ReadOnlyArray<ServerRequest>,\ndeviceToken: ?string,\n+ inconsistencyResponses:\n+ $ReadOnlyArray<ThreadPollPushInconsistencyClientResponse>,\n): (startingPayload: PingStartingPayload) => PingActionInput => {\n- const clientResponses = [];\n+ const clientResponses = [...inconsistencyResponses];\nfor (let serverRequest of activeServerRequests) {\nif (serverRequest.type === serverRequestTypes.PLATFORM) {\nclientResponses.push({\n" }, { "change_type": "MODIFY", "old_path": "lib/types/ping-types.js", "new_path": "lib/types/ping-types.js", "diff": "@@ -55,7 +55,10 @@ export type PingResult = {|\nloggedIn: bool,\nprevState: PingPrevState,\nupdatesResult: ?UpdatesResult,\n- serverRequests?: $ReadOnlyArray<ServerRequest>,\n+ requests: {\n+ serverRequests: $ReadOnlyArray<ServerRequest>,\n+ deliveredClientResponses: $ReadOnlyArray<ClientResponse>,\n+ },\n|};\nexport type PingStartingPayload = {|\n" }, { "change_type": "MODIFY", "old_path": "server/src/responders/ping-responders.js", "new_path": "server/src/responders/ping-responders.js", "diff": "@@ -105,6 +105,11 @@ async function pingResponder(\n},\n));\nviewerMissingDeviceToken = false;\n+ } else if (\n+ clientResponse.type ===\n+ serverRequestTypes.THREAD_POLL_PUSH_INCONSISTENCY\n+ ) {\n+ // TODO record here\n}\n}\n}\n@@ -161,6 +166,14 @@ async function pingResponder(\n...threadsResult.userInfos,\n});\n+ const serverRequests = [];\n+ if (viewerMissingPlatform) {\n+ serverRequests.push({ type: serverRequestTypes.PLATFORM });\n+ }\n+ if (viewerMissingDeviceToken) {\n+ serverRequests.push({ type: serverRequestTypes.DEVICE_TOKEN });\n+ }\n+\nconst messagesCurrentAsOf = mostRecentMessageTimestamp(\nmessagesResult.rawMessageInfos,\nclientMessagesCurrentAsOf,\n@@ -174,22 +187,12 @@ async function pingResponder(\nserverTime: messagesCurrentAsOf,\nrawEntryInfos: entriesResult.rawEntryInfos,\nuserInfos,\n+ serverRequests,\n};\nif (updatesResult) {\nresponse.updatesResult = updatesResult;\n}\n- const serverRequests = [];\n- if (viewerMissingPlatform) {\n- serverRequests.push({ type: serverRequestTypes.PLATFORM });\n- }\n- if (viewerMissingDeviceToken) {\n- serverRequests.push({ type: serverRequestTypes.DEVICE_TOKEN });\n- }\n- if (serverRequests.length > 0) {\n- response.serverRequests = serverRequests;\n- }\n-\nreturn response;\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
serverRequestTypes.THREAD_POLL_PUSH_INCONSISTENCY Inform the server when there is inconsistency between poll and push results for the `ThreadStore`.
129,187
25.06.2018 13:42:40
14,400
52dbd5da95928bcce4cbfd6d5c6942ce37847b92
Add platformDetails to registerConfig
[ { "change_type": "MODIFY", "old_path": "lib/actions/ping-actions.js", "new_path": "lib/actions/ping-actions.js", "diff": "@@ -8,7 +8,6 @@ import type {\n} from '../types/activity-types';\nimport threadWatcher from '../shared/thread-watcher';\n-import { getConfig } from '../utils/config';\nconst pingActionTypes = Object.freeze({\nstarted: \"PING_STARTED\",\n" }, { "change_type": "MODIFY", "old_path": "lib/actions/user-actions.js", "new_path": "lib/actions/user-actions.js", "diff": "@@ -69,7 +69,7 @@ async function register(\n): Promise<RegisterResult> {\nconst response = await fetchJSON(\n'create_account',\n- { ...registerInfo, platform: getConfig().platform },\n+ { ...registerInfo, platform: getConfig().platformDetails.platform },\n);\nreturn {\ncurrentUserInfo: {\n@@ -120,7 +120,7 @@ async function logIn(\n{\n...logInInfo,\nwatchedIDs,\n- platform: getConfig().platform,\n+ platform: getConfig().platformDetails.platform,\n},\n);\n@@ -167,7 +167,7 @@ async function resetPassword(\n{\n...updatePasswordInfo,\nwatchedIDs,\n- platform: getConfig().platform,\n+ platform: getConfig().platformDetails.platform,\n},\n);\n" }, { "change_type": "MODIFY", "old_path": "lib/selectors/ping-selectors.js", "new_path": "lib/selectors/ping-selectors.js", "diff": "@@ -67,7 +67,7 @@ const pingActionInput = createSelector(\nif (serverRequest.type === serverRequestTypes.PLATFORM) {\nclientResponses.push({\ntype: serverRequestTypes.PLATFORM,\n- platform: getConfig().platform,\n+ platform: getConfig().platformDetails.platform,\n});\n} else if (\nserverRequest.type === serverRequestTypes.DEVICE_TOKEN &&\n" }, { "change_type": "MODIFY", "old_path": "lib/types/device-types.js", "new_path": "lib/types/device-types.js", "diff": "@@ -23,3 +23,9 @@ export type DeviceTokenUpdateRequest = {|\ndeviceType: DeviceType,\ndeviceToken: string,\n|};\n+\n+export type PlatformDetails = {|\n+ platform: Platform,\n+ codeVersion?: number,\n+ stateVersion?: number,\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';\n-import type { Platform } from '../types/device-types';\n+import type { PlatformDetails } from '../types/device-types';\nimport invariant from 'invariant';\n@@ -15,7 +15,7 @@ export type Config = {\ngetNewCookie: ?((response: Object) => Promise<?string>),\nsetCookieOnRequest: bool,\ncalendarRangeInactivityLimit: ?number,\n- platform: Platform,\n+ platformDetails: PlatformDetails,\n};\nlet registeredConfig: ?Config = null;\n" }, { "change_type": "MODIFY", "old_path": "native/account/native-credentials.js", "new_path": "native/account/native-credentials.js", "diff": "@@ -14,7 +14,6 @@ import {\nimport URL from 'url-parse';\nimport { logInActionTypes, logIn } from 'lib/actions/user-actions';\n-import { getConfig } from 'lib/utils/config';\nimport { getDeviceTokenUpdateRequest } from '../utils/device-token-utils';\n" }, { "change_type": "MODIFY", "old_path": "native/app.react.js", "new_path": "native/app.react.js", "diff": "@@ -105,6 +105,7 @@ import {\n} from './push/android';\nimport NotificationBody from './push/notification-body.react';\nimport ErrorBoundary from './error-boundary.react';\n+import { persistConfig, codeVersion } from './persist';\nregisterConfig({\nresolveInvalidatedCookie,\n@@ -116,7 +117,11 @@ registerConfig({\n},\nsetCookieOnRequest: true,\ncalendarRangeInactivityLimit: sessionInactivityLimit,\n+ platformDetails: {\nplatform: Platform.OS,\n+ codeVersion,\n+ stateVersion: persistConfig.version,\n+ },\n});\nconst msInDay = 24 * 60 * 60 * 1000;\n" }, { "change_type": "MODIFY", "old_path": "web/app.react.js", "new_path": "web/app.react.js", "diff": "@@ -94,7 +94,7 @@ registerConfig({\nsetCookieOnRequest: false,\n// Never reset the calendar range\ncalendarRangeInactivityLimit: null,\n- platform: \"web\",\n+ platformDetails: { platform: \"web\" },\n});\ntype Props = {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Add platformDetails to registerConfig
129,187
26.06.2018 13:33:30
14,400
e3644a2a0b5146710952bb6ea4b4c3366bc47159
Generate a report for thread push/poll inconsistency
[ { "change_type": "MODIFY", "old_path": "lib/actions/report-actions.js", "new_path": "lib/actions/report-actions.js", "diff": "import type { FetchJSON } from '../utils/fetch-json';\nimport type {\n- ErrorReportCreationRequest,\n- ErrorReportCreationResponse,\n+ ReportCreationRequest,\n+ ReportCreationResponse,\n} from '../types/report-types';\n-const sendErrorReportActionTypes = Object.freeze({\n- started: \"SEND_ERROR_REPORT_STARTED\",\n- success: \"SEND_ERROR_REPORT_SUCCESS\",\n- failed: \"SEND_ERROR_REPORT_FAILED\",\n+const sendReportActionTypes = Object.freeze({\n+ started: \"SEND_REPORT_STARTED\",\n+ success: \"SEND_REPORT_SUCCESS\",\n+ failed: \"SEND_REPORT_FAILED\",\n});\nconst fetchJSONOptions = { timeout: 60000 };\n-async function sendErrorReport(\n+async function sendReport(\nfetchJSON: FetchJSON,\n- request: ErrorReportCreationRequest,\n-): Promise<ErrorReportCreationResponse> {\n+ request: ReportCreationRequest,\n+): Promise<ReportCreationResponse> {\nconst response = await fetchJSON(\n- 'create_error_report',\n+ 'create_report',\nrequest,\nfetchJSONOptions,\n);\n@@ -25,6 +25,6 @@ async function sendErrorReport(\n}\nexport {\n- sendErrorReportActionTypes,\n- sendErrorReport,\n+ sendReportActionTypes,\n+ sendReport,\n};\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/thread-reducer.js", "new_path": "lib/reducers/thread-reducer.js", "diff": "@@ -34,6 +34,7 @@ import {\npingActionTypes,\nupdateActivityActionTypes,\n} from '../actions/ping-actions';\n+import { getConfig } from '../utils/config';\nfunction pingPoll(\nthreadInfos: {[id: string]: RawThreadInfo},\n@@ -184,6 +185,7 @@ function findInconsistencies(\n}\nreturn [{\ntype: serverRequestTypes.THREAD_POLL_PUSH_INCONSISTENCY,\n+ platformDetails: getConfig().platformDetails,\nbeforeAction,\naction,\npollResult,\n" }, { "change_type": "MODIFY", "old_path": "lib/types/endpoints.js", "new_path": "lib/types/endpoints.js", "diff": "@@ -33,5 +33,6 @@ export const endpoint = Object.freeze({\nCREATE_ERROR_REPORT: 'create_error_report',\nFETCH_ERROR_REPORT_INFOS: 'fetch_error_report_infos',\nREQUEST_ACCESS: 'request_access',\n+ CREATE_REPORT: 'create_report',\n});\nexport type Endpoint = $Values<typeof endpoint>;\n" }, { "change_type": "MODIFY", "old_path": "lib/types/redux-types.js", "new_path": "lib/types/redux-types.js", "diff": "@@ -46,7 +46,7 @@ import type {\n} from './message-types';\nimport type { SetCookiePayload } from '../utils/action-utils';\nimport type { UpdateActivityResult } from './activity-types';\n-import type { ErrorReportCreationResponse } from './report-types';\n+import type { ReportCreationResponse } from './report-types';\nimport type { ServerRequest } from './request-types';\nimport type {\nCalendarFilter,\n@@ -498,16 +498,16 @@ export type BaseAction =\ntype: \"HANDLE_VERIFICATION_CODE_SUCCESS\",\nloadingInfo: LoadingInfo,\n|} | {|\n- type: \"SEND_ERROR_REPORT_STARTED\",\n+ type: \"SEND_REPORT_STARTED\",\nloadingInfo: LoadingInfo,\n|} | {|\n- type: \"SEND_ERROR_REPORT_FAILED\",\n+ type: \"SEND_REPORT_FAILED\",\nerror: true,\npayload: Error,\nloadingInfo: LoadingInfo,\n|} | {|\n- type: \"SEND_ERROR_REPORT_SUCCESS\",\n- payload: ErrorReportCreationResponse,\n+ type: \"SEND_REPORT_SUCCESS\",\n+ payload: ReportCreationResponse,\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"SET_URL_PREFIX\",\n" }, { "change_type": "MODIFY", "old_path": "lib/types/report-types.js", "new_path": "lib/types/report-types.js", "diff": "import type { BaseAppState, BaseAction } from './redux-types';\nimport type { UserInfo } from './user-types';\n-import type { DeviceType } from './device-types';\n+import type { PlatformDetails } from './device-types';\n+import type { RawThreadInfo } from './thread-types';\n+\n+import invariant from 'invariant';\n+\n+export const reportTypes = Object.freeze({\n+ ERROR: 0,\n+ THREAD_POLL_PUSH_INCONSISTENCY: 1,\n+});\n+type ReportType = $Values<typeof reportTypes>;\n+function assertReportType(reportType: number): ReportType {\n+ invariant(\n+ reportType === 0 ||\n+ reportType === 1,\n+ \"number is not ReportType enum\",\n+ );\n+ return reportType;\n+}\nexport type ErrorInfo = { componentStack: string };\nexport type ErrorData = {| error: Error, info?: ErrorInfo |};\n@@ -11,27 +28,35 @@ export type FlatErrorData = {|\ncomponentStack?: ?string,\n|};\n-export type ErrorReportCreationRequest = {|\n- deviceType: DeviceType,\n+type ErrorReportCreationRequest = {|\n+ type: 0,\n+ platformDetails: PlatformDetails,\nerrors: $ReadOnlyArray<FlatErrorData>,\npreloadedState: BaseAppState<*>,\ncurrentState: BaseAppState<*>,\nactions: $ReadOnlyArray<BaseAction>,\n- codeVersion: number,\n- stateVersion: number,\n|};\n+type ThreadPollPushInconsistencyReportCreationRequest = {|\n+ type: 1,\n+ platformDetails: PlatformDetails,\n+ beforeAction: {[id: string]: RawThreadInfo},\n+ action: BaseAction,\n+ pollResult: {[id: string]: RawThreadInfo},\n+ pushResult: {[id: string]: RawThreadInfo},\n+|};\n+export type ReportCreationRequest =\n+ | ErrorReportCreationRequest\n+ | ThreadPollPushInconsistencyReportCreationRequest;\n-export type ErrorReportCreationResponse = {|\n+export type ReportCreationResponse = {|\nid: string,\n|};\n-export type ErrorReportInfo = {|\n+type ReportInfo = {|\nid: string,\nviewerID: string,\n- deviceType: DeviceType,\n+ platformDetails: PlatformDetails,\ncreationTime: number,\n- codeVersion: number,\n- stateVersion: number,\n|};\nexport type FetchErrorReportInfosRequest = {|\n@@ -39,17 +64,10 @@ export type FetchErrorReportInfosRequest = {|\n|};\nexport type FetchErrorReportInfosResponse = {|\n- reports: $ReadOnlyArray<ErrorReportInfo>,\n+ reports: $ReadOnlyArray<ReportInfo>,\nuserInfos: $ReadOnlyArray<UserInfo>,\n|};\n-export type ErrorReport = {|\n- ...ErrorReportCreationRequest,\n- viewerID: string,\n- creationTime: number,\n- id: string,\n-|};\n-\nexport type ReduxToolsImport = {|\npreloadedState: BaseAppState<*>,\npayload: $ReadOnlyArray<BaseAction>,\n" }, { "change_type": "MODIFY", "old_path": "lib/types/request-types.js", "new_path": "lib/types/request-types.js", "diff": "// @flow\n-import type { Platform } from './device-types';\n+import type { Platform, PlatformDetails } from './device-types';\nimport type { RawThreadInfo } from './thread-types';\nimport type { BaseAction } from './redux-types';\n@@ -45,6 +45,7 @@ type DeviceTokenClientResponse = {|\nexport type ThreadPollPushInconsistencyClientResponse = {|\ntype: 2,\n+ platformDetails: PlatformDetails,\nbeforeAction: {[id: string]: RawThreadInfo},\naction: BaseAction,\npollResult: {[id: string]: RawThreadInfo},\n" }, { "change_type": "MODIFY", "old_path": "native/crash.react.js", "new_path": "native/crash.react.js", "diff": "// @flow\n-import type {\n- ErrorReportCreationRequest,\n- ErrorReportCreationResponse,\n+import {\n+ type ReportCreationRequest,\n+ type ReportCreationResponse,\n+ reportTypes,\n} from 'lib/types/report-types';\nimport type { DispatchActionPromise } from 'lib/utils/action-utils';\nimport type { AppState } from './redux-setup';\n@@ -25,10 +26,7 @@ import PropTypes from 'prop-types';\nimport invariant from 'invariant';\nimport { connect } from 'lib/utils/redux-utils';\n-import {\n- sendErrorReportActionTypes,\n- sendErrorReport,\n-} from 'lib/actions/report-actions';\n+import { sendReportActionTypes, sendReport } from 'lib/actions/report-actions';\nimport sleep from 'lib/utils/sleep';\nimport Button from './components/button.react';\n@@ -46,9 +44,9 @@ type Props = {\n// Redux dispatch functions\ndispatchActionPromise: DispatchActionPromise,\n// async functions that hit server APIs\n- sendErrorReport: (\n- request: ErrorReportCreationRequest,\n- ) => Promise<ErrorReportCreationResponse>,\n+ sendReport: (\n+ request: ReportCreationRequest,\n+ ) => Promise<ReportCreationResponse>,\n};\ntype State = {|\nerrorReportID: ?string,\n@@ -64,7 +62,7 @@ class Crash extends React.PureComponent<Props, State> {\n}),\n})).isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\n- sendErrorReport: PropTypes.func.isRequired,\n+ sendReport: PropTypes.func.isRequired,\n};\nerrorTitle = _shuffle(errorTitles)[0];\nstate = {\n@@ -74,7 +72,7 @@ class Crash extends React.PureComponent<Props, State> {\ncomponentDidMount() {\nthis.props.dispatchActionPromise(\n- sendErrorReportActionTypes,\n+ sendReportActionTypes,\nthis.sendReport(),\n);\nthis.timeOut();\n@@ -144,8 +142,13 @@ class Crash extends React.PureComponent<Props, State> {\n}\nasync sendReport() {\n- const result = await this.props.sendErrorReport({\n- deviceType: Platform.OS,\n+ const result = await this.props.sendReport({\n+ type: reportTypes.ERROR,\n+ platformDetails: {\n+ platform: Platform.OS,\n+ codeVersion,\n+ stateVersion: persistConfig.version,\n+ },\nerrors: this.props.errorData.map(data => ({\nerrorMessage: data.error.message,\ncomponentStack: data.info && data.info.componentStack,\n@@ -153,8 +156,6 @@ class Crash extends React.PureComponent<Props, State> {\npreloadedState: reduxLogger.preloadedState,\ncurrentState: store.getState(),\nactions: reduxLogger.actions,\n- codeVersion,\n- stateVersion: persistConfig.version,\n});\nthis.setState({\nerrorReportID: result.id,\n@@ -252,5 +253,5 @@ const styles = StyleSheet.create({\nexport default connect(\nundefined,\n- { sendErrorReport },\n+ { sendReport },\n)(Crash);\n" }, { "change_type": "DELETE", "old_path": "server/src/creators/error-report-creator.js", "new_path": null, "diff": "-// @flow\n-\n-import type { Viewer } from '../session/viewer';\n-import type {\n- ErrorReportCreationRequest,\n- ErrorReportCreationResponse,\n-} from 'lib/types/report-types';\n-\n-import { dbQuery, SQL } from '../database';\n-import createIDs from './id-creator';\n-\n-async function createErrorReport(\n- viewer: Viewer,\n- errorReport: ErrorReportCreationRequest,\n-): Promise<ErrorReportCreationResponse> {\n- const [ id ] = await createIDs(\"reports\", 1);\n- const { deviceType, ...report } = errorReport;\n- const row = [\n- id,\n- viewer.id,\n- deviceType,\n- JSON.stringify(report),\n- Date.now(),\n- ];\n- const query = SQL`\n- INSERT INTO reports (id, user, platform, report, creation_time)\n- VALUES ${[row]}\n- `;\n- await dbQuery(query);\n- return { id };\n-}\n-\n-export default createErrorReport;\n" }, { "change_type": "MODIFY", "old_path": "server/src/fetchers/report-fetchers.js", "new_path": "server/src/fetchers/report-fetchers.js", "diff": "@@ -38,10 +38,12 @@ async function fetchErrorReportInfos(\nreports.push({\nid: row.id.toString(),\nviewerID,\n- deviceType: row.platform,\n- creationTime: row.creation_time,\n+ platformDetails: {\n+ platform: row.platform,\ncodeVersion: row.report.codeVersion,\nstateVersion: row.report.stateVersion,\n+ },\n+ creationTime: row.creation_time,\n});\nif (row.username) {\nuserInfos[viewerID] = {\n" }, { "change_type": "MODIFY", "old_path": "server/src/responders/ping-responders.js", "new_path": "server/src/responders/ping-responders.js", "diff": "import type { PingRequest, PingResponse } from 'lib/types/ping-types';\nimport { defaultNumberPerThread } from 'lib/types/message-types';\nimport type { Viewer } from '../session/viewer';\n-import { serverRequestTypes } from 'lib/types/request-types';\n+import {\n+ serverRequestTypes,\n+ type ThreadPollPushInconsistencyClientResponse,\n+} from 'lib/types/request-types';\nimport { isDeviceType, assertDeviceType } from 'lib/types/device-types';\n+import { reportTypes } from 'lib/types/report-types';\nimport t from 'tcomb';\nimport invariant from 'invariant';\n@@ -27,6 +31,7 @@ import { fetchCurrentUserInfo } from '../fetchers/user-fetchers';\nimport { fetchUpdateInfos } from '../fetchers/update-fetchers';\nimport { recordDeliveredUpdate, setCookiePlatform } from '../session/cookies';\nimport { deviceTokenUpdater } from '../updaters/device-token-updaters';\n+import createReport from '../creators/report-creator';\nconst pingRequestInputValidator = tShape({\ncalendarQuery: entryQueryInputValidator,\n@@ -109,7 +114,10 @@ async function pingResponder(\nclientResponse.type ===\nserverRequestTypes.THREAD_POLL_PUSH_INCONSISTENCY\n) {\n- // TODO record here\n+ clientResponsePromises.push(recordThreadPollPushInconsistency(\n+ viewer,\n+ clientResponse,\n+ ));\n}\n}\n}\n@@ -196,6 +204,18 @@ async function pingResponder(\nreturn response;\n}\n+async function recordThreadPollPushInconsistency(\n+ viewer: Viewer,\n+ response: ThreadPollPushInconsistencyClientResponse,\n+): Promise<void> {\n+ const { type, ...rest } = response;\n+ const reportCreationRequest = {\n+ ...rest,\n+ type: reportTypes.THREAD_POLL_PUSH_INCONSISTENCY,\n+ };\n+ await createReport(viewer, reportCreationRequest);\n+}\n+\nexport {\npingResponder,\n};\n" }, { "change_type": "MODIFY", "old_path": "server/src/responders/report-responders.js", "new_path": "server/src/responders/report-responders.js", "diff": "// @flow\n-import type {\n- ErrorReportCreationResponse,\n- ErrorReportCreationRequest,\n- FetchErrorReportInfosResponse,\n- FetchErrorReportInfosRequest,\n+import {\n+ type ReportCreationResponse,\n+ type ReportCreationRequest,\n+ type FetchErrorReportInfosResponse,\n+ type FetchErrorReportInfosRequest,\n+ reportTypes,\n} from 'lib/types/report-types';\nimport type { Viewer } from '../session/viewer';\nimport type { $Response, $Request } from 'express';\n@@ -13,15 +14,28 @@ import t from 'tcomb';\nimport { ServerError } from 'lib/utils/errors';\n-import { validateInput, tShape } from '../utils/validation-utils';\n-import createErrorReport from '../creators/error-report-creator';\n+import {\n+ validateInput,\n+ tShape,\n+ tPlatform,\n+ tPlatformDetails,\n+} from '../utils/validation-utils';\n+import createReport from '../creators/report-creator';\nimport {\nfetchErrorReportInfos,\nfetchReduxToolsImport,\n} from '../fetchers/report-fetchers';\n-const errorReportCreationRequestInputValidator = tShape({\n- deviceType: t.enums.of(['ios', 'android']),\n+const reportCreationRequestInputValidator = t.union([\n+ tShape({\n+ type: t.maybe(t.irreducible(\n+ 'reportTypes.ERROR',\n+ x => x === reportTypes.ERROR,\n+ )),\n+ platformDetails: t.maybe(tPlatformDetails),\n+ deviceType: t.maybe(tPlatform),\n+ codeVersion: t.maybe(t.Number),\n+ stateVersion: t.maybe(t.Number),\nerrors: t.list(tShape({\nerrorMessage: t.String,\ncomponentStack: t.maybe(t.String),\n@@ -29,17 +43,37 @@ const errorReportCreationRequestInputValidator = tShape({\npreloadedState: t.Object,\ncurrentState: t.Object,\nactions: t.list(t.Object),\n- codeVersion: t.Number,\n- stateVersion: t.Number,\n-});\n+ }),\n+ tShape({\n+ type: t.irreducible(\n+ 'reportTypes.THREAD_POLL_PUSH_INCONSISTENCY',\n+ x => x === reportTypes.THREAD_POLL_PUSH_INCONSISTENCY,\n+ ),\n+ platformDetails: tPlatformDetails,\n+ beforeAction: t.Object,\n+ action: t.Object,\n+ pollResult: t.Object,\n+ pushResult: t.Object,\n+ }),\n+]);\n-async function errorReportCreationResponder(\n+async function reportCreationResponder(\nviewer: Viewer,\ninput: any,\n-): Promise<ErrorReportCreationResponse> {\n- const request: ErrorReportCreationRequest = input;\n- validateInput(errorReportCreationRequestInputValidator, request);\n- return await createErrorReport(viewer, request);\n+): Promise<ReportCreationResponse> {\n+ validateInput(reportCreationRequestInputValidator, input);\n+ if (input.type === null || input.type === undefined) {\n+ input.type = reportTypes.ERROR;\n+ }\n+ if (!input.platformDetails && input.deviceType) {\n+ const { deviceType, codeVersion, stateVersion, ...rest } = input;\n+ input = {\n+ ...rest,\n+ platformDetails: { platform: deviceType, codeVersion, stateVersion },\n+ };\n+ }\n+ const request: ReportCreationRequest = input;\n+ return await createReport(viewer, request);\n}\nconst fetchErrorReportInfosRequestInputValidator = tShape({\n@@ -73,7 +107,7 @@ async function errorReportDownloadHandler(\n}\nexport {\n- errorReportCreationResponder,\n+ reportCreationResponder,\nerrorReportFetchInfosResponder,\nerrorReportDownloadHandler,\n};\n" }, { "change_type": "MODIFY", "old_path": "server/src/responders/user-responders.js", "new_path": "server/src/responders/user-responders.js", "diff": "@@ -154,7 +154,7 @@ const registerRequestInputValidator = tShape({\nusername: t.String,\nemail: t.String,\npassword: t.String,\n- platform: tPlatform,\n+ platform: t.maybe(tPlatform),\n});\nasync function accountCreationResponder(\n@@ -172,7 +172,7 @@ const logInRequestInputValidator = tShape({\nwatchedIDs: t.list(t.String),\ncalendarQuery: t.maybe(entryQueryInputValidator),\ndeviceTokenUpdateRequest: t.maybe(deviceTokenUpdateRequestInputValidator),\n- platform: tPlatform,\n+ platform: t.maybe(tPlatform),\n});\nasync function logInResponder(\n@@ -262,7 +262,7 @@ const updatePasswordRequestInputValidator = tShape({\nwatchedIDs: t.list(t.String),\ncalendarQuery: t.maybe(entryQueryInputValidator),\ndeviceTokenUpdateRequest: t.maybe(deviceTokenUpdateRequestInputValidator),\n- platform: tPlatform,\n+ platform: t.maybe(tPlatform),\n});\nasync function passwordUpdateResponder(\n" }, { "change_type": "MODIFY", "old_path": "server/src/server.js", "new_path": "server/src/server.js", "diff": "@@ -55,7 +55,7 @@ import {\nimport { pingResponder } from './responders/ping-responders';\nimport { websiteResponder } from './responders/website-responders';\nimport {\n- errorReportCreationResponder,\n+ reportCreationResponder,\nerrorReportFetchInfosResponder,\nerrorReportDownloadHandler,\n} from './responders/report-responders';\n@@ -94,7 +94,8 @@ const jsonEndpoints: {[id: Endpoint]: JSONResponder} = {\n'create_account': accountCreationResponder,\n'log_in': logInResponder,\n'update_password': passwordUpdateResponder,\n- 'create_error_report': errorReportCreationResponder,\n+ 'create_error_report': reportCreationResponder,\n+ 'create_report': reportCreationResponder,\n'fetch_error_report_infos': errorReportFetchInfosResponder,\n'request_access': requestAccessResponder,\n};\n" }, { "change_type": "MODIFY", "old_path": "server/src/utils/validation-utils.js", "new_path": "server/src/utils/validation-utils.js", "diff": "@@ -18,7 +18,7 @@ function tString(value: string) {\nreturn t.irreducible('literal string', x => x === value);\n}\n-function tShape(spec: *) {\n+function tShape(spec: {[key: string]: *}) {\nreturn t.interface(spec, { strict: true });\n}\n@@ -42,8 +42,13 @@ function tNumEnum(assertFunc: (input: number) => *) {\nconst tDate = tRegex(/^[0-9]{4}-[0-1][0-9]-[0-3][0-9]$/);\nconst tColor = tRegex(/^[a-fA-F0-9]{6}$/); // we don't include # char\n-const tPlatform = t.maybe(t.enums.of(['ios', 'android', 'web']));\n-const tDeviceType = t.maybe(t.enums.of(['ios', 'android']));\n+const tPlatform = t.enums.of(['ios', 'android', 'web']);\n+const tDeviceType = t.enums.of(['ios', 'android']);\n+const tPlatformDetails = tShape({\n+ platform: tPlatform,\n+ codeVersion: t.maybe(t.Number),\n+ stateVersion: t.maybe(t.Number),\n+});\nexport {\nvalidateInput,\n@@ -56,4 +61,5 @@ export {\ntColor,\ntPlatform,\ntDeviceType,\n+ tPlatformDetails,\n};\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Generate a report for thread push/poll inconsistency
129,187
26.06.2018 14:04:51
14,400
b15aba9f5b9de7da6e1f402a022eec17be7bbb44
[server] Stop deleting all the entries in the ids table Oops. At least this table doesn't actually currently matter...
[ { "change_type": "MODIFY", "old_path": "server/src/deleters/thread-deleters.js", "new_path": "server/src/deleters/thread-deleters.js", "diff": "@@ -73,7 +73,7 @@ async function deleteThread(\nLEFT JOIN ids ire ON ire.id = re.id\nLEFT JOIN memberships mm ON mm.thread = t.id\nLEFT JOIN roles r ON r.thread = t.id\n- LEFT JOIN ids ir ON r.thread = t.id\n+ LEFT JOIN ids ir ON ir.id = r.id\nLEFT JOIN messages ms ON ms.thread = t.id\nLEFT JOIN ids im ON im.id = ms.id\nLEFT JOIN focused f ON f.thread = t.id\n@@ -121,7 +121,7 @@ async function deleteInaccessibleThreads(): Promise<void> {\nLEFT JOIN revisions re ON re.entry = e.id\nLEFT JOIN ids ire ON ire.id = re.id\nLEFT JOIN roles r ON r.thread = t.id\n- LEFT JOIN ids ir ON r.thread = t.id\n+ LEFT JOIN ids ir ON ir.id = r.id\nLEFT JOIN messages ms ON ms.thread = t.id\nLEFT JOIN ids im ON im.id = ms.id\nLEFT JOIN focused f ON f.thread = t.id\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Stop deleting all the entries in the ids table Oops. At least this table doesn't actually currently matter...
129,187
26.06.2018 15:10:52
14,400
ec14aa5397fb2d7d5e1b1f6dc025674e521301b2
Some bugfixes for the last several dozen commits
[ { "change_type": "MODIFY", "old_path": "lib/reducers/message-reducer.js", "new_path": "lib/reducers/message-reducer.js", "diff": "@@ -216,6 +216,10 @@ function mergeNewMessages(\nlastPruned: oldThread.lastPruned,\n};\n}\n+ const oldNotInNew = _difference(oldThread.messageIDs)(messageIDs);\n+ for (let messageID of oldNotInNew) {\n+ oldMessageInfosToCombine.push(oldMessageStore.messages[messageID]);\n+ }\nconst startReached = oldThread.startReached ||\ntruncate === messageTruncationStatus.EXHAUSTIVE;\nif (_difference(messageIDs)(oldThread.messageIDs).length === 0) {\n@@ -231,10 +235,6 @@ function mergeNewMessages(\nlastPruned: oldThread.lastPruned,\n};\n}\n- const oldNotInNew = _difference(oldThread.messageIDs)(messageIDs);\n- for (let messageID of oldNotInNew) {\n- oldMessageInfosToCombine.push(oldMessageStore.messages[messageID]);\n- }\nconst mergedMessageIDs = [ ...messageIDs, ...oldNotInNew ];\nmustResortThreadMessageIDs.push(threadID);\nreturn {\n" }, { "change_type": "MODIFY", "old_path": "server/src/creators/message-creator.js", "new_path": "server/src/creators/message-creator.js", "diff": "@@ -222,8 +222,8 @@ async function updateUnreadStatus(\nconst [ result ] = await dbQuery(query);\nconst setUnreadPairs = result.map(row => ({\n- userID: row.user.toString,\n- threadID: row.thread.toString,\n+ userID: row.user.toString(),\n+ threadID: row.thread.toString(),\n}));\nconst updateConditions = setUnreadPairs.map(\npair => SQL`(user = ${pair.userID} AND thread = ${pair.threadID})`,\n@@ -233,7 +233,7 @@ async function updateUnreadStatus(\nSET unread = 1\nWHERE\n`;\n- updateQuery.append(mergeOrConditions(threadConditionClauses));\n+ updateQuery.append(mergeOrConditions(updateConditions));\nconst now = Date.now();\nawait Promise.all([\n" }, { "change_type": "MODIFY", "old_path": "server/src/creators/update-creator.js", "new_path": "server/src/creators/update-creator.js", "diff": "@@ -241,9 +241,9 @@ async function createUpdates(\nif (insertRows.length > 0) {\nconst insertQuery = viewerInfo\n? SQL`\n- INSERT INTO updates(id, user, type, key, content, time, updater_cookie)\n+ INSERT INTO updates(id, user, type, \\`key\\`, content, time, updater_cookie)\n`\n- : SQL`INSERT INTO updates(id, user, type, key, content, time) `;\n+ : SQL`INSERT INTO updates(id, user, type, \\`key\\`, content, time) `;\ninsertQuery.append(SQL`VALUES ${insertRows}`);\npromises.insert = dbQuery(insertQuery);\n}\n@@ -279,12 +279,12 @@ async function fetchUpdateInfosWithUpdateDatas(\n): Promise<FetchUpdatesResult> {\nconst threadIDsNeedingFetch = new Set();\nconst threadIDsNeedingDetailedFetch = new Set(); // entries and messages\n- if (!viewerInfo.threadInfos) {\nfor (let viewerUpdateData of updateDatas) {\nconst updateData = viewerUpdateData.data;\nif (\n- updateData.type === updateTypes.UPDATE_THREAD ||\n- updateData.type === updateTypes.JOIN_THREAD\n+ !viewerInfo.threadInfos &&\n+ (updateData.type === updateTypes.UPDATE_THREAD ||\n+ updateData.type === updateTypes.JOIN_THREAD)\n) {\nthreadIDsNeedingFetch.add(updateData.threadID);\n}\n@@ -292,7 +292,6 @@ async function fetchUpdateInfosWithUpdateDatas(\nthreadIDsNeedingDetailedFetch.add(updateData.threadID);\n}\n}\n- }\nconst promises = {};\n@@ -305,9 +304,9 @@ async function fetchUpdateInfosWithUpdateDatas(\nlet calendarQuery;\nif (threadIDsNeedingDetailedFetch.size > 0) {\n- const threadSelectionCriteria = {};\n+ const threadSelectionCriteria = { threadCursors: {} };\nfor (let threadID of threadIDsNeedingDetailedFetch) {\n- threadSelectionCriteria[threadID] = false;\n+ threadSelectionCriteria.threadCursors[threadID] = false;\n}\npromises.messageInfosResult = fetchMessageInfos(\nviewerInfo.viewer,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Some bugfixes for the last several dozen commits
129,187
26.06.2018 18:38:42
14,400
86f18aaf66cab664eb12fc22f2237d170749c90e
Introducing squadbot, who will send me messages when reports are created
[ { "change_type": "ADD", "old_path": null, "new_path": "lib/facts/bots.json", "diff": "+{\n+ \"squadbot\": {\n+ \"userID\": \"5\",\n+ \"ashoatThreadID\": \"83793\"\n+ }\n+}\n" }, { "change_type": "MODIFY", "old_path": "server/src/creators/report-creator.js", "new_path": "server/src/creators/report-creator.js", "diff": "// @flow\nimport type { Viewer } from '../session/viewer';\n-import type {\n- ReportCreationRequest,\n- ReportCreationResponse,\n+import {\n+ type ReportCreationRequest,\n+ type ReportCreationResponse,\n+ reportTypes,\n} from 'lib/types/report-types';\n+import { messageTypes } from 'lib/types/message-types';\n+\n+import bots from 'lib/facts/bots';\n+import _isEqual from 'lodash/fp/isEqual';\nimport { dbQuery, SQL } from '../database';\nimport createIDs from './id-creator';\n+import { fetchUsername } from '../fetchers/user-fetchers';\n+import urlFacts from '../../facts/url';\n+import createMessages from './message-creator';\n+\n+const { baseDomain, basePath, https } = urlFacts;\n+const { squadbot } = bots;\nasync function createReport(\nviewer: Viewer,\n@@ -28,7 +39,69 @@ async function createReport(\nVALUES ${[row]}\n`;\nawait dbQuery(query);\n+ sendSquadbotMessage(viewer, request, id);\nreturn { id };\n}\n+async function sendSquadbotMessage(\n+ viewer: Viewer,\n+ request: ReportCreationRequest,\n+ reportID: string,\n+): Promise<void> {\n+ const canGenerateMessage = getSquadbotMessage(request, reportID, null);\n+ if (!canGenerateMessage) {\n+ return;\n+ }\n+ const username = await fetchUsername(viewer.id);\n+ const message = getSquadbotMessage(request, reportID, username);\n+ if (!message) {\n+ return;\n+ }\n+ const time = Date.now();\n+ await createMessages([{\n+ type: messageTypes.TEXT,\n+ threadID: squadbot.ashoatThreadID,\n+ creatorID: squadbot.userID,\n+ time,\n+ text: message,\n+ }]);\n+}\n+\n+function getSquadbotMessage(\n+ request: ReportCreationRequest,\n+ reportID: string,\n+ username: ?string,\n+): ?string {\n+ const name = username ? username : \"[null]\";\n+ const { platformDetails } = request;\n+ const { platform, codeVersion } = platformDetails;\n+ const platformString = codeVersion ? `${platform} v${codeVersion}` : platform;\n+ if (request.type === reportTypes.ERROR) {\n+ const protocol = https ? \"https\" : \"http\";\n+ return `${name} got an error :(\\n` +\n+ `using ${platformString}\\n` +\n+ `${baseDomain}${basePath}download_error_report/${reportID}`;\n+ } else if (request.type === reportTypes.THREAD_POLL_PUSH_INCONSISTENCY) {\n+ const { pushResult, pollResult, action } = request;\n+ const nonMatchingThreadIDs = new Set();\n+ for (let threadID in pollResult) {\n+ if (!_isEqual(pushResult[threadID])(pollResult[threadID])) {\n+ nonMatchingThreadIDs.add(threadID);\n+ }\n+ }\n+ for (let threadID in pushResult) {\n+ if (!pollResult[threadID]) {\n+ nonMatchingThreadIDs.add(threadID);\n+ }\n+ }\n+ const nonMatchingString = [...nonMatchingThreadIDs].join(\", \");\n+ return `system detected poll/push inconsistency for ${name}!\\n` +\n+ `using ${platformString}\\n` +\n+ `occurred during ${action.type}\\n` +\n+ `thread IDs that are inconsistent: ${nonMatchingString}`;\n+ } else {\n+ return null;\n+ }\n+}\n+\nexport default createReport;\n" }, { "change_type": "MODIFY", "old_path": "server/src/fetchers/user-fetchers.js", "new_path": "server/src/fetchers/user-fetchers.js", "diff": "@@ -95,10 +95,21 @@ async function fetchAllUserIDs(): Promise<string[]> {\nreturn result.map(row => row.id.toString());\n}\n+async function fetchUsername(id: string): Promise<?string> {\n+ const query = SQL`SELECT username FROM users WHERE id = ${id}`;\n+ const [ result ] = await dbQuery(query);\n+ if (result.length === 0) {\n+ return null;\n+ }\n+ const row = result[0];\n+ return row.username;\n+}\n+\nexport {\nfetchUserInfos,\nverifyUserIDs,\nverifyUserOrCookieIDs,\nfetchCurrentUserInfo,\nfetchAllUserIDs,\n+ fetchUsername,\n};\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Introducing squadbot, who will send me messages when reports are created
129,187
03.07.2018 14:04:05
14,400
aaecb86ad5e5d55a986693b6e77246f2ca5a83fb
[lib] Set threads to unread when notifs indicate new messages Unrelatedly, handle legacy server response for `serverRequests` field on ping.
[ { "change_type": "MODIFY", "old_path": "lib/actions/ping-actions.js", "new_path": "lib/actions/ping-actions.js", "diff": "@@ -45,7 +45,7 @@ async function ping(\nprevState: actionInput.prevState,\nupdatesResult: response.updatesResult,\nrequests: {\n- serverRequests: response.serverRequests,\n+ serverRequests: response.serverRequests ? response.serverRequests : [],\ndeliveredClientResponses: actionInput.clientResponses,\n},\n};\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/thread-reducer.js", "new_path": "lib/reducers/thread-reducer.js", "diff": "@@ -34,6 +34,7 @@ import {\npingActionTypes,\nupdateActivityActionTypes,\n} from '../actions/ping-actions';\n+import { saveMessagesActionType } from '../actions/message-actions';\nimport { getConfig } from '../utils/config';\nfunction pingPoll(\n@@ -311,6 +312,36 @@ export default function reduceThreadInfos(\nthreadInfos: newThreadInfos,\ninconsistencyResponses: state.inconsistencyResponses,\n};\n+ } else if (action.type === saveMessagesActionType) {\n+ const threadIDs = new Set();\n+ for (let messageInfo of action.payload.rawMessageInfos) {\n+ threadIDs.add(messageInfo.threadID);\n+ }\n+ const changedThreadInfos = {};\n+ for (let threadID of threadIDs) {\n+ if (\n+ !state.threadInfos[threadID] ||\n+ state.threadInfos[threadID].currentUser.unread\n+ ) {\n+ continue;\n+ }\n+ changedThreadInfos[threadID] = {\n+ ...state.threadInfos[threadID],\n+ currentUser: {\n+ ...state.threadInfos[threadID].currentUser,\n+ unread: true,\n+ },\n+ };\n+ }\n+ if (Object.keys(changedThreadInfos).length !== 0) {\n+ return {\n+ threadInfos: {\n+ ...state.threadInfos,\n+ ...changedThreadInfos,\n+ },\n+ inconsistencyResponses: state.inconsistencyResponses,\n+ };\n+ }\n}\nreturn state;\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[lib] Set threads to unread when notifs indicate new messages Unrelatedly, handle legacy server response for `serverRequests` field on ping.
129,187
03.07.2018 15:23:16
14,400
b6bb56f52eefddb11e3d25d5684754739cec8a51
[server] Catch exceptions thrown by async calls Make sure we try-catch the promises we set to run in the background, as exceptions from these will soon cause Node to crash the thread.
[ { "change_type": "MODIFY", "old_path": "server/src/creators/message-creator.js", "new_path": "server/src/creators/message-creator.js", "diff": "@@ -28,6 +28,7 @@ import {\nimport createIDs from './id-creator';\nimport { sendPushNotifs } from '../push/send';\nimport { createUpdates } from './update-creator';\n+import { handleAsyncPromise } from '../responders/handlers';\ntype ThreadRestriction = {|\ncreatorID?: ?string,\n@@ -152,13 +153,13 @@ async function createMessages(\n}\n// These return Promises but we don't want to wait on them\n- sendPushNotifsForNewMessages(\n+ handleAsyncPromise(sendPushNotifsForNewMessages(\nthreadRestrictions,\nsubthreadPermissionsToCheck,\nthreadsToNotifMessageIndices,\nmessageInfos,\n- );\n- updateUnreadStatus(threadRestrictions);\n+ ));\n+ handleAsyncPromise(updateUnreadStatus(threadRestrictions));\nconst messageInsertQuery = SQL`\nINSERT INTO messages(id, thread, user, type, content, time)\n" }, { "change_type": "MODIFY", "old_path": "server/src/creators/report-creator.js", "new_path": "server/src/creators/report-creator.js", "diff": "@@ -16,6 +16,7 @@ import createIDs from './id-creator';\nimport { fetchUsername } from '../fetchers/user-fetchers';\nimport urlFacts from '../../facts/url';\nimport createMessages from './message-creator';\n+import { handleAsyncPromise } from '../responders/handlers';\nconst { baseDomain, basePath, https } = urlFacts;\nconst { squadbot } = bots;\n@@ -39,7 +40,7 @@ async function createReport(\nVALUES ${[row]}\n`;\nawait dbQuery(query);\n- sendSquadbotMessage(viewer, request, id);\n+ handleAsyncPromise(sendSquadbotMessage(viewer, request, id));\nreturn { id };\n}\n" }, { "change_type": "MODIFY", "old_path": "server/src/deleters/account-deleters.js", "new_path": "server/src/deleters/account-deleters.js", "diff": "@@ -15,6 +15,7 @@ import { dbQuery, SQL } from '../database';\nimport { createNewAnonymousCookie } from '../session/cookies';\nimport { fetchAllUserIDs } from '../fetchers/user-fetchers';\nimport { createUpdates } from '../creators/update-creator';\n+import { handleAsyncPromise } from '../responders/handlers';\nasync function deleteAccount(\nviewer: Viewer,\n@@ -56,7 +57,7 @@ async function deleteAccount(\n]);\nviewer.setNewCookie(anonymousViewerData);\n- createAccountDeletionUpdates(deletedUserID);\n+ handleAsyncPromise(createAccountDeletionUpdates(deletedUserID));\nreturn {\ncurrentUserInfo: {\n" }, { "change_type": "MODIFY", "old_path": "server/src/emails/access-request.js", "new_path": "server/src/emails/access-request.js", "diff": "@@ -41,7 +41,7 @@ async function sendAccessRequestEmailToAshoat(\n);\nconst html = renderEmail(email);\n- sendmail.sendMail({\n+ await sendmail.sendMail({\nfrom: \"no-reply@squadcal.org\",\nto: ashoat.email,\nsubject: title,\n" }, { "change_type": "MODIFY", "old_path": "server/src/emails/reset-password.js", "new_path": "server/src/emails/reset-password.js", "diff": "@@ -40,7 +40,7 @@ async function sendPasswordResetEmail(\n);\nconst html = renderEmail(email);\n- sendmail.sendMail({\n+ await sendmail.sendMail({\nfrom: \"no-reply@squadcal.org\",\nto: emailAddress,\nsubject: title,\n" }, { "change_type": "MODIFY", "old_path": "server/src/emails/verification.js", "new_path": "server/src/emails/verification.js", "diff": "@@ -49,7 +49,7 @@ async function sendEmailAddressVerificationEmail(\n);\nconst html = renderEmail(email);\n- sendmail.sendMail({\n+ await sendmail.sendMail({\nfrom: \"no-reply@squadcal.org\",\nto: emailAddress,\nsubject: title,\n" }, { "change_type": "MODIFY", "old_path": "server/src/responders/handlers.js", "new_path": "server/src/responders/handlers.js", "diff": "@@ -66,6 +66,14 @@ function handleException(error: Error, res: $Response) {\n}\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@@ -86,4 +94,5 @@ export {\njsonHandler,\ndownloadHandler,\nhtmlHandler,\n+ handleAsyncPromise,\n};\n" }, { "change_type": "MODIFY", "old_path": "server/src/session/cookies.js", "new_path": "server/src/session/cookies.js", "diff": "@@ -19,6 +19,7 @@ import urlFacts from '../../facts/url';\nimport createIDs from '../creators/id-creator';\nimport { assertSecureRequest } from '../utils/security-utils';\nimport { deleteCookie } from '../deleters/cookie-deleters';\n+import { handleAsyncPromise } from '../responders/handlers';\nconst { baseDomain, basePath, https } = urlFacts;\n@@ -361,7 +362,7 @@ async function addCookieToJSONResponse(\nreturn;\n}\nif (!viewer.getData().insertionTime) {\n- extendCookieLifespan(viewer.cookieID);\n+ handleAsyncPromise(extendCookieLifespan(viewer.cookieID));\n}\nif (viewer.initializationSource !== cookieSource.BODY) {\nres.cookie(\n@@ -377,7 +378,7 @@ async function addCookieToJSONResponse(\nfunction addCookieToHomeResponse(viewer: Viewer, res: $Response) {\nif (!viewer.getData().insertionTime) {\n- extendCookieLifespan(viewer.cookieID);\n+ handleAsyncPromise(extendCookieLifespan(viewer.cookieID));\n}\nres.cookie(\nviewer.cookieName,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Catch exceptions thrown by async calls Make sure we try-catch the promises we set to run in the background, as exceptions from these will soon cause Node to crash the thread.
129,187
04.07.2018 11:03:01
14,400
8095d17ab985914ffe9206a5cade85e8bbaa34c8
Have server maintain all PlatformDetails for native clients We want to know `codeVersion` and `stateVersion` for all applicable cookies.
[ { "change_type": "MODIFY", "old_path": "lib/actions/user-actions.js", "new_path": "lib/actions/user-actions.js", "diff": "@@ -69,7 +69,7 @@ async function register(\n): Promise<RegisterResult> {\nconst response = await fetchJSON(\n'create_account',\n- { ...registerInfo, platform: getConfig().platformDetails.platform },\n+ { ...registerInfo, platformDetails: getConfig().platformDetails },\n);\nreturn {\ncurrentUserInfo: {\n@@ -120,7 +120,7 @@ async function logIn(\n{\n...logInInfo,\nwatchedIDs,\n- platform: getConfig().platformDetails.platform,\n+ platformDetails: getConfig().platformDetails,\n},\n);\n@@ -167,7 +167,7 @@ async function resetPassword(\n{\n...updatePasswordInfo,\nwatchedIDs,\n- platform: getConfig().platformDetails.platform,\n+ platformDetails: getConfig().platformDetails,\n},\n);\n" }, { "change_type": "MODIFY", "old_path": "lib/selectors/ping-selectors.js", "new_path": "lib/selectors/ping-selectors.js", "diff": "@@ -40,6 +40,7 @@ const pingStartingPayload = createSelector(\n},\n);\n+let initialPlatformDetailsSentAsOf = null;\n// This gets generated and passed in to the action function, which then passes\n// it on in the PING_SUCCESS payload\nconst pingActionInput = createSelector(\n@@ -51,6 +52,7 @@ const pingActionInput = createSelector(\n(state: BaseAppState<*>) => state.activeServerRequests,\n(state: BaseAppState<*>) => state.deviceToken,\n(state: BaseAppState<*>) => state.threadStore.inconsistencyResponses,\n+ (state: BaseAppState<*>) => state.pingTimestamps.lastSuccess,\n(\nthreadInfos: {[id: string]: RawThreadInfo},\nentryInfos: {[id: string]: RawEntryInfo},\n@@ -61,8 +63,10 @@ const pingActionInput = createSelector(\ndeviceToken: ?string,\ninconsistencyResponses:\n$ReadOnlyArray<ThreadPollPushInconsistencyClientResponse>,\n+ lastSuccess: number,\n): (startingPayload: PingStartingPayload) => PingActionInput => {\nconst clientResponses = [...inconsistencyResponses];\n+ let serverRequestedPlatformDetails = false;\nfor (let serverRequest of activeServerRequests) {\nif (serverRequest.type === serverRequestTypes.PLATFORM) {\nclientResponses.push({\n@@ -77,7 +81,26 @@ const pingActionInput = createSelector(\ntype: serverRequestTypes.DEVICE_TOKEN,\ndeviceToken,\n});\n+ } else if (serverRequest.type === serverRequestTypes.PLATFORM_DETAILS) {\n+ serverRequestedPlatformDetails = true;\n+ clientResponses.push({\n+ type: serverRequestTypes.PLATFORM_DETAILS,\n+ platformDetails: getConfig().platformDetails,\n+ });\n+ }\n}\n+ // Whenever the app starts up, it's possible that the version has updated.\n+ // We always communicate the PlatformDetails in that case.\n+ if (\n+ !serverRequestedPlatformDetails &&\n+ (initialPlatformDetailsSentAsOf === null ||\n+ initialPlatformDetailsSentAsOf === lastSuccess)\n+ ) {\n+ initialPlatformDetailsSentAsOf = lastSuccess;\n+ clientResponses.push({\n+ type: serverRequestTypes.PLATFORM_DETAILS,\n+ platformDetails: getConfig().platformDetails,\n+ });\n}\nreturn (startingPayload: PingStartingPayload) => ({\nloggedIn: startingPayload.loggedIn,\n" }, { "change_type": "MODIFY", "old_path": "lib/types/account-types.js", "new_path": "lib/types/account-types.js", "diff": "@@ -18,7 +18,7 @@ import type {\n} from './message-types';\nimport type {\nDeviceTokenUpdateRequest,\n- Platform,\n+ PlatformDetails,\nDeviceType,\n} from './device-types';\nimport type { UpdateInfo, UpdatesResult } from './update-types';\n@@ -47,7 +47,7 @@ export type RegisterRequest = {|\nusername: string,\nemail: string,\npassword: string,\n- platform?: Platform,\n+ platformDetails?: PlatformDetails,\n|};\nexport type RegisterResponse = {|\n@@ -91,7 +91,7 @@ export type LogInRequest = {|\npassword: string,\ncalendarQuery?: ?CalendarQuery,\ndeviceTokenUpdateRequest?: ?DeviceTokenUpdateRequest,\n- platform?: Platform,\n+ platformDetails?: PlatformDetails,\nwatchedIDs: $ReadOnlyArray<string>,\n|};\n@@ -125,7 +125,7 @@ export type UpdatePasswordRequest = {|\npassword: string,\ncalendarQuery?: ?CalendarQuery,\ndeviceTokenUpdateRequest?: ?DeviceTokenUpdateRequest,\n- platform?: Platform,\n+ platformDetails?: PlatformDetails,\nwatchedIDs: $ReadOnlyArray<string>,\n|};\n" }, { "change_type": "MODIFY", "old_path": "lib/types/request-types.js", "new_path": "lib/types/request-types.js", "diff": "@@ -13,6 +13,7 @@ export const serverRequestTypes = Object.freeze({\nPLATFORM: 0,\nDEVICE_TOKEN: 1,\nTHREAD_POLL_PUSH_INCONSISTENCY: 2,\n+ PLATFORM_DETAILS: 3,\n});\ntype ServerRequestType = $Values<typeof serverRequestTypes>;\nfunction assertServerRequestType(\n@@ -21,7 +22,8 @@ function assertServerRequestType(\ninvariant(\nserverRequestType === 0 ||\nserverRequestType === 1 ||\n- serverRequestType === 2,\n+ serverRequestType === 2 ||\n+ serverRequestType === 3,\n\"number is not ServerRequestType enum\",\n);\nreturn serverRequestType;\n@@ -52,6 +54,14 @@ export type ThreadPollPushInconsistencyClientResponse = {|\npushResult: {[id: string]: RawThreadInfo},\n|};\n+type PlatformDetailsServerRequest = {|\n+ type: 3,\n+|};\n+type PlatformDetailsClientResponse = {|\n+ type: 3,\n+ platformDetails: PlatformDetails,\n+|};\n+\nexport const serverRequestPropType = PropTypes.oneOfType([\nPropTypes.shape({\ntype: PropTypes.oneOf([ serverRequestTypes.PLATFORM ]).isRequired,\n@@ -59,12 +69,17 @@ export const serverRequestPropType = PropTypes.oneOfType([\nPropTypes.shape({\ntype: PropTypes.oneOf([ serverRequestTypes.DEVICE_TOKEN ]).isRequired,\n}),\n+ PropTypes.shape({\n+ type: PropTypes.oneOf([ serverRequestTypes.PLATFORM_DETAILS ]).isRequired,\n+ }),\n]);\nexport type ServerRequest =\n| PlatformServerRequest\n- | DeviceTokenServerRequest;\n+ | DeviceTokenServerRequest\n+ | PlatformDetailsServerRequest;\nexport type ClientResponse =\n| PlatformClientResponse\n| DeviceTokenClientResponse\n- | ThreadPollPushInconsistencyClientResponse;\n+ | ThreadPollPushInconsistencyClientResponse\n+ | PlatformDetailsClientResponse;\n" }, { "change_type": "MODIFY", "old_path": "server/src/creators/account-creator.js", "new_path": "server/src/creators/account-creator.js", "diff": "@@ -75,7 +75,7 @@ async function createAccount(\nVALUES ${[newUserRow]}\n`;\nconst [ userViewerData ] = await Promise.all([\n- createNewUserCookie(id, 0, request.platform),\n+ createNewUserCookie(id, 0, request.platformDetails),\ndeleteCookie(viewer.getData().cookieID),\ndbQuery(newUserQuery),\nsendEmailAddressVerificationEmail(\n" }, { "change_type": "MODIFY", "old_path": "server/src/deleters/account-deleters.js", "new_path": "server/src/deleters/account-deleters.js", "diff": "@@ -52,7 +52,7 @@ async function deleteAccount(\nWHERE u.id = ${deletedUserID}\n`;\nconst [ anonymousViewerData ] = await Promise.all([\n- createNewAnonymousCookie(viewer.platform),\n+ createNewAnonymousCookie(viewer.platformDetails),\ndbQuery(deletionQuery),\n]);\nviewer.setNewCookie(anonymousViewerData);\n" }, { "change_type": "MODIFY", "old_path": "server/src/responders/ping-responders.js", "new_path": "server/src/responders/ping-responders.js", "diff": "@@ -17,7 +17,12 @@ import { ServerError } from 'lib/utils/errors';\nimport { mostRecentMessageTimestamp } from 'lib/shared/message-utils';\nimport { mostRecentUpdateTimestamp } from 'lib/shared/update-utils';\n-import { validateInput, tShape, tPlatform } from '../utils/validation-utils';\n+import {\n+ validateInput,\n+ tShape,\n+ tPlatform,\n+ tPlatformDetails,\n+} from '../utils/validation-utils';\nimport {\nentryQueryInputValidator,\nnormalizeCalendarQuery,\n@@ -29,7 +34,11 @@ import { fetchEntryInfos } from '../fetchers/entry-fetchers';\nimport { updateActivityTime } from '../updaters/activity-updaters';\nimport { fetchCurrentUserInfo } from '../fetchers/user-fetchers';\nimport { fetchUpdateInfos } from '../fetchers/update-fetchers';\n-import { recordDeliveredUpdate, setCookiePlatform } from '../session/cookies';\n+import {\n+ recordDeliveredUpdate,\n+ setCookiePlatform,\n+ setCookiePlatformDetails,\n+} from '../session/cookies';\nimport { deviceTokenUpdater } from '../updaters/device-token-updaters';\nimport createReport from '../creators/report-creator';\n@@ -54,6 +63,24 @@ const pingRequestInputValidator = tShape({\n),\ndeviceToken: t.String,\n}),\n+ tShape({\n+ type: t.irreducible(\n+ 'serverRequestTypes.THREAD_POLL_PUSH_INCONSISTENCY',\n+ x => x === serverRequestTypes.THREAD_POLL_PUSH_INCONSISTENCY,\n+ ),\n+ platformDetails: tPlatformDetails,\n+ beforeAction: t.Object,\n+ action: t.Object,\n+ pollResult: t.Object,\n+ pushResult: t.Object,\n+ }),\n+ tShape({\n+ type: t.irreducible(\n+ 'serverRequestTypes.PLATFORM_DETAILS',\n+ x => x === serverRequestTypes.PLATFORM_DETAILS,\n+ ),\n+ platformDetails: tPlatformDetails,\n+ }),\n]))),\n});\n@@ -91,6 +118,13 @@ async function pingResponder(\nconst clientResponsePromises = [];\nlet viewerMissingPlatform = !viewer.platform;\n+ const platformDetails = viewer.platformDetails;\n+ let viewerMissingPlatformDetails = !platformDetails ||\n+ (isDeviceType(viewer.platform) &&\n+ (platformDetails.codeVersion === null ||\n+ platformDetails.codeVersion === undefined ||\n+ platformDetails.stateVersion === null ||\n+ platformDetails.stateVersion === undefined));\nlet viewerMissingDeviceToken =\nisDeviceType(viewer.platform) && viewer.loggedIn && !viewer.deviceToken;\nif (request.clientResponses) {\n@@ -101,6 +135,9 @@ async function pingResponder(\nclientResponse.platform,\n));\nviewerMissingPlatform = false;\n+ if (!isDeviceType(clientResponse.platform)) {\n+ viewerMissingPlatformDetails = false;\n+ }\n} else if (clientResponse.type === serverRequestTypes.DEVICE_TOKEN) {\nclientResponsePromises.push(deviceTokenUpdater(\nviewer,\n@@ -118,6 +155,13 @@ async function pingResponder(\nviewer,\nclientResponse,\n));\n+ } else if (clientResponse.type === serverRequestTypes.PLATFORM_DETAILS) {\n+ clientResponsePromises.push(setCookiePlatformDetails(\n+ viewer.cookieID,\n+ clientResponse.platformDetails,\n+ ));\n+ viewerMissingPlatform = false;\n+ viewerMissingPlatformDetails = false;\n}\n}\n}\n@@ -178,6 +222,9 @@ async function pingResponder(\nif (viewerMissingPlatform) {\nserverRequests.push({ type: serverRequestTypes.PLATFORM });\n}\n+ if (viewerMissingPlatformDetails) {\n+ serverRequests.push({ type: serverRequestTypes.PLATFORM_DETAILS });\n+ }\nif (viewerMissingDeviceToken) {\nserverRequests.push({ type: serverRequestTypes.DEVICE_TOKEN });\n}\n" }, { "change_type": "MODIFY", "old_path": "server/src/responders/user-responders.js", "new_path": "server/src/responders/user-responders.js", "diff": "@@ -38,6 +38,7 @@ import {\nvalidateInput,\ntShape,\ntPlatform,\n+ tPlatformDetails,\ntDeviceType,\n} from '../utils/validation-utils';\nimport {\n@@ -124,7 +125,7 @@ async function logOutResponder(\nconst cookieID = viewer.getData().cookieID;\nif (viewer.loggedIn) {\nconst [ anonymousViewerData ] = await Promise.all([\n- createNewAnonymousCookie(viewer.platform),\n+ createNewAnonymousCookie(viewer.platformDetails),\ndeleteCookiesOnLogOut(viewer.userID, cookieID),\n]);\nviewer.setNewCookie(anonymousViewerData);\n@@ -155,12 +156,17 @@ const registerRequestInputValidator = tShape({\nemail: t.String,\npassword: t.String,\nplatform: t.maybe(tPlatform),\n+ platformDetails: t.maybe(tPlatformDetails),\n});\nasync function accountCreationResponder(\nviewer: Viewer,\ninput: any,\n): Promise<RegisterResponse> {\n+ if (!input.platformDetails && input.platform) {\n+ input.platformDetails = { platform: input.platform };\n+ delete input.platform;\n+ }\nconst request: RegisterRequest = input;\nvalidateInput(registerRequestInputValidator, request);\nreturn await createAccount(viewer, request);\n@@ -173,6 +179,7 @@ const logInRequestInputValidator = tShape({\ncalendarQuery: t.maybe(entryQueryInputValidator),\ndeviceTokenUpdateRequest: t.maybe(deviceTokenUpdateRequestInputValidator),\nplatform: t.maybe(tPlatform),\n+ platformDetails: t.maybe(tPlatformDetails),\n});\nasync function logInResponder(\n@@ -180,6 +187,10 @@ async function logInResponder(\ninput: any,\n): Promise<LogInResponse> {\nvalidateInput(logInRequestInputValidator, input);\n+ if (!input.platformDetails && input.platform) {\n+ input.platformDetails = { platform: input.platform };\n+ delete input.platform;\n+ }\nconst request: LogInRequest = input;\nconst calendarQuery = request.calendarQuery\n@@ -210,7 +221,7 @@ async function logInResponder(\nconst newPingTime = Date.now();\nconst [ userViewerData ] = await Promise.all([\n- createNewUserCookie(id, newPingTime, request.platform),\n+ createNewUserCookie(id, newPingTime, request.platformDetails),\ndeleteCookie(viewer.getData().cookieID),\n]);\nviewer.setNewCookie(userViewerData);\n@@ -263,6 +274,7 @@ const updatePasswordRequestInputValidator = tShape({\ncalendarQuery: t.maybe(entryQueryInputValidator),\ndeviceTokenUpdateRequest: t.maybe(deviceTokenUpdateRequestInputValidator),\nplatform: t.maybe(tPlatform),\n+ platformDetails: t.maybe(tPlatformDetails),\n});\nasync function passwordUpdateResponder(\n@@ -270,6 +282,10 @@ async function passwordUpdateResponder(\ninput: any,\n): Promise<LogInResponse> {\nvalidateInput(updatePasswordRequestInputValidator, input);\n+ if (!input.platformDetails && input.platform) {\n+ input.platformDetails = { platform: input.platform };\n+ delete input.platform;\n+ }\nconst request: UpdatePasswordRequest = input;\nif (request.calendarQuery) {\nrequest.calendarQuery = normalizeCalendarQuery(request.calendarQuery);\n" }, { "change_type": "MODIFY", "old_path": "server/src/session/cookies.js", "new_path": "server/src/session/cookies.js", "diff": "@@ -4,7 +4,7 @@ import type { $Response, $Request } from 'express';\nimport type { UserInfo, CurrentUserInfo } from 'lib/types/user-types';\nimport type { RawThreadInfo } from 'lib/types/thread-types';\nimport type { ViewerData, AnonymousViewerData, UserViewerData } from './viewer';\n-import type { Platform } from 'lib/types/device-types';\n+import type { Platform, PlatformDetails } from 'lib/types/device-types';\nimport bcrypt from 'twin-bcrypt';\nimport url from 'url';\n@@ -48,7 +48,7 @@ type FetchViewerResult =\ncookieName: string,\ncookieID: string,\nsource: CookieSource,\n- platform: ?Platform,\n+ platformDetails: ?PlatformDetails,\n|};\nasync function fetchUserViewer(\n@@ -60,7 +60,7 @@ async function fetchUserViewer(\nreturn { type: \"nonexistant\", cookieName: cookieType.USER, source };\n}\nconst query = SQL`\n- SELECT hash, user, last_used, platform, device_token\n+ SELECT hash, user, last_used, platform, device_token, versions\nFROM cookies\nWHERE id = ${cookieID} AND user IS NOT NULL\n`;\n@@ -68,7 +68,19 @@ async function fetchUserViewer(\nif (result.length === 0) {\nreturn { type: \"nonexistant\", cookieName: cookieType.USER, source };\n}\n+\nconst cookieRow = result[0];\n+ let platformDetails = null;\n+ if (cookieRow.platform && cookieRow.versions) {\n+ platformDetails = {\n+ platform: cookieRow.platform,\n+ codeVersion: cookieRow.versions.codeVersion,\n+ stateVersion: cookieRow.versions.stateVersion,\n+ };\n+ } else if (cookieRow.platform) {\n+ platformDetails = { platform: cookieRow.platform };\n+ }\n+\nif (\n!bcrypt.compareSync(cookiePassword, cookieRow.hash) ||\ncookieIsExpired(cookieRow.last_used)\n@@ -78,7 +90,7 @@ async function fetchUserViewer(\ncookieName: cookieType.USER,\ncookieID,\nsource,\n- platform: cookieRow.platform,\n+ platformDetails,\n};\n}\nconst userID = cookieRow.user.toString();\n@@ -86,7 +98,7 @@ async function fetchUserViewer(\n{\nloggedIn: true,\nid: userID,\n- platform: cookieRow.platform,\n+ platformDetails,\ndeviceToken: cookieRow.device_token,\nuserID,\ncookieID,\n@@ -106,7 +118,7 @@ async function fetchAnonymousViewer(\nreturn { type: \"nonexistant\", cookieName: cookieType.ANONYMOUS, source };\n}\nconst query = SQL`\n- SELECT last_used, hash, platform, device_token\n+ SELECT last_used, hash, platform, device_token, versions\nFROM cookies\nWHERE id = ${cookieID} AND user IS NULL\n`;\n@@ -114,7 +126,19 @@ async function fetchAnonymousViewer(\nif (result.length === 0) {\nreturn { type: \"nonexistant\", cookieName: cookieType.ANONYMOUS, source };\n}\n+\nconst cookieRow = result[0];\n+ let platformDetails = null;\n+ if (cookieRow.platform && cookieRow.versions) {\n+ platformDetails = {\n+ platform: cookieRow.platform,\n+ codeVersion: cookieRow.versions.codeVersion,\n+ stateVersion: cookieRow.versions.stateVersion,\n+ };\n+ } else if (cookieRow.platform) {\n+ platformDetails = { platform: cookieRow.platform };\n+ }\n+\nif (\n!bcrypt.compareSync(cookiePassword, cookieRow.hash) ||\ncookieIsExpired(cookieRow.last_used)\n@@ -124,14 +148,14 @@ async function fetchAnonymousViewer(\ncookieName: cookieType.ANONYMOUS,\ncookieID,\nsource,\n- platform: cookieRow.platform,\n+ platformDetails,\n};\n}\nconst viewer = new Viewer(\n{\nloggedIn: false,\nid: cookieID,\n- platform: cookieRow.platform,\n+ platformDetails,\ndeviceToken: cookieRow.device_token,\ncookieID,\ncookiePassword,\n@@ -184,27 +208,28 @@ async function fetchViewerForJSONRequest(req: $Request): Promise<Viewer> {\nreturn await handleFetchViewerResult(result);\n}\n+const webPlatformDetails = { platform: \"web\" };\nasync function fetchViewerForHomeRequest(req: $Request): Promise<Viewer> {\nassertSecureRequest(req);\nconst result = await fetchViewerFromCookieData(req.cookies);\n- return await handleFetchViewerResult(result, \"web\");\n+ return await handleFetchViewerResult(result, webPlatformDetails);\n}\nasync function handleFetchViewerResult(\nresult: ?FetchViewerResult,\n- inputPlatform?: Platform,\n+ inputPlatformDetails?: PlatformDetails,\n) {\nif (result && result.type === \"valid\") {\nreturn result.viewer;\n}\n- let platform = inputPlatform;\n- if (!platform && result && result.type === \"invalidated\") {\n- platform = result.platform;\n+ let platformDetails = inputPlatformDetails;\n+ if (!platformDetails && result && result.type === \"invalidated\") {\n+ platformDetails = result.platformDetails;\n}\nconst [ anonymousViewerData ] = await Promise.all([\n- createNewAnonymousCookie(platform),\n+ createNewAnonymousCookie(platformDetails),\nresult && result.type === \"invalidated\"\n? deleteCookie(result.cookieID)\n: null,\n@@ -278,24 +303,26 @@ async function addCookieChangeInfoToResult(\nresult.cookieChange = cookieChange;\n}\n+const defaultPlatformDetails = {};\nasync function createNewAnonymousCookie(\n- platform: ?Platform,\n+ platformDetails: ?PlatformDetails,\n): Promise<AnonymousViewerData> {\nconst time = Date.now();\nconst cookiePassword = crypto.randomBytes(32).toString('hex');\nconst cookieHash = bcrypt.hashSync(cookiePassword);\nconst [ id ] = await createIDs(\"cookies\", 1);\n- const cookieRow = [id, cookieHash, null, platform, time, time, 0];\n+ const { platform, ...versions } = (platformDetails || defaultPlatformDetails);\n+ const cookieRow = [id, cookieHash, null, platform, time, time, 0, versions];\nconst query = SQL`\nINSERT INTO cookies(id, hash, user, platform, creation_time, last_used,\n- last_update)\n+ last_update, versions)\nVALUES ${[cookieRow]}\n`;\nawait dbQuery(query);\nreturn {\nloggedIn: false,\nid,\n- platform,\n+ platformDetails,\ndeviceToken: null,\ncookieID: id,\ncookiePassword,\n@@ -306,24 +333,33 @@ async function createNewAnonymousCookie(\nasync function createNewUserCookie(\nuserID: string,\ninitialLastUpdate: number,\n- platform: ?Platform,\n+ platformDetails: ?PlatformDetails,\n): Promise<UserViewerData> {\nconst time = Date.now();\nconst cookiePassword = crypto.randomBytes(32).toString('hex');\nconst cookieHash = bcrypt.hashSync(cookiePassword);\nconst [ cookieID ] = await createIDs(\"cookies\", 1);\n- const cookieRow =\n- [cookieID, cookieHash, userID, platform, time, time, initialLastUpdate];\n+ const { platform, ...versions } = (platformDetails || defaultPlatformDetails);\n+ const cookieRow = [\n+ cookieID,\n+ cookieHash,\n+ userID,\n+ platform,\n+ time,\n+ time,\n+ initialLastUpdate,\n+ versions,\n+ ];\nconst query = SQL`\nINSERT INTO cookies(id, hash, user, platform, creation_time, last_used,\n- last_update)\n+ last_update, versions)\nVALUES ${[cookieRow]}\n`;\nawait dbQuery(query);\nreturn {\nloggedIn: true,\nid: userID,\n- platform,\n+ platformDetails,\ndeviceToken: null,\nuserID,\ncookieID,\n@@ -405,6 +441,19 @@ async function setCookiePlatform(\nawait dbQuery(query);\n}\n+async function setCookiePlatformDetails(\n+ cookieID: string,\n+ platformDetails: PlatformDetails,\n+): Promise<void> {\n+ const { platform, ...versions } = platformDetails;\n+ const query = SQL`\n+ UPDATE cookies\n+ SET platform = ${platform}, versions = ${versions}\n+ WHERE id = ${cookieID}\n+ `;\n+ await dbQuery(query);\n+}\n+\nexport {\ncookieLifetime,\ncookieType,\n@@ -416,4 +465,5 @@ export {\naddCookieToJSONResponse,\naddCookieToHomeResponse,\nsetCookiePlatform,\n+ setCookiePlatformDetails,\n};\n" }, { "change_type": "MODIFY", "old_path": "server/src/session/viewer.js", "new_path": "server/src/session/viewer.js", "diff": "// @flow\nimport { type CookieSource, cookieType } from './cookies';\n-import type { Platform } from 'lib/types/device-types';\n+import type { Platform, PlatformDetails } from 'lib/types/device-types';\nimport invariant from 'invariant';\nexport type UserViewerData = {|\n+loggedIn: true,\n+id: string,\n- +platform: ?Platform,\n+ +platformDetails: ?PlatformDetails,\n+deviceToken: ?string,\n+userID: string,\n+cookieID: string,\n@@ -19,7 +19,7 @@ export type UserViewerData = {|\nexport type AnonymousViewerData = {|\n+loggedIn: false,\n+id: string,\n- +platform: ?Platform,\n+ +platformDetails: ?PlatformDetails,\n+deviceToken: ?string,\n+cookieID: string,\n+cookiePassword: string,\n@@ -95,8 +95,14 @@ class Viewer {\nreturn `${this.cookieName}=${this.cookieString}`;\n}\n+ get platformDetails(): ?PlatformDetails {\n+ return this.data.platformDetails;\n+ }\n+\nget platform(): ?Platform {\n- return this.data.platform;\n+ return this.data.platformDetails\n+ ? this.data.platformDetails.platform\n+ : null;\n}\nget deviceToken(): ?string {\n" }, { "change_type": "MODIFY", "old_path": "server/src/updaters/account-updaters.js", "new_path": "server/src/updaters/account-updaters.js", "diff": "@@ -175,7 +175,7 @@ async function updatePassword(\nconst newPingTime = Date.now();\nconst [ userViewerData ] = await Promise.all([\n- createNewUserCookie(userID, newPingTime, request.platform),\n+ createNewUserCookie(userID, newPingTime, request.platformDetails),\nclearVerifyCodes(verificationResult),\n]);\nviewer.setNewCookie(userViewerData);\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Have server maintain all PlatformDetails for native clients We want to know `codeVersion` and `stateVersion` for all applicable cookies.
129,187
04.07.2018 12:28:22
14,400
d06ae81c0cb0006122d613f03db6ccab2254d712
Bugfixes and optimizations for the last commit
[ { "change_type": "MODIFY", "old_path": "lib/selectors/ping-selectors.js", "new_path": "lib/selectors/ping-selectors.js", "diff": "@@ -66,9 +66,14 @@ const pingActionInput = createSelector(\nlastSuccess: number,\n): (startingPayload: PingStartingPayload) => PingActionInput => {\nconst clientResponses = [...inconsistencyResponses];\n- let serverRequestedPlatformDetails = false;\n+ const serverRequestedPlatformDetails = activeServerRequests.some(\n+ request => request.type === serverRequestTypes.PLATFORM_DETAILS,\n+ );\nfor (let serverRequest of activeServerRequests) {\n- if (serverRequest.type === serverRequestTypes.PLATFORM) {\n+ if (\n+ serverRequest.type === serverRequestTypes.PLATFORM &&\n+ !serverRequestedPlatformDetails\n+ ) {\nclientResponses.push({\ntype: serverRequestTypes.PLATFORM,\nplatform: getConfig().platformDetails.platform,\n@@ -82,7 +87,6 @@ const pingActionInput = createSelector(\ndeviceToken,\n});\n} else if (serverRequest.type === serverRequestTypes.PLATFORM_DETAILS) {\n- serverRequestedPlatformDetails = true;\nclientResponses.push({\ntype: serverRequestTypes.PLATFORM_DETAILS,\nplatformDetails: getConfig().platformDetails,\n@@ -92,16 +96,17 @@ const pingActionInput = createSelector(\n// Whenever the app starts up, it's possible that the version has updated.\n// We always communicate the PlatformDetails in that case.\nif (\n- !serverRequestedPlatformDetails &&\n- (initialPlatformDetailsSentAsOf === null ||\n- initialPlatformDetailsSentAsOf === lastSuccess)\n+ initialPlatformDetailsSentAsOf === null ||\n+ initialPlatformDetailsSentAsOf === lastSuccess\n) {\ninitialPlatformDetailsSentAsOf = lastSuccess;\n+ if (!serverRequestedPlatformDetails) {\nclientResponses.push({\ntype: serverRequestTypes.PLATFORM_DETAILS,\nplatformDetails: getConfig().platformDetails,\n});\n}\n+ }\nreturn (startingPayload: PingStartingPayload) => ({\nloggedIn: startingPayload.loggedIn,\ncalendarQuery: startingPayload.calendarQuery,\n" }, { "change_type": "MODIFY", "old_path": "server/src/responders/ping-responders.js", "new_path": "server/src/responders/ping-responders.js", "diff": "@@ -116,7 +116,6 @@ async function pingResponder(\n}\nconst threadSelectionCriteria = { threadCursors, joinedThreads: true };\n- const clientResponsePromises = [];\nlet viewerMissingPlatform = !viewer.platform;\nconst platformDetails = viewer.platformDetails;\nlet viewerMissingPlatformDetails = !platformDetails ||\n@@ -127,9 +126,18 @@ async function pingResponder(\nplatformDetails.stateVersion === undefined));\nlet viewerMissingDeviceToken =\nisDeviceType(viewer.platform) && viewer.loggedIn && !viewer.deviceToken;\n- if (request.clientResponses) {\n- for (let clientResponse of request.clientResponses) {\n- if (clientResponse.type === serverRequestTypes.PLATFORM) {\n+\n+ const { clientResponses } = request;\n+ const clientResponsePromises = [];\n+ if (clientResponses) {\n+ const clientSentPlatformDetails = clientResponses.some(\n+ response => response.type === serverRequestTypes.PLATFORM_DETAILS,\n+ );\n+ for (let clientResponse of clientResponses) {\n+ if (\n+ clientResponse.type === serverRequestTypes.PLATFORM &&\n+ !clientSentPlatformDetails\n+ ) {\nclientResponsePromises.push(setCookiePlatform(\nviewer.cookieID,\nclientResponse.platform,\n" }, { "change_type": "MODIFY", "old_path": "server/src/session/cookies.js", "new_path": "server/src/session/cookies.js", "diff": "@@ -312,7 +312,19 @@ async function createNewAnonymousCookie(\nconst cookieHash = bcrypt.hashSync(cookiePassword);\nconst [ id ] = await createIDs(\"cookies\", 1);\nconst { platform, ...versions } = (platformDetails || defaultPlatformDetails);\n- const cookieRow = [id, cookieHash, null, platform, time, time, 0, versions];\n+ const versionsString = Object.keys(versions).length > 0\n+ ? JSON.stringify(versions)\n+ : null;\n+ const cookieRow = [\n+ id,\n+ cookieHash,\n+ null,\n+ platform,\n+ time,\n+ time,\n+ 0,\n+ versionsString,\n+ ];\nconst query = SQL`\nINSERT INTO cookies(id, hash, user, platform, creation_time, last_used,\nlast_update, versions)\n@@ -340,6 +352,9 @@ async function createNewUserCookie(\nconst cookieHash = bcrypt.hashSync(cookiePassword);\nconst [ cookieID ] = await createIDs(\"cookies\", 1);\nconst { platform, ...versions } = (platformDetails || defaultPlatformDetails);\n+ const versionsString = Object.keys(versions).length > 0\n+ ? JSON.stringify(versions)\n+ : null;\nconst cookieRow = [\ncookieID,\ncookieHash,\n@@ -348,7 +363,7 @@ async function createNewUserCookie(\ntime,\ntime,\ninitialLastUpdate,\n- versions,\n+ versionsString,\n];\nconst query = SQL`\nINSERT INTO cookies(id, hash, user, platform, creation_time, last_used,\n@@ -446,9 +461,12 @@ async function setCookiePlatformDetails(\nplatformDetails: PlatformDetails,\n): Promise<void> {\nconst { platform, ...versions } = platformDetails;\n+ const versionsString = Object.keys(versions).length > 0\n+ ? JSON.stringify(versions)\n+ : null;\nconst query = SQL`\nUPDATE cookies\n- SET platform = ${platform}, versions = ${versions}\n+ SET platform = ${platform}, versions = ${versionsString}\nWHERE id = ${cookieID}\n`;\nawait dbQuery(query);\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Bugfixes and optimizations for the last commit
129,187
09.07.2018 10:32:11
14,400
73d51f6c229ae42769d07c0bc119b740ac6c756b
[web] Fix splash screen styling It started breaking on Chrome so I had to rethink `div.splash-top-container`
[ { "change_type": "MODIFY", "old_path": "web/style.css", "new_path": "web/style.css", "diff": "@@ -1055,7 +1055,6 @@ div.splash-header-container {\ntop: 0;\nleft: 0;\nright: 0;\n- height: 790px;\nheight: 61px;\nz-index: 3;\nbackground-image: url(../images/background.png);\n@@ -1065,14 +1064,14 @@ div.splash-header-container {\n}\ndiv.splash-top-container {\nposition: fixed;\n- top: 61px;\n+ top: 0;\nleft: 0;\nright: 0;\nheight: 100%;\nbackground-image: url(../images/background.png);\nbackground-size: 3000px 2000px;\n- background-attachment: fixed;\nbackground-repeat-y: repeat;\n+ padding-top: 61px;\n}\ndiv.splash-top {\nmax-width: 1024px;\n@@ -1302,7 +1301,4 @@ div.custom-select select:focus {\ndiv.splash-header-container, div.splash-top-container, div.splash-bottom {\nbackground-attachment: initial;\n}\n- div.splash-top-container {\n- background-position-y: -61px;\n- }\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[web] Fix splash screen styling It started breaking on Chrome so I had to rethink `div.splash-top-container`
129,187
09.07.2018 19:34:06
14,400
6878d9674e552c23836a4424a81694ed0c214264
Assorted fixes after testing master
[ { "change_type": "MODIFY", "old_path": "lib/facts/bots.json", "new_path": "lib/facts/bots.json", "diff": "{\n\"squadbot\": {\n\"userID\": \"5\",\n- \"ashoatThreadID\": \"83793\"\n+ \"ashoatThreadID\": \"83794\"\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/device-token-reducer.js", "new_path": "lib/reducers/device-token-reducer.js", "diff": "@@ -8,7 +8,7 @@ export default function reduceDeviceToken(\nstate: ?string,\naction: BaseAction,\n) {\n- if (action.type === setDeviceTokenActionTypes.success) {\n+ if (action.type === setDeviceTokenActionTypes.started) {\nreturn action.payload;\n}\nreturn state;\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/server-requests-reducer.js", "new_path": "lib/reducers/server-requests-reducer.js", "diff": "@@ -9,16 +9,19 @@ export default function reduceServerRequests(\nstate: $ReadOnlyArray<ServerRequest>,\naction: BaseAction,\n): $ReadOnlyArray<ServerRequest> {\n- if (action.type === pingActionTypes.success) {\n- const { requests } = action.payload;\n+ if (\n+ action.type === pingActionTypes.success &&\n+ action.payload.requests.serverRequests.length > 0\n+ ) {\nreturn [\n- // For now, we assume that each ping responds to every server request\n- // present at the time. Note that we're relying on reference comparisons.\n- ...state.filter(\n- request => !requests.deliveredClientResponses.includes(request),\n- ),\n- ...requests.serverRequests,\n+ ...state,\n+ ...action.payload.requests.serverRequests,\n];\n+ } else if (action.type === pingActionTypes.started && state.length > 0) {\n+ // For now, we assume that each ping responds to every server request\n+ // present at the time. The result of the ping will include all server\n+ // requests that weren't responded to, so it's safe to clear them here.\n+ return [];\n}\nreturn state;\n}\n" }, { "change_type": "MODIFY", "old_path": "lib/reducers/thread-reducer.js", "new_path": "lib/reducers/thread-reducer.js", "diff": "@@ -184,6 +184,21 @@ function findInconsistencies(\nif (_isEqual(pollResult)(pushResult)) {\nreturn emptyArray;\n}\n+ if (action.type === pingActionTypes.success) {\n+ // We can get a memory leak if we include a previous\n+ // ThreadPollPushInconsistencyClientResponse in this one\n+ action = {\n+ type: \"PING_SUCCESS\",\n+ loadingInfo: action.loadingInfo,\n+ payload: {\n+ ...action.payload,\n+ requests: {\n+ ...action.payload.requests,\n+ deliveredClientResponses: [],\n+ },\n+ },\n+ };\n+ }\nreturn [{\ntype: serverRequestTypes.THREAD_POLL_PUSH_INCONSISTENCY,\nplatformDetails: getConfig().platformDetails,\n@@ -249,8 +264,8 @@ export default function reduceThreadInfos(\nthreadInfos: pollResult,\ninconsistencyResponses: [\n...state.inconsistencyResponses.filter(\n- request =>\n- !payload.requests.deliveredClientResponses.includes(request),\n+ response =>\n+ !payload.requests.deliveredClientResponses.includes(response),\n),\n...findInconsistencies(\nstate.threadInfos,\n" }, { "change_type": "MODIFY", "old_path": "lib/shared/notif-utils.js", "new_path": "lib/shared/notif-utils.js", "diff": "@@ -69,7 +69,7 @@ function assertSingleMessageInfo(\nthrow new Error(\"expected single MessageInfo, but none present!\");\n} else if (messageInfos.length !== 1) {\nconst messageIDs = messageInfos.map(messageInfo => messageInfo.id);\n- console.warn(\n+ console.log(\n\"expected single MessageInfo, but there are multiple! \" +\nmessageIDs.join(\", \")\n);\n" }, { "change_type": "MODIFY", "old_path": "lib/types/redux-types.js", "new_path": "lib/types/redux-types.js", "diff": "@@ -476,6 +476,7 @@ export type BaseAction =\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"SET_DEVICE_TOKEN_STARTED\",\n+ payload: string,\nloadingInfo: LoadingInfo,\n|} | {|\ntype: \"SET_DEVICE_TOKEN_FAILED\",\n" }, { "change_type": "MODIFY", "old_path": "lib/utils/action-utils.js", "new_path": "lib/utils/action-utils.js", "diff": "@@ -93,7 +93,7 @@ function wrapActionPromise<\nloadingInfo,\n});\n} catch (e) {\n- console.warn(e);\n+ console.log(e);\ndispatch({\ntype: (actionTypes.failed: CT),\nerror: true,\n" }, { "change_type": "ADD", "old_path": null, "new_path": "lib/utils/objects.js", "diff": "+function findMaximumDepth(obj: Object): ?{ path: string, depth: number } {\n+ let longestPath = null;\n+ let longestDepth = null\n+ for (let key in obj) {\n+ const value = obj[key];\n+ if (typeof value !== \"object\" || !value) {\n+ if (!longestDepth) {\n+ longestPath = key;\n+ longestDepth = 1;\n+ }\n+ continue;\n+ }\n+ const childResult = findMaximumDepth(obj[key]);\n+ if (!childResult) {\n+ continue;\n+ }\n+ const { path, depth } = childResult;\n+ const ourDepth = depth + 1;\n+ if (longestDepth === null || ourDepth > longestDepth) {\n+ longestPath = `${key}.${path}`;\n+ longestDepth = ourDepth;\n+ }\n+ }\n+ if (!longestPath || !longestDepth) {\n+ return null;\n+ }\n+ return { path: longestPath, depth: longestDepth };\n+}\n+\n+export {\n+ findMaximumDepth,\n+};\n" }, { "change_type": "MODIFY", "old_path": "native/app.react.js", "new_path": "native/app.react.js", "diff": "@@ -577,11 +577,15 @@ class AppWithNavigationState extends React.PureComponent<Props> {\nif (deviceType === \"ios\") {\niosPushPermissionResponseReceived();\n}\n+ if (deviceToken !== this.props.deviceToken) {\nthis.props.dispatchActionPromise(\nsetDeviceTokenActionTypes,\nthis.props.setDeviceToken(deviceToken, deviceType),\n+ undefined,\n+ deviceToken,\n);\n}\n+ }\nfailedToRegisterPushPermissions = (error) => {\nif (!this.props.appLoggedIn) {\n" }, { "change_type": "MODIFY", "old_path": "server/src/creators/message-creator.js", "new_path": "server/src/creators/message-creator.js", "diff": "@@ -226,6 +226,10 @@ async function updateUnreadStatus(\nuserID: row.user.toString(),\nthreadID: row.thread.toString(),\n}));\n+ if (setUnreadPairs.length === 0) {\n+ return;\n+ }\n+\nconst updateConditions = setUnreadPairs.map(\npair => SQL`(user = ${pair.userID} AND thread = ${pair.threadID})`,\n);\n@@ -238,7 +242,7 @@ async function updateUnreadStatus(\nconst now = Date.now();\nawait Promise.all([\n- dbQuery(query),\n+ dbQuery(updateQuery),\ncreateUpdates(setUnreadPairs.map(pair => ({\ntype: updateTypes.UPDATE_THREAD_READ_STATUS,\nuserID: pair.userID,\n" }, { "change_type": "MODIFY", "old_path": "server/src/database.js", "new_path": "server/src/database.js", "diff": "@@ -66,6 +66,10 @@ async function dbQuery(statement: SQLStatement) {\n}\n}\n+function rawSQL(statement: SQLStatement) {\n+ return mysql.format(statement.sql, statement.values);\n+}\n+\nexport {\nSQL,\nSQLStatement,\n@@ -73,4 +77,5 @@ export {\nmergeAndConditions,\nmergeOrConditions,\ndbQuery,\n+ rawSQL,\n};\n" }, { "change_type": "MODIFY", "old_path": "server/src/fetchers/update-fetchers.js", "new_path": "server/src/fetchers/update-fetchers.js", "diff": "@@ -53,7 +53,7 @@ function viewerUpdateDataFromRow(\n): ViewerUpdateData {\nconst type = assertUpdateType(row.type);\nlet data;\n- const id = row.id;\n+ const id = row.id.toString();\nif (type === updateTypes.DELETE_ACCOUNT) {\nconst content = JSON.parse(row.content);\ndata = {\n" }, { "change_type": "MODIFY", "old_path": "server/src/updaters/thread-updaters.js", "new_path": "server/src/updaters/thread-updaters.js", "diff": "@@ -514,7 +514,7 @@ async function updateThread(\n// This forces an update for this thread,\n// regardless of whether any membership rows are changed\nObject.keys(sqlUpdate).length > 0\n- ? new Set(request.threadID)\n+ ? new Set([ request.threadID ])\n: new Set(),\n),\n]);\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Assorted fixes after testing master
129,187
09.07.2018 22:26:52
14,400
99cbde4867f019de6625207f812aa7e1edab5f33
[native] Fix Flow for React Native 0.56
[ { "change_type": "MODIFY", "old_path": "native/.flowconfig", "new_path": "native/.flowconfig", "diff": "; \"node_modules/react-native\" but in the source repo it is in the root\n.*/Libraries/react-native/React.js\n+.*/node_modules/react-native/Libraries/react-native/react-native-implementation.js\n+\n; Ignore polyfills\n.*/Libraries/polyfills/.*\n" }, { "change_type": "MODIFY", "old_path": "native/calendar/calendar.react.js", "new_path": "native/calendar/calendar.react.js", "diff": "@@ -993,7 +993,7 @@ class InnerCalendar extends React.PureComponent<Props, State> {\nconst item = _find\n(item => item.entryInfo && entryKey(item.entryInfo) === key)\n(ldwh);\n- return item && !item.id && true;\n+ return !!item;\n},\n)(this.latestExtraData.activeEntries),\nvisibleEntries,\n" }, { "change_type": "ADD", "old_path": null, "new_path": "native/flow-typed/npm/AnimatedNode_vx.x.x.js", "diff": "+// flow-typed signature: 8c9353451871ceaff1c2f19d380d1911\n+// flow-typed version: <<STUB>>/AnimatedNode_vx.x.x/flow_v0.75.0\n+\n+/**\n+ * This is an autogenerated libdef stub for:\n+ *\n+ * 'AnimatedNode'\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 'AnimatedNode' {\n+ declare module.exports: any;\n+}\n" }, { "change_type": "ADD", "old_path": null, "new_path": "native/flow-typed/npm/RelativeImageStub_vx.x.x.js", "diff": "+// flow-typed signature: ce1ee9b65eaf74748c34a270dd577b83\n+// flow-typed version: <<STUB>>/RelativeImageStub_vx.x.x/flow_v0.75.0\n+\n+/**\n+ * This is an autogenerated libdef stub for:\n+ *\n+ * 'RelativeImageStub'\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 'RelativeImageStub' {\n+ declare module.exports: any;\n+}\n" }, { "change_type": "MODIFY", "old_path": "native/flow-typed/npm/react-navigation_v2.x.x.js", "new_path": "native/flow-typed/npm/react-navigation_v2.x.x.js", "diff": "@@ -187,7 +187,7 @@ declare module 'react-navigation' {\n| NavigationLeafRoute\n| NavigationStateRoute;\n- declare export type NavigationLeafRoute = {\n+ declare export type NavigationLeafRoute = {|\n/**\n* React's key used by some navigators. No need to specify these manually,\n* they will be defined by the router.\n@@ -207,10 +207,12 @@ declare module 'react-navigation' {\n* e.g. `{ car_id: 123 }` in a route that displays a car.\n*/\nparams?: NavigationParams,\n- };\n+ |};\n- declare export type NavigationStateRoute = NavigationLeafRoute &\n- NavigationState;\n+ declare export type NavigationStateRoute = {|\n+ ...NavigationLeafRoute,\n+ ...$Exact<NavigationState>,\n+ |};\n/**\n* Router\n" }, { "change_type": "MODIFY", "old_path": "native/keyboard.js", "new_path": "native/keyboard.js", "diff": "import { AppState, Keyboard, Platform } from 'react-native';\n-type Coordinates = {\n- width: number,\n- height: number,\n+type ScreenRect = $ReadOnly<{|\nscreenX: number,\nscreenY: number,\n-};\n-export type KeyboardEvent = {\n- duration: number,\n- startCoordinates: Coordinates,\n- endCoordinates: Coordinates,\n-};\n+ width: number,\n+ height: number,\n+|}>;\n+export type KeyboardEvent = $ReadOnly<{|\n+ duration?: number,\n+ easing?: string,\n+ endCoordinates: ScreenRect,\n+ startCoordinates?: ScreenRect,\n+|}>;\ntype KeyboardCallback = (event: KeyboardEvent) => void;\ntype IgnoredKeyboardEvent = {|\ncallback: KeyboardCallback,\n" }, { "change_type": "MODIFY", "old_path": "native/navigation-setup.js", "new_path": "native/navigation-setup.js", "diff": "@@ -520,7 +520,7 @@ function removeModalsIfPingIndicatesLoggedIn(\nstate: NavigationState,\npayload: PingResult,\n): NavigationState {\n- if (!payload.userInfo || payload.loggedIn) {\n+ if (payload.currentUserInfo.anonymous) {\n// The SET_COOKIE action should handle logging somebody out as a result of a\n// cookie invalidation triggered by a ping server call. PING_SUCCESS is only\n// handling specific log ins that occur from LoggedOutModal.\n@@ -693,7 +693,10 @@ function handleNotificationPress(\nviewerID,\nuserInfos,\n);\n- newState.routes[0] = { ...newState.routes[0], index: 1 };\n+ newState.routes[0] = {\n+ ...assertNavigationRouteNotLeafNode(newState.routes[0]),\n+ index: 1,\n+ };\nreturn newState;\n}\n" }, { "change_type": "MODIFY", "old_path": "native/package.json", "new_path": "native/package.json", "diff": "\"lib\": \"0.0.1\",\n\"lodash\": \"^4.17.5\",\n\"react\": \"16.4.1\",\n- \"react-native\": \"0.56.0\",\n+ \"react-native\": \"^0.56.0\",\n\"react-native-exit-app\": \"^1.0.0\",\n\"react-native-fcm\": \"git+https://git@github.com/ashoat/react-native-fcm.git\",\n\"react-native-floating-action\": \"^1.9.0\",\n" }, { "change_type": "MODIFY", "old_path": "native/utils/navigation-utils.js", "new_path": "native/utils/navigation-utils.js", "diff": "@@ -80,7 +80,7 @@ function getThreadIDFromParams(object: { params?: NavigationParams }): string {\n}\nfunction currentRouteRecurse(state: NavigationRoute): NavigationLeafRoute {\n- if (state.index) {\n+ if (state.index || state.routes) {\nconst stateRoute = assertNavigationRouteNotLeafNode(state);\nreturn currentRouteRecurse(stateRoute.routes[stateRoute.index]);\n} else {\n" }, { "change_type": "MODIFY", "old_path": "yarn.lock", "new_path": "yarn.lock", "diff": "@@ -7933,7 +7933,7 @@ react-native-vector-icons@^4.5.0:\nprop-types \"^15.5.10\"\nyargs \"^8.0.2\"\n-react-native@0.56.0:\n+react-native@^0.56.0:\nversion \"0.56.0\"\nresolved \"https://registry.yarnpkg.com/react-native/-/react-native-0.56.0.tgz#66686f781ec39a44376aadd4bbc55c8573ab61e5\"\ndependencies:\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Fix Flow for React Native 0.56
129,187
10.07.2018 10:43:19
14,400
bfc4e67206b237895fe99ceb7512c0ee910179d5
[server] Sanitize invalid input before logging Namely, replace any plaintext passwords.
[ { "change_type": "MODIFY", "old_path": "server/src/responders/thread-responders.js", "new_path": "server/src/responders/thread-responders.js", "diff": "@@ -25,6 +25,7 @@ import {\ntShape,\ntNumEnum,\ntColor,\n+ tPassword,\n} from '../utils/validation-utils';\nimport { deleteThread } from '../deleters/thread-deleters';\nimport {\n@@ -42,7 +43,7 @@ import {\nconst threadDeletionRequestInputValidator = tShape({\nthreadID: t.String,\n- accountPassword: t.String,\n+ accountPassword: tPassword,\n});\nasync function threadDeletionResponder(\n@@ -113,7 +114,7 @@ const updateThreadRequestInputValidator = tShape({\nparentThreadID: t.maybe(t.String),\nnewMemberIDs: t.maybe(t.list(t.String)),\n}),\n- accountPassword: t.maybe(t.String),\n+ accountPassword: t.maybe(tPassword),\n});\nasync function threadUpdateResponder(\n" }, { "change_type": "MODIFY", "old_path": "server/src/responders/user-responders.js", "new_path": "server/src/responders/user-responders.js", "diff": "@@ -40,6 +40,7 @@ import {\ntPlatform,\ntPlatformDetails,\ntDeviceType,\n+ tPassword,\n} from '../utils/validation-utils';\nimport {\ncreateNewAnonymousCookie,\n@@ -84,9 +85,9 @@ async function userSubscriptionUpdateResponder(\nconst accountUpdateInputValidator = tShape({\nupdatedFields: tShape({\nemail: t.maybe(t.String),\n- password: t.maybe(t.String),\n+ password: t.maybe(tPassword),\n}),\n- currentPassword: t.String,\n+ currentPassword: tPassword,\n});\nasync function accountUpdateResponder(\n@@ -139,7 +140,7 @@ async function logOutResponder(\n}\nconst deleteAccountRequestInputValidator = tShape({\n- password: t.String,\n+ password: tPassword,\n});\nasync function accountDeletionResponder(\n@@ -154,7 +155,7 @@ async function accountDeletionResponder(\nconst registerRequestInputValidator = tShape({\nusername: t.String,\nemail: t.String,\n- password: t.String,\n+ password: tPassword,\nplatform: t.maybe(tPlatform),\nplatformDetails: t.maybe(tPlatformDetails),\n});\n@@ -174,7 +175,7 @@ async function accountCreationResponder(\nconst logInRequestInputValidator = tShape({\nusernameOrEmail: t.String,\n- password: t.String,\n+ password: tPassword,\nwatchedIDs: t.list(t.String),\ncalendarQuery: t.maybe(entryQueryInputValidator),\ndeviceTokenUpdateRequest: t.maybe(deviceTokenUpdateRequestInputValidator),\n@@ -269,7 +270,7 @@ async function logInResponder(\nconst updatePasswordRequestInputValidator = tShape({\ncode: t.String,\n- password: t.String,\n+ password: tPassword,\nwatchedIDs: t.list(t.String),\ncalendarQuery: t.maybe(entryQueryInputValidator),\ndeviceTokenUpdateRequest: t.maybe(deviceTokenUpdateRequestInputValidator),\n" }, { "change_type": "MODIFY", "old_path": "server/src/utils/validation-utils.js", "new_path": "server/src/utils/validation-utils.js", "diff": "@@ -5,9 +5,42 @@ import t from 'tcomb';\nimport { ServerError } from 'lib/utils/errors';\nfunction validateInput(inputValidator: *, input: *) {\n- if (!inputValidator.is(input)) {\n- throw new ServerError('invalid_parameters', { input });\n+ if (inputValidator.is(input)) {\n+ return;\n}\n+ const sanitizedInput = sanitizeInput(inputValidator, input);\n+ throw new ServerError('invalid_parameters', { input: sanitizedInput });\n+}\n+\n+const fakePassword = \"********\";\n+function sanitizeInput(inputValidator: *, input: *) {\n+ if (!inputValidator) {\n+ return input;\n+ }\n+ if (inputValidator === tPassword && typeof input === \"string\") {\n+ return fakePassword;\n+ }\n+ if (\n+ inputValidator.meta.kind === \"maybe\" &&\n+ inputValidator.meta.type === tPassword &&\n+ typeof input === \"string\"\n+ ) {\n+ return fakePassword;\n+ }\n+ if (\n+ inputValidator.meta.kind !== \"interface\" ||\n+ typeof input !== \"object\" ||\n+ !input\n+ ) {\n+ return input;\n+ }\n+ const result = {};\n+ for (let key in input) {\n+ const value = input[key];\n+ const validator = inputValidator.meta.props[key];\n+ result[key] = sanitizeInput(validator, value);\n+ }\n+ return result;\n}\nfunction tBool(value: bool) {\n@@ -49,6 +82,7 @@ const tPlatformDetails = tShape({\ncodeVersion: t.maybe(t.Number),\nstateVersion: t.maybe(t.Number),\n});\n+const tPassword = t.refinement(t.String, (password: string) => password);\nexport {\nvalidateInput,\n@@ -62,4 +96,5 @@ export {\ntPlatform,\ntDeviceType,\ntPlatformDetails,\n+ tPassword,\n};\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Sanitize invalid input before logging Namely, replace any plaintext passwords.
129,187
10.07.2018 11:49:40
14,400
cf2286a4cd7eb655cbbf609e52c31bb838b06cf4
[native] Update to
[ { "change_type": "MODIFY", "old_path": "native/package.json", "new_path": "native/package.json", "diff": "\"react-native-notifications\": \"git+https://git@github.com/ashoat/react-native-notifications.git\",\n\"react-native-onepassword\": \"^1.0.6\",\n\"react-native-segmented-control-tab\": \"^3.2.1\",\n- \"react-native-splash-screen\": \"^3.0.6\",\n+ \"react-native-splash-screen\": \"^3.1.0\",\n\"react-native-vector-icons\": \"^4.5.0\",\n\"react-navigation\": \"^2.3.1\",\n\"react-navigation-redux-helpers\": \"^2.0.1\",\n" }, { "change_type": "MODIFY", "old_path": "yarn.lock", "new_path": "yarn.lock", "diff": "@@ -7905,9 +7905,9 @@ react-native-segmented-control-tab@^3.2.1:\ndependencies:\nprop-types \"^15.5.10\"\n-react-native-splash-screen@^3.0.6:\n- version \"3.0.6\"\n- resolved \"https://registry.yarnpkg.com/react-native-splash-screen/-/react-native-splash-screen-3.0.6.tgz#c0bbf2c8ae40a313c4c7044f55e569414ff68332\"\n+react-native-splash-screen@^3.1.0:\n+ version \"3.1.0\"\n+ resolved \"https://registry.yarnpkg.com/react-native-splash-screen/-/react-native-splash-screen-3.1.0.tgz#9636f83d711dadded27167cdc3dc6aa98ec222ee\"\nreact-native-swipe-gestures@^1.0.2:\nversion \"1.0.2\"\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Update to react-native-splash-screen@3.1.0
129,187
10.07.2018 14:35:44
14,400
997abace9ff1bcecb0806f6caac67839a8ba4fc1
[native] codeVersion -> 13 First new release in over two months!
[ { "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 12\n- versionName \"0.0.12\"\n+ versionCode 13\n+ versionName \"0.0.13\"\nndk {\nabiFilters \"armeabi-v7a\", \"x86\"\n}\n" }, { "change_type": "MODIFY", "old_path": "native/android/app/src/main/AndroidManifest.xml", "new_path": "native/android/app/src/main/AndroidManifest.xml", "diff": "xmlns:android=\"http://schemas.android.com/apk/res/android\"\nxmlns:tools=\"http://schemas.android.com/tools\"\npackage=\"org.squadcal\"\n- android:versionCode=\"12\"\n- android:versionName=\"0.0.12\"\n+ android:versionCode=\"13\"\n+ android:versionName=\"0.0.13\"\n>\n<uses-permission android:name=\"android.permission.INTERNET\" />\n<uses-permission android:name=\"android.permission.SYSTEM_ALERT_WINDOW\"/>\n" }, { "change_type": "MODIFY", "old_path": "native/ios/SquadCal/AppDelegate.m", "new_path": "native/ios/SquadCal/AppDelegate.m", "diff": "#import <React/RCTRootView.h>\n#import <React/RCTLinkingManager.h>\n#import \"RNNotifications.h\"\n-#import \"SplashScreen.h\"\n+#import \"RNSplashScreen.h\"\n@implementation AppDelegate\nrootViewController.view = rootView;\nself.window.rootViewController = rootViewController;\n[self.window makeKeyAndVisible];\n- [SplashScreen show];\n+ [RNSplashScreen show];\nreturn YES;\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.12</string>\n+ <string>0.0.13</string>\n<key>CFBundleSignature</key>\n<string>????</string>\n<key>CFBundleVersion</key>\n- <string>12</string>\n+ <string>13</string>\n<key>LSApplicationQueriesSchemes</key>\n<array>\n<string>org-appextension-feature-password-management</string>\n" }, { "change_type": "MODIFY", "old_path": "native/persist.js", "new_path": "native/persist.js", "diff": "@@ -80,7 +80,7 @@ const persistConfig = {\nmigrate: createMigrate(migrations, { debug: __DEV__ }),\n};\n-const codeVersion = 12;\n+const codeVersion = 13;\n// This local exists to avoid a circular dependency where redux-setup needs to\n// import all the navigation and screen stuff, but some of those screens want to\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] codeVersion -> 13 First new release in over two months!
129,187
10.07.2018 15:12:13
14,400
4f3e6ab6c46b4332bab3d61f6fa75cda3c5579fa
[lib] Include all bots in isStaff
[ { "change_type": "MODIFY", "old_path": "lib/shared/user-utils.js", "new_path": "lib/shared/user-utils.js", "diff": "@@ -5,6 +5,7 @@ import type { RelativeMemberInfo } from '../types/thread-types';\nimport ashoat from '../facts/ashoat';\nimport friends from '../facts/friends';\n+import bots from '../facts/bots';\nfunction stringForUser(user: RelativeUserInfo | RelativeMemberInfo): string {\nif (user.isViewer) {\n@@ -17,7 +18,16 @@ function stringForUser(user: RelativeUserInfo | RelativeMemberInfo): string {\n}\nfunction isStaff(userID: string) {\n- return userID === ashoat.id;\n+ if (userID === ashoat.id) {\n+ return true;\n+ }\n+ for (let key in bots) {\n+ const bot = bots[key];\n+ if (userID === bot.userID) {\n+ return true;\n+ }\n+ }\n+ return false;\n}\nfunction hasWebChat(userID: string) {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[lib] Include all bots in isStaff
129,187
16.07.2018 10:36:30
14,400
19da21976a1b5ea35f81ca2614455712c89bd8f8
[native] Don't attempt scrollToKey until listDataWithHeights is ready
[ { "change_type": "MODIFY", "old_path": "native/calendar/calendar.react.js", "new_path": "native/calendar/calendar.react.js", "diff": "@@ -446,6 +446,12 @@ class InnerCalendar extends React.PureComponent<Props, State> {\nif (newStartDate < lastStartDate || newEndDate > lastEndDate) {\nthis.loadingFromScroll = false;\n}\n+\n+ const { keyboardShownHeight, lastEntryKeyActive } = this;\n+ if (newLDWH && keyboardShownHeight && lastEntryKeyActive) {\n+ this.scrollToKey(lastEntryKeyActive, keyboardShownHeight);\n+ this.lastEntryKeyActive = null;\n+ }\n}\nstatic datesFromListData(\n@@ -887,7 +893,7 @@ class InnerCalendar extends React.PureComponent<Props, State> {\nonEnterEntryEditMode = (entryInfo: EntryInfoWithHeight) => {\nconst key = entryKey(entryInfo);\nconst keyboardShownHeight = this.keyboardShownHeight;\n- if (keyboardShownHeight) {\n+ if (keyboardShownHeight && this.state.listDataWithHeights) {\nthis.scrollToKey(key, keyboardShownHeight);\n} else {\nthis.lastEntryKeyActive = key;\n@@ -899,7 +905,7 @@ class InnerCalendar extends React.PureComponent<Props, State> {\nconst keyboardShownHeight = event.endCoordinates.height + inputBarHeight;\nthis.keyboardShownHeight = keyboardShownHeight;\nconst lastEntryKeyActive = this.lastEntryKeyActive;\n- if (lastEntryKeyActive) {\n+ if (lastEntryKeyActive && this.state.listDataWithHeights) {\nthis.scrollToKey(lastEntryKeyActive, keyboardShownHeight);\nthis.lastEntryKeyActive = null;\n}\n@@ -928,12 +934,9 @@ class InnerCalendar extends React.PureComponent<Props, State> {\nif (Platform.OS === \"ios\") {\nvisibleHeight += tabBarSize;\n}\n- invariant(\n- this.currentScrollPosition !== undefined &&\n- this.currentScrollPosition !== null,\n- \"should be set\",\n- );\nif (\n+ this.currentScrollPosition !== undefined &&\n+ this.currentScrollPosition !== null &&\nitemStart > this.currentScrollPosition &&\nitemEnd < this.currentScrollPosition + visibleHeight\n) {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Don't attempt scrollToKey until listDataWithHeights is ready
129,187
17.07.2018 11:49:12
14,400
2f1b425ecf32e84eb357cc737381401727c259e0
Fix network memory leak The workaround is just to clone the result from the network request. Took me so long to figure this out.
[ { "change_type": "MODIFY", "old_path": "lib/utils/action-utils.js", "new_path": "lib/utils/action-utils.js", "diff": "@@ -357,12 +357,11 @@ function bindCookieAndUtilsIntoFetchJSON(\nreturn attemptToResolveInvalidation(newAnonymousCookie);\n};\n- return (async (\n+ return (\nendpoint: Endpoint,\ndata: Object,\noptions?: FetchJSONOptions,\n- ) => {\n- return await fetchJSON(\n+ ) => fetchJSON(\ncookie,\nboundSetCookie,\nwaitIfCookieInvalidated,\n@@ -372,7 +371,6 @@ function bindCookieAndUtilsIntoFetchJSON(\ndata,\noptions,\n);\n- });\n}\ntype ActionFunc = (fetchJSON: FetchJSON, ...rest: $FlowFixMe) => Promise<*>;\n@@ -409,9 +407,7 @@ const baseCreateBoundServerCallsSelector = (actionFunc: ActionFunc) => {\nurlPrefix,\ndeviceToken,\n);\n- return (async (...rest: $FlowFixMe) => {\n- return await actionFunc(boundFetchJSON, ...rest);\n- });\n+ return (...rest: $FlowFixMe) => actionFunc(boundFetchJSON, ...rest);\n},\n);\n}\n" }, { "change_type": "MODIFY", "old_path": "lib/utils/fetch-json.js", "new_path": "lib/utils/fetch-json.js", "diff": "@@ -6,6 +6,7 @@ import invariant from 'invariant';\nimport _map from 'lodash/fp/map';\nimport _find from 'lodash/fp/find';\nimport _filter from 'lodash/fp/filter';\n+import _cloneDeep from 'lodash/fp/cloneDeep';\nimport { ServerError, FetchTimeout } from './errors';\nimport { getConfig } from './config';\n@@ -54,7 +55,6 @@ async function fetchJSON(\n: { input };\nconst url = urlPrefix ? `${urlPrefix}/${endpoint}` : endpoint;\nconst fetchPromise = fetch(url, {\n- // Flow gets confused by some enum type, so we need this cast\n'method': 'POST',\n// This is necessary to allow cookie headers to get passed down to us\n'credentials': 'same-origin',\n@@ -75,7 +75,7 @@ async function fetchJSON(\nconst text = await response.text();\nlet json;\ntry {\n- json = JSON.parse(text);\n+ json = _cloneDeep(JSON.parse(text));\n} catch (e) {\nconsole.log(text);\nthrow e;\n" }, { "change_type": "MODIFY", "old_path": "native/app.react.js", "new_path": "native/app.react.js", "diff": "@@ -60,7 +60,7 @@ import SplashScreen from 'react-native-splash-screen';\nimport { registerConfig } from 'lib/utils/config';\nimport { connect } from 'lib/utils/redux-utils';\n-import { pingActionTypes, ping } from 'lib/actions/ping-actions';\n+import { ping } from 'lib/actions/ping-actions';\nimport {\nsessionInactivityLimit,\nsessionTimeLeft,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Fix network memory leak The workaround is just to clone the result from the network request. Took me so long to figure this out.
129,187
18.07.2018 15:07:45
14,400
f5d2190041549dc4a8890043590dd63e4edf6e43
[native] Update react-native-keychain And also add Feather from `react-native-vector-icons`
[ { "change_type": "ADD", "old_path": "native/android/app/src/main/assets/fonts/Feather.ttf", "new_path": "native/android/app/src/main/assets/fonts/Feather.ttf", "diff": "Binary files /dev/null and b/native/android/app/src/main/assets/fonts/Feather.ttf differ\n" }, { "change_type": "MODIFY", "old_path": "native/ios/SquadCal.xcodeproj/project.pbxproj", "new_path": "native/ios/SquadCal.xcodeproj/project.pbxproj", "diff": "AFA44E75249D4766A4ED74C7 /* Octicons.ttf in Resources */ = {isa = PBXBuildFile; fileRef = 2D04F3CCBAFF4A8184206FAC /* Octicons.ttf */; };\nBBC287C467984DA6BF85800E /* libSplashScreen.a in Frameworks */ = {isa = PBXBuildFile; fileRef = 8B6A1FF570694BFCB0D65D0E /* libSplashScreen.a */; };\nFA7F2215AD7646E2BE985BF3 /* SimpleLineIcons.ttf in Resources */ = {isa = PBXBuildFile; fileRef = AE31AFFF88FB4112A29ADE33 /* SimpleLineIcons.ttf */; };\n+ 09369EAAB869410E9C0208B4 /* Feather.ttf in Resources */ = {isa = PBXBuildFile; fileRef = A06F10E4481746D2B76CA60E /* Feather.ttf */; };\n/* End PBXBuildFile section */\n/* Begin PBXContainerItemProxy section */\nE7D7D614C3184B1BB95EE661 /* OnePassword.xcodeproj */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = \"wrapper.pb-project\"; name = OnePassword.xcodeproj; path = \"../node_modules/react-native-onepassword/OnePassword.xcodeproj\"; sourceTree = \"<group>\"; };\nEA40FBBA484449FAA8915A48 /* Foundation.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = Foundation.ttf; path = \"../node_modules/react-native-vector-icons/Fonts/Foundation.ttf\"; sourceTree = \"<group>\"; };\nEBD8879422144B0188A8336F /* Zocial.ttf */ = {isa = PBXFileReference; explicitFileType = undefined; fileEncoding = 9; includeInIndex = 0; lastKnownFileType = unknown; name = Zocial.ttf; path = \"../node_modules/react-native-vector-icons/Fonts/Zocial.ttf\"; sourceTree = \"<group>\"; };\n+ A06F10E4481746D2B76CA60E /* Feather.ttf */ = {isa = PBXFileReference; name = \"Feather.ttf\"; path = \"../node_modules/react-native-vector-icons/Fonts/Feather.ttf\"; sourceTree = \"<group>\"; fileEncoding = undefined; lastKnownFileType = unknown; explicitFileType = undefined; includeInIndex = 0; };\n/* End PBXFileReference section */\n/* Begin PBXFrameworksBuildPhase section */\n7FB58ABB1E7F6BC600B4C1B1 /* Anaheim-Regular.ttf */,\n7FB58ABC1E7F6BC600B4C1B1 /* OpenSans-Regular.ttf */,\n7FB58ABD1E7F6BC600B4C1B1 /* OpenSans-Semibold.ttf */,\n+ A06F10E4481746D2B76CA60E /* Feather.ttf */,\n);\nname = Resources;\nsourceTree = \"<group>\";\nAFA44E75249D4766A4ED74C7 /* Octicons.ttf in Resources */,\nFA7F2215AD7646E2BE985BF3 /* SimpleLineIcons.ttf in Resources */,\n2E5ADC2BAEA24F1AAD81E147 /* Zocial.ttf in Resources */,\n+ 09369EAAB869410E9C0208B4 /* Feather.ttf in Resources */,\n);\nrunOnlyForDeploymentPostprocessing = 0;\n};\n" }, { "change_type": "MODIFY", "old_path": "native/ios/SquadCal/Info.plist", "new_path": "native/ios/SquadCal/Info.plist", "diff": "</dict>\n</dict>\n<key>NSLocationWhenInUseUsageDescription</key>\n- <string></string>\n+ <string>React Native binary makes Apple think we use this, but we don't.</string>\n<key>UIAppFonts</key>\n<array>\n<string>OpenSans-Semibold.ttf</string>\n<string>Octicons.ttf</string>\n<string>SimpleLineIcons.ttf</string>\n<string>Zocial.ttf</string>\n+ <string>Feather.ttf</string>\n</array>\n<key>UIBackgroundModes</key>\n<array>\n<false/>\n<key>NSLocationAlwaysUsageDescription</key>\n<string>React Native binary makes Apple think we use this, but we don't.</string>\n- <key>NSLocationWhenInUseUsageDescription</key>\n- <string>React Native binary makes Apple think we use this, but we don't.</string>\n</dict>\n</plist>\n" }, { "change_type": "MODIFY", "old_path": "native/package.json", "new_path": "native/package.json", "diff": "\"react-native-floating-action\": \"^1.9.0\",\n\"react-native-hyperlink\": \"git+https://git@github.com/ashoat/react-native-hyperlink.git#both\",\n\"react-native-in-app-notification\": \"^2.1.0\",\n- \"react-native-keychain\": \"^1.2.1\",\n+ \"react-native-keychain\": \"^3.0.0-rc.3\",\n\"react-native-modal\": \"^6.2.0\",\n\"react-native-notifications\": \"git+https://git@github.com/ashoat/react-native-notifications.git\",\n\"react-native-onepassword\": \"^1.0.6\",\n" }, { "change_type": "MODIFY", "old_path": "yarn.lock", "new_path": "yarn.lock", "diff": "@@ -7789,9 +7789,9 @@ react-native-in-app-notification@^2.1.0:\ndependencies:\nreact-native-swipe-gestures \"^1.0.2\"\n-react-native-keychain@^1.2.1:\n- version \"1.2.1\"\n- resolved \"https://registry.yarnpkg.com/react-native-keychain/-/react-native-keychain-1.2.1.tgz#6b2bed32ca0460d641974193715d18c808b0f12f\"\n+react-native-keychain@^3.0.0-rc.3:\n+ version \"3.0.0-rc.3\"\n+ resolved \"https://registry.yarnpkg.com/react-native-keychain/-/react-native-keychain-3.0.0-rc.3.tgz#891ea07a564d1bf46b644bc615af21f15a04b12b\"\nreact-native-modal@^6.2.0:\nversion \"6.4.0\"\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Update react-native-keychain And also add Feather from `react-native-vector-icons`
129,187
18.07.2018 15:07:52
14,400
6cb95260b58261e7408794249920c8269e77c0a2
[server] Fix up loader.mjs for Node 10
[ { "change_type": "MODIFY", "old_path": "server/loader.mjs", "new_path": "server/loader.mjs", "diff": "@@ -7,8 +7,13 @@ const builtins = Module.builtinModules;\nconst extensions = { js: 'esm', json: \"json\" };\nconst access = Promise.denodeify(fs.access);\nconst readFile = Promise.denodeify(fs.readFile);\n+const baseURL = new URL('file://');\n-export async function resolve(specifier, parentModuleURL, defaultResolve) {\n+export async function resolve(\n+ specifier,\n+ parentModuleURL = baseURL,\n+ defaultResolve,\n+) {\n// Hitting node.js builtins from server\nif (builtins.includes(specifier)) {\n//console.log(`${specifier} is builtin`);\n@@ -45,7 +50,10 @@ export async function resolve(specifier, parentModuleURL, defaultResolve) {\n// Hitting web from server\nif (specifier.startsWith('web')) {\nconst result = defaultResolve(specifier, parentModuleURL);\n- const resultURL = result.url.replace(\"squadcal/web\", \"squadcal/server/dist/web\");\n+ const resultURL = result.url.replace(\n+ \"squadcal/web\",\n+ \"squadcal/server/dist/web\",\n+ );\n//console.log(`${specifier} -> ${resultURL} is server -> web`);\nreturn {\nurl: resultURL,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Fix up loader.mjs for Node 10
129,187
18.07.2018 15:07:08
14,400
06f5399e35dadd239823263582309c32bdd81dea
[native] Fix Entry resizing on iOS Height changes no longer get reported on a node with an explicit-height parent, so we have to remove the nodes we're using from the flow by absolute-positioning them.
[ { "change_type": "MODIFY", "old_path": "native/calendar/entry.react.js", "new_path": "native/calendar/entry.react.js", "diff": "@@ -344,7 +344,10 @@ class InternalEntry extends React.Component<Props, State> {\n}\nconst textStyle = { color: textColor };\nconst linkStyle = darkColor ? styles.lightLinkText : styles.darkLinkText;\n- const textContainerStyle = { height: this.state.height };\n+ // We use an empty View to set the height of the entry, and then position\n+ // the Text and TextInput absolutely. This allows to measure height changes\n+ // to the Text while controlling the actual height of the entry.\n+ const heightStyle = { height: this.state.height };\nconst entryStyle = { backgroundColor: `#${this.state.threadInfo.color}` };\nconst opacity = editing ? 1.0 : 0.6;\nreturn (\n@@ -356,8 +359,13 @@ class InternalEntry extends React.Component<Props, State> {\nandroidFormat=\"opacity\"\niosActiveOpacity={opacity}\n>\n- <View style={textContainerStyle}>\n- <Hyperlink linkDefault={true} linkStyle={linkStyle}>\n+ <View>\n+ <View style={heightStyle} />\n+ <Hyperlink\n+ linkDefault={true}\n+ linkStyle={linkStyle}\n+ style={styles.textContainer}\n+ >\n<Text\nstyle={[styles.text, textStyle]}\nonLayout={this.onTextLayout}\n@@ -624,16 +632,20 @@ const styles = StyleSheet.create({\ncolor: '#333333',\nfontFamily: 'Arial',\n},\n+ textContainer: {\n+ position: 'absolute',\n+ top: 0,\n+ padding: 0,\n+ margin: 0,\n+ },\ntextInput: {\nposition: 'absolute',\ntop: Platform.OS === \"android\" ? 5 : 0,\n- bottom: Platform.OS === \"android\" ? 6 : 0,\nleft: 10,\nright: 10,\npadding: 0,\nmargin: 0,\nfontSize: 16,\n- color: '#333333',\nfontFamily: 'Arial',\n},\nactionLinks: {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Fix Entry resizing on iOS Height changes no longer get reported on a node with an explicit-height parent, so we have to remove the nodes we're using from the flow by absolute-positioning them.
129,187
18.07.2018 15:05:20
14,400
d1f00d2667556e4339be37d9207f96d650b33400
[native] Fix accidental log-out `NAVIGATE_TO_APP` was getting triggered by `onInitialAppLoad` when `LoggedOutModal` gets instantiated for the first time. That should only happen when the app is started, and looks like that will get handled by `componentWillReceiveProps` anyways.
[ { "change_type": "MODIFY", "old_path": "native/account/logged-out-modal.react.js", "new_path": "native/account/logged-out-modal.react.js", "diff": "@@ -238,9 +238,6 @@ class InnerLoggedOutModal extends React.PureComponent<Props, State> {\nif (this.props.isForeground) {\nthis.onForeground();\n}\n- if (this.props.rehydrateConcluded) {\n- this.onInitialAppLoad(this.props);\n- }\n}\ncomponentWillUnmount() {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Fix accidental log-out `NAVIGATE_TO_APP` was getting triggered by `onInitialAppLoad` when `LoggedOutModal` gets instantiated for the first time. That should only happen when the app is started, and looks like that will get handled by `componentWillReceiveProps` anyways.
129,187
18.07.2018 17:38:20
14,400
cc9f5c942112ef19ffe76ee119ecbc9f09d4f1d3
[native] codeVersion -> 14 I guess 13 is bad luck...
[ { "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 13\n- versionName \"0.0.13\"\n+ versionCode 14\n+ versionName \"0.0.14\"\nndk {\nabiFilters \"armeabi-v7a\", \"x86\"\n}\n" }, { "change_type": "MODIFY", "old_path": "native/android/app/src/main/AndroidManifest.xml", "new_path": "native/android/app/src/main/AndroidManifest.xml", "diff": "xmlns:android=\"http://schemas.android.com/apk/res/android\"\nxmlns:tools=\"http://schemas.android.com/tools\"\npackage=\"org.squadcal\"\n- android:versionCode=\"13\"\n- android:versionName=\"0.0.13\"\n+ android:versionCode=\"14\"\n+ android:versionName=\"0.0.14\"\n>\n<uses-permission android:name=\"android.permission.INTERNET\" />\n<uses-permission android:name=\"android.permission.SYSTEM_ALERT_WINDOW\"/>\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.13</string>\n+ <string>0.0.14</string>\n<key>CFBundleSignature</key>\n<string>????</string>\n<key>CFBundleVersion</key>\n- <string>13</string>\n+ <string>14</string>\n<key>LSApplicationQueriesSchemes</key>\n<array>\n<string>org-appextension-feature-password-management</string>\n" }, { "change_type": "MODIFY", "old_path": "native/persist.js", "new_path": "native/persist.js", "diff": "@@ -80,7 +80,7 @@ const persistConfig = {\nmigrate: createMigrate(migrations, { debug: __DEV__ }),\n};\n-const codeVersion = 13;\n+const codeVersion = 14;\n// This local exists to avoid a circular dependency where redux-setup needs to\n// import all the navigation and screen stuff, but some of those screens want to\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] codeVersion -> 14 I guess 13 is bad luck...
129,187
20.07.2018 16:18:00
14,400
033e37a7d0c5157b7a5ab74c9eca84b7dd8312f8
[native] Update a couple packages
[ { "change_type": "MODIFY", "old_path": "native/package.json", "new_path": "native/package.json", "diff": "\"react-native-floating-action\": \"^1.9.0\",\n\"react-native-hyperlink\": \"git+https://git@github.com/ashoat/react-native-hyperlink.git#both\",\n\"react-native-in-app-notification\": \"^2.1.0\",\n- \"react-native-keychain\": \"^3.0.0-rc.3\",\n+ \"react-native-keychain\": \"^3.0.0\",\n\"react-native-modal\": \"^6.2.0\",\n\"react-native-notifications\": \"git+https://git@github.com/ashoat/react-native-notifications.git\",\n\"react-native-onepassword\": \"^1.0.6\",\n\"react-native-segmented-control-tab\": \"^3.2.1\",\n\"react-native-splash-screen\": \"^3.1.0\",\n\"react-native-vector-icons\": \"^4.5.0\",\n- \"react-navigation\": \"^2.6.2\",\n+ \"react-navigation\": \"^2.8.0\",\n\"react-navigation-redux-helpers\": \"^2.0.1\",\n\"react-redux\": \"^5.0.6\",\n\"redux\": \"^3.7.2\",\n" }, { "change_type": "MODIFY", "old_path": "yarn.lock", "new_path": "yarn.lock", "diff": "@@ -7789,9 +7789,9 @@ react-native-in-app-notification@^2.1.0:\ndependencies:\nreact-native-swipe-gestures \"^1.0.2\"\n-react-native-keychain@^3.0.0-rc.3:\n- version \"3.0.0-rc.3\"\n- resolved \"https://registry.yarnpkg.com/react-native-keychain/-/react-native-keychain-3.0.0-rc.3.tgz#891ea07a564d1bf46b644bc615af21f15a04b12b\"\n+react-native-keychain@^3.0.0:\n+ version \"3.0.0\"\n+ resolved \"https://registry.yarnpkg.com/react-native-keychain/-/react-native-keychain-3.0.0.tgz#29da1dfa43c2581f76bf9420914fd38a1558cf18\"\nreact-native-modal@^6.2.0:\nversion \"6.4.0\"\n@@ -7943,9 +7943,9 @@ react-navigation-tabs@0.5.1:\nreact-native-safe-area-view \"^0.7.0\"\nreact-native-tab-view \"^1.0.0\"\n-react-navigation@^2.6.2:\n- version \"2.6.2\"\n- resolved \"https://registry.yarnpkg.com/react-navigation/-/react-navigation-2.6.2.tgz#a8fdb69c5876698f7e58c5a3962a78ba24bb2058\"\n+react-navigation@^2.8.0:\n+ version \"2.8.0\"\n+ resolved \"https://registry.yarnpkg.com/react-navigation/-/react-navigation-2.8.0.tgz#c7f07a8d97ac99fa872e655783ad0a71563a9094\"\ndependencies:\nclamp \"^1.0.1\"\ncreate-react-context \"^0.2.1\"\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Update a couple packages
129,187
23.07.2018 20:00:48
14,400
1ff9e507a521e9dadb6345085a8fa94c886f05e8
updateTypes.BAD_DEVICE_TOKEN Now, the server will explicitly tell clients that their device token is invalid and they need to fetch a new one. Fixes issue that only I experience where I'm switching between prod and dev mode and need to switch my cookie's device token every once in a while.
[ { "change_type": "MODIFY", "old_path": "lib/reducers/device-token-reducer.js", "new_path": "lib/reducers/device-token-reducer.js", "diff": "// @flow\nimport type { BaseAction } from '../types/redux-types';\n+import { updateTypes } from '../types/update-types';\nimport { setDeviceTokenActionTypes } from '../actions/device-actions';\n+import { pingActionTypes } from '../actions/ping-actions';\nexport default function reduceDeviceToken(\nstate: ?string,\n@@ -10,6 +12,17 @@ export default function reduceDeviceToken(\n) {\nif (action.type === setDeviceTokenActionTypes.started) {\nreturn action.payload;\n+ } else if (action.type === pingActionTypes.success) {\n+ if (action.payload.updatesResult) {\n+ for (let update of action.payload.updatesResult.newUpdates) {\n+ if (\n+ update.type === updateTypes.BAD_DEVICE_TOKEN &&\n+ update.deviceToken === state\n+ ) {\n+ return null;\n+ }\n+ }\n+ }\n}\nreturn state;\n}\n" }, { "change_type": "MODIFY", "old_path": "lib/types/update-types.js", "new_path": "lib/types/update-types.js", "diff": "@@ -15,6 +15,7 @@ export const updateTypes = Object.freeze({\nUPDATE_THREAD_READ_STATUS: 2,\nDELETE_THREAD: 3,\nJOIN_THREAD: 4,\n+ BAD_DEVICE_TOKEN: 5,\n});\nexport type UpdateType = $Values<typeof updateTypes>;\nexport function assertUpdateType(\n@@ -25,7 +26,8 @@ export function assertUpdateType(\nourUpdateType === 1 ||\nourUpdateType === 2 ||\nourUpdateType === 3 ||\n- ourUpdateType === 4,\n+ ourUpdateType === 4 ||\n+ ourUpdateType === 5,\n\"number is not UpdateType enum\",\n);\nreturn ourUpdateType;\n@@ -62,12 +64,19 @@ type ThreadJoinUpdateData = {|\ntime: number,\nthreadID: string,\n|};\n+type BadDeviceTokenUpdateData = {|\n+ type: 5,\n+ userID: string,\n+ time: number,\n+ deviceToken: string,\n+|};\nexport type UpdateData =\n| AccountDeletionUpdateData\n| ThreadUpdateData\n| ThreadReadStatusUpdateData\n| ThreadDeletionUpdateData\n- | ThreadJoinUpdateData;\n+ | ThreadJoinUpdateData\n+ | BadDeviceTokenUpdateData;\ntype AccountDeletionUpdateInfo = {|\ntype: 0,\n@@ -104,12 +113,19 @@ type ThreadJoinUpdateInfo = {|\ncalendarQuery: CalendarQuery,\nrawEntryInfos: $ReadOnlyArray<RawEntryInfo>,\n|};\n+type BadDeviceTokenUpdateInfo = {|\n+ type: 5,\n+ id: string,\n+ time: number,\n+ deviceToken: string,\n+|};\nexport type UpdateInfo =\n| AccountDeletionUpdateInfo\n| ThreadUpdateInfo\n| ThreadReadStatusUpdateInfo\n| ThreadDeletionUpdateInfo\n- | ThreadJoinUpdateInfo;\n+ | ThreadJoinUpdateInfo\n+ | BadDeviceTokenUpdateInfo;\nexport type UpdatesResult = {|\ncurrentAsOf: number,\n" }, { "change_type": "MODIFY", "old_path": "native/app.react.js", "new_path": "native/app.react.js", "diff": "@@ -441,7 +441,6 @@ class AppWithNavigationState extends React.PureComponent<Props> {\n);\n}\nif (justLoggedIn) {\n- this.ensurePushNotifsEnabled();\nthis.startTimeouts(nextProps, \"active\");\n}\n@@ -489,13 +488,19 @@ class AppWithNavigationState extends React.PureComponent<Props> {\nbreak;\n}\n}\n+ }\n+ componentDidUpdate(prevProps: Props) {\nif (\n+ (this.props.loggedIn && !prevProps.loggedIn) ||\n+ (!this.props.deviceToken && prevProps.deviceToken) ||\n+ (\nAppWithNavigationState.serverRequestsHasDeviceTokenRequest(\n- nextProps.activeServerRequests,\n+ this.props.activeServerRequests,\n) &&\n!AppWithNavigationState.serverRequestsHasDeviceTokenRequest(\n- this.props.activeServerRequests,\n+ prevProps.activeServerRequests,\n+ )\n)\n) {\nthis.ensurePushNotifsEnabled();\n" }, { "change_type": "MODIFY", "old_path": "server/src/creators/update-creator.js", "new_path": "server/src/creators/update-creator.js", "diff": "@@ -47,9 +47,6 @@ import {\nimport { fetchMessageInfos } from '../fetchers/message-fetchers';\nimport { fetchEntryInfos } from '../fetchers/entry-fetchers';\n-// If the viewer is not passed in, the returned array will be empty, and the\n-// update won't have an updater_cookie. This should only be done when we are\n-// sure none of the updates are destined for the viewer.\nexport type ViewerInfo =\n| {| viewer: Viewer |}\n| {|\n@@ -69,9 +66,18 @@ const sortFunction = (\nb: UpdateData | UpdateInfo,\n) => a.time - b.time;\n+// Creates rows in the updates table based on the inputed updateDatas. Returns\n+// UpdateInfos pertaining to the provided viewerInfo, as well as related\n+// UserInfos.\n+// - If no viewerInfo is provided, no UpdateInfos will be returned. and the\n+// update row won't have an updater_cookie, meaning no cookie will be excluded\n+// from the update.\n+// - Most updates go to all a user's cookies, but if you want to target one in\n+// particular, you can use targetCookie.\nasync function createUpdates(\nupdateDatas: $ReadOnlyArray<UpdateData>,\n- viewerInfo?: ViewerInfo,\n+ viewerInfo?: ?ViewerInfo,\n+ targetCookie?: string,\n): Promise<UpdatesResult> {\nif (updateDatas.length === 0) {\nreturn defaultResult;\n@@ -194,6 +200,9 @@ async function createUpdates(\n) {\nconst { threadID } = updateData;\ncontent = JSON.stringify({ threadID });\n+ } else if (updateData.type == updateTypes.BAD_DEVICE_TOKEN) {\n+ const { deviceToken } = updateData;\n+ content = JSON.stringify({ deviceToken });\n} else {\ninvariant(false, `unrecognized updateType ${updateData.type}`);\n}\n@@ -214,10 +223,9 @@ async function createUpdates(\nkey,\ncontent,\nupdateData.time,\n+ viewerInfo ? viewerInfo.viewer.cookieID : null,\n+ targetCookie ? targetCookie : null,\n];\n- if (viewerInfo) {\n- insertRow.push(viewerInfo.viewer.cookieID);\n- }\ninsertRows.push(insertRow);\n}\n@@ -239,11 +247,10 @@ async function createUpdates(\nconst promises = {};\nif (insertRows.length > 0) {\n- const insertQuery = viewerInfo\n- ? SQL`\n- INSERT INTO updates(id, user, type, \\`key\\`, content, time, updater_cookie)\n- `\n- : SQL`INSERT INTO updates(id, user, type, \\`key\\`, content, time) `;\n+ const insertQuery = SQL`\n+ INSERT INTO updates(id, user, type, \\`key\\`,\n+ content, time, updater_cookie, target_cookie)\n+ `;\ninsertQuery.append(SQL`VALUES ${insertRows}`);\npromises.insert = dbQuery(insertQuery);\n}\n@@ -439,6 +446,13 @@ function updateInfosFromUpdateDatas(\ncalendarQuery,\nrawEntryInfos,\n});\n+ } else if (updateData.type === updateTypes.BAD_DEVICE_TOKEN) {\n+ updateInfos.push({\n+ type: updateTypes.BAD_DEVICE_TOKEN,\n+ id,\n+ time: updateData.time,\n+ deviceToken: updateData.deviceToken,\n+ });\n} else {\ninvariant(false, `unrecognized updateType ${updateData.type}`);\n}\n" }, { "change_type": "MODIFY", "old_path": "server/src/fetchers/update-fetchers.js", "new_path": "server/src/fetchers/update-fetchers.js", "diff": "@@ -32,6 +32,7 @@ async function fetchUpdateInfos(\nFROM updates\nWHERE user = ${viewer.id} AND time > ${currentAsOf}\nAND (updater_cookie IS NULL OR updater_cookie != ${viewer.cookieID})\n+ AND (target_cookie IS NULL OR target_cookie = ${viewer.cookieID})\nORDER BY time ASC\n`;\nconst [ result ] = await dbQuery(query);\n@@ -95,6 +96,14 @@ function viewerUpdateDataFromRow(\ntime: row.time,\nthreadID,\n};\n+ } else if (type === updateTypes.BAD_DEVICE_TOKEN) {\n+ const { deviceToken } = JSON.parse(row.content);\n+ data = {\n+ type: updateTypes.BAD_DEVICE_TOKEN,\n+ userID: viewer.id,\n+ time: row.time,\n+ deviceToken,\n+ };\n} else {\ninvariant(false, `unrecognized updateType ${type}`);\n}\n" }, { "change_type": "MODIFY", "old_path": "server/src/push/send.js", "new_path": "server/src/push/send.js", "diff": "@@ -12,6 +12,7 @@ import type {\nCollapsableNotifInfo,\nFetchCollapsableNotifsResult,\n} from '../fetchers/message-fetchers';\n+import { updateTypes } from 'lib/types/update-types';\nimport apn from 'apn';\nimport invariant from 'invariant';\n@@ -37,6 +38,7 @@ import { fetchServerThreadInfos } from '../fetchers/thread-fetchers';\nimport { fetchUserInfos } from '../fetchers/user-fetchers';\nimport { fetchCollapsableNotifs } from '../fetchers/message-fetchers';\nimport createIDs from '../creators/id-creator';\n+import { createUpdates } from '../creators/update-creator';\ntype Device = { deviceType: DeviceType, deviceToken: string };\ntype PushUserInfo = {\n@@ -198,16 +200,10 @@ async function sendPushNotifs(pushInfo: PushInfo) {\nnotifications[deliveryResult.dbID][5].androidID =\ndeliveryResult.fcmIDs[0];\n}\n- if (deliveryResult.invalidFCMTokens) {\n+ if (deliveryResult.invalidTokens) {\ninvalidTokens.push({\nuserID: notifications[deliveryResult.dbID][1],\n- fcmTokens: deliveryResult.invalidFCMTokens,\n- });\n- }\n- if (deliveryResult.invalidAPNTokens) {\n- invalidTokens.push({\n- userID: notifications[deliveryResult.dbID][1],\n- apnTokens: deliveryResult.invalidAPNTokens,\n+ tokens: deliveryResult.invalidTokens,\n});\n}\n}\n@@ -470,38 +466,66 @@ function prepareAndroidNotification(\n};\n}\n-type InvalidToken = {\n+type InvalidToken = {|\nuserID: string,\n- fcmTokens?: string[],\n- apnTokens?: string[],\n-};\n-async function removeInvalidTokens(invalidTokens: InvalidToken[]) {\n- const query = SQL`\n- UPDATE cookies\n- SET device_token = NULL\n+ tokens: string[],\n+|};\n+async function removeInvalidTokens(\n+ invalidTokens: $ReadOnlyArray<InvalidToken>,\n+): Promise<void> {\n+ const sqlTuples = invalidTokens.map(invalidTokenUser =>\n+ SQL`(\n+ user = ${invalidTokenUser.userID} AND\n+ device_token IN (${invalidTokenUser.tokens})\n+ )`\n+ );\n+ const sqlCondition = mergeOrConditions(sqlTuples);\n+\n+ const selectQuery = SQL`\n+ SELECT id, user, device_token\n+ FROM cookies\nWHERE\n`;\n+ selectQuery.append(sqlCondition);\n+ const [ result ] = await dbQuery(selectQuery);\n- const sqlTuples = [];\n- for (let invalidTokenUser of invalidTokens) {\n- const deviceConditions = [];\n- if (invalidTokenUser.fcmTokens && invalidTokenUser.fcmTokens.length > 0) {\n- deviceConditions.push(\n- SQL`device_token IN (${invalidTokenUser.fcmTokens})`,\n+ const userCookiePairsToInvalidDeviceTokens = new Map();\n+ for (let row of result) {\n+ const userCookiePair = `${row.user}|${row.id}`;\n+ const existing = userCookiePairsToInvalidDeviceTokens.get(userCookiePair);\n+ if (existing) {\n+ existing.add(row.device_token);\n+ } else {\n+ userCookiePairsToInvalidDeviceTokens.set(\n+ userCookiePair,\n+ new Set([row.device_token]),\n);\n}\n- if (invalidTokenUser.apnTokens && invalidTokenUser.apnTokens.length > 0) {\n- deviceConditions.push(\n- SQL`device_token IN (${invalidTokenUser.apnTokens})`,\n- );\n}\n- const statement = SQL`(user = ${invalidTokenUser.userID} AND `;\n- statement.append(mergeOrConditions(deviceConditions)).append(SQL`)`);\n- sqlTuples.push(statement);\n+\n+ const time = Date.now();\n+ const promises = [];\n+ for (let entry of userCookiePairsToInvalidDeviceTokens) {\n+ const [ userCookiePair, deviceTokens ] = entry;\n+ const [ userID, cookieID ] = userCookiePair.split('|');\n+ const updateDatas = [...deviceTokens].map(deviceToken => ({\n+ type: updateTypes.BAD_DEVICE_TOKEN,\n+ userID,\n+ time,\n+ deviceToken,\n+ }));\n+ promises.push(createUpdates(updateDatas, null, cookieID));\n}\n- query.append(mergeOrConditions(sqlTuples));\n- await dbQuery(query);\n+ const updateQuery = SQL`\n+ UPDATE cookies\n+ SET device_token = NULL\n+ WHERE\n+ `;\n+ updateQuery.append(sqlCondition);\n+ promises.push(dbQuery(updateQuery));\n+\n+ await Promise.all(promises);\n}\nexport {\n" }, { "change_type": "MODIFY", "old_path": "server/src/push/utils.js", "new_path": "server/src/push/utils.js", "diff": "@@ -41,7 +41,7 @@ async function apnPush(\n}\n}\nif (invalidTokens.length > 0) {\n- return { errors, invalidAPNTokens: invalidTokens, dbID };\n+ return { errors, invalidTokens, dbID };\n} else if (errors.length > 0) {\nreturn { errors, dbID };\n} else {\n@@ -102,7 +102,7 @@ async function fcmPush(\nresult.success = true;\n}\nif (invalidTokens.length > 0) {\n- result.invalidFCMTokens = invalidTokens;\n+ result.invalidTokens = invalidTokens;\n}\nreturn result;\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
updateTypes.BAD_DEVICE_TOKEN Now, the server will explicitly tell clients that their device token is invalid and they need to fetch a new one. Fixes issue that only I experience where I'm switching between prod and dev mode and need to switch my cookie's device token every once in a while.
129,187
23.07.2018 20:08:09
14,400
a277394512c8c99b8873ae25d849be01ccaed4e0
[server] Qualify URL use in Node loader.mjs
[ { "change_type": "MODIFY", "old_path": "server/loader.mjs", "new_path": "server/loader.mjs", "diff": "@@ -7,7 +7,7 @@ const builtins = Module.builtinModules;\nconst extensions = { js: 'esm', json: \"json\" };\nconst access = Promise.denodeify(fs.access);\nconst readFile = Promise.denodeify(fs.readFile);\n-const baseURL = new URL('file://');\n+const baseURL = new url.URL('file://');\nexport async function resolve(\nspecifier,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Qualify URL use in Node loader.mjs
129,187
25.07.2018 14:20:54
14,400
a527fcf7fa9114d381b4c275200146ecbd78f4cd
Always include CalendarQuery when logging in (Or resetting password.) This also refactors the extra params we need for log in to be in a type `LogInExtraInfo`, so we can easily add more if need be.
[ { "change_type": "ADD", "old_path": null, "new_path": "lib/selectors/account-selectors.js", "diff": "+// @flow\n+\n+import type { BaseAppState } from '../types/redux-types';\n+import type { CalendarQuery } from '../types/entry-types';\n+import type { LogInExtraInfo } from '../types/account-types';\n+import { isDeviceType, assertDeviceType } from '../types/device-types';\n+\n+import { createSelector } from 'reselect';\n+\n+import { currentCalendarQuery } from './nav-selectors';\n+import { getConfig } from '../utils/config';\n+\n+const logInExtraInfoSelector = createSelector(\n+ (state: BaseAppState<*>) => state.deviceToken,\n+ currentCalendarQuery,\n+ (\n+ deviceToken: ?string,\n+ calendarQuery: () => CalendarQuery,\n+ ) => {\n+ let deviceTokenUpdateRequest = null;\n+ const platform = getConfig().platformDetails.platform;\n+ if (deviceToken && isDeviceType(platform)) {\n+ const deviceType = assertDeviceType(platform);\n+ deviceTokenUpdateRequest = { deviceType, deviceToken };\n+ }\n+ // Return a function since we depend on the time of evaluation\n+ return (): LogInExtraInfo => ({\n+ calendarQuery: calendarQuery(),\n+ deviceTokenUpdateRequest,\n+ });\n+ },\n+);\n+\n+export {\n+ logInExtraInfoSelector,\n+};\n" }, { "change_type": "MODIFY", "old_path": "lib/selectors/nav-selectors.js", "new_path": "lib/selectors/nav-selectors.js", "diff": "@@ -9,7 +9,6 @@ import type { CalendarFilter } from '../types/filter-types';\nimport { createSelector } from 'reselect';\nimport _some from 'lodash/fp/some';\n-import invariant from 'invariant';\nimport { threadPermissions } from '../types/thread-types';\nimport { fifteenDaysEarlier, fifteenDaysLater } from '../utils/date-utils';\n@@ -52,23 +51,17 @@ const currentCalendarQuery = createSelector(\n(state: BaseAppState<*>) => state.navInfo,\n(state: BaseAppState<*>) => state.calendarFilters,\n(\n- lastUserInteractionCalendar: ?number,\n+ lastUserInteractionCalendar: number,\nnavInfo: BaseNavInfo,\ncalendarFilters: $ReadOnlyArray<CalendarFilter>,\n) => {\n- const lastUserInteractionCalendar2 = lastUserInteractionCalendar;\n- invariant(\n- lastUserInteractionCalendar2 !== undefined &&\n- lastUserInteractionCalendar2 !== null,\n- \"calendar should have a lastUserInteraction entry\",\n- );\n// Return a function since we depend on the time of evaluation\nreturn (): CalendarQuery => ({\nstartDate: currentStartDate(\n- lastUserInteractionCalendar2,\n+ lastUserInteractionCalendar,\nnavInfo.startDate,\n),\n- endDate: currentEndDate(lastUserInteractionCalendar2, navInfo.endDate),\n+ endDate: currentEndDate(lastUserInteractionCalendar, navInfo.endDate),\nfilters: calendarFilters,\n});\n},\n" }, { "change_type": "MODIFY", "old_path": "lib/types/account-types.js", "new_path": "lib/types/account-types.js", "diff": "@@ -79,11 +79,15 @@ export type LogInStartingPayload = {|\ncalendarQuery?: CalendarQuery,\n|};\n+export type LogInExtraInfo = {|\n+ calendarQuery: CalendarQuery,\n+ deviceTokenUpdateRequest?: ?DeviceTokenUpdateRequest,\n+|};\n+\nexport type LogInInfo = {|\n+ ...LogInExtraInfo,\nusernameOrEmail: string,\npassword: string,\n- calendarQuery?: ?CalendarQuery,\n- deviceTokenUpdateRequest?: ?DeviceTokenUpdateRequest,\n|};\nexport type LogInRequest = {|\n@@ -114,10 +118,9 @@ export type LogInResult = {|\n|};\nexport type UpdatePasswordInfo = {|\n+ ...LogInExtraInfo,\ncode: string,\npassword: string,\n- calendarQuery?: ?CalendarQuery,\n- deviceTokenUpdateRequest?: ?DeviceTokenUpdateRequest,\n|};\nexport type UpdatePasswordRequest = {|\n" }, { "change_type": "MODIFY", "old_path": "lib/utils/action-utils.js", "new_path": "lib/utils/action-utils.js", "diff": "@@ -14,6 +14,7 @@ import type {\nLogInActionSource,\nLogInStartingPayload,\nLogInResult,\n+ LogInExtraInfo,\n} from '../types/account-types';\nimport type { Endpoint } from '../types/endpoints';\n@@ -224,9 +225,9 @@ function setCookie(\nasync function fetchNewCookieFromNativeCredentials(\ndispatch: Dispatch,\ncookie: ?string,\n- source: null | LogInActionSource,\nurlPrefix: string,\n- deviceToken: ?string,\n+ source: LogInActionSource,\n+ logInExtraInfo: () => LogInExtraInfo,\n): Promise<?string> {\nlet newValidCookie = null;\nlet fetchJSONCallback = null;\n@@ -283,7 +284,7 @@ async function fetchNewCookieFromNativeCredentials(\nawait resolveInvalidatedCookie(\nboundFetchJSON,\ndispatchRecoveryAttempt,\n- deviceToken,\n+ logInExtraInfo,\n);\nreturn newValidCookie;\n}\n@@ -294,7 +295,7 @@ function bindCookieAndUtilsIntoFetchJSON(\ndispatch: Dispatch,\ncookie: ?string,\nurlPrefix: string,\n- deviceToken: ?string,\n+ logInExtraInfo: () => LogInExtraInfo,\n): FetchJSON {\nconst boundSetCookie = (newCookie: ?string, response: Object) => {\nsetCookie(dispatch, cookie, newCookie, response);\n@@ -319,9 +320,9 @@ function bindCookieAndUtilsIntoFetchJSON(\nconst newValidCookie = await fetchNewCookieFromNativeCredentials(\ndispatch,\nnewAnonymousCookie,\n- cookieInvalidationResolutionAttempt,\nurlPrefix,\n- deviceToken,\n+ cookieInvalidationResolutionAttempt,\n+ logInExtraInfo,\n);\ncurrentlyWaitingForNewCookie = false;\n@@ -333,7 +334,7 @@ function bindCookieAndUtilsIntoFetchJSON(\ndispatch,\nnewValidCookie,\nurlPrefix,\n- deviceToken,\n+ logInExtraInfo,\n)\n: null;\nfor (const func of currentWaitingCalls) {\n@@ -378,7 +379,7 @@ type BindServerCallsParams = {\ndispatch: Dispatch,\ncookie: ?string,\nurlPrefix: string,\n- deviceToken: ?string,\n+ logInExtraInfo: () => LogInExtraInfo,\n};\n// All server calls needs to include some information from the Redux state\n@@ -394,18 +395,18 @@ const baseCreateBoundServerCallsSelector = (actionFunc: ActionFunc) => {\n(state: BindServerCallsParams) => state.dispatch,\n(state: BindServerCallsParams) => state.cookie,\n(state: BindServerCallsParams) => state.urlPrefix,\n- (state: BindServerCallsParams) => state.deviceToken,\n+ (state: BindServerCallsParams) => state.logInExtraInfo,\n(\ndispatch: Dispatch,\ncookie: ?string,\nurlPrefix: string,\n- deviceToken: ?string,\n+ logInExtraInfo: () => LogInExtraInfo,\n) => {\nconst boundFetchJSON = bindCookieAndUtilsIntoFetchJSON(\ndispatch,\ncookie,\nurlPrefix,\n- deviceToken,\n+ logInExtraInfo,\n);\nreturn (...rest: $FlowFixMe) => actionFunc(boundFetchJSON, ...rest);\n},\n@@ -418,20 +419,24 @@ export type ServerCalls = {[name: string]: ServerCall};\nfunction bindServerCalls(serverCalls: ServerCalls) {\nreturn (\n- stateProps: { cookie: ?string, urlPrefix: string, deviceToken: ?string },\n+ stateProps: {\n+ cookie: ?string,\n+ urlPrefix: string,\n+ logInExtraInfo: () => LogInExtraInfo,\n+ },\ndispatchProps: Object,\nownProps: {[propName: string]: mixed},\n) => {\nconst dispatch = dispatchProps.dispatch;\ninvariant(dispatch, \"should be defined\");\n- const { cookie, urlPrefix, deviceToken } = stateProps;\n+ const { cookie, urlPrefix, logInExtraInfo } = stateProps;\nconst boundServerCalls = _mapValues(\n(serverCall: (fetchJSON: FetchJSON, ...rest: any) => Promise<any>) =>\ncreateBoundServerCallsSelector(serverCall)({\ndispatch,\ncookie,\nurlPrefix,\n- deviceToken,\n+ logInExtraInfo,\n}),\n)(serverCalls);\nreturn {\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@@ -10,7 +11,7 @@ export type Config = {\nresolveInvalidatedCookie: ?((\nfetchJSON: FetchJSON,\ndispatchRecoveryAttempt: DispatchRecoveryAttempt,\n- deviceToken: ?string,\n+ logInExtraInfo: () => LogInExtraInfo,\n) => Promise<void>),\ngetNewCookie: ?((response: Object) => Promise<?string>),\nsetCookieOnRequest: 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 { BaseAppState } from '../types/redux-types';\n+import type { LogInExtraInfo } from '../types/account-types';\nimport { connect as reactReduxConnect } from 'react-redux';\nimport invariant from 'invariant';\n@@ -10,6 +11,7 @@ import {\nincludeDispatchActionProps,\nbindServerCalls,\n} from './action-utils';\n+import { logInExtraInfoSelector } from '../selectors/account-selectors';\nfunction connect<S: BaseAppState<*>, OP: Object, SP: Object>(\ninputMapStateToProps: ?((state: S, ownProps: OP) => SP),\n@@ -24,13 +26,13 @@ function connect<S: BaseAppState<*>, OP: Object, SP: Object>(\n...SP,\ncookie: ?string,\nurlPrefix: string,\n- deviceToken: ?string,\n+ logInExtraInfo: () => LogInExtraInfo,\n} => {\nreturn {\n...mapStateToProps(state, ownProps),\ncookie: state.cookie,\nurlPrefix: state.urlPrefix,\n- deviceToken: state.deviceToken,\n+ logInExtraInfo: logInExtraInfoSelector(state),\n};\n};\n} else if (serverCallExists && mapStateToProps) {\n@@ -38,14 +40,14 @@ function connect<S: BaseAppState<*>, OP: Object, SP: Object>(\n...SP,\ncookie: ?string,\nurlPrefix: string,\n- deviceToken: ?string,\n+ logInExtraInfo: () => LogInExtraInfo,\n} => {\nreturn {\n// $FlowFixMe\n...mapStateToProps(state),\ncookie: state.cookie,\nurlPrefix: state.urlPrefix,\n- deviceToken: state.deviceToken,\n+ logInExtraInfo: logInExtraInfoSelector(state),\n};\n};\n} else if (mapStateToProps && mapStateToProps.length > 1) {\n@@ -62,12 +64,12 @@ function connect<S: BaseAppState<*>, OP: Object, SP: Object>(\nmapState = (state: S): {\ncookie: ?string,\nurlPrefix: string,\n- deviceToken: ?string,\n+ logInExtraInfo: () => LogInExtraInfo,\n} => {\nreturn {\ncookie: state.cookie,\nurlPrefix: state.urlPrefix,\n- deviceToken: state.deviceToken,\n+ logInExtraInfo: logInExtraInfoSelector(state),\n};\n};\n} else {\n" }, { "change_type": "MODIFY", "old_path": "native/account/log-in-panel.react.js", "new_path": "native/account/log-in-panel.react.js", "diff": "import type { DispatchActionPromise } from 'lib/utils/action-utils';\nimport type { AppState } from '../redux-setup';\nimport type { LoadingStatus } from 'lib/types/loading-types';\n-import type { LogInInfo, LogInResult } from 'lib/types/account-types';\n-import type { CalendarQuery } from 'lib/types/entry-types';\n+import type {\n+ LogInInfo,\n+ LogInExtraInfo,\n+ LogInResult,\n+} from 'lib/types/account-types';\nimport {\ntype StateContainer,\nstateContainerPropType,\n@@ -33,7 +36,7 @@ import {\nlogIn,\n} from 'lib/actions/user-actions';\nimport { createLoadingStatusSelector } from 'lib/selectors/loading-selectors';\n-import { currentCalendarQuery } from 'lib/selectors/nav-selectors';\n+import { logInExtraInfoSelector } from 'lib/selectors/account-selectors';\nimport { TextInput, usernamePlaceholder } from './modal-components.react';\nimport {\n@@ -45,7 +48,6 @@ import {\nfetchNativeCredentials,\nsetNativeCredentials,\n} from './native-credentials';\n-import { getDeviceTokenUpdateRequest } from '../utils/device-token-utils';\nexport type LogInState = {\nusernameOrEmailInputText: string,\n@@ -59,8 +61,7 @@ type Props = {\nstate: StateContainer<LogInState>,\n// Redux state\nloadingStatus: LoadingStatus,\n- currentCalendarQuery: () => CalendarQuery,\n- deviceToken: ?string,\n+ logInExtraInfo: () => LogInExtraInfo,\n// Redux dispatch functions\ndispatchActionPromise: DispatchActionPromise,\n// async functions that hit server APIs\n@@ -75,8 +76,7 @@ class LogInPanel extends React.PureComponent<Props> {\ninnerRef: PropTypes.func.isRequired,\nstate: stateContainerPropType.isRequired,\nloadingStatus: PropTypes.string.isRequired,\n- currentCalendarQuery: PropTypes.func.isRequired,\n- deviceToken: PropTypes.string,\n+ logInExtraInfo: PropTypes.func.isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\nlogIn: PropTypes.func.isRequired,\n};\n@@ -200,12 +200,12 @@ class LogInPanel extends React.PureComponent<Props> {\n}\nKeyboard.dismiss();\n- const calendarQuery = this.props.currentCalendarQuery();\n+ const extraInfo = this.props.logInExtraInfo();\nthis.props.dispatchActionPromise(\nlogInActionTypes,\n- this.logInAction(calendarQuery),\n+ this.logInAction(extraInfo),\nundefined,\n- { calendarQuery },\n+ { calendarQuery: extraInfo.calendarQuery },\n);\n}\n@@ -222,15 +222,12 @@ class LogInPanel extends React.PureComponent<Props> {\n);\n}\n- async logInAction(calendarQuery: CalendarQuery) {\n- const deviceTokenUpdateRequest =\n- getDeviceTokenUpdateRequest(this.props.deviceToken);\n+ async logInAction(extraInfo: LogInExtraInfo) {\ntry {\nconst result = await this.props.logIn({\nusernameOrEmail: this.props.state.state.usernameOrEmailInputText,\npassword: this.props.state.state.passwordInputText,\n- calendarQuery,\n- deviceTokenUpdateRequest,\n+ ...extraInfo,\n});\nthis.props.setActiveAlert(false);\nawait setNativeCredentials({\n@@ -329,8 +326,7 @@ const loadingStatusSelector = createLoadingStatusSelector(logInActionTypes);\nexport default connect(\n(state: AppState) => ({\nloadingStatus: loadingStatusSelector(state),\n- currentCalendarQuery: currentCalendarQuery(state),\n- deviceToken: state.deviceToken,\n+ logInExtraInfo: logInExtraInfoSelector(state),\n}),\n{ logIn },\n)(LogInPanel);\n" }, { "change_type": "MODIFY", "old_path": "native/account/logged-out-modal.react.js", "new_path": "native/account/logged-out-modal.react.js", "diff": "@@ -16,6 +16,7 @@ import type {\nimport type { KeyboardEvent, EmitterSubscription } from '../keyboard';\nimport type { LogInState } from './log-in-panel.react';\nimport type { RegisterState } from './register-panel.react';\n+import type { LogInExtraInfo } from 'lib/types/account-types';\nimport * as React from 'react';\nimport {\n@@ -51,6 +52,7 @@ import {\nimport sleep from 'lib/utils/sleep';\nimport { dispatchPing } from 'lib/shared/ping-utils';\nimport { connect } from 'lib/utils/redux-utils';\n+import { logInExtraInfoSelector } from 'lib/selectors/account-selectors';\nimport {\nwindowHeight,\n@@ -93,7 +95,7 @@ type Props = {\nisForeground: bool,\npingStartingPayload: () => PingStartingPayload,\npingActionInput: (startingPayload: PingStartingPayload) => PingActionInput,\n- deviceToken: ?string,\n+ logInExtraInfo: () => LogInExtraInfo,\n// Redux dispatch functions\ndispatch: Dispatch,\ndispatchActionPayload: DispatchActionPayload,\n@@ -125,7 +127,7 @@ class InnerLoggedOutModal extends React.PureComponent<Props, State> {\nisForeground: PropTypes.bool.isRequired,\npingStartingPayload: PropTypes.func.isRequired,\npingActionInput: PropTypes.func.isRequired,\n- deviceToken: PropTypes.string,\n+ logInExtraInfo: PropTypes.func.isRequired,\ndispatch: PropTypes.func.isRequired,\ndispatchActionPayload: PropTypes.func.isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\n@@ -305,9 +307,9 @@ class InnerLoggedOutModal extends React.PureComponent<Props, State> {\nconst newCookie = await fetchNewCookieFromNativeCredentials(\nnextProps.dispatch,\ncookie,\n- appStartNativeCredentialsAutoLogIn,\nurlPrefix,\n- nextProps.deviceToken,\n+ appStartNativeCredentialsAutoLogIn,\n+ nextProps.logInExtraInfo,\n);\nif (!newCookie || !newCookie.startsWith(\"user=\")) {\nshowPrompt();\n@@ -325,9 +327,9 @@ class InnerLoggedOutModal extends React.PureComponent<Props, State> {\nconst newCookie = await fetchNewCookieFromNativeCredentials(\nnextProps.dispatch,\ncookie,\n- appStartReduxLoggedInButInvalidCookie,\nurlPrefix,\n- nextProps.deviceToken,\n+ appStartReduxLoggedInButInvalidCookie,\n+ nextProps.logInExtraInfo,\n);\nif (newCookie && newCookie.startsWith(\"user=\")) {\n// If this happens we know that LOG_IN_SUCCESS has been dispatched\n@@ -351,7 +353,7 @@ class InnerLoggedOutModal extends React.PureComponent<Props, State> {\ndispatch: props.dispatch,\ncookie,\nurlPrefix,\n- deviceToken: props.deviceToken,\n+ logInExtraInfo: props.logInExtraInfo,\n});\ndispatchPing({ ...props, ping: boundPing });\n}\n@@ -842,7 +844,7 @@ const LoggedOutModal = connect(\nisForeground: isForegroundSelector(state),\npingStartingPayload: pingNativeStartingPayload(state),\npingActionInput: pingActionInput(state),\n- deviceToken: state.deviceToken,\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,8 +16,6 @@ import URL from 'url-parse';\nimport { logInActionTypes, logIn } from 'lib/actions/user-actions';\n-import { getDeviceTokenUpdateRequest } from '../utils/device-token-utils';\n-\ntype Credentials = {|\nusername: string,\npassword: string,\n@@ -219,11 +218,11 @@ async function deleteNativeCredentialsFor(username: string) {\nasync function resolveInvalidatedCookie(\nfetchJSON: FetchJSON,\ndispatchRecoveryAttempt: DispatchRecoveryAttempt,\n- deviceToken: ?string,\n+ logInExtraInfo: () => LogInExtraInfo,\n) {\n- const deviceTokenUpdateRequest = getDeviceTokenUpdateRequest(deviceToken);\nconst keychainCredentials = await fetchNativeKeychainCredentials();\nif (keychainCredentials) {\n+ const extraInfo = logInExtraInfo();\nconst newCookie = await dispatchRecoveryAttempt(\nlogInActionTypes,\nlogIn(\n@@ -231,7 +230,7 @@ async function resolveInvalidatedCookie(\n{\nusernameOrEmail: keychainCredentials.username,\npassword: keychainCredentials.password,\n- deviceTokenUpdateRequest,\n+ ...extraInfo,\n},\n),\n);\n@@ -241,6 +240,7 @@ async function resolveInvalidatedCookie(\n}\nconst sharedWebCredentials = getNativeSharedWebCredentials();\nif (sharedWebCredentials) {\n+ const extraInfo = logInExtraInfo();\nawait dispatchRecoveryAttempt(\nlogInActionTypes,\nlogIn(\n@@ -248,7 +248,7 @@ async function resolveInvalidatedCookie(\n{\nusernameOrEmail: sharedWebCredentials.username,\npassword: sharedWebCredentials.password,\n- deviceTokenUpdateRequest,\n+ ...extraInfo,\n},\n),\n);\n" }, { "change_type": "MODIFY", "old_path": "native/account/reset-password-panel.react.js", "new_path": "native/account/reset-password-panel.react.js", "diff": "import type { AppState } from '../redux-setup';\nimport type { LoadingStatus } from 'lib/types/loading-types';\nimport type { DispatchActionPromise } from 'lib/utils/action-utils';\n-import type { UpdatePasswordInfo, LogInResult } from 'lib/types/account-types';\n-import type { CalendarQuery } from 'lib/types/entry-types';\n+import type {\n+ UpdatePasswordInfo,\n+ LogInExtraInfo,\n+ LogInResult,\n+} from 'lib/types/account-types';\nimport React from 'react';\nimport {\n@@ -26,7 +29,7 @@ import {\nresetPassword,\n} from 'lib/actions/user-actions';\nimport { connect } from 'lib/utils/redux-utils';\n-import { currentCalendarQuery } from 'lib/selectors/nav-selectors';\n+import { logInExtraInfoSelector } from 'lib/selectors/account-selectors';\nimport { TextInput } from './modal-components.react';\nimport {\n@@ -34,7 +37,6 @@ import {\nPanelOnePasswordButton,\nPanel,\n} from './panel-components.react';\n-import { getDeviceTokenUpdateRequest } from '../utils/device-token-utils';\ntype Props = {\nverifyCode: string,\n@@ -45,8 +47,7 @@ type Props = {\nopacityValue: Animated.Value,\n// Redux state\nloadingStatus: LoadingStatus,\n- currentCalendarQuery: () => CalendarQuery,\n- deviceToken: ?string,\n+ logInExtraInfo: () => LogInExtraInfo,\n// Redux dispatch functions\ndispatchActionPromise: DispatchActionPromise,\n// async functions that hit server APIs\n@@ -66,8 +67,7 @@ class ResetPasswordPanel extends React.PureComponent<Props, State> {\nsetActiveAlert: PropTypes.func.isRequired,\nopacityValue: PropTypes.object.isRequired,\nloadingStatus: PropTypes.string.isRequired,\n- currentCalendarQuery: PropTypes.func.isRequired,\n- deviceToken: PropTypes.string,\n+ logInExtraInfo: PropTypes.func.isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\nresetPassword: PropTypes.func.isRequired,\n};\n@@ -182,12 +182,12 @@ class ResetPasswordPanel extends React.PureComponent<Props, State> {\nreturn;\n}\nKeyboard.dismiss();\n- const calendarQuery = this.props.currentCalendarQuery();\n+ const extraInfo = this.props.logInExtraInfo();\nthis.props.dispatchActionPromise(\nresetPasswordActionTypes,\n- this.resetPasswordAction(calendarQuery),\n+ this.resetPasswordAction(extraInfo),\nundefined,\n- { calendarQuery },\n+ { calendarQuery: extraInfo.calendarQuery },\n);\n}\n@@ -205,15 +205,12 @@ class ResetPasswordPanel extends React.PureComponent<Props, State> {\n);\n}\n- async resetPasswordAction(calendarQuery: CalendarQuery) {\n- const deviceTokenUpdateRequest =\n- getDeviceTokenUpdateRequest(this.props.deviceToken);\n+ async resetPasswordAction(extraInfo: LogInExtraInfo) {\ntry {\nconst result = await this.props.resetPassword({\n+ ...extraInfo,\ncode: this.props.verifyCode,\npassword: this.state.passwordInputText,\n- calendarQuery,\n- deviceTokenUpdateRequest,\n});\nthis.props.setActiveAlert(false);\nthis.props.onSuccess();\n@@ -275,8 +272,7 @@ const loadingStatusSelector\nexport default connect(\n(state: AppState) => ({\nloadingStatus: loadingStatusSelector(state),\n- currentCalendarQuery: currentCalendarQuery(state),\n- deviceToken: state.deviceToken,\n+ logInExtraInfo: logInExtraInfoSelector(state),\n}),\n{ resetPassword },\n)(ResetPasswordPanel);\n" }, { "change_type": "DELETE", "old_path": "native/utils/device-token-utils.js", "new_path": null, "diff": "-// @flow\n-\n-import type { DeviceTokenUpdateRequest } from 'lib/types/device-types';\n-\n-import { Platform } from 'react-native';\n-\n-function getDeviceTokenUpdateRequest(\n- deviceToken: ?string,\n-): ?DeviceTokenUpdateRequest {\n- if (!deviceToken) {\n- return null;\n- }\n- return {\n- deviceType: Platform.OS,\n- deviceToken,\n- };\n-}\n-\n-export {\n- getDeviceTokenUpdateRequest,\n-};\n" }, { "change_type": "MODIFY", "old_path": "web/modals/account/log-in-modal.react.js", "new_path": "web/modals/account/log-in-modal.react.js", "diff": "import type { AppState } from '../../redux-setup';\nimport type { DispatchActionPromise } from 'lib/utils/action-utils';\n-import type { LogInInfo, LogInResult } from 'lib/types/account-types';\n+import type {\n+ LogInInfo,\n+ LogInExtraInfo,\n+ LogInResult,\n+} from 'lib/types/account-types';\nimport * as React from 'react';\nimport invariant from 'invariant';\n@@ -15,6 +19,7 @@ import {\nimport { connect } from 'lib/utils/redux-utils';\nimport { logInActionTypes, logIn } from 'lib/actions/user-actions';\nimport { createLoadingStatusSelector } from 'lib/selectors/loading-selectors';\n+import { logInExtraInfoSelector } from 'lib/selectors/account-selectors';\nimport css from '../../style.css';\nimport Modal from '../modal.react';\n@@ -24,6 +29,7 @@ type Props = {\nsetModal: (modal: ?React.Node) => void,\n// Redux state\ninputDisabled: bool,\n+ logInExtraInfo: () => LogInExtraInfo,\n// Redux dispatch functions\ndispatchActionPromise: DispatchActionPromise,\n// async functions that hit server APIs\n@@ -157,14 +163,21 @@ class LogInModal extends React.PureComponent<Props, State> {\nreturn;\n}\n- this.props.dispatchActionPromise(logInActionTypes, this.logInAction());\n+ const extraInfo = this.props.logInExtraInfo();\n+ this.props.dispatchActionPromise(\n+ logInActionTypes,\n+ this.logInAction(extraInfo),\n+ undefined,\n+ { calendarQuery: extraInfo.calendarQuery },\n+ );\n}\n- async logInAction() {\n+ async logInAction(extraInfo: LogInExtraInfo) {\ntry {\nconst result = await this.props.logIn({\nusernameOrEmail: this.state.usernameOrEmail,\npassword: this.state.password,\n+ ...extraInfo,\n});\nthis.clearModal();\nreturn result;\n@@ -223,6 +236,7 @@ class LogInModal extends React.PureComponent<Props, State> {\nLogInModal.propTypes = {\nsetModal: PropTypes.func.isRequired,\ninputDisabled: PropTypes.bool.isRequired,\n+ logInExtraInfo: PropTypes.func.isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\nlogIn: PropTypes.func.isRequired,\n};\n@@ -232,6 +246,7 @@ const loadingStatusSelector = createLoadingStatusSelector(logInActionTypes);\nexport default connect(\n(state: AppState) => ({\ninputDisabled: loadingStatusSelector(state) === \"loading\",\n+ logInExtraInfo: logInExtraInfoSelector(state),\n}),\n{ logIn },\n)(LogInModal);\n" }, { "change_type": "MODIFY", "old_path": "web/modals/account/reset-password-modal.react.js", "new_path": "web/modals/account/reset-password-modal.react.js", "diff": "import type { AppState } from '../../redux-setup';\nimport type { DispatchActionPromise } from 'lib/utils/action-utils';\n-import type { UpdatePasswordInfo, LogInResult } from 'lib/types/account-types';\n+import type {\n+ UpdatePasswordInfo,\n+ LogInExtraInfo,\n+ LogInResult,\n+} from 'lib/types/account-types';\nimport * as React from 'react';\nimport invariant from 'invariant';\n@@ -14,6 +18,7 @@ import {\nresetPassword,\n} from 'lib/actions/user-actions';\nimport { createLoadingStatusSelector } from 'lib/selectors/loading-selectors';\n+import { logInExtraInfoSelector } from 'lib/selectors/account-selectors';\nimport css from '../../style.css';\nimport Modal from '../modal.react';\n@@ -25,6 +30,7 @@ type Props = {\nresetPasswordUsername: string,\nverifyCode: string,\ninputDisabled: bool,\n+ logInExtraInfo: () => LogInExtraInfo,\n// Redux dispatch functions\ndispatchActionPromise: DispatchActionPromise,\n// async functions that hit server APIs\n@@ -156,17 +162,21 @@ class ResetPasswordModal extends React.PureComponent<Props, State> {\nreturn;\n}\n+ const extraInfo = this.props.logInExtraInfo();\nthis.props.dispatchActionPromise(\nresetPasswordActionTypes,\n- this.resetPasswordAction(),\n+ this.resetPasswordAction(extraInfo),\n+ undefined,\n+ { calendarQuery: extraInfo.calendarQuery },\n);\n}\n- async resetPasswordAction() {\n+ async resetPasswordAction(extraInfo: LogInExtraInfo) {\ntry {\nconst response = await this.props.resetPassword({\ncode: this.props.verifyCode,\npassword: this.state.password,\n+ ...extraInfo,\n});\nthis.props.onSuccess();\nreturn response;\n@@ -194,6 +204,7 @@ ResetPasswordModal.propTypes = {\nresetPasswordUsername: PropTypes.string.isRequired,\nverifyCode: PropTypes.string.isRequired,\ninputDisabled: PropTypes.bool.isRequired,\n+ logInExtraInfo: PropTypes.func.isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\nresetPassword: PropTypes.func.isRequired,\n};\n@@ -206,6 +217,7 @@ export default connect(\nresetPasswordUsername: state.resetPasswordUsername,\nverifyCode: state.navInfo.verify,\ninputDisabled: loadingStatusSelector(state) === \"loading\",\n+ logInExtraInfo: logInExtraInfoSelector(state),\n}),\n{ resetPassword },\n)(ResetPasswordModal);\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Always include CalendarQuery when logging in (Or resetting password.) This also refactors the extra params we need for log in to be in a type `LogInExtraInfo`, so we can easily add more if need be.
129,187
25.07.2018 15:12:58
14,400
885aea0e0ffd2f4b17e7e61c349929929afe286c
Include CalendarQuery in RegisterRequest
[ { "change_type": "MODIFY", "old_path": "lib/reducers/nav-reducer.js", "new_path": "lib/reducers/nav-reducer.js", "diff": "@@ -11,6 +11,7 @@ import {\nimport {\nlogInActionTypes,\nresetPasswordActionTypes,\n+ registerActionTypes,\n} from '../actions/user-actions';\nimport { pingActionTypes } from '../actions/ping-actions';\n@@ -44,6 +45,7 @@ export default function reduceBaseNavInfo<T: BaseNavInfo>(\n} else if (\naction.type === logInActionTypes.started ||\naction.type === resetPasswordActionTypes.started ||\n+ action.type === registerActionTypes.started ||\naction.type === pingActionTypes.started\n) {\nconst calendarQuery = action.payload && action.payload.calendarQuery;\n" }, { "change_type": "MODIFY", "old_path": "lib/types/account-types.js", "new_path": "lib/types/account-types.js", "diff": "@@ -38,6 +38,7 @@ export type LogOutResponse = {|\n|};\nexport type RegisterInfo = {|\n+ ...LogInExtraInfo,\nusername: string,\nemail: string,\npassword: string,\n@@ -47,6 +48,8 @@ export type RegisterRequest = {|\nusername: string,\nemail: string,\npassword: string,\n+ calendarQuery?: ?CalendarQuery,\n+ deviceTokenUpdateRequest?: ?DeviceTokenUpdateRequest,\nplatformDetails?: PlatformDetails,\n|};\n" }, { "change_type": "MODIFY", "old_path": "lib/types/redux-types.js", "new_path": "lib/types/redux-types.js", "diff": "@@ -195,6 +195,7 @@ export type BaseAction =\n|} | {|\ntype: \"REGISTER_STARTED\",\nloadingInfo: LoadingInfo,\n+ payload?: LogInStartingPayload,\n|} | {|\ntype: \"REGISTER_FAILED\",\nerror: true,\n" }, { "change_type": "MODIFY", "old_path": "native/account/register-panel.react.js", "new_path": "native/account/register-panel.react.js", "diff": "import type { DispatchActionPromise } from 'lib/utils/action-utils';\nimport type { AppState } from '../redux-setup';\nimport type { LoadingStatus } from 'lib/types/loading-types';\n-import type { RegisterInfo, RegisterResult } from 'lib/types/account-types';\n+import type {\n+ RegisterInfo,\n+ LogInExtraInfo,\n+ RegisterResult,\n+} from 'lib/types/account-types';\nimport {\ntype StateContainer,\nstateContainerPropType,\n@@ -30,6 +34,7 @@ import {\nvalidUsernameRegex,\nvalidEmailRegex,\n} from 'lib/shared/account-regexes';\n+import { logInExtraInfoSelector } from 'lib/selectors/account-selectors';\nimport { TextInput } from './modal-components.react';\nimport {\n@@ -52,6 +57,7 @@ type Props = {\nstate: StateContainer<RegisterState>,\n// Redux state\nloadingStatus: LoadingStatus,\n+ logInExtraInfo: () => LogInExtraInfo,\n// Redux dispatch functions\ndispatchActionPromise: DispatchActionPromise,\n// async functions that hit server APIs\n@@ -65,6 +71,7 @@ class RegisterPanel extends React.PureComponent<Props> {\nonePasswordSupported: PropTypes.bool.isRequired,\nstate: stateContainerPropType.isRequired,\nloadingStatus: PropTypes.string.isRequired,\n+ logInExtraInfo: PropTypes.func.isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\nregister: PropTypes.func.isRequired,\n};\n@@ -257,9 +264,12 @@ class RegisterPanel extends React.PureComponent<Props> {\n);\n} else {\nKeyboard.dismiss();\n+ const extraInfo = this.props.logInExtraInfo();\nthis.props.dispatchActionPromise(\nregisterActionTypes,\n- this.registerAction(),\n+ this.registerAction(extraInfo),\n+ undefined,\n+ { calendarQuery: extraInfo.calendarQuery },\n);\n}\n}\n@@ -304,12 +314,13 @@ class RegisterPanel extends React.PureComponent<Props> {\n);\n}\n- async registerAction() {\n+ async registerAction(extraInfo: LogInExtraInfo) {\ntry {\nconst result = await this.props.register({\nusername: this.props.state.state.usernameInputText,\nemail: this.props.state.state.emailInputText,\npassword: this.props.state.state.passwordInputText,\n+ ...extraInfo,\n});\nthis.props.setActiveAlert(false);\nawait setNativeCredentials({\n@@ -409,6 +420,7 @@ const loadingStatusSelector = createLoadingStatusSelector(registerActionTypes);\nexport default connect(\n(state: AppState) => ({\nloadingStatus: loadingStatusSelector(state),\n+ logInExtraInfo: logInExtraInfoSelector(state),\n}),\n{ register },\n)(RegisterPanel);\n" }, { "change_type": "MODIFY", "old_path": "server/src/creators/account-creator.js", "new_path": "server/src/creators/account-creator.js", "diff": "@@ -24,6 +24,7 @@ import { deleteCookie } from '../deleters/cookie-deleters';\nimport { sendEmailAddressVerificationEmail } from '../emails/verification';\nimport createMessages from './message-creator';\nimport createThread from './thread-creator';\n+import { verifyCalendarQueryThreadIDs } from '../responders/entry-responders';\nconst ashoatMessages = [\n\"welcome to SquadCal! thanks for helping to test the alpha.\",\n@@ -55,10 +56,14 @@ async function createAccount(\nFROM users\nWHERE LCASE(email) = LCASE(${request.email})\n`;\n- const [ [ usernameResult ], [ emailResult ] ] = await Promise.all([\n+ const promises = [\ndbQuery(usernameQuery),\ndbQuery(emailQuery),\n- ]);\n+ ];\n+ if (request.calendarQuery) {\n+ promises.push(verifyCalendarQueryThreadIDs(request.calendarQuery));\n+ }\n+ const [ [ usernameResult ], [ emailResult ] ] = await Promise.all(promises);\nif (usernameResult[0].count !== 0) {\nthrow new ServerError('username_taken');\n}\n" }, { "change_type": "MODIFY", "old_path": "server/src/responders/entry-responders.js", "new_path": "server/src/responders/entry-responders.js", "diff": "@@ -54,6 +54,19 @@ const entryQueryInputValidator = tShape({\n}),\n]))),\n});\n+const newEntryQueryInputValidator = tShape({\n+ startDate: tDate,\n+ endDate: tDate,\n+ filters: t.list(t.union([\n+ tShape({\n+ type: tString(calendarThreadFilterTypes.NOT_DELETED),\n+ }),\n+ tShape({\n+ type: tString(calendarThreadFilterTypes.THREAD_LIST),\n+ threadIDs: t.list(t.String),\n+ }),\n+ ])),\n+});\nfunction normalizeCalendarQuery(\ninput: any,\n@@ -187,6 +200,7 @@ async function entryRestorationResponder(\nexport {\nentryQueryInputValidator,\n+ newEntryQueryInputValidator,\nnormalizeCalendarQuery,\nverifyCalendarQueryThreadIDs,\nentryFetchResponder,\n" }, { "change_type": "MODIFY", "old_path": "server/src/responders/user-responders.js", "new_path": "server/src/responders/user-responders.js", "diff": "@@ -54,6 +54,7 @@ import { deleteAccount } from '../deleters/account-deleters';\nimport createAccount from '../creators/account-creator';\nimport {\nentryQueryInputValidator,\n+ newEntryQueryInputValidator,\nnormalizeCalendarQuery,\nverifyCalendarQueryThreadIDs,\n} from './entry-responders';\n@@ -156,6 +157,8 @@ const registerRequestInputValidator = tShape({\nusername: t.String,\nemail: t.String,\npassword: tPassword,\n+ calendarQuery: t.maybe(newEntryQueryInputValidator),\n+ deviceTokenUpdateRequest: t.maybe(deviceTokenUpdateRequestInputValidator),\nplatform: t.maybe(tPlatform),\nplatformDetails: t.maybe(tPlatformDetails),\n});\n" }, { "change_type": "MODIFY", "old_path": "web/modals/account/register-modal.react.js", "new_path": "web/modals/account/register-modal.react.js", "diff": "import type { AppState } from '../../redux-setup';\nimport type { DispatchActionPromise } from 'lib/utils/action-utils';\n-import type { RegisterInfo, RegisterResult } from 'lib/types/account-types';\n+import type {\n+ RegisterInfo,\n+ LogInExtraInfo,\n+ RegisterResult,\n+} from 'lib/types/account-types';\nimport * as React from 'react';\nimport invariant from 'invariant';\n@@ -15,6 +19,7 @@ import {\nimport { connect } from 'lib/utils/redux-utils';\nimport { registerActionTypes, register } from 'lib/actions/user-actions';\nimport { createLoadingStatusSelector } from 'lib/selectors/loading-selectors';\n+import { logInExtraInfoSelector } from 'lib/selectors/account-selectors';\nimport css from '../../style.css';\nimport Modal from '../modal.react';\n@@ -24,6 +29,7 @@ type Props = {\nsetModal: (modal: ?React.Node) => void,\n// Redux state\ninputDisabled: bool,\n+ logInExtraInfo: () => LogInExtraInfo,\n// Redux dispatch functions\ndispatchActionPromise: DispatchActionPromise,\n// async functions that hit server APIs\n@@ -219,19 +225,23 @@ class RegisterModal extends React.PureComponent<Props, State> {\n},\n);\n} else {\n+ const extraInfo = this.props.logInExtraInfo();\nthis.props.dispatchActionPromise(\nregisterActionTypes,\n- this.registerAction(),\n+ this.registerAction(extraInfo),\n+ undefined,\n+ { calendarQuery: extraInfo.calendarQuery },\n);\n}\n}\n- async registerAction() {\n+ async registerAction(extraInfo: LogInExtraInfo) {\ntry {\nconst result = await this.props.register({\nusername: this.state.username,\nemail: this.state.email,\npassword: this.state.password,\n+ ...extraInfo,\n});\nthis.props.setModal(<VerifyEmailModal onClose={this.clearModal} />);\nreturn result;\n@@ -286,6 +296,7 @@ class RegisterModal extends React.PureComponent<Props, State> {\nRegisterModal.propTypes = {\nsetModal: PropTypes.func.isRequired,\ninputDisabled: PropTypes.bool.isRequired,\n+ logInExtraInfo: PropTypes.func.isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\nregister: PropTypes.func.isRequired,\n};\n@@ -295,6 +306,7 @@ const loadingStatusSelector = createLoadingStatusSelector(registerActionTypes);\nexport default connect(\n(state: AppState) => ({\ninputDisabled: loadingStatusSelector(state) === \"loading\",\n+ logInExtraInfo: logInExtraInfoSelector(state),\n}),\n{ register },\n)(RegisterModal);\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Include CalendarQuery in RegisterRequest
129,187
26.07.2018 11:12:24
14,400
c344a20a6b399d23b1a86c4f7f581b693048c045
[server] `filters` table to store CalendarQueries on a per-cookie basis
[ { "change_type": "MODIFY", "old_path": "server/src/creators/account-creator.js", "new_path": "server/src/creators/account-creator.js", "diff": "@@ -25,6 +25,7 @@ import { sendEmailAddressVerificationEmail } from '../emails/verification';\nimport createMessages from './message-creator';\nimport createThread from './thread-creator';\nimport { verifyCalendarQueryThreadIDs } from '../responders/entry-responders';\n+import { createFilter } from './filter-creator';\nconst ashoatMessages = [\n\"welcome to SquadCal! thanks for helping to test the alpha.\",\n@@ -60,8 +61,9 @@ async function createAccount(\ndbQuery(usernameQuery),\ndbQuery(emailQuery),\n];\n- if (request.calendarQuery) {\n- promises.push(verifyCalendarQueryThreadIDs(request.calendarQuery));\n+ const { calendarQuery } = request;\n+ if (calendarQuery) {\n+ promises.push(verifyCalendarQueryThreadIDs(calendarQuery));\n}\nconst [ [ usernameResult ], [ emailResult ] ] = await Promise.all(promises);\nif (usernameResult[0].count !== 0) {\n@@ -111,6 +113,7 @@ async function createAccount(\ninitialMemberIDs: [ashoat.id],\n},\n),\n+ calendarQuery ? createFilter(viewer, calendarQuery) : undefined,\n]);\nlet messageTime = Date.now();\nconst ashoatMessageDatas = ashoatMessages.map(message => ({\n" }, { "change_type": "ADD", "old_path": null, "new_path": "server/src/creators/filter-creator.js", "diff": "+// @flow\n+\n+import type { Viewer } from '../session/viewer';\n+import type { CalendarQuery } from 'lib/types/entry-types';\n+\n+import { dbQuery, SQL } from '../database';\n+\n+// \"Filter\" here refers to the \"filters\" table in MySQL, which stores\n+// CalendarQueries on a per-cookie basis\n+async function createFilter(\n+ viewer: Viewer,\n+ calendarQuery: CalendarQuery,\n+): Promise<void> {\n+ const row = [\n+ viewer.id,\n+ viewer.cookieID,\n+ JSON.stringify(calendarQuery),\n+ Date.now(),\n+ ];\n+ const query = SQL`\n+ INSERT INTO filters (user, cookie, query, time)\n+ VALUES ${[row]}\n+ ON DUPLICATE KEY UPDATE query = VALUES(query), time = VALUES(time)\n+ `;\n+ await dbQuery(query);\n+}\n+\n+export {\n+ createFilter,\n+};\n" }, { "change_type": "MODIFY", "old_path": "server/src/responders/ping-responders.js", "new_path": "server/src/responders/ping-responders.js", "diff": "@@ -41,6 +41,7 @@ import {\n} from '../session/cookies';\nimport { deviceTokenUpdater } from '../updaters/device-token-updaters';\nimport createReport from '../creators/report-creator';\n+import { createFilter } from '../creators/filter-creator';\nconst pingRequestInputValidator = tShape({\ncalendarQuery: entryQueryInputValidator,\n@@ -108,7 +109,8 @@ async function pingResponder(\nthrow new ServerError('invalid_parameters');\n}\n- await verifyCalendarQueryThreadIDs(request.calendarQuery);\n+ const { calendarQuery } = request;\n+ await verifyCalendarQueryThreadIDs(calendarQuery);\nconst threadCursors = {};\nfor (let watchedThreadID of request.watchedIDs) {\n@@ -188,11 +190,12 @@ async function pingResponder(\ndefaultNumberPerThread,\n),\nfetchThreadInfos(viewer),\n- fetchEntryInfos(viewer, request.calendarQuery),\n+ fetchEntryInfos(viewer, calendarQuery),\nfetchCurrentUserInfo(viewer),\nclientResponsePromises.length > 0\n? Promise.all(clientResponsePromises)\n: null,\n+ calendarQuery ? createFilter(viewer, calendarQuery) : undefined,\n]);\nlet updatesResult = null;\n@@ -200,7 +203,7 @@ async function pingResponder(\nconst { updateInfos } = await fetchUpdateInfos(\nviewer,\noldUpdatesCurrentAsOf,\n- { ...threadsResult, calendarQuery: request.calendarQuery },\n+ { ...threadsResult, calendarQuery },\n);\nconst newUpdatesCurrentAsOf = mostRecentUpdateTimestamp(\n[...updateInfos],\n" }, { "change_type": "MODIFY", "old_path": "server/src/responders/user-responders.js", "new_path": "server/src/responders/user-responders.js", "diff": "@@ -64,6 +64,7 @@ import { fetchEntryInfos } from '../fetchers/entry-fetchers';\nimport { deviceTokenUpdater } from '../updaters/device-token-updaters';\nimport { deviceTokenUpdateRequestInputValidator } from './device-responders';\nimport { sendAccessRequestEmailToAshoat } from '../emails/access-request';\n+import { createFilter } from '../creators/filter-creator';\nconst subscriptionUpdateRequestInputValidator = tShape({\nthreadID: t.String,\n@@ -246,6 +247,7 @@ async function logInResponder(\nrequest.deviceTokenUpdateRequest\n? deviceTokenUpdater(viewer, request.deviceTokenUpdateRequest)\n: undefined,\n+ calendarQuery ? createFilter(viewer, calendarQuery) : undefined,\n]);\nconst rawEntryInfos = entriesResult ? entriesResult.rawEntryInfos : null;\n" }, { "change_type": "MODIFY", "old_path": "server/src/updaters/account-updaters.js", "new_path": "server/src/updaters/account-updaters.js", "diff": "@@ -24,6 +24,7 @@ import { createNewUserCookie } from '../session/cookies';\nimport { fetchMessageInfos } from '../fetchers/message-fetchers';\nimport { fetchEntryInfos } from '../fetchers/entry-fetchers';\nimport { verifyCalendarQueryThreadIDs } from '../responders/entry-responders';\n+import { createFilter } from '../creators/filter-creator';\nasync function accountUpdater(\nviewer: Viewer,\n@@ -193,6 +194,7 @@ async function updatePassword(\ndefaultNumberPerThread,\n),\ncalendarQuery ? fetchEntryInfos(viewer, calendarQuery) : undefined,\n+ calendarQuery ? createFilter(viewer, calendarQuery) : undefined,\n]);\nconst rawEntryInfos = entriesResult ? entriesResult.rawEntryInfos : null;\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] `filters` table to store CalendarQueries on a per-cookie basis
129,187
26.07.2018 13:47:57
14,400
eea0195da2f18bd5e385f985f54465693bb922b8
[server] Only save new CalendarQuery if it's different from the old one
[ { "change_type": "ADD", "old_path": null, "new_path": "server/src/fetchers/filter-fetchers.js", "diff": "+// @flow\n+\n+import type { Viewer } from '../session/viewer';\n+import type { CalendarQuery } from 'lib/types/entry-types';\n+\n+import { dbQuery, SQL } from '../database';\n+\n+// \"Filter\" here refers to the \"filters\" table in MySQL, which stores\n+// CalendarQueries on a per-cookie basis\n+async function fetchCurrentFilter(\n+ viewer: Viewer,\n+): Promise<?CalendarQuery> {\n+ const query = SQL`\n+ SELECT query\n+ FROM filters\n+ WHERE user = ${viewer.id} AND cookie = ${viewer.cookieID}\n+ `;\n+ const [ result ] = await dbQuery(query);\n+ if (result.length === 0) {\n+ return null;\n+ }\n+ const row = result[0];\n+ return row.query;\n+}\n+\n+export {\n+ fetchCurrentFilter,\n+};\n" }, { "change_type": "MODIFY", "old_path": "server/src/responders/ping-responders.js", "new_path": "server/src/responders/ping-responders.js", "diff": "@@ -12,6 +12,7 @@ import { reportTypes } from 'lib/types/report-types';\nimport t from 'tcomb';\nimport invariant from 'invariant';\n+import _isEqual from 'lodash/fp/isEqual';\nimport { ServerError } from 'lib/utils/errors';\nimport { mostRecentMessageTimestamp } from 'lib/shared/message-utils';\n@@ -42,6 +43,7 @@ import {\nimport { deviceTokenUpdater } from '../updaters/device-token-updaters';\nimport createReport from '../creators/report-creator';\nimport { createFilter } from '../creators/filter-creator';\n+import { fetchCurrentFilter } from '../fetchers/filter-fetchers';\nconst pingRequestInputValidator = tShape({\ncalendarQuery: entryQueryInputValidator,\n@@ -182,6 +184,7 @@ async function pingResponder(\nthreadsResult,\nentriesResult,\ncurrentUserInfo,\n+ currentCalendarQuery,\n] = await Promise.all([\nfetchMessageInfosSince(\nviewer,\n@@ -192,10 +195,10 @@ async function pingResponder(\nfetchThreadInfos(viewer),\nfetchEntryInfos(viewer, calendarQuery),\nfetchCurrentUserInfo(viewer),\n+ calendarQuery ? fetchCurrentFilter(viewer) : undefined,\nclientResponsePromises.length > 0\n? Promise.all(clientResponsePromises)\n: null,\n- calendarQuery ? createFilter(viewer, calendarQuery) : undefined,\n]);\nlet updatesResult = null;\n@@ -215,13 +218,20 @@ async function pingResponder(\n};\n}\n- const timestampUpdatePromises = [ updateActivityTime(viewer) ];\n+ const updatePromises = [ updateActivityTime(viewer) ];\nif (updatesResult && updatesResult.newUpdates.length > 0) {\n- timestampUpdatePromises.push(\n+ updatePromises.push(\nrecordDeliveredUpdate(viewer.cookieID, updatesResult.currentAsOf),\n);\n}\n- await Promise.all(timestampUpdatePromises);\n+ if (\n+ calendarQuery &&\n+ (!currentCalendarQuery ||\n+ !_isEqual(currentCalendarQuery)(calendarQuery))\n+ ) {\n+ updatePromises.push(createFilter(viewer, calendarQuery));\n+ }\n+ await Promise.all(updatePromises);\nconst userInfos: any = Object.values({\n...messagesResult.userInfos,\n" }, { "change_type": "MODIFY", "old_path": "server/src/responders/user-responders.js", "new_path": "server/src/responders/user-responders.js", "diff": "@@ -64,7 +64,7 @@ import { fetchEntryInfos } from '../fetchers/entry-fetchers';\nimport { deviceTokenUpdater } from '../updaters/device-token-updaters';\nimport { deviceTokenUpdateRequestInputValidator } from './device-responders';\nimport { sendAccessRequestEmailToAshoat } from '../emails/access-request';\n-import { createFilter } from '../creators/filter-creator';\n+import { updateFilterIfChanged } from '../updaters/filter-updaters';\nconst subscriptionUpdateRequestInputValidator = tShape({\nthreadID: t.String,\n@@ -247,7 +247,7 @@ async function logInResponder(\nrequest.deviceTokenUpdateRequest\n? deviceTokenUpdater(viewer, request.deviceTokenUpdateRequest)\n: undefined,\n- calendarQuery ? createFilter(viewer, calendarQuery) : undefined,\n+ calendarQuery ? updateFilterIfChanged(viewer, calendarQuery) : undefined,\n]);\nconst rawEntryInfos = entriesResult ? entriesResult.rawEntryInfos : null;\n" }, { "change_type": "MODIFY", "old_path": "server/src/updaters/account-updaters.js", "new_path": "server/src/updaters/account-updaters.js", "diff": "@@ -24,7 +24,7 @@ import { createNewUserCookie } from '../session/cookies';\nimport { fetchMessageInfos } from '../fetchers/message-fetchers';\nimport { fetchEntryInfos } from '../fetchers/entry-fetchers';\nimport { verifyCalendarQueryThreadIDs } from '../responders/entry-responders';\n-import { createFilter } from '../creators/filter-creator';\n+import { updateFilterIfChanged } from '../updaters/filter-updaters';\nasync function accountUpdater(\nviewer: Viewer,\n@@ -194,7 +194,7 @@ async function updatePassword(\ndefaultNumberPerThread,\n),\ncalendarQuery ? fetchEntryInfos(viewer, calendarQuery) : undefined,\n- calendarQuery ? createFilter(viewer, calendarQuery) : undefined,\n+ calendarQuery ? updateFilterIfChanged(viewer, calendarQuery) : undefined,\n]);\nconst rawEntryInfos = entriesResult ? entriesResult.rawEntryInfos : null;\n" }, { "change_type": "ADD", "old_path": null, "new_path": "server/src/updaters/filter-updaters.js", "diff": "+// @flow\n+\n+import type { Viewer } from '../session/viewer';\n+import type { CalendarQuery } from 'lib/types/entry-types';\n+\n+import _isEqual from 'lodash/fp/isEqual';\n+\n+import { dbQuery, SQL } from '../database';\n+import { fetchCurrentFilter } from '../fetchers/filter-fetchers';\n+import { createFilter } from '../creators/filter-creator';\n+\n+// \"Filter\" here refers to the \"filters\" table in MySQL, which stores\n+// CalendarQueries on a per-cookie basis\n+async function updateFilterIfChanged(\n+ viewer: Viewer,\n+ newCalendarQuery: CalendarQuery,\n+): Promise<void> {\n+ const oldCalendarQuery = await fetchCurrentFilter(viewer);\n+ if (oldCalendarQuery && _isEqual(oldCalendarQuery)(newCalendarQuery)) {\n+ return;\n+ }\n+ await createFilter(viewer, newCalendarQuery);\n+}\n+\n+export {\n+ updateFilterIfChanged,\n+};\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Only save new CalendarQuery if it's different from the old one
129,187
26.07.2018 14:39:17
14,400
bec4cd91d5c998ab8aaca4594a4e166055b953f0
[native] Don't allow ping to log in except at app start A `PING_SUCCESS` should only result in a log-in if the corresponding `PING_STARTED` occurred while the user was logged out.
[ { "change_type": "MODIFY", "old_path": "native/navigation-setup.js", "new_path": "native/navigation-setup.js", "diff": "@@ -526,6 +526,13 @@ function removeModalsIfPingIndicatesLoggedIn(\n// handling specific log ins that occur from LoggedOutModal.\nreturn state;\n}\n+ if (payload.loggedIn) {\n+ // If the user was logged in at the time the ping was started, then the only\n+ // reason they would logged out now is either a cookie invalidation or a\n+ // user-initiated log out. We only want to allow a ping to log somebody in\n+ // when the app is started and the user is logged out.\n+ return state;\n+ }\nreturn removeModals(state, justLoggedOutModal);\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Don't allow ping to log in except at app start A `PING_SUCCESS` should only result in a log-in if the corresponding `PING_STARTED` occurred while the user was logged out.
129,187
26.07.2018 15:18:19
14,400
d934e32db0ab9edca1ea4cad3e67461c28eb5fa3
[server] Fix subscription issues All new threads were getting disabled push notifs, AND it was impossible to enable push notifs. Sigh...
[ { "change_type": "MODIFY", "old_path": "server/src/updaters/thread-permission-updaters.js", "new_path": "server/src/updaters/thread-permission-updaters.js", "diff": "@@ -438,9 +438,7 @@ async function saveMemberships(toSave: $ReadOnlyArray<RowToSave>) {\nrowToSave.threadID,\nrowToSave.role,\ntime,\n- rowToSave.subscription\n- ? JSON.stringify(rowToSave.subscription)\n- : defaultSubscriptionString,\n+ subscription,\nJSON.stringify(rowToSave.permissions),\nrowToSave.permissionsForChildren\n? JSON.stringify(rowToSave.permissionsForChildren)\n" }, { "change_type": "MODIFY", "old_path": "server/src/updaters/user-subscription-updaters.js", "new_path": "server/src/updaters/user-subscription-updaters.js", "diff": "@@ -18,7 +18,7 @@ async function userSubscriptionUpdater(\nviewer: Viewer,\nupdate: SubscriptionUpdateRequest,\n): Promise<ThreadSubscription> {\n- const threadInfos = await fetchThreadInfos(\n+ const { threadInfos } = await fetchThreadInfos(\nviewer,\nSQL`t.id = ${update.threadID}`,\n);\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Fix subscription issues All new threads were getting disabled push notifs, AND it was impossible to enable push notifs. Sigh...
129,187
27.07.2018 20:34:25
14,400
0f692bf05a3de2b4c2b43e2a68fa09b9cc43ea77
[lib] Prevent cookie invalidation recovery with native credentials while logged out Also fixes a small bug where the options weren't being passed down to the rebound post-recovery `fetchJSON` function.
[ { "change_type": "MODIFY", "old_path": "lib/utils/action-utils.js", "new_path": "lib/utils/action-utils.js", "diff": "@@ -234,7 +234,7 @@ async function fetchNewCookieFromNativeCredentials(\nconst boundFetchJSON = async (\nendpoint: Endpoint,\ndata: {[key: string]: mixed},\n- options?: FetchJSONOptions,\n+ options?: ?FetchJSONOptions,\n) => {\nconst innerBoundSetCookie = (newCookie: ?string, response: Object) => {\nif (newCookie !== cookie) {\n@@ -296,6 +296,7 @@ function bindCookieAndUtilsIntoFetchJSON(\ncookie: ?string,\nurlPrefix: string,\nlogInExtraInfo: () => LogInExtraInfo,\n+ loggedIn: bool,\n): FetchJSON {\nconst boundSetCookie = (newCookie: ?string, response: Object) => {\nsetCookie(dispatch, cookie, newCookie, response);\n@@ -335,6 +336,7 @@ function bindCookieAndUtilsIntoFetchJSON(\nnewValidCookie,\nurlPrefix,\nlogInExtraInfo,\n+ loggedIn,\n)\n: null;\nfor (const func of currentWaitingCalls) {\n@@ -351,6 +353,11 @@ function bindCookieAndUtilsIntoFetchJSON(\n// fetchJSON instance continue\nreturn new Promise(r => r(null));\n}\n+ if (!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+ }\nif (currentlyWaitingForNewCookie) {\nreturn new Promise(r => fetchJSONCallsWaitingForNewCookie.push(r));\n}\n@@ -361,7 +368,7 @@ function bindCookieAndUtilsIntoFetchJSON(\nreturn (\nendpoint: Endpoint,\ndata: Object,\n- options?: FetchJSONOptions,\n+ options?: ?FetchJSONOptions,\n) => fetchJSON(\ncookie,\nboundSetCookie,\n@@ -380,6 +387,7 @@ type BindServerCallsParams = {\ncookie: ?string,\nurlPrefix: string,\nlogInExtraInfo: () => LogInExtraInfo,\n+ loggedIn: bool,\n};\n// All server calls needs to include some information from the Redux state\n@@ -396,17 +404,20 @@ const baseCreateBoundServerCallsSelector = (actionFunc: ActionFunc) => {\n(state: BindServerCallsParams) => state.cookie,\n(state: BindServerCallsParams) => state.urlPrefix,\n(state: BindServerCallsParams) => state.logInExtraInfo,\n+ (state: BindServerCallsParams) => state.loggedIn,\n(\ndispatch: Dispatch,\ncookie: ?string,\nurlPrefix: string,\nlogInExtraInfo: () => LogInExtraInfo,\n+ loggedIn: bool,\n) => {\nconst boundFetchJSON = bindCookieAndUtilsIntoFetchJSON(\ndispatch,\ncookie,\nurlPrefix,\nlogInExtraInfo,\n+ loggedIn,\n);\nreturn (...rest: $FlowFixMe) => actionFunc(boundFetchJSON, ...rest);\n},\n@@ -423,13 +434,19 @@ function bindServerCalls(serverCalls: ServerCalls) {\ncookie: ?string,\nurlPrefix: string,\nlogInExtraInfo: () => LogInExtraInfo,\n+ currentUserInfoLoggedIn: bool,\n},\ndispatchProps: Object,\nownProps: {[propName: string]: mixed},\n) => {\nconst dispatch = dispatchProps.dispatch;\ninvariant(dispatch, \"should be defined\");\n- const { cookie, urlPrefix, logInExtraInfo } = stateProps;\n+ const {\n+ cookie,\n+ urlPrefix,\n+ logInExtraInfo,\n+ currentUserInfoLoggedIn: loggedIn,\n+ } = stateProps;\nconst boundServerCalls = _mapValues(\n(serverCall: (fetchJSON: FetchJSON, ...rest: any) => Promise<any>) =>\ncreateBoundServerCallsSelector(serverCall)({\n@@ -437,6 +454,7 @@ function bindServerCalls(serverCalls: ServerCalls) {\ncookie,\nurlPrefix,\nlogInExtraInfo,\n+ loggedIn,\n}),\n)(serverCalls);\nreturn {\n" }, { "change_type": "MODIFY", "old_path": "lib/utils/fetch-json.js", "new_path": "lib/utils/fetch-json.js", "diff": "@@ -22,7 +22,7 @@ export type FetchJSONOptions = {|\nexport type FetchJSON = (\nendpoint: Endpoint,\ninput: Object,\n- options?: FetchJSONOptions,\n+ options?: ?FetchJSONOptions,\n) => Promise<Object>;\nconst defaultTimeout = 10000;\n@@ -46,7 +46,7 @@ async function fetchJSON(\n) {\nconst possibleReplacement = await waitIfCookieInvalidated();\nif (possibleReplacement) {\n- return await possibleReplacement(endpoint, input);\n+ return await possibleReplacement(endpoint, input, options);\n}\nconst definedCookie = cookie ? cookie : null;\n@@ -88,7 +88,7 @@ async function fetchJSON(\nif (json.cookieChange && json.cookieChange.cookieInvalidated) {\nconst possibleReplacement = await cookieInvalidationRecovery(newCookie);\nif (possibleReplacement) {\n- return await possibleReplacement(endpoint, input);\n+ return await possibleReplacement(endpoint, input, options);\n}\n}\nsetCookieCallback(newCookie, json);\n" }, { "change_type": "MODIFY", "old_path": "lib/utils/redux-utils.js", "new_path": "lib/utils/redux-utils.js", "diff": "@@ -27,12 +27,15 @@ function connect<S: BaseAppState<*>, OP: Object, SP: Object>(\ncookie: ?string,\nurlPrefix: string,\nlogInExtraInfo: () => LogInExtraInfo,\n+ currentUserInfoLoggedIn: bool,\n} => {\nreturn {\n...mapStateToProps(state, ownProps),\ncookie: state.cookie,\nurlPrefix: state.urlPrefix,\nlogInExtraInfo: logInExtraInfoSelector(state),\n+ currentUserInfoLoggedIn:\n+ !!(state.currentUserInfo && !state.currentUserInfo.anonymous && true),\n};\n};\n} else if (serverCallExists && mapStateToProps) {\n@@ -41,6 +44,7 @@ function connect<S: BaseAppState<*>, OP: Object, SP: Object>(\ncookie: ?string,\nurlPrefix: string,\nlogInExtraInfo: () => LogInExtraInfo,\n+ currentUserInfoLoggedIn: bool,\n} => {\nreturn {\n// $FlowFixMe\n@@ -48,6 +52,8 @@ function connect<S: BaseAppState<*>, OP: Object, SP: Object>(\ncookie: state.cookie,\nurlPrefix: state.urlPrefix,\nlogInExtraInfo: logInExtraInfoSelector(state),\n+ currentUserInfoLoggedIn:\n+ !!(state.currentUserInfo && !state.currentUserInfo.anonymous && true),\n};\n};\n} else if (mapStateToProps && mapStateToProps.length > 1) {\n@@ -65,11 +71,14 @@ function connect<S: BaseAppState<*>, OP: Object, SP: Object>(\ncookie: ?string,\nurlPrefix: string,\nlogInExtraInfo: () => LogInExtraInfo,\n+ currentUserInfoLoggedIn: bool,\n} => {\nreturn {\ncookie: state.cookie,\nurlPrefix: state.urlPrefix,\nlogInExtraInfo: logInExtraInfoSelector(state),\n+ currentUserInfoLoggedIn:\n+ !!(state.currentUserInfo && !state.currentUserInfo.anonymous && true),\n};\n};\n} else {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[lib] Prevent cookie invalidation recovery with native credentials while logged out Also fixes a small bug where the options weren't being passed down to the rebound post-recovery `fetchJSON` function.
129,187
27.07.2018 20:35:27
14,400
fd3f6c70c1863146cdc0cf93e34dbced8eac5c99
[native] Remove native credentials before log out/delete account requests Also, forgot to remove third parameter in call to `LoggedOutModal.dispatchPing` after I removed it from the definition.
[ { "change_type": "MODIFY", "old_path": "native/account/logged-out-modal.react.js", "new_path": "native/account/logged-out-modal.react.js", "diff": "@@ -345,7 +345,7 @@ class InnerLoggedOutModal extends React.PureComponent<Props, State> {\n// We are here either because the user cookie exists but Redux says we're\n// not logged in, or because Redux says we're logged in but we don't have\n// a user cookie and we failed to acquire one above\n- InnerLoggedOutModal.dispatchPing(nextProps, cookie, urlPrefix);\n+ InnerLoggedOutModal.dispatchPing(nextProps, cookie);\n}\nstatic dispatchPing(props: Props, cookie: ?string) {\n@@ -354,6 +354,7 @@ class InnerLoggedOutModal extends React.PureComponent<Props, State> {\ncookie,\nurlPrefix: props.urlPrefix,\nlogInExtraInfo: props.logInExtraInfo,\n+ loggedIn: props.loggedIn,\n});\ndispatchPing({ ...props, ping: boundPing });\n}\n" }, { "change_type": "MODIFY", "old_path": "native/more/delete-account.react.js", "new_path": "native/more/delete-account.react.js", "diff": "@@ -172,10 +172,10 @@ class InnerDeleteAccount extends React.PureComponent<Props, State> {\nasync deleteAccount() {\ntry {\n- const result = await this.props.deleteAccount(this.state.password);\nif (this.props.username) {\nawait deleteNativeCredentialsFor(this.props.username);\n}\n+ const result = await this.props.deleteAccount(this.state.password);\nreturn result;\n} catch (e) {\nif (e.message === 'invalid_credentials') {\n" }, { "change_type": "MODIFY", "old_path": "native/more/more-screen.react.js", "new_path": "native/more/more-screen.react.js", "diff": "@@ -204,11 +204,11 @@ class InnerMoreScreen extends React.PureComponent<Props> {\n);\n}\n- onPressLogOut = async () => {\n+ onPressLogOut = () => {\nconst alertTitle = Platform.OS === \"ios\"\n? \"Keep Login Info in Keychain\"\n: \"Keep Login Info\";\n- const sharedWebCredentials = await getNativeSharedWebCredentials();\n+ const sharedWebCredentials = getNativeSharedWebCredentials();\nconst alertDescription = sharedWebCredentials\n? \"We will automatically fill out log-in forms with your credentials \" +\n\"in the app and keep them available on squadcal.org in Safari.\"\n@@ -246,11 +246,8 @@ class InnerMoreScreen extends React.PureComponent<Props> {\nasync logOutAndDeleteNativeCredentials() {\nconst username = this.props.username;\ninvariant(username, \"can't log out if not logged in\");\n- const [ result ] = await Promise.all([\n- this.props.logOut(),\n- deleteNativeCredentialsFor(username),\n- ]);\n- return result;\n+ await deleteNativeCredentialsFor(username);\n+ return await this.props.logOut();\n}\nonPressResendVerificationEmail = () => {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Remove native credentials before log out/delete account requests Also, forgot to remove third parameter in call to `LoggedOutModal.dispatchPing` after I removed it from the definition.
129,187
27.07.2018 20:35:52
14,400
98c3044c363162f66811ab91f409098f890f02b4
[server] Make setNewCookie set cookieInvalidated back to false
[ { "change_type": "MODIFY", "old_path": "server/src/session/viewer.js", "new_path": "server/src/session/viewer.js", "diff": "@@ -55,13 +55,11 @@ class Viewer {\nsetNewCookie(data: ViewerData) {\nthis.data = data;\nthis.cookieChanged = true;\n- if (this.cookieName !== cookieType.ANONYMOUS) {\n- // A cookie invalidation is treated similarly to a log-out by the client.\n- // If we're passing them a valid user cookie, it shouldn't be treated as\n- // an invalidation.\n+ // If the request explicitly sets a new cookie, there's no point in telling\n+ // the client that their old cookie is invalid. Note that clients treat\n+ // cookieInvalidated as a forced log-out, which isn't necessary here.\nthis.cookieInvalidated = false;\n}\n- }\nget id(): string {\nreturn this.data.id;\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Make setNewCookie set cookieInvalidated back to false
129,187
27.07.2018 21:23:46
14,400
27b8a37a20d571e08e24eba07a64f7bf4b608955
[lib] Explicitly set Error.message V8 doesn't seem to set it with the `super(message)` call. Not sure about either JSC.
[ { "change_type": "MODIFY", "old_path": "lib/utils/errors.js", "new_path": "lib/utils/errors.js", "diff": "@@ -5,6 +5,7 @@ class ExtendableError extends Error {\nconstructor(message: string) {\nsuper(message);\nthis.name = this.constructor.name;\n+ this.message = message;\nif (typeof Error.captureStackTrace === 'function') {\nError.captureStackTrace(this, this.constructor);\n} else {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[lib] Explicitly set Error.message V8 doesn't seem to set it with the `super(message)` call. Not sure about either JSC.
129,187
30.07.2018 10:27:04
14,400
103155ac836e624907183323b56c474b51cb9b7b
[server] Delete cookie-specific updates after delivery
[ { "change_type": "MODIFY", "old_path": "server/src/deleters/update-deleters.js", "new_path": "server/src/deleters/update-deleters.js", "diff": "// @flow\n+import type { Viewer } from '../session/viewer';\n+\nimport invariant from 'invariant';\nimport { dbQuery, SQL, SQLStatement, mergeOrConditions } from '../database';\n@@ -35,7 +37,17 @@ async function deleteExpiredUpdates(): Promise<void> {\n`);\n}\n+async function deleteUpdatesBeforeTimeTargettingCookie(\n+ viewer: Viewer,\n+ beforeTime: number,\n+): Promise<void> {\n+ const condition =\n+ SQL`u.target_cookie = ${viewer.cookieID} AND u.time <= ${beforeTime}`;\n+ await deleteUpdatesByConditions([condition]);\n+}\n+\nexport {\ndeleteExpiredUpdates,\ndeleteUpdatesByConditions,\n+ deleteUpdatesBeforeTimeTargettingCookie,\n};\n" }, { "change_type": "MODIFY", "old_path": "server/src/responders/ping-responders.js", "new_path": "server/src/responders/ping-responders.js", "diff": "@@ -44,6 +44,9 @@ import { deviceTokenUpdater } from '../updaters/device-token-updaters';\nimport createReport from '../creators/report-creator';\nimport { createFilter } from '../creators/filter-creator';\nimport { fetchCurrentFilter } from '../fetchers/filter-fetchers';\n+import {\n+ deleteUpdatesBeforeTimeTargettingCookie,\n+} from '../deleters/update-deleters';\nconst pingRequestInputValidator = tShape({\ncalendarQuery: entryQueryInputValidator,\n@@ -203,11 +206,17 @@ async function pingResponder(\nlet updatesResult = null;\nif (oldUpdatesCurrentAsOf !== null && oldUpdatesCurrentAsOf !== undefined) {\n- const { updateInfos } = await fetchUpdateInfos(\n+ const [{ updateInfos }] = await Promise.all([\n+ fetchUpdateInfos(\nviewer,\noldUpdatesCurrentAsOf,\n{ ...threadsResult, calendarQuery },\n- );\n+ ),\n+ deleteUpdatesBeforeTimeTargettingCookie(\n+ viewer,\n+ oldUpdatesCurrentAsOf,\n+ ),\n+ ]);\nconst newUpdatesCurrentAsOf = mostRecentUpdateTimestamp(\n[...updateInfos],\noldUpdatesCurrentAsOf,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Delete cookie-specific updates after delivery
129,187
31.07.2018 10:33:18
14,400
cc9b83e156597eba3d7d044071175dd535ab83e1
Check visibility of activeChatThreadID in websiteResponder Also a bugfix in `message-creator` when there are messages from multiple creators (don't think this ever happens), and a bugfix in web's `ThreadSettingsModal` to avoid seeming like an empty password is specified when none is actually being specified.
[ { "change_type": "MODIFY", "old_path": "server/src/creators/message-creator.js", "new_path": "server/src/creators/message-creator.js", "diff": "@@ -94,7 +94,7 @@ async function createMessages(\nsubthread: undefined,\n};\n}\n- if (newThreadRestriction !== newThreadRestriction) {\n+ if (newThreadRestriction !== threadRestriction) {\nthreadRestrictions.set(threadID, newThreadRestriction);\n}\n}\n" }, { "change_type": "MODIFY", "old_path": "server/src/responders/website-responders.js", "new_path": "server/src/responders/website-responders.js", "diff": "@@ -5,6 +5,7 @@ import type { AppState, Action } from 'web/redux-setup';\nimport type { Store } from 'redux';\nimport { defaultPingTimestamps } from 'lib/types/ping-types';\nimport { defaultCalendarFilters } from 'lib/types/filter-types';\n+import { threadPermissions } from 'lib/types/thread-types';\nimport html from 'common-tags/lib/html';\nimport { createStore } from 'redux';\n@@ -27,6 +28,7 @@ import { freshMessageStore } from 'lib/reducers/message-reducer';\nimport { verifyField } from 'lib/types/verify-types';\nimport { mostRecentMessageTimestamp } from 'lib/shared/message-utils';\nimport { mostRecentReadThread } from 'lib/selectors/thread-selectors';\n+import { threadHasPermission } from 'lib/shared/thread-utils';\nimport * as ReduxSetup from 'web/redux-setup';\nimport App from 'web/dist/app.build';\nimport { navInfoFromURL } from 'web/url-utils';\n@@ -34,7 +36,7 @@ import { navInfoFromURL } from 'web/url-utils';\nimport { Viewer } from '../session/viewer';\nimport { handleCodeVerificationRequest } from '../models/verification';\nimport { fetchMessageInfos } from '../fetchers/message-fetchers';\n-import { verifyThreadID, fetchThreadInfos } from '../fetchers/thread-fetchers';\n+import { fetchThreadInfos } from '../fetchers/thread-fetchers';\nimport { fetchEntryInfos } from '../fetchers/entry-fetchers';\nimport { fetchCurrentUserInfo } from '../fetchers/user-fetchers';\nimport { updateActivityTime } from '../updaters/activity-updaters';\n@@ -87,12 +89,13 @@ async function websiteResponder(viewer: Viewer, url: string): Promise<string> {\nmostRecentMessageTimestamp(rawMessageInfos, initialTime),\nthreadInfos,\n);\n- if (navInfo.activeChatThreadID) {\n- const validThreadID = await verifyThreadID(navInfo.activeChatThreadID);\n- if (!validThreadID) {\n+ const threadID = navInfo.activeChatThreadID;\n+ if (\n+ threadID &&\n+ !threadHasPermission(threadInfos[threadID], threadPermissions.VISIBLE)\n+ ) {\nnavInfo.activeChatThreadID = null;\n}\n- }\nif (!navInfo.activeChatThreadID) {\nconst mostRecentThread = mostRecentReadThread(messageStore, threadInfos);\nif (mostRecentThread) {\n" }, { "change_type": "MODIFY", "old_path": "web/modals/threads/thread-settings-modal.react.js", "new_path": "web/modals/threads/thread-settings-modal.react.js", "diff": "@@ -436,7 +436,9 @@ class ThreadSettingsModal extends React.PureComponent<Props, State> {\nconst response = await this.props.changeThreadSettings({\nthreadID: this.props.threadInfo.id,\nchanges: this.state.queuedChanges,\n- accountPassword: this.state.accountPassword,\n+ accountPassword: this.state.accountPassword\n+ ? this.state.accountPassword\n+ : null,\n});\nthis.props.onClose();\nreturn response;\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Check visibility of activeChatThreadID in websiteResponder Also a bugfix in `message-creator` when there are messages from multiple creators (don't think this ever happens), and a bugfix in web's `ThreadSettingsModal` to avoid seeming like an empty password is specified when none is actually being specified.
129,187
31.07.2018 11:00:33
14,400
01bc4e03c8bd7dd68dd8eef3009714d4042c8575
Fix up handling of navInfo and URL when user is logged out on web Also a type fix I forgot for the last commit.
[ { "change_type": "MODIFY", "old_path": "lib/types/thread-types.js", "new_path": "lib/types/thread-types.js", "diff": "@@ -302,7 +302,7 @@ export type ThreadChanges = {\nexport type UpdateThreadRequest = {|\nthreadID: string,\nchanges: ThreadChanges,\n- accountPassword?: string,\n+ accountPassword?: ?string,\n|};\nexport type NewThreadRequest = {|\n" }, { "change_type": "MODIFY", "old_path": "web/app.react.js", "new_path": "web/app.react.js", "diff": "@@ -197,6 +197,8 @@ class App extends React.PureComponent<Props, State> {\nhistory.replace(newURL);\n}\nthis.startTimeouts(this.props);\n+ } else if (this.props.location.pathname !== '/') {\n+ history.replace('/');\n}\nApp.updateFocusedThreads(this.props, null, null);\n@@ -354,6 +356,7 @@ class App extends React.PureComponent<Props, State> {\n}\ncomponentWillReceiveProps(nextProps: Props) {\n+ if (nextProps.loggedIn) {\nif (nextProps.location.pathname !== this.props.location.pathname) {\nconst newNavInfo = navInfoFromURL(\nnextProps.location.pathname,\n@@ -373,16 +376,16 @@ class App extends React.PureComponent<Props, State> {\n}\nif (\n- nextProps.loggedIn &&\n- (nextProps.navInfo.startDate !== this.props.navInfo.startDate ||\n+ nextProps.navInfo.startDate !== this.props.navInfo.startDate ||\nnextProps.navInfo.endDate !== this.props.navInfo.endDate ||\n- (nextProps.includeDeleted && !this.props.includeDeleted))\n+ (nextProps.includeDeleted && !this.props.includeDeleted)\n) {\nnextProps.dispatchActionPromise(\nfetchEntriesActionTypes,\nnextProps.fetchEntries(nextProps.currentCalendarQuery()),\n);\n}\n+ }\nconst prevLastPingSuccess = this.props.pingTimestamps.lastSuccess;\nconst nextLastPingSuccess = nextProps.pingTimestamps.lastSuccess;\n@@ -419,6 +422,11 @@ class App extends React.PureComponent<Props, State> {\nthis.props.activeThreadLatestMessage,\n);\n}\n+\n+ const justLoggedOut = !nextProps.loggedIn && this.props.loggedIn;\n+ if (justLoggedOut && nextProps.location.pathname !== '/') {\n+ history.replace('/');\n+ }\n}\nrender() {\n" }, { "change_type": "MODIFY", "old_path": "web/redux-setup.js", "new_path": "web/redux-setup.js", "diff": "@@ -131,6 +131,20 @@ export function reducer(inputState: AppState | void, action: Action) {\n}\nfunction validateState(oldState: AppState, state: AppState): AppState {\n+ if (\n+ state.navInfo.activeChatThreadID &&\n+ !state.threadStore.threadInfos[state.navInfo.activeChatThreadID]\n+ ) {\n+ // Makes sure the active thread always exists\n+ state = {\n+ ...state,\n+ navInfo: {\n+ ...state.navInfo,\n+ activeChatThreadID: mostRecentReadThreadSelector(state),\n+ },\n+ };\n+ }\n+\nconst oldActiveThread = activeThreadSelector(oldState);\nconst activeThread = activeThreadSelector(state);\nif (\n@@ -139,13 +153,7 @@ function validateState(oldState: AppState, state: AppState): AppState {\n) {\n// Makes sure a currently focused thread is never unread\nstate = {\n- navInfo: state.navInfo,\n- currentUserInfo: state.currentUserInfo,\n- sessionID: state.sessionID,\n- verifyField: state.verifyField,\n- resetPasswordUsername: state.resetPasswordUsername,\n- entryStore: state.entryStore,\n- lastUserInteraction: state.lastUserInteraction,\n+ ...state,\nthreadStore: {\n...state.threadStore,\nthreadInfos: {\n@@ -159,20 +167,9 @@ function validateState(oldState: AppState, state: AppState): AppState {\n},\n},\n},\n- userInfos: state.userInfos,\n- messageStore: state.messageStore,\n- drafts: state.drafts,\n- updatesCurrentAsOf: state.updatesCurrentAsOf,\n- loadingStatuses: state.loadingStatuses,\n- pingTimestamps: state.pingTimestamps,\n- activeServerRequests: state.activeServerRequests,\n- calendarFilters: state.calendarFilters,\n- cookie: state.cookie,\n- deviceToken: state.deviceToken,\n- urlPrefix: state.urlPrefix,\n- windowDimensions: state.windowDimensions,\n};\n}\n+\nif (\nactiveThread &&\noldActiveThread !== activeThread &&\n@@ -180,17 +177,9 @@ function validateState(oldState: AppState, state: AppState): AppState {\n) {\n// Update messageStore.threads[activeThread].lastNavigatedTo\nstate = {\n- navInfo: state.navInfo,\n- currentUserInfo: state.currentUserInfo,\n- sessionID: state.sessionID,\n- verifyField: state.verifyField,\n- resetPasswordUsername: state.resetPasswordUsername,\n- entryStore: state.entryStore,\n- lastUserInteraction: state.lastUserInteraction,\n- threadStore: state.threadStore,\n- userInfos: state.userInfos,\n+ ...state,\nmessageStore: {\n- messages: state.messageStore.messages,\n+ ...state.messageStore,\nthreads: {\n...state.messageStore.threads,\n[activeThread]: {\n@@ -198,53 +187,7 @@ function validateState(oldState: AppState, state: AppState): AppState {\nlastNavigatedTo: Date.now(),\n},\n},\n- currentAsOf: state.messageStore.currentAsOf,\n},\n- drafts: state.drafts,\n- updatesCurrentAsOf: state.updatesCurrentAsOf,\n- loadingStatuses: state.loadingStatuses,\n- pingTimestamps: state.pingTimestamps,\n- activeServerRequests: state.activeServerRequests,\n- calendarFilters: state.calendarFilters,\n- cookie: state.cookie,\n- deviceToken: state.deviceToken,\n- urlPrefix: state.urlPrefix,\n- windowDimensions: state.windowDimensions,\n- };\n- }\n-\n- if (\n- state.navInfo.activeChatThreadID &&\n- !state.threadStore.threadInfos[state.navInfo.activeChatThreadID]\n- ) {\n- // Makes sure the active thread always exists\n- state = {\n- navInfo: {\n- startDate: state.navInfo.startDate,\n- endDate: state.navInfo.endDate,\n- tab: state.navInfo.tab,\n- verify: state.navInfo.verify,\n- activeChatThreadID: mostRecentReadThreadSelector(state),\n- },\n- currentUserInfo: state.currentUserInfo,\n- sessionID: state.sessionID,\n- verifyField: state.verifyField,\n- resetPasswordUsername: state.resetPasswordUsername,\n- entryStore: state.entryStore,\n- lastUserInteraction: state.lastUserInteraction,\n- threadStore: state.threadStore,\n- userInfos: state.userInfos,\n- messageStore: state.messageStore,\n- drafts: state.drafts,\n- updatesCurrentAsOf: state.updatesCurrentAsOf,\n- loadingStatuses: state.loadingStatuses,\n- pingTimestamps: state.pingTimestamps,\n- activeServerRequests: state.activeServerRequests,\n- calendarFilters: state.calendarFilters,\n- cookie: state.cookie,\n- deviceToken: state.deviceToken,\n- urlPrefix: state.urlPrefix,\n- windowDimensions: state.windowDimensions,\n};\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Fix up handling of navInfo and URL when user is logged out on web Also a type fix I forgot for the last commit.
129,187
31.07.2018 18:21:53
14,400
32b20c6ea5256e1b8f75241ca8241272fa9b793e
Include last twenty action types in thread inconsistency report
[ { "change_type": "MODIFY", "old_path": "lib/reducers/thread-reducer.js", "new_path": "lib/reducers/thread-reducer.js", "diff": "@@ -36,6 +36,7 @@ import {\n} from '../actions/ping-actions';\nimport { saveMessagesActionType } from '../actions/message-actions';\nimport { getConfig } from '../utils/config';\n+import { reduxLogger } from '../utils/redux-logger';\nfunction pingPoll(\nthreadInfos: {[id: string]: RawThreadInfo},\n@@ -206,6 +207,7 @@ function findInconsistencies(\naction,\npollResult,\npushResult,\n+ lastActionTypes: reduxLogger.actions.map(action => action.type),\n}];\n}\n" }, { "change_type": "MODIFY", "old_path": "lib/types/report-types.js", "new_path": "lib/types/report-types.js", "diff": "@@ -43,6 +43,7 @@ type ThreadPollPushInconsistencyReportCreationRequest = {|\naction: BaseAction,\npollResult: {[id: string]: RawThreadInfo},\npushResult: {[id: string]: RawThreadInfo},\n+ lastActionTypes?: $ReadOnlyArray<$PropertyType<BaseAction, 'type'>>,\n|};\nexport type ReportCreationRequest =\n| ErrorReportCreationRequest\n" }, { "change_type": "MODIFY", "old_path": "lib/types/request-types.js", "new_path": "lib/types/request-types.js", "diff": "@@ -52,6 +52,7 @@ export type ThreadPollPushInconsistencyClientResponse = {|\naction: BaseAction,\npollResult: {[id: string]: RawThreadInfo},\npushResult: {[id: string]: RawThreadInfo},\n+ lastActionTypes?: $ReadOnlyArray<$PropertyType<BaseAction, 'type'>>,\n|};\ntype PlatformDetailsServerRequest = {|\n" }, { "change_type": "RENAME", "old_path": "native/redux-logger.js", "new_path": "lib/utils/redux-logger.js", "diff": "// @flow\n-import type { AppState } from './redux-setup';\n+import type { BaseAppState } from '../types/redux-types';\n-import { REHYDRATE } from 'redux-persist';\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';\nclass ReduxLogger {\n@@ -10,7 +13,7 @@ class ReduxLogger {\nlastNActions = [];\nlastNStates = [];\n- get preloadedState(): AppState {\n+ get preloadedState(): BaseAppState<*> {\nreturn this.lastNStates[0];\n}\n@@ -18,7 +21,7 @@ class ReduxLogger {\nreturn [...this.lastNActions];\n}\n- addAction(action: *, state: AppState) {\n+ addAction(action: *, state: BaseAppState<*>) {\nif (\nthis.lastNActions.length > 0 &&\nthis.lastNActions[this.lastNActions.length - 1].type === REHYDRATE\n@@ -40,4 +43,14 @@ class ReduxLogger {\nconst reduxLogger = new ReduxLogger();\n-export default reduxLogger;\n+const reduxLoggerMiddleware = (store: *) => (next: *) => (action: *) => {\n+ // We want the state before the action\n+ const state = store.getState();\n+ reduxLogger.addAction(action, state);\n+ return next(action);\n+};\n+\n+export {\n+ reduxLogger,\n+ reduxLoggerMiddleware,\n+};\n" }, { "change_type": "MODIFY", "old_path": "native/crash.react.js", "new_path": "native/crash.react.js", "diff": "@@ -28,11 +28,11 @@ import invariant from 'invariant';\nimport { connect } from 'lib/utils/redux-utils';\nimport { sendReportActionTypes, sendReport } from 'lib/actions/report-actions';\nimport sleep from 'lib/utils/sleep';\n+import { reduxLogger } from 'lib/utils/redux-logger';\nimport Button from './components/button.react';\nimport { store } from './redux-setup';\nimport { persistConfig, codeVersion, getPersistor } from './persist';\n-import reduxLogger from './redux-logger';\nconst errorTitles = [\n\"Oh no!!\",\n" }, { "change_type": "MODIFY", "old_path": "native/redux-setup.js", "new_path": "native/redux-setup.js", "diff": "@@ -40,6 +40,7 @@ import { newSessionID } from 'lib/selectors/session-selectors';\nimport { notificationPressActionType } from 'lib/shared/notif-utils';\nimport { sendMessageActionTypes } from 'lib/actions/message-actions';\nimport { pingActionTypes } from 'lib/actions/ping-actions';\n+import { reduxLoggerMiddleware } from 'lib/utils/redux-logger';\nimport { MessageListRouteName } from './chat/message-list.react';\nimport { activeThreadSelector } from './selectors/nav-selectors';\n@@ -56,7 +57,6 @@ import {\nreduceThreadIDsToNotifIDs,\n} from './push/android';\nimport { persistConfig, setPersistor } from './persist';\n-import reduxLogger from './redux-logger';\nimport {\ndefaultURLPrefix,\nnatServer,\n@@ -469,13 +469,6 @@ function validateState(oldState: AppState, state: AppState): AppState {\nreturn state;\n}\n-const reduxLoggerMiddleware = store => next => action => {\n- // We want the state before the action\n- const state = store.getState();\n- reduxLogger.addAction(action, state);\n- return next(action);\n-};\n-\nconst reactNavigationMiddleware = createReactNavigationReduxMiddleware(\n\"root\",\n(state: AppState) => state.navInfo.navigationState,\n" }, { "change_type": "MODIFY", "old_path": "server/src/responders/ping-responders.js", "new_path": "server/src/responders/ping-responders.js", "diff": "@@ -79,6 +79,7 @@ const pingRequestInputValidator = tShape({\naction: t.Object,\npollResult: t.Object,\npushResult: t.Object,\n+ lastActionTypes: t.maybe(t.list(t.String)),\n}),\ntShape({\ntype: t.irreducible(\n" }, { "change_type": "MODIFY", "old_path": "web/root.js", "new_path": "web/root.js", "diff": "@@ -13,6 +13,8 @@ import {\ncomposeWithDevTools,\n} from 'redux-devtools-extension/logOnlyInProduction';\n+import { reduxLoggerMiddleware } from 'lib/utils/redux-logger';\n+\nimport App from './app.react';\nimport history from './router-history';\nimport { reducer } from './redux-setup';\n@@ -21,7 +23,9 @@ declare var preloadedState: AppState;\nconst store: Store<AppState, Action> = createStore(\nreducer,\npreloadedState,\n- composeWithDevTools({})(applyMiddleware(thunk)),\n+ composeWithDevTools({})(\n+ applyMiddleware(thunk, reduxLoggerMiddleware),\n+ ),\n);\nconst RootRouter = () => (\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Include last twenty action types in thread inconsistency report
129,187
01.08.2018 10:27:37
14,400
73f358b702303dec7b70c5f9370de7ee9e7c5bd8
[server] Ignore the most common kind of thread inconsistency response This one is a bug that results from a hack in `thread-reducer`.
[ { "change_type": "MODIFY", "old_path": "lib/types/report-types.js", "new_path": "lib/types/report-types.js", "diff": "@@ -36,7 +36,7 @@ type ErrorReportCreationRequest = {|\ncurrentState: BaseAppState<*>,\nactions: $ReadOnlyArray<BaseAction>,\n|};\n-type ThreadPollPushInconsistencyReportCreationRequest = {|\n+export type ThreadPollPushInconsistencyReportCreationRequest = {|\ntype: 1,\nplatformDetails: PlatformDetails,\nbeforeAction: {[id: string]: RawThreadInfo},\n" }, { "change_type": "MODIFY", "old_path": "server/src/creators/report-creator.js", "new_path": "server/src/creators/report-creator.js", "diff": "@@ -4,6 +4,7 @@ import type { Viewer } from '../session/viewer';\nimport {\ntype ReportCreationRequest,\ntype ReportCreationResponse,\n+ type ThreadPollPushInconsistencyReportCreationRequest,\nreportTypes,\n} from 'lib/types/report-types';\nimport { messageTypes } from 'lib/types/message-types';\n@@ -11,6 +12,8 @@ import { messageTypes } from 'lib/types/message-types';\nimport bots from 'lib/facts/bots';\nimport _isEqual from 'lodash/fp/isEqual';\n+import { pingActionTypes } from 'lib/actions/ping-actions';\n+\nimport { dbQuery, SQL } from '../database';\nimport createIDs from './id-creator';\nimport { fetchUsername } from '../fetchers/user-fetchers';\n@@ -24,7 +27,10 @@ const { squadbot } = bots;\nasync function createReport(\nviewer: Viewer,\nrequest: ReportCreationRequest,\n-): Promise<ReportCreationResponse> {\n+): Promise<?ReportCreationResponse> {\n+ if (ignoreReport(request)) {\n+ return null;\n+ }\nconst [ id ] = await createIDs(\"reports\", 1);\nconst { type, platformDetails, ...report } = request;\nconst row = [\n@@ -68,6 +74,38 @@ async function sendSquadbotMessage(\n}]);\n}\n+function ignoreReport(request: ReportCreationRequest): bool {\n+ if (request.type !== reportTypes.THREAD_POLL_PUSH_INCONSISTENCY) {\n+ return false;\n+ }\n+ if (request.action.type !== pingActionTypes.success) {\n+ return false;\n+ }\n+ const { beforeAction, pollResult, pushResult } = request;\n+ const payloadThreadInfos = request.action.payload.threadInfos;\n+ const prevStateThreadInfos = request.action.payload.prevState.threadInfos;\n+ const nonMatchingThreadIDs = getInconsistentThreadIDsFromReport(request);\n+ for (let threadID of nonMatchingThreadIDs) {\n+ const newThreadInfo = payloadThreadInfos[threadID];\n+ const prevThreadInfo = prevStateThreadInfos[threadID];\n+ if (!_isEqual(prevThreadInfo)(newThreadInfo)) {\n+ return false;\n+ }\n+ const currentThreadInfo = beforeAction[threadID];\n+ const pollThreadInfo = pollResult[threadID];\n+ if (!_isEqual(currentThreadInfo)(pollThreadInfo)) {\n+ return false;\n+ }\n+ const pushThreadInfo = pushResult[threadID];\n+ if (!_isEqual(pushThreadInfo)(newThreadInfo)) {\n+ return false;\n+ }\n+ }\n+ // Currently we only ignore cases that are the result of the thread-reducer\n+ // conditional with the comment above that starts with \"If the thread at the\"\n+ return true;\n+}\n+\nfunction getSquadbotMessage(\nrequest: ReportCreationRequest,\nreportID: string,\n@@ -83,6 +121,20 @@ function getSquadbotMessage(\n`using ${platformString}\\n` +\n`${baseDomain}${basePath}download_error_report/${reportID}`;\n} else if (request.type === reportTypes.THREAD_POLL_PUSH_INCONSISTENCY) {\n+ const nonMatchingThreadIDs = getInconsistentThreadIDsFromReport(request);\n+ const nonMatchingString = [...nonMatchingThreadIDs].join(\", \");\n+ return `system detected poll/push inconsistency for ${name}!\\n` +\n+ `using ${platformString}\\n` +\n+ `occurred during ${request.action.type}\\n` +\n+ `thread IDs that are inconsistent: ${nonMatchingString}`;\n+ } else {\n+ return null;\n+ }\n+}\n+\n+function getInconsistentThreadIDsFromReport(\n+ request: ThreadPollPushInconsistencyReportCreationRequest,\n+): Set<string> {\nconst { pushResult, pollResult, action } = request;\nconst nonMatchingThreadIDs = new Set();\nfor (let threadID in pollResult) {\n@@ -95,14 +147,7 @@ function getSquadbotMessage(\nnonMatchingThreadIDs.add(threadID);\n}\n}\n- const nonMatchingString = [...nonMatchingThreadIDs].join(\", \");\n- return `system detected poll/push inconsistency for ${name}!\\n` +\n- `using ${platformString}\\n` +\n- `occurred during ${action.type}\\n` +\n- `thread IDs that are inconsistent: ${nonMatchingString}`;\n- } else {\n- return null;\n- }\n+ return nonMatchingThreadIDs;\n}\nexport default createReport;\n" }, { "change_type": "MODIFY", "old_path": "server/src/responders/report-responders.js", "new_path": "server/src/responders/report-responders.js", "diff": "@@ -73,7 +73,11 @@ async function reportCreationResponder(\n};\n}\nconst request: ReportCreationRequest = input;\n- return await createReport(viewer, request);\n+ const response = await createReport(viewer, request);\n+ if (!response) {\n+ throw new ServerError('ignored_report');\n+ }\n+ return response;\n}\nconst fetchErrorReportInfosRequestInputValidator = tShape({\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Ignore the most common kind of thread inconsistency response This one is a bug that results from a hack in `thread-reducer`.
129,187
01.08.2018 10:41:05
14,400
074b2170a0308f2bc63ea48a9ae3bc6d9f5e3396
[server] Record as delivered only the ping timestamp passed by the client Don't automatically assume the server-generated ping timestamp actually gets delivered. Also reduce one `await` step by combining some.
[ { "change_type": "MODIFY", "old_path": "server/src/responders/ping-responders.js", "new_path": "server/src/responders/ping-responders.js", "diff": "@@ -17,6 +17,7 @@ import _isEqual from 'lodash/fp/isEqual';\nimport { ServerError } from 'lib/utils/errors';\nimport { mostRecentMessageTimestamp } from 'lib/shared/message-utils';\nimport { mostRecentUpdateTimestamp } from 'lib/shared/update-utils';\n+import { promiseAll } from 'lib/utils/promises';\nimport {\nvalidateInput,\n@@ -205,19 +206,40 @@ async function pingResponder(\n: null,\n]);\n- let updatesResult = null;\n+ const promises = {};\n+ promises.activityUpdate = updateActivityTime(viewer);\n+ if (\n+ calendarQuery &&\n+ (!currentCalendarQuery ||\n+ !_isEqual(currentCalendarQuery)(calendarQuery))\n+ ) {\n+ promises.filterCreation = createFilter(viewer, calendarQuery);\n+ }\nif (oldUpdatesCurrentAsOf !== null && oldUpdatesCurrentAsOf !== undefined) {\n- const [{ updateInfos }] = await Promise.all([\n- fetchUpdateInfos(\n+ promises.deleteExpiredUpdates = deleteUpdatesBeforeTimeTargettingCookie(\nviewer,\noldUpdatesCurrentAsOf,\n- { ...threadsResult, calendarQuery },\n- ),\n- deleteUpdatesBeforeTimeTargettingCookie(\n+ );\n+ promises.fetchUpdateResult = fetchUpdateInfos(\nviewer,\noldUpdatesCurrentAsOf,\n- ),\n- ]);\n+ { ...threadsResult, calendarQuery },\n+ );\n+ promises.recordDelivery = recordDeliveredUpdate(\n+ viewer.cookieID,\n+ oldUpdatesCurrentAsOf,\n+ );\n+ }\n+\n+ const { fetchUpdateResult } = await promiseAll(promises);\n+\n+ let updatesResult = null;\n+ if (fetchUpdateResult) {\n+ invariant(\n+ oldUpdatesCurrentAsOf !== null && oldUpdatesCurrentAsOf !== undefined,\n+ \"should be set\",\n+ );\n+ const { updateInfos } = fetchUpdateResult;\nconst newUpdatesCurrentAsOf = mostRecentUpdateTimestamp(\n[...updateInfos],\noldUpdatesCurrentAsOf,\n@@ -228,21 +250,6 @@ async function pingResponder(\n};\n}\n- const updatePromises = [ updateActivityTime(viewer) ];\n- if (updatesResult && updatesResult.newUpdates.length > 0) {\n- updatePromises.push(\n- recordDeliveredUpdate(viewer.cookieID, updatesResult.currentAsOf),\n- );\n- }\n- if (\n- calendarQuery &&\n- (!currentCalendarQuery ||\n- !_isEqual(currentCalendarQuery)(calendarQuery))\n- ) {\n- updatePromises.push(createFilter(viewer, calendarQuery));\n- }\n- await Promise.all(updatePromises);\n-\nconst userInfos: any = Object.values({\n...messagesResult.userInfos,\n...entriesResult.userInfos,\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Record as delivered only the ping timestamp passed by the client Don't automatically assume the server-generated ping timestamp actually gets delivered. Also reduce one `await` step by combining some.
129,187
01.08.2018 10:58:05
14,400
0d0019423ddbce6f423203e4810bf29855db0b6f
Don't ignore ping setting a thread to unread if backgrounded The thread shouldn't count as "active" if the app/website is backgrounded.
[ { "change_type": "MODIFY", "old_path": "native/redux-setup.js", "new_path": "native/redux-setup.js", "diff": "@@ -34,6 +34,7 @@ import { NavigationActions, StackActions } from 'react-navigation';\nimport {\ncreateReactNavigationReduxMiddleware,\n} from 'react-navigation-redux-helpers';\n+import { AppState as NativeAppState } from 'react-native';\nimport baseReducer from 'lib/reducers/master-reducer';\nimport { newSessionID } from 'lib/selectors/session-selectors';\n@@ -348,10 +349,10 @@ function reducer(state: AppState = defaultState, action: *) {\n}\nfunction validateState(oldState: AppState, state: AppState): AppState {\n- const oldActiveThread = activeThreadSelector(oldState);\nconst activeThread = activeThreadSelector(state);\nif (\nactiveThread &&\n+ NativeAppState.currentState === \"active\" &&\nstate.threadStore.threadInfos[activeThread].currentUser.unread\n) {\n// Makes sure a currently focused thread is never unread\n@@ -392,6 +393,8 @@ function validateState(oldState: AppState, state: AppState): AppState {\n_persist: state._persist,\n};\n}\n+\n+ const oldActiveThread = activeThreadSelector(oldState);\nif (\nactiveThread &&\noldActiveThread !== activeThread &&\n" }, { "change_type": "MODIFY", "old_path": "server/package.json", "new_path": "server/package.json", "diff": "\"description\": \"\",\n\"main\": \"dist/server\",\n\"scripts\": {\n- \"babel\": \"babel src/ --out-dir dist/ --ignore 'lib/flow-typed','lib/node_modules','lib/package.json','web/flow-typed','web/node_modules','web/package.json','web/dist/hot','web/dist/dev.build.js','web/dist/prod.**.build.js','web/dist/prod.build.css','web/webpack.config.js','web/account-bar.react.js','web/app.react.js','web/calendar','web/chat','web/flow','web/loading-indicator.react.js','web/modals','web/root.js','web/router-history.js','web/script.js','web/selectors/chat-selectors.js','web/selectors/entry-selectors.js','web/server-rendering.js','web/splash','web/style.css','web/vector-utils.js','web/vectors.react.js' --copy-files\",\n+ \"babel\": \"babel src/ --out-dir dist/ --ignore 'lib/flow-typed','lib/node_modules','lib/package.json','web/flow-typed','web/node_modules','web/package.json','web/dist/hot','web/dist/dev.build.js','web/dist/prod.**.build.js','web/dist/prod.build.css','web/webpack.config.js','web/account-bar.react.js','web/app.react.js','web/calendar','web/chat','web/flow','web/loading-indicator.react.js','web/modals','web/root.js','web/router-history.js','web/script.js','web/selectors/chat-selectors.js','web/selectors/entry-selectors.js','web/splash','web/style.css','web/vector-utils.js','web/vectors.react.js' --copy-files\",\n\"prod\": \"node --experimental-modules --loader ./loader.mjs dist/server\",\n\"dev\": \"NODE_ENV=dev concurrently \\\"npm run babel -- --watch\\\" \\\"nodemon -e js,json,build --watch dist --experimental-modules --loader ./loader.mjs dist/server\\\"\"\n},\n" }, { "change_type": "MODIFY", "old_path": "server/src/responders/website-responders.js", "new_path": "server/src/responders/website-responders.js", "diff": "@@ -29,6 +29,8 @@ import { verifyField } from 'lib/types/verify-types';\nimport { mostRecentMessageTimestamp } from 'lib/shared/message-utils';\nimport { mostRecentReadThread } from 'lib/selectors/thread-selectors';\nimport { threadHasPermission } from 'lib/shared/thread-utils';\n+\n+import 'web/server-rendering';\nimport * as ReduxSetup from 'web/redux-setup';\nimport App from 'web/dist/app.build';\nimport { navInfoFromURL } from 'web/url-utils';\n" }, { "change_type": "MODIFY", "old_path": "web/redux-setup.js", "new_path": "web/redux-setup.js", "diff": "@@ -14,6 +14,7 @@ import type { CalendarFilter } from 'lib/types/filter-types';\nimport PropTypes from 'prop-types';\nimport invariant from 'invariant';\n+import Visibility from 'visibilityjs';\nimport baseReducer from 'lib/reducers/master-reducer';\nimport {\n@@ -145,10 +146,10 @@ function validateState(oldState: AppState, state: AppState): AppState {\n};\n}\n- const oldActiveThread = activeThreadSelector(oldState);\nconst activeThread = activeThreadSelector(state);\nif (\nactiveThread &&\n+ !Visibility.hidden() &&\nstate.threadStore.threadInfos[activeThread].currentUser.unread\n) {\n// Makes sure a currently focused thread is never unread\n@@ -170,6 +171,7 @@ function validateState(oldState: AppState, state: AppState): AppState {\n};\n}\n+ const oldActiveThread = activeThreadSelector(oldState);\nif (\nactiveThread &&\noldActiveThread !== activeThread &&\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Don't ignore ping setting a thread to unread if backgrounded The thread shouldn't count as "active" if the app/website is backgrounded.
129,187
01.08.2018 11:52:52
14,400
6159faf2d30146d35dd2a45e9563ec4e01424579
Include first activity update in first ping when foregrounding This avoids a race condition between the activity update and the ping that has been causing poll/push inconsistency.
[ { "change_type": "MODIFY", "old_path": "lib/shared/ping-utils.js", "new_path": "lib/shared/ping-utils.js", "diff": "@@ -6,6 +6,7 @@ import type {\nPingResult,\n} from '../types/ping-types';\nimport type { DispatchActionPromise } from '../utils/action-utils';\n+import { serverRequestTypes } from '../types/request-types';\nimport { pingActionTypes } from '../actions/ping-actions';\n@@ -20,15 +21,18 @@ function earliestTimeConsideredCurrent() {\ntype Props = {\npingStartingPayload: () => PingStartingPayload,\n- pingActionInput: (startingPayload: PingStartingPayload) => PingActionInput,\n+ pingActionInput: (\n+ startingPayload: PingStartingPayload,\n+ justForegrounded: bool,\n+ ) => PingActionInput,\n// Redux dispatch functions\ndispatchActionPromise: DispatchActionPromise,\n// async functions that hit server APIs\nping: (actionInput: PingActionInput) => Promise<PingResult>,\n};\n-function dispatchPing(props: Props) {\n+function dispatchPing(props: Props, justForegrounded: bool) {\nconst startingPayload = props.pingStartingPayload();\n- const actionInput = props.pingActionInput(startingPayload);\n+ const actionInput = props.pingActionInput(startingPayload, justForegrounded);\nprops.dispatchActionPromise(\npingActionTypes,\nprops.ping(actionInput),\n@@ -37,8 +41,32 @@ function dispatchPing(props: Props) {\n);\n}\n+const pingActionInputSelector = (\n+ activeThread: ?string,\n+ actionInput: (startingPayload: PingStartingPayload) => PingActionInput,\n+) => (\n+ startingPayload: PingStartingPayload,\n+ justForegrounded: bool,\n+) => {\n+ const genericActionInput = actionInput(startingPayload);\n+ if (!justForegrounded || !genericActionInput.loggedIn || !activeThread) {\n+ return genericActionInput;\n+ }\n+ return {\n+ ...genericActionInput,\n+ clientResponses: [\n+ ...genericActionInput.clientResponses,\n+ {\n+ type: serverRequestTypes.INITIAL_ACTIVITY_UPDATE,\n+ threadID: activeThread,\n+ },\n+ ],\n+ };\n+};\n+\nexport {\npingFrequency,\nearliestTimeConsideredCurrent,\ndispatchPing,\n+ pingActionInputSelector,\n};\n" }, { "change_type": "MODIFY", "old_path": "lib/types/request-types.js", "new_path": "lib/types/request-types.js", "diff": "@@ -14,6 +14,7 @@ export const serverRequestTypes = Object.freeze({\nDEVICE_TOKEN: 1,\nTHREAD_POLL_PUSH_INCONSISTENCY: 2,\nPLATFORM_DETAILS: 3,\n+ INITIAL_ACTIVITY_UPDATE: 4,\n});\ntype ServerRequestType = $Values<typeof serverRequestTypes>;\nfunction assertServerRequestType(\n@@ -23,7 +24,8 @@ function assertServerRequestType(\nserverRequestType === 0 ||\nserverRequestType === 1 ||\nserverRequestType === 2 ||\n- serverRequestType === 3,\n+ serverRequestType === 3 ||\n+ serverRequestType === 4,\n\"number is not ServerRequestType enum\",\n);\nreturn serverRequestType;\n@@ -63,6 +65,11 @@ type PlatformDetailsClientResponse = {|\nplatformDetails: PlatformDetails,\n|};\n+type InitialActivityUpdateClientResponse = {|\n+ type: 4,\n+ threadID: string,\n+|};\n+\nexport const serverRequestPropType = PropTypes.oneOfType([\nPropTypes.shape({\ntype: PropTypes.oneOf([ serverRequestTypes.PLATFORM ]).isRequired,\n@@ -83,4 +90,5 @@ export type ClientResponse =\n| PlatformClientResponse\n| DeviceTokenClientResponse\n| ThreadPollPushInconsistencyClientResponse\n- | PlatformDetailsClientResponse;\n+ | PlatformDetailsClientResponse\n+ | InitialActivityUpdateClientResponse;\n" }, { "change_type": "MODIFY", "old_path": "native/account/logged-out-modal.react.js", "new_path": "native/account/logged-out-modal.react.js", "diff": "@@ -356,7 +356,7 @@ class InnerLoggedOutModal extends React.PureComponent<Props, State> {\nlogInExtraInfo: props.logInExtraInfo,\nloggedIn: props.loggedIn,\n});\n- dispatchPing({ ...props, ping: boundPing });\n+ dispatchPing({ ...props, ping: boundPing }, true);\n}\nhardwareBack = () => {\n" }, { "change_type": "MODIFY", "old_path": "native/app.react.js", "new_path": "native/app.react.js", "diff": "@@ -87,8 +87,10 @@ import {\n} from './navigation-setup';\nimport { store } from './redux-setup';\nimport { resolveInvalidatedCookie } from './account/native-credentials';\n-import { pingNativeStartingPayload } from './selectors/ping-selectors';\n-import { pingActionInput } from 'lib/selectors/ping-selectors';\n+import {\n+ pingNativeStartingPayload,\n+ pingNativeActionInput,\n+} from './selectors/ping-selectors';\nimport ConnectedStatusBar from './connected-status-bar.react';\nimport {\nactiveThreadSelector,\n@@ -134,7 +136,10 @@ type Props = {\ncookie: ?string,\nnavigationState: NavigationState,\npingStartingPayload: () => PingStartingPayload,\n- pingActionInput: (startingPayload: PingStartingPayload) => PingActionInput,\n+ pingActionInput: (\n+ startingPayload: PingStartingPayload,\n+ justForegrounded: bool,\n+ ) => PingActionInput,\nactiveThread: ?string,\nappLoggedIn: bool,\nloggedIn: bool,\n@@ -208,7 +213,6 @@ class AppWithNavigationState extends React.PureComponent<Props> {\nif (this.props.loggedIn) {\nthis.startTimeouts(this.props, \"active\");\n}\n- AppWithNavigationState.updateFocusedThreads(this.props, null, null);\nif (Platform.OS === \"ios\") {\nNotificationsIOS.addEventListener(\n\"remoteNotificationsRegistered\",\n@@ -353,15 +357,19 @@ class AppWithNavigationState extends React.PureComponent<Props> {\nreturn false;\n}\n- possiblePing = (inputProps?: Props, inputAppState?: ?string) => {\n+ possiblePing = (\n+ inputProps?: Props,\n+ inputAppState?: ?string,\n+ justForegrounded?: ?bool,\n+ ) => {\nconst appState = inputAppState ? inputAppState : this.currentState;\nconst props = inputProps ? inputProps : this.props;\nif (this.shouldDispatchPing(props, appState)) {\n- this.pingNow(props);\n+ this.pingNow(props, justForegrounded);\n}\n}\n- pingNow(inputProps?: Props) {\n+ pingNow(inputProps?: Props, justForegrounded?: ?bool) {\nconst props = inputProps ? inputProps : this.props;\n// This will only trigger if the ping is complete by then. If the ping isn't\n// complete by the time this timeout fires, componentWillReceiveProps takes\n@@ -370,7 +378,7 @@ class AppWithNavigationState extends React.PureComponent<Props> {\n// This one runs in case something is wrong with pingCounter state or timing\n// and the first one gets swallowed without triggering another ping.\nsetTimeout(this.possiblePing, pingFrequency * 10);\n- dispatchPing(props);\n+ dispatchPing(props, !!justForegrounded);\n}\npossiblyNewSessionID = (inputProps?: Props, inputAppState?: ?string) => {\n@@ -399,7 +407,7 @@ class AppWithNavigationState extends React.PureComponent<Props> {\nconst props = inputProps ? inputProps : this.props;\nconst appState = inputAppState ? inputAppState : this.currentState;\nif (props.loggedIn) {\n- this.possiblePing(props, appState);\n+ this.possiblePing(props, appState, true);\n} else {\nthis.possiblyNewSessionID(props, appState);\n}\n@@ -414,7 +422,6 @@ class AppWithNavigationState extends React.PureComponent<Props> {\nthis.currentState === \"active\"\n) {\nthis.startTimeouts();\n- AppWithNavigationState.updateFocusedThreads(this.props, null, null);\nif (this.props.appLoggedIn) {\nthis.ensurePushNotifsEnabled();\n}\n@@ -433,16 +440,15 @@ class AppWithNavigationState extends React.PureComponent<Props> {\ncomponentWillReceiveProps(nextProps: Props) {\nconst justLoggedIn = nextProps.loggedIn && !this.props.loggedIn;\n- if (justLoggedIn || nextProps.activeThread !== this.props.activeThread) {\n+ if (justLoggedIn) {\n+ this.startTimeouts(nextProps, \"active\");\n+ } else if (nextProps.activeThread !== this.props.activeThread) {\nAppWithNavigationState.updateFocusedThreads(\nnextProps,\nthis.props.activeThread,\nthis.props.activeThreadLatestMessage,\n);\n}\n- if (justLoggedIn) {\n- this.startTimeouts(nextProps, \"active\");\n- }\nconst nextActiveThread = nextProps.activeThread;\nif (nextActiveThread && nextActiveThread !== this.props.activeThread) {\n@@ -870,7 +876,7 @@ const ConnectedAppWithNavigationState = connect(\nreturn {\nnavigationState: state.navInfo.navigationState,\npingStartingPayload: pingNativeStartingPayload(state),\n- pingActionInput: pingActionInput(state),\n+ pingActionInput: pingNativeActionInput(state),\nactiveThread,\nappLoggedIn,\nloggedIn: appLoggedIn &&\n" }, { "change_type": "MODIFY", "old_path": "native/selectors/ping-selectors.js", "new_path": "native/selectors/ping-selectors.js", "diff": "@@ -6,7 +6,11 @@ import type { ThreadMessageInfo } from 'lib/types/message-types';\nimport { createSelector } from 'reselect';\n-import { pingStartingPayload } from 'lib/selectors/ping-selectors';\n+import {\n+ pingStartingPayload,\n+ pingActionInput,\n+} from 'lib/selectors/ping-selectors';\n+import { pingActionInputSelector } from 'lib/shared/ping-utils';\nimport { activeThreadSelector } from './nav-selectors';\n@@ -50,6 +54,13 @@ const pingNativeStartingPayload = createSelector(\n},\n);\n+const pingNativeActionInput = createSelector(\n+ activeThreadSelector,\n+ pingActionInput,\n+ pingActionInputSelector,\n+);\n+\nexport {\npingNativeStartingPayload,\n+ pingNativeActionInput,\n};\n" }, { "change_type": "MODIFY", "old_path": "server/src/responders/ping-responders.js", "new_path": "server/src/responders/ping-responders.js", "diff": "@@ -33,7 +33,10 @@ import {\nimport { fetchMessageInfosSince } from '../fetchers/message-fetchers';\nimport { fetchThreadInfos } from '../fetchers/thread-fetchers';\nimport { fetchEntryInfos } from '../fetchers/entry-fetchers';\n-import { updateActivityTime } from '../updaters/activity-updaters';\n+import {\n+ updateActivityTime,\n+ activityUpdater,\n+} from '../updaters/activity-updaters';\nimport { fetchCurrentUserInfo } from '../fetchers/user-fetchers';\nimport { fetchUpdateInfos } from '../fetchers/update-fetchers';\nimport {\n@@ -89,6 +92,13 @@ const pingRequestInputValidator = tShape({\n),\nplatformDetails: tPlatformDetails,\n}),\n+ tShape({\n+ type: t.irreducible(\n+ 'serverRequestTypes.INITIAL_ACTIVITY_UPDATE',\n+ x => x === serverRequestTypes.INITIAL_ACTIVITY_UPDATE,\n+ ),\n+ threadID: t.String,\n+ }),\n]))),\n});\n@@ -179,8 +189,18 @@ async function pingResponder(\n));\nviewerMissingPlatform = false;\nviewerMissingPlatformDetails = false;\n+ } else if (\n+ clientResponse.type === serverRequestTypes.INITIAL_ACTIVITY_UPDATE\n+ ) {\n+ clientResponsePromises.push(activityUpdater(\n+ viewer,\n+ { updates: [ { focus: true, threadID: clientResponse.threadID } ] },\n+ ));\n+ }\n}\n}\n+ if (clientResponsePromises.length > 0) {\n+ await Promise.all(clientResponsePromises);\n}\nconst oldUpdatesCurrentAsOf = request.updatesCurrentAsOf;\n@@ -201,9 +221,6 @@ async function pingResponder(\nfetchEntryInfos(viewer, calendarQuery),\nfetchCurrentUserInfo(viewer),\ncalendarQuery ? fetchCurrentFilter(viewer) : undefined,\n- clientResponsePromises.length > 0\n- ? Promise.all(clientResponsePromises)\n- : null,\n]);\nconst promises = {};\n" }, { "change_type": "MODIFY", "old_path": "web/app.react.js", "new_path": "web/app.react.js", "diff": "@@ -41,7 +41,6 @@ import { createLoadingStatusSelector } from 'lib/selectors/loading-selectors';\nimport { connect } from 'lib/utils/redux-utils';\nimport {\npingStartingPayload,\n- pingActionInput,\n} from 'lib/selectors/ping-selectors';\nimport { pingActionTypes, ping } from 'lib/actions/ping-actions';\nimport { pingFrequency, dispatchPing } from 'lib/shared/ping-utils';\n@@ -78,6 +77,7 @@ import history from './router-history';\nimport { updateNavInfoActionType } from './redux-setup';\nimport Splash from './splash/splash.react';\nimport Chat from './chat/chat.react';\n+import { pingWebActionInput } from './selectors/ping-selectors';\n// We want Webpack's css-loader and style-loader to handle the Fontawesome CSS,\n// so we disable the autoAddCss logic and import the CSS file.\n@@ -107,7 +107,10 @@ type Props = {\nentriesLoadingStatus: LoadingStatus,\ncurrentCalendarQuery: () => CalendarQuery,\npingStartingPayload: () => PingStartingPayload,\n- pingActionInput: (startingPayload: PingStartingPayload) => PingActionInput,\n+ pingActionInput: (\n+ startingPayload: PingStartingPayload,\n+ justForegrounded: bool,\n+ ) => PingActionInput,\npingTimestamps: PingTimestamps,\nsessionTimeLeft: () => number,\nnextSessionID: () => ?string,\n@@ -201,8 +204,6 @@ class App extends React.PureComponent<Props, State> {\nhistory.replace('/');\n}\n- App.updateFocusedThreads(this.props, null, null);\n-\nVisibility.change(this.onVisibilityChange);\n}\n@@ -213,7 +214,6 @@ class App extends React.PureComponent<Props, State> {\nonVisibilityChange = (e, state: string) => {\nif (state === \"visible\") {\nthis.startTimeouts(this.props);\n- App.updateFocusedThreads(this.props, null, null);\n} else {\nthis.closingApp();\n}\n@@ -281,14 +281,14 @@ class App extends React.PureComponent<Props, State> {\nreturn false;\n}\n- possiblePing = (inputProps?: Props) => {\n+ possiblePing = (inputProps?: Props, justForegrounded?: ?bool) => {\nconst props = inputProps ? inputProps : this.props;\nif (this.shouldDispatchPing(props)) {\n- this.pingNow(inputProps);\n+ this.pingNow(inputProps, justForegrounded);\n}\n}\n- pingNow(inputProps?: Props) {\n+ pingNow(inputProps?: Props, justForegrounded?: ?bool) {\nconst props = inputProps ? inputProps : this.props;\n// This will only trigger if the ping is complete by then. If the ping isn't\n// complete by the time this timeout fires, componentWillReceiveProps takes\n@@ -297,7 +297,7 @@ class App extends React.PureComponent<Props, State> {\n// This one runs in case something is wrong with pingCounter state or timing\n// and the first one gets swallowed without triggering another ping.\nsetTimeout(this.possiblePing, pingFrequency * 10);\n- dispatchPing(props);\n+ dispatchPing(props, !!justForegrounded);\n}\npossiblyNewSessionID = (inputProps?: Props) => {\n@@ -324,7 +324,7 @@ class App extends React.PureComponent<Props, State> {\nstartTimeouts(inputProps?: Props) {\nconst props = inputProps ? inputProps : this.props;\nif (props.loggedIn) {\n- this.possiblePing(props);\n+ this.possiblePing(props, true);\n} else {\nthis.possiblyNewSessionID(props);\n}\n@@ -413,9 +413,7 @@ class App extends React.PureComponent<Props, State> {\nhistory.replace(newURL);\n}\nthis.startTimeouts(nextProps);\n- }\n-\n- if (justLoggedIn || nextProps.activeThread !== this.props.activeThread) {\n+ } else if (nextProps.activeThread !== this.props.activeThread) {\nApp.updateFocusedThreads(\nnextProps,\nthis.props.activeThread,\n@@ -575,7 +573,7 @@ export default connect(\nentriesLoadingStatus: loadingStatusSelector(state),\ncurrentCalendarQuery: currentCalendarQuery(state),\npingStartingPayload: pingStartingPayload(state),\n- pingActionInput: pingActionInput(state),\n+ pingActionInput: pingWebActionInput(state),\npingTimestamps: state.pingTimestamps,\nsessionTimeLeft: sessionTimeLeft(state),\nnextSessionID: nextSessionID(state),\n" }, { "change_type": "ADD", "old_path": null, "new_path": "web/selectors/ping-selectors.js", "diff": "+// @flow\n+\n+import { createSelector } from 'reselect';\n+\n+import { pingActionInput } from 'lib/selectors/ping-selectors';\n+import { pingActionInputSelector } from 'lib/shared/ping-utils';\n+\n+import { activeThreadSelector } from './nav-selectors';\n+\n+const pingWebActionInput = createSelector(\n+ activeThreadSelector,\n+ pingActionInput,\n+ pingActionInputSelector,\n+);\n+\n+export {\n+ pingWebActionInput,\n+};\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Include first activity update in first ping when foregrounding This avoids a race condition between the activity update and the ping that has been causing poll/push inconsistency.
129,187
01.08.2018 14:02:04
14,400
3ccb72c5d40e2d9153f5c252dc8c2cf056bcb890
[native] codeVersion -> 15
[ { "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 14\n- versionName \"0.0.14\"\n+ versionCode 15\n+ versionName \"0.0.15\"\nndk {\nabiFilters \"armeabi-v7a\", \"x86\"\n}\n" }, { "change_type": "MODIFY", "old_path": "native/android/app/src/main/AndroidManifest.xml", "new_path": "native/android/app/src/main/AndroidManifest.xml", "diff": "xmlns:android=\"http://schemas.android.com/apk/res/android\"\nxmlns:tools=\"http://schemas.android.com/tools\"\npackage=\"org.squadcal\"\n- android:versionCode=\"14\"\n- android:versionName=\"0.0.14\"\n+ android:versionCode=\"15\"\n+ android:versionName=\"0.0.15\"\n>\n<uses-permission android:name=\"android.permission.INTERNET\" />\n<uses-permission android:name=\"android.permission.SYSTEM_ALERT_WINDOW\"/>\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.14</string>\n+ <string>0.0.15</string>\n<key>CFBundleSignature</key>\n<string>????</string>\n<key>CFBundleVersion</key>\n- <string>14</string>\n+ <string>15</string>\n<key>LSApplicationQueriesSchemes</key>\n<array>\n<string>org-appextension-feature-password-management</string>\n" }, { "change_type": "MODIFY", "old_path": "native/persist.js", "new_path": "native/persist.js", "diff": "@@ -80,7 +80,7 @@ const persistConfig = {\nmigrate: createMigrate(migrations, { debug: __DEV__ }),\n};\n-const codeVersion = 14;\n+const codeVersion = 15;\n// This local exists to avoid a circular dependency where redux-setup needs to\n// import all the navigation and screen stuff, but some of those screens want to\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] codeVersion -> 15
129,187
02.08.2018 11:44:11
14,400
2a53fcde91e8ec965479eb162b59c3d14c5c458b
[native] Delay SET_DEVICE_TOKEN until after REHYDRATE Otherwise it gets sent with a `null` cookie, which triggers a non-invalidating `SET_COOKIE` post-`REHYDRATE`, which fucks everything up.
[ { "change_type": "MODIFY", "old_path": "native/app.react.js", "new_path": "native/app.react.js", "diff": "@@ -200,6 +200,7 @@ class AppWithNavigationState extends React.PureComponent<Props> {\ninitialAndroidNotifHandled = false;\nopenThreadOnceReceived: Set<string> = new Set();\nupdateBadgeCountAfterNextPing = true;\n+ queuedDeviceToken: ?string = null;\ncomponentDidMount() {\nif (Platform.OS === \"android\") {\n@@ -517,6 +518,16 @@ class AppWithNavigationState extends React.PureComponent<Props> {\n) {\nthis.ensurePushNotifsEnabled();\n}\n+\n+ if (\n+ this.props.appLoggedIn &&\n+ !prevProps.appLoggedIn &&\n+ this.queuedDeviceToken !== null &&\n+ this.queuedDeviceToken !== undefined\n+ ) {\n+ this.setDeviceToken(this.queuedDeviceToken);\n+ this.queuedDeviceToken = null;\n+ }\n}\nstatic serverRequestsHasDeviceTokenRequest(\n@@ -595,14 +606,22 @@ class AppWithNavigationState extends React.PureComponent<Props> {\niosPushPermissionResponseReceived();\n}\nif (deviceToken !== this.props.deviceToken) {\n+ if (this.props.appLoggedIn) {\n+ this.setDeviceToken(deviceToken);\n+ } else {\n+ this.queuedDeviceToken = deviceToken;\n+ }\n+ }\n+ }\n+\n+ setDeviceToken(deviceToken: string) {\nthis.props.dispatchActionPromise(\nsetDeviceTokenActionTypes,\n- this.props.setDeviceToken(deviceToken, deviceType),\n+ this.props.setDeviceToken(deviceToken, Platform.OS),\nundefined,\ndeviceToken,\n);\n}\n- }\nfailedToRegisterPushPermissions = (error) => {\nif (!this.props.appLoggedIn) {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Delay SET_DEVICE_TOKEN until after REHYDRATE Otherwise it gets sent with a `null` cookie, which triggers a non-invalidating `SET_COOKIE` post-`REHYDRATE`, which fucks everything up.
129,187
02.08.2018 11:46:26
14,400
e702a69ee7142f559583e91fc66cb9ed06fc636a
[native] codeVersion -> 16
[ { "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 15\n- versionName \"0.0.15\"\n+ versionCode 16\n+ versionName \"0.0.16\"\nndk {\nabiFilters \"armeabi-v7a\", \"x86\"\n}\n" }, { "change_type": "MODIFY", "old_path": "native/android/app/src/main/AndroidManifest.xml", "new_path": "native/android/app/src/main/AndroidManifest.xml", "diff": "xmlns:android=\"http://schemas.android.com/apk/res/android\"\nxmlns:tools=\"http://schemas.android.com/tools\"\npackage=\"org.squadcal\"\n- android:versionCode=\"15\"\n- android:versionName=\"0.0.15\"\n+ android:versionCode=\"16\"\n+ android:versionName=\"0.0.16\"\n>\n<uses-permission android:name=\"android.permission.INTERNET\" />\n<uses-permission android:name=\"android.permission.SYSTEM_ALERT_WINDOW\"/>\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.15</string>\n+ <string>0.0.16</string>\n<key>CFBundleSignature</key>\n<string>????</string>\n<key>CFBundleVersion</key>\n- <string>15</string>\n+ <string>16</string>\n<key>LSApplicationQueriesSchemes</key>\n<array>\n<string>org-appextension-feature-password-management</string>\n" }, { "change_type": "MODIFY", "old_path": "native/persist.js", "new_path": "native/persist.js", "diff": "@@ -80,7 +80,7 @@ const persistConfig = {\nmigrate: createMigrate(migrations, { debug: __DEV__ }),\n};\n-const codeVersion = 15;\n+const codeVersion = 16;\n// This local exists to avoid a circular dependency where redux-setup needs to\n// import all the navigation and screen stuff, but some of those screens want to\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] codeVersion -> 16
129,187
02.08.2018 14:22:54
14,400
f673a354f8278254459034e9e1df1e3e3373e58c
[server] Allow specification of target_cookie on a per-update basis Sticking it into `UpdateData`.
[ { "change_type": "MODIFY", "old_path": "lib/types/update-types.js", "new_path": "lib/types/update-types.js", "diff": "@@ -69,6 +69,7 @@ type BadDeviceTokenUpdateData = {|\nuserID: string,\ntime: number,\ndeviceToken: string,\n+ targetCookie: string,\n|};\nexport type UpdateData =\n| AccountDeletionUpdateData\n" }, { "change_type": "MODIFY", "old_path": "server/src/creators/update-creator.js", "new_path": "server/src/creators/update-creator.js", "diff": "@@ -68,16 +68,12 @@ const sortFunction = (\n// Creates rows in the updates table based on the inputed updateDatas. Returns\n// UpdateInfos pertaining to the provided viewerInfo, as well as related\n-// UserInfos.\n-// - If no viewerInfo is provided, no UpdateInfos will be returned. and the\n-// update row won't have an updater_cookie, meaning no cookie will be excluded\n-// from the update.\n-// - Most updates go to all a user's cookies, but if you want to target one in\n-// particular, you can use targetCookie.\n+// UserInfos. If no viewerInfo is provided, no UpdateInfos will be returned. And\n+// the update row won't have an updater_cookie, meaning no cookie will be\n+// excluded from the update.\nasync function createUpdates(\nupdateDatas: $ReadOnlyArray<UpdateData>,\nviewerInfo?: ?ViewerInfo,\n- targetCookie?: string,\n): Promise<UpdatesResult> {\nif (updateDatas.length === 0) {\nreturn defaultResult;\n@@ -186,7 +182,7 @@ async function createUpdates(\nviewerUpdateDatas.push({ data: updateData, id: ids[i] });\n}\n- let content;\n+ let content, targetCookie = null;\nif (updateData.type === updateTypes.DELETE_ACCOUNT) {\ncontent = JSON.stringify({ deletedUserID: updateData.deletedUserID });\n} else if (updateData.type === updateTypes.UPDATE_THREAD) {\n@@ -200,9 +196,10 @@ async function createUpdates(\n) {\nconst { threadID } = updateData;\ncontent = JSON.stringify({ threadID });\n- } else if (updateData.type == updateTypes.BAD_DEVICE_TOKEN) {\n- const { deviceToken } = updateData;\n+ } else if (updateData.type === updateTypes.BAD_DEVICE_TOKEN) {\n+ const { deviceToken, targetCookie: cookieFromData } = updateData;\ncontent = JSON.stringify({ deviceToken });\n+ targetCookie = cookieFromData;\n} else {\ninvariant(false, `unrecognized updateType ${updateData.type}`);\n}\n@@ -224,7 +221,7 @@ async function createUpdates(\ncontent,\nupdateData.time,\nviewerInfo ? viewerInfo.viewer.cookieID : null,\n- targetCookie ? targetCookie : null,\n+ targetCookie,\n];\ninsertRows.push(insertRow);\n}\n" }, { "change_type": "MODIFY", "old_path": "server/src/fetchers/update-fetchers.js", "new_path": "server/src/fetchers/update-fetchers.js", "diff": "@@ -103,6 +103,9 @@ function viewerUpdateDataFromRow(\nuserID: viewer.id,\ntime: row.time,\ndeviceToken,\n+ // This UpdateData is only used to generate a UpdateInfo,\n+ // and UpdateInfo doesn't care about the targetCookie field\n+ targetCookie: \"\",\n};\n} else {\ninvariant(false, `unrecognized updateType ${type}`);\n" }, { "change_type": "MODIFY", "old_path": "server/src/push/send.js", "new_path": "server/src/push/send.js", "diff": "@@ -514,8 +514,9 @@ async function removeInvalidTokens(\nuserID,\ntime,\ndeviceToken,\n+ targetCookie: cookieID,\n}));\n- promises.push(createUpdates(updateDatas, null, cookieID));\n+ promises.push(createUpdates(updateDatas));\n}\nconst updateQuery = SQL`\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[server] Allow specification of target_cookie on a per-update basis Sticking it into `UpdateData`.
129,187
03.08.2018 21:40:22
14,400
99b0f5c32e999d2a5d00882069670933980673b3
Code to create new updateTypes.UPDATE_ENTRY updates
[ { "change_type": "MODIFY", "old_path": "lib/actions/entry-actions.js", "new_path": "lib/actions/entry-actions.js", "diff": "import type {\nRawEntryInfo,\nCalendarQuery,\n- SaveEntryRequest,\n+ SaveEntryInfo,\nSaveEntryResponse,\n- CreateEntryRequest,\n+ CreateEntryInfo,\nSaveEntryPayload,\n+ DeleteEntryInfo,\nDeleteEntryResponse,\n+ RestoreEntryInfo,\nRestoreEntryResponse,\nFetchEntryInfosResult,\nCalendarResult,\n@@ -87,7 +89,7 @@ const createEntryActionTypes = Object.freeze({\n});\nasync function createEntry(\nfetchJSON: FetchJSON,\n- request: CreateEntryRequest,\n+ request: CreateEntryInfo,\n): Promise<SaveEntryPayload> {\nconst result = await fetchJSON('create_entry', request);\nreturn {\n@@ -95,6 +97,7 @@ async function createEntry(\ntext: request.text,\nnewMessageInfos: result.newMessageInfos,\nthreadID: request.threadID,\n+ updatesResult: result.updatesResult,\n};\n}\n@@ -106,13 +109,14 @@ const saveEntryActionTypes = Object.freeze({\nconst concurrentModificationResetActionType = \"CONCURRENT_MODIFICATION_RESET\";\nasync function saveEntry(\nfetchJSON: FetchJSON,\n- request: SaveEntryRequest,\n+ request: SaveEntryInfo,\n): Promise<SaveEntryResponse> {\nconst result = await fetchJSON('update_entry', request);\nreturn {\nentryID: result.entryID,\ntext: request.text,\nnewMessageInfos: result.newMessageInfos,\n+ updatesResult: result.updatesResult,\n};\n}\n@@ -123,19 +127,16 @@ const deleteEntryActionTypes = Object.freeze({\n});\nasync function deleteEntry(\nfetchJSON: FetchJSON,\n- entryID: string,\n- prevText: string,\n- sessionID: string,\n+ info: DeleteEntryInfo,\n): Promise<DeleteEntryResponse> {\nconst response = await fetchJSON('delete_entry', {\n- entryID,\n- prevText,\n- sessionID,\n+ ...info,\ntimestamp: Date.now(),\n});\nreturn {\nnewMessageInfos: response.newMessageInfos,\nthreadID: response.threadID,\n+ updatesResult: response.updatesResult,\n};\n}\n@@ -159,17 +160,16 @@ const restoreEntryActionTypes = Object.freeze({\n});\nasync function restoreEntry(\nfetchJSON: FetchJSON,\n- entryID: string,\n- sessionID: string,\n+ info: RestoreEntryInfo,\n): Promise<RestoreEntryResponse> {\nconst response = await fetchJSON('restore_entry', {\n- entryID,\n- sessionID,\n+ ...info,\ntimestamp: Date.now(),\n});\nreturn {\nnewMessageInfos: response.newMessageInfos,\nentryInfo: response.entryInfo,\n+ updatesResult: response.updatesResult,\n};\n}\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';\nimport type { CalendarFilter } from './filter-types';\n+import type { CreateUpdatesResult } from './update-types';\nimport PropTypes from 'prop-types';\n@@ -70,17 +71,28 @@ export type CalendarQuery = {|\nfilters: $ReadOnlyArray<CalendarFilter>,\n|};\n+export type SaveEntryInfo = {|\n+ entryID: string,\n+ text: string,\n+ prevText: string,\n+ sessionID: string,\n+ timestamp: number,\n+ calendarQuery: CalendarQuery,\n+|};\n+\nexport type SaveEntryRequest = {|\nentryID: string,\ntext: string,\nprevText: string,\nsessionID: string,\ntimestamp: number,\n+ calendarQuery?: CalendarQuery,\n|};\nexport type SaveEntryResult = {|\nentryID: string,\nnewMessageInfos: $ReadOnlyArray<RawMessageInfo>,\n+ updatesResult: CreateUpdatesResult,\n|};\nexport type SaveEntryResponse = {|\n@@ -93,12 +105,22 @@ export type SaveEntryPayload = {|\nthreadID: string,\n|};\n+export type CreateEntryInfo = {|\n+ text: string,\n+ sessionID: string,\n+ timestamp: number,\n+ date: string,\n+ threadID: string,\n+ calendarQuery: CalendarQuery,\n+|};\n+\nexport type CreateEntryRequest = {|\ntext: string,\nsessionID: string,\ntimestamp: number,\ndate: string,\nthreadID: string,\n+ calendarQuery?: CalendarQuery,\n|};\nexport type CreateEntryResponse = {|\n@@ -106,27 +128,44 @@ export type CreateEntryResponse = {|\nlocalID: string,\n|};\n+export type DeleteEntryInfo = {|\n+ entryID: string,\n+ prevText: string,\n+ sessionID: string,\n+ calendarQuery: CalendarQuery,\n+|};\n+\nexport type DeleteEntryRequest = {|\nentryID: string,\nprevText: string,\nsessionID: string,\ntimestamp: number,\n+ calendarQuery?: CalendarQuery,\n+|};\n+\n+export type RestoreEntryInfo = {|\n+ entryID: string,\n+ sessionID: string,\n+ calendarQuery: CalendarQuery,\n|};\nexport type RestoreEntryRequest = {|\nentryID: string,\nsessionID: string,\ntimestamp: number,\n+ calendarQuery?: CalendarQuery,\n|};\nexport type DeleteEntryResponse = {|\nnewMessageInfos: $ReadOnlyArray<RawMessageInfo>,\nthreadID: string,\n+ updatesResult: CreateUpdatesResult,\n|};\nexport type RestoreEntryResponse = {|\nnewMessageInfos: $ReadOnlyArray<RawMessageInfo>,\nentryInfo: RawEntryInfo,\n+ updatesResult: CreateUpdatesResult,\n|};\nexport type FetchEntryInfosResponse = {|\n" }, { "change_type": "MODIFY", "old_path": "lib/types/update-types.js", "new_path": "lib/types/update-types.js", "diff": "@@ -5,7 +5,8 @@ import type {\nRawMessageInfo,\nMessageTruncationStatus,\n} from './message-types';\n-import type { RawEntryInfo, CalendarQuery } from './entry-types';\n+import type { RawEntryInfo } from './entry-types';\n+import type { AccountUserInfo } from './user-types';\nimport invariant from 'invariant';\n@@ -148,3 +149,8 @@ export type UpdatesResult = {|\ncurrentAsOf: number,\nnewUpdates: $ReadOnlyArray<UpdateInfo>,\n|};\n+\n+export type CreateUpdatesResult = {|\n+ viewerUpdates: $ReadOnlyArray<UpdateInfo>,\n+ userInfos: {[id: string]: AccountUserInfo},\n+|};\n" }, { "change_type": "MODIFY", "old_path": "native/calendar/entry.react.js", "new_path": "native/calendar/entry.react.js", "diff": "import type { EntryInfoWithHeight } from './calendar.react';\nimport {\nentryInfoPropType,\n- type CreateEntryRequest,\n- type SaveEntryRequest,\n+ type CreateEntryInfo,\n+ type SaveEntryInfo,\ntype SaveEntryResponse,\n+ type DeleteEntryInfo,\ntype DeleteEntryResponse,\n+ type CalendarQuery,\n} from 'lib/types/entry-types';\nimport type { ThreadInfo } from 'lib/types/thread-types';\nimport { threadInfoPropType } from 'lib/types/thread-types';\n@@ -64,6 +66,7 @@ import { entryKey } from 'lib/shared/entry-utils';\nimport { registerFetchKey } from 'lib/reducers/loading-reducer';\nimport { threadInfoSelector } from 'lib/selectors/thread-selectors';\nimport { dateString } from 'lib/utils/date-utils';\n+import { nonThreadCalendarQuery } from 'lib/selectors/nav-selectors';\nimport Button from '../components/button.react';\nimport { ChatRouteName } from '../chat/chat.react';\n@@ -88,17 +91,14 @@ type Props = {\nsessionStartingPayload: () => { newSessionID?: string },\nsessionID: () => string,\nnextSessionID: () => ?string,\n+ calendarQuery: () => CalendarQuery,\n// Redux dispatch functions\ndispatchActionPayload: DispatchActionPayload,\ndispatchActionPromise: DispatchActionPromise,\n// async functions that hit server APIs\n- createEntry: (request: CreateEntryRequest) => Promise<SaveEntryResponse>,\n- saveEntry: (request: SaveEntryRequest) => Promise<SaveEntryResponse>,\n- deleteEntry: (\n- entryID: string,\n- prevText: string,\n- sessionID: string,\n- ) => Promise<DeleteEntryResponse>,\n+ createEntry: (info: CreateEntryInfo) => Promise<SaveEntryResponse>,\n+ saveEntry: (info: SaveEntryInfo) => Promise<SaveEntryResponse>,\n+ deleteEntry: (info: DeleteEntryInfo) => Promise<DeleteEntryResponse>,\n};\ntype State = {|\nediting: bool,\n@@ -122,6 +122,7 @@ class InternalEntry extends React.Component<Props, State> {\nsessionStartingPayload: PropTypes.func.isRequired,\nsessionID: PropTypes.func.isRequired,\nnextSessionID: PropTypes.func.isRequired,\n+ calendarQuery: PropTypes.func.isRequired,\ndispatchActionPayload: PropTypes.func.isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\ncreateEntry: PropTypes.func.isRequired,\n@@ -488,6 +489,7 @@ class InternalEntry extends React.Component<Props, State> {\nthis.props.entryInfo.day,\n),\nthreadID: this.props.entryInfo.threadID,\n+ calendarQuery: this.props.calendarQuery(),\n});\nif (curSaveAttempt + 1 === this.nextSaveAttemptIndex) {\nthis.guardedSetState({ loadingStatus: \"inactive\" });\n@@ -520,6 +522,7 @@ class InternalEntry extends React.Component<Props, State> {\nprevText: this.props.entryInfo.text,\nsessionID: this.props.sessionID(),\ntimestamp: Date.now(),\n+ calendarQuery: this.props.calendarQuery(),\n});\nif (curSaveAttempt + 1 === this.nextSaveAttemptIndex) {\nthis.guardedSetState({ loadingStatus: \"inactive\" });\n@@ -587,11 +590,12 @@ class InternalEntry extends React.Component<Props, State> {\nasync deleteAction(serverID: ?string) {\nif (serverID) {\n- return await this.props.deleteEntry(\n- serverID,\n- this.props.entryInfo.text,\n- this.props.sessionID(),\n- );\n+ return await this.props.deleteEntry({\n+ entryID: serverID,\n+ prevText: this.props.entryInfo.text,\n+ sessionID: this.props.sessionID(),\n+ calendarQuery: this.props.calendarQuery(),\n+ });\n} else if (this.creating) {\nthis.needsDeleteAfterCreation = true;\n}\n@@ -704,6 +708,7 @@ const Entry = connect(\nsessionStartingPayload: sessionStartingPayload(state),\nsessionID: currentSessionID(state),\nnextSessionID: nextSessionID(state),\n+ calendarQuery: nonThreadCalendarQuery(state),\n}),\n{ createEntry, saveEntry, deleteEntry },\n)(InternalEntry);\n" }, { "change_type": "MODIFY", "old_path": "server/src/creators/entry-creator.js", "new_path": "server/src/creators/entry-creator.js", "diff": "@@ -9,12 +9,16 @@ import { messageTypes } from 'lib/types/message-types';\nimport { threadPermissions } from 'lib/types/thread-types';\nimport { ServerError } from 'lib/utils/errors';\n+import { dateFromString } from 'lib/utils/date-utils'\nimport { dbQuery, SQL } from '../database';\nimport fetchOrCreateDayID from '../creators/day-creator';\nimport createIDs from '../creators/id-creator';\nimport createMessages from '../creators/message-creator';\nimport { checkThreadPermission } from '../fetchers/thread-fetchers';\n+import {\n+ createUpdateDatasForChangedEntryInfo\n+} from '../updaters/entry-updaters';\nasync function createEntry(\nviewer: Viewer,\n@@ -72,6 +76,7 @@ async function createEntry(\nlast_update, deleted)\nVALUES ${[revisionRow]}\n`;\n+\nconst messageData = {\ntype: messageTypes.CREATE_ENTRY,\nthreadID: request.threadID,\n@@ -81,13 +86,32 @@ async function createEntry(\ndate: request.date,\ntext: request.text,\n};\n- const [ newMessageInfos ] = await Promise.all([\n+\n+ const date = dateFromString(request.date);\n+ const rawEntryInfo = {\n+ id: entryID,\n+ threadID: request.threadID,\n+ text: request.text,\n+ year: date.getFullYear(),\n+ month: date.getMonth() + 1,\n+ day: date.getDate(),\n+ creationTime: request.timestamp,\n+ creatorID: viewerID,\n+ deleted: false,\n+ };\n+\n+ const [ newMessageInfos, updatesResult ] = await Promise.all([\ncreateMessages([messageData]),\n+ createUpdateDatasForChangedEntryInfo(\n+ viewer,\n+ rawEntryInfo,\n+ request.calendarQuery,\n+ ),\ndbQuery(entryInsertQuery),\ndbQuery(revisionInsertQuery),\n]);\n- return { entryID, newMessageInfos };\n+ return { entryID, newMessageInfos, updatesResult };\n}\nexport default createEntry;\n" }, { "change_type": "MODIFY", "old_path": "server/src/creators/update-creator.js", "new_path": "server/src/creators/update-creator.js", "diff": "import {\ntype UpdateInfo,\ntype UpdateData,\n+ type CreateUpdatesResult,\nupdateTypes,\n} from 'lib/types/update-types';\nimport type { Viewer } from '../session/viewer';\n@@ -51,21 +52,23 @@ import {\nfetchEntryInfos,\nfetchEntryInfosByID,\n} from '../fetchers/entry-fetchers';\n+import { fetchCurrentFilter } from '../fetchers/filter-fetchers';\n+import { fetchUserInfos } from '../fetchers/user-fetchers';\nexport type ViewerInfo =\n| {| viewer: Viewer |}\n| {|\nviewer: Viewer,\n- threadInfos: {[id: string]: RawThreadInfo},\n- userInfos: {[id: string]: AccountUserInfo},\ncalendarQuery: ?CalendarQuery,\n- |};\n-type UpdatesResult = {|\n- viewerUpdates: $ReadOnlyArray<UpdateInfo>,\n+ |}\n+ | {|\n+ viewer: Viewer,\n+ calendarQuery: ?CalendarQuery,\n+ threadInfos: {[id: string]: RawThreadInfo},\nuserInfos: {[id: string]: AccountUserInfo},\n|};\nconst emptyArray = [];\n-const defaultResult = { viewerUpdates: [], userInfos: {} };\n+const defaultUpdateCreationResult = { viewerUpdates: [], userInfos: {} };\nconst sortFunction = (\na: UpdateData | UpdateInfo,\nb: UpdateData | UpdateInfo,\n@@ -79,9 +82,9 @@ const sortFunction = (\nasync function createUpdates(\nupdateDatas: $ReadOnlyArray<UpdateData>,\nviewerInfo?: ?ViewerInfo,\n-): Promise<UpdatesResult> {\n+): Promise<CreateUpdatesResult> {\nif (updateDatas.length === 0) {\n- return defaultResult;\n+ return defaultUpdateCreationResult;\n}\nconst sortedUpdateDatas = [...updateDatas].sort(sortFunction);\n@@ -279,7 +282,7 @@ async function createUpdates(\nconst { updatesResult } = await promiseAll(promises);\nif (!updatesResult) {\n- return defaultResult;\n+ return defaultUpdateCreationResult;\n}\nconst { updateInfos, userInfos } = updatesResult;\nreturn { viewerUpdates: updateInfos, userInfos };\n@@ -315,20 +318,25 @@ async function fetchUpdateInfosWithUpdateDatas(\nconst promises = {};\n- if (threadIDsNeedingFetch.size > 0) {\n+ if (!viewerInfo.threadInfos && threadIDsNeedingFetch.size > 0) {\npromises.threadResult = fetchThreadInfos(\nviewerInfo.viewer,\nSQL`t.id IN (${[...threadIDsNeedingFetch]})`,\n);\n}\n- // defaultCalendarQuery will only ever get used in the case of a legacy\n- // client calling join_thread without specifying a CalendarQuery. Those\n- // legacy clients will be discarding the UpdateInfos anyways, so we don't\n- // need to worry about the CalendarQuery correctness.\n- const calendarQuery = viewerInfo.calendarQuery\n+ let calendarQuery: ?CalendarQuery = viewerInfo.calendarQuery\n? viewerInfo.calendarQuery\n- : defaultCalendarQuery();\n+ : null;\n+ if (!calendarQuery) {\n+ // This should only ever happen for \"legacy\" clients who call in without\n+ // providing this information. These clients wouldn't know how to deal with\n+ // the corresponding UpdateInfos anyways, so no reason to be worried.\n+ calendarQuery = await fetchCurrentFilter(viewerInfo.viewer);\n+ }\n+ if (!calendarQuery) {\n+ calendarQuery = defaultCalendarQuery();\n+ }\nif (threadIDsNeedingDetailedFetch.size > 0) {\nconst threadSelectionCriteria = { threadCursors: {} };\nfor (let threadID of threadIDsNeedingDetailedFetch) {\n@@ -376,7 +384,7 @@ async function fetchUpdateInfosWithUpdateDatas(\nthreadInfosResult = { threadInfos: {}, userInfos: {} };\n}\n- return updateInfosFromUpdateDatas(\n+ return await updateInfosFromUpdateDatas(\nupdateDatas,\n{\nthreadInfosResult,\n@@ -395,10 +403,10 @@ export type UpdateInfosRawData = {|\ncalendarResult: ?FetchEntryInfosResponse,\nentryInfosResult: ?$ReadOnlyArray<RawEntryInfo>,\n|};\n-function updateInfosFromUpdateDatas(\n+async function updateInfosFromUpdateDatas(\nupdateDatas: $ReadOnlyArray<ViewerUpdateData>,\nrawData: UpdateInfosRawData,\n-): FetchUpdatesResult {\n+): Promise<FetchUpdatesResult> {\nconst {\nthreadInfosResult,\nmessageInfosResult,\n@@ -493,6 +501,10 @@ function updateInfosFromUpdateDatas(\nif (!rawEntryInfoWithinCalendarQuery(entryInfo, calendarQuery)) {\ncontinue;\n}\n+ userIDs = new Set([\n+ ...userIDs,\n+ ...usersInRawEntryInfos([entryInfo]),\n+ ]);\nupdateInfos.push({\ntype: updateTypes.UPDATE_ENTRY,\nid,\n@@ -505,10 +517,23 @@ function updateInfosFromUpdateDatas(\n}\nconst userInfos = {};\n+ const userIDsToFetch = [];\nfor (let userID of userIDs) {\nconst userInfo = threadInfosResult.userInfos[userID];\nif (userInfo) {\nuserInfos[userID] = userInfo;\n+ } else {\n+ userIDsToFetch.push(userID);\n+ }\n+ }\n+ if (userIDsToFetch.length > 0) {\n+ const fetchedUserInfos = await fetchUserInfos(userIDsToFetch);\n+ for (let userID in fetchedUserInfos) {\n+ const userInfo = fetchedUserInfos[userID];\n+ if (userInfo && userInfo.username) {\n+ const { id, username } = userInfo;\n+ userInfos[userID] = { id, username };\n+ }\n}\n}\n@@ -559,5 +584,6 @@ function updateInfosFromUpdateDatas(\nexport {\ncreateUpdates,\n+ defaultUpdateCreationResult,\nfetchUpdateInfosWithUpdateDatas,\n};\n" }, { "change_type": "MODIFY", "old_path": "server/src/deleters/entry-deleters.js", "new_path": "server/src/deleters/entry-deleters.js", "diff": "@@ -18,6 +18,9 @@ import { dbQuery, SQL } from '../database';\nimport { checkThreadPermissionForEntry } from '../fetchers/entry-fetchers';\nimport createIDs from '../creators/id-creator';\nimport createMessages from '../creators/message-creator';\n+import {\n+ createUpdateDatasForChangedEntryInfo\n+} from '../updaters/entry-updaters';\nconst lastRevisionQuery = (entryID: string) =>\n(SQL`\n@@ -72,8 +75,8 @@ async function deleteEntry(\n);\n}\n- const promises = [];\n- promises.push(dbQuery(SQL`\n+ const dbPromises = [];\n+ dbPromises.push(dbQuery(SQL`\nUPDATE entries SET deleted = 1 WHERE id = ${request.entryID}\n`));\nconst [ revisionID ] = await createIDs(\"revisions\", 1);\n@@ -87,25 +90,46 @@ async function deleteEntry(\nrequest.timestamp,\n1,\n];\n- promises.push(dbQuery(SQL`\n+ dbPromises.push(dbQuery(SQL`\nINSERT INTO revisions(id, entry, author, text, creation_time, session_id,\nlast_update, deleted)\nVALUES ${[revisionRow]}\n`));\n+\nconst threadID = lastRevisionRow.thread.toString();\nconst messageData = {\ntype: messageTypes.DELETE_ENTRY,\n- threadID: threadID,\n+ threadID,\ncreatorID: viewerID,\ntime: Date.now(),\nentryID: request.entryID.toString(),\ndate: dateString(lastRevisionRow.date),\ntext,\n};\n- promises.unshift(createMessages([messageData]));\n- const [ newMessageInfos ] = await Promise.all(promises);\n- return { threadID, newMessageInfos };\n+ const rawEntryInfo = {\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+ }\n+\n+ const [ newMessageInfos, updatesResult ] = await Promise.all([\n+ createMessages([messageData]),\n+ createUpdateDatasForChangedEntryInfo(\n+ viewer,\n+ rawEntryInfo,\n+ request.calendarQuery,\n+ ),\n+ Promise.all(dbPromises),\n+ ]);\n+\n+ return { threadID, newMessageInfos, updatesResult };\n}\nasync function restoreEntry(\n@@ -133,8 +157,8 @@ async function restoreEntry(\nconst text = lastRevisionRow.text;\nconst viewerID = viewer.id;\n- const promises = [];\n- promises.push(dbQuery(SQL`\n+ const dbPromises = [];\n+ dbPromises.push(dbQuery(SQL`\nUPDATE entries SET deleted = 0 WHERE id = ${request.entryID}\n`));\nconst [ revisionID ] = await createIDs(\"revisions\", 1);\n@@ -148,11 +172,12 @@ async function restoreEntry(\nrequest.timestamp,\n0,\n];\n- promises.push(dbQuery(SQL`\n+ dbPromises.push(dbQuery(SQL`\nINSERT INTO revisions(id, entry, author, text, creation_time, session_id,\nlast_update, deleted)\nVALUES ${[revisionRow]}\n`));\n+\nconst threadID = lastRevisionRow.thread.toString();\nconst messageData = {\ntype: messageTypes.RESTORE_ENTRY,\n@@ -163,9 +188,7 @@ async function restoreEntry(\ndate: dateString(lastRevisionRow.date),\ntext,\n};\n- promises.unshift(createMessages([messageData]));\n- const [ newMessageInfos ] = await Promise.all(promises);\nconst entryInfo = {\nid: request.entryID,\nthreadID,\n@@ -176,9 +199,19 @@ async function restoreEntry(\ncreationTime: lastRevisionRow.creation_time,\ncreatorID: lastRevisionRow.creator.toString(),\ndeleted: false,\n- }\n+ };\n+\n+ const [ newMessageInfos, updatesResult ] = await Promise.all([\n+ createMessages([messageData]),\n+ createUpdateDatasForChangedEntryInfo(\n+ viewer,\n+ entryInfo,\n+ request.calendarQuery,\n+ ),\n+ Promise.all(dbPromises),\n+ ]);\n- return { entryInfo, newMessageInfos };\n+ return { entryInfo, newMessageInfos, updatesResult };\n}\nasync function deleteOrphanedEntries(): Promise<void> {\n" }, { "change_type": "MODIFY", "old_path": "server/src/responders/entry-responders.js", "new_path": "server/src/responders/entry-responders.js", "diff": "@@ -139,6 +139,7 @@ const createEntryRequestInputValidator = tShape({\ntimestamp: t.Number,\ndate: tDate,\nthreadID: t.String,\n+ calendarQuery: t.maybe(newEntryQueryInputValidator),\n});\nasync function entryCreationResponder(\n@@ -156,6 +157,7 @@ const saveEntryRequestInputValidator = tShape({\nprevText: t.String,\nsessionID: t.String,\ntimestamp: t.Number,\n+ calendarQuery: t.maybe(newEntryQueryInputValidator),\n});\nasync function entryUpdateResponder(\n@@ -172,6 +174,7 @@ const deleteEntryRequestInputValidator = tShape({\nprevText: t.String,\nsessionID: t.String,\ntimestamp: t.Number,\n+ calendarQuery: t.maybe(newEntryQueryInputValidator),\n});\nasync function entryDeletionResponder(\n@@ -187,6 +190,7 @@ const restoreEntryRequestInputValidator = tShape({\nentryID: t.String,\nsessionID: t.String,\ntimestamp: t.Number,\n+ calendarQuery: t.maybe(newEntryQueryInputValidator),\n});\nasync function entryRestorationResponder(\n" }, { "change_type": "MODIFY", "old_path": "server/src/updaters/entry-updaters.js", "new_path": "server/src/updaters/entry-updaters.js", "diff": "@@ -4,9 +4,10 @@ import type {\nSaveEntryRequest,\nSaveEntryResult,\nRawEntryInfo,\n+ CalendarQuery,\n} from 'lib/types/entry-types';\nimport type { Viewer } from '../session/viewer';\n-import { updateTypes, type UpdateData } from 'lib/types/update-types';\n+import { updateTypes, type CreateUpdatesResult } from 'lib/types/update-types';\nimport invariant from 'invariant';\n@@ -14,7 +15,10 @@ import { ServerError } from 'lib/utils/errors';\nimport { threadPermissions } from 'lib/types/thread-types';\nimport { messageTypes } from 'lib/types/message-types';\nimport { dateString } from 'lib/utils/date-utils';\n-import { rawEntryInfoWithinCalendarQuery } from 'lib/shared/entry-utils';\n+import {\n+ rawEntryInfoWithinCalendarQuery,\n+ defaultCalendarQuery,\n+} from 'lib/shared/entry-utils';\nimport { dbQuery, SQL } from '../database';\nimport {\n@@ -23,7 +27,14 @@ import {\n} from '../fetchers/entry-fetchers';\nimport createIDs from '../creators/id-creator';\nimport createMessages from '../creators/message-creator';\n-import { fetchFiltersForThread } from '../fetchers/filter-fetchers';\n+import {\n+ fetchCurrentFilter,\n+ fetchFiltersForThread,\n+} from '../fetchers/filter-fetchers';\n+import {\n+ defaultUpdateCreationResult,\n+ createUpdates,\n+} from '../creators/update-creator';\nasync function updateEntry(\nviewer: Viewer,\n@@ -73,7 +84,7 @@ async function updateEntry(\n}\nconst viewerID = viewer.id;\n- const promises = [];\n+ const dbPromises = [];\nlet insertNewRevision = false;\nlet updateEntry = false;\nif (\n@@ -83,11 +94,15 @@ async function updateEntry(\nif (lastRevisionRow.last_update >= request.timestamp) {\n// Updates got sent out of order and as a result an update newer than us\n// has already been committed, so there's nothing to do\n- return { entryID: request.entryID, newMessageInfos: [] };\n+ return {\n+ entryID: request.entryID,\n+ newMessageInfos: [],\n+ updatesResult: defaultUpdateCreationResult,\n+ };\n}\nupdateEntry = true;\nif (lastRevisionRow.last_update + 120000 > request.timestamp) {\n- promises.push(dbQuery(SQL`\n+ dbPromises.push(dbQuery(SQL`\nUPDATE revisions\nSET last_update = ${request.timestamp}, text = ${request.text}\nWHERE id = ${lastRevisionRow.id}\n@@ -113,7 +128,7 @@ async function updateEntry(\ninsertNewRevision = true;\n}\nif (updateEntry) {\n- promises.push(dbQuery(SQL`\n+ dbPromises.push(dbQuery(SQL`\nUPDATE entries\nSET last_update = ${request.timestamp}, text = ${request.text}\nWHERE id = ${request.entryID}\n@@ -131,13 +146,15 @@ async function updateEntry(\nrequest.timestamp,\n0,\n];\n- promises.push(dbQuery(SQL`\n+ dbPromises.push(dbQuery(SQL`\nINSERT INTO revisions(id, entry, author, text, creation_time,\nsession_id, last_update, deleted)\nVALUES ${[revisionRow]}\n`));\n}\n- const messageData = {\n+\n+ const [ newMessageInfos, updatesResult ] = await Promise.all([\n+ createMessages([{\ntype: messageTypes.EDIT_ENTRY,\nthreadID: entryInfo.threadID,\ncreatorID: viewerID,\n@@ -145,19 +162,58 @@ async function updateEntry(\nentryID: request.entryID,\ndate: dateString(entryInfo.year, entryInfo.month, entryInfo.day),\ntext: request.text,\n- };\n- promises.unshift(createMessages([messageData]));\n-\n- const [ newMessageInfos ] = await Promise.all(promises);\n- return { entryID: request.entryID, newMessageInfos };\n+ }]),\n+ createUpdateDatasForChangedEntryInfo(\n+ viewer,\n+ entryInfo,\n+ request.calendarQuery,\n+ ),\n+ Promise.all(dbPromises),\n+ ]);\n+ return { entryID: request.entryID, newMessageInfos, updatesResult };\n}\n+// The passed-in RawEntryInfo doesn't need to be the version with updated text,\n+// as the returned UpdateInfos will have newly fetched RawEntryInfos. However,\n+// the passed-in RawEntryInfo's date is used for determining which clients need\n+// the update. Right now it's impossible to change an entry's date, but when it\n+// becomes possible, we will need to update both clients with the old date and\n+// clients with the new date.\nasync function createUpdateDatasForChangedEntryInfo(\n+ viewer: Viewer,\nentryInfo: RawEntryInfo,\n-): Promise<void> {\n+ inputCalendarQuery: ?CalendarQuery,\n+): Promise<CreateUpdatesResult> {\nconst entryID = entryInfo.id;\ninvariant(entryID, \"should be set\");\n- const filters = await fetchFiltersForThread(entryInfo.threadID);\n+ const [ fetchedFilters, fetchedCalendarQuery ] = await Promise.all([\n+ fetchFiltersForThread(entryInfo.threadID),\n+ inputCalendarQuery ? undefined : fetchCurrentFilter(viewer),\n+ ]);\n+\n+ let calendarQuery;\n+ if (inputCalendarQuery) {\n+ calendarQuery = inputCalendarQuery;\n+ } else if (fetchedCalendarQuery) {\n+ // This should only ever happen for \"legacy\" clients who call in without\n+ // providing this information. These clients wouldn't know how to deal with\n+ // the corresponding UpdateInfos anyways, so no reason to be worried.\n+ calendarQuery = fetchedCalendarQuery;\n+ } else {\n+ calendarQuery = defaultCalendarQuery();\n+ }\n+\n+ let replaced = false;\n+ const filters = fetchedFilters.map(\n+ filter => filter.cookieID === viewer.cookieID && filter.userID === viewer.id\n+ ? (replaced = true && { ...filter, calendarQuery })\n+ : filter,\n+ );\n+ if (!replaced) {\n+ const { id: userID, cookieID } = viewer;\n+ filters.push({ userID, cookieID, calendarQuery });\n+ }\n+\nconst time = Date.now();\nconst updateDatas = filters.filter(\nfilter => rawEntryInfoWithinCalendarQuery(entryInfo, filter.calendarQuery),\n@@ -168,6 +224,10 @@ async function createUpdateDatasForChangedEntryInfo(\nentryID,\ntargetCookie: filter.cookieID,\n}));\n+ return await createUpdates(\n+ updateDatas,\n+ { viewer, calendarQuery },\n+ );\n}\nexport {\n" }, { "change_type": "MODIFY", "old_path": "server/src/updaters/thread-updaters.js", "new_path": "server/src/updaters/thread-updaters.js", "diff": "@@ -545,7 +545,7 @@ async function joinThread(\nthrow new ServerError('invalid_parameters');\n}\n- const calendarQuery = request.calendarQuery;\n+ const { calendarQuery } = request;\nif (calendarQuery) {\nconst threadFilterIDs = filteredThreadIDs(calendarQuery.filters);\nif (\n@@ -584,7 +584,7 @@ async function joinThread(\ncreatorID: viewer.id,\ntime: Date.now(),\n};\n- const [ fetchThreadsResult ] = await Promise.all([\n+ const [ membershipResult ] = await Promise.all([\ncommitMembershipChangeset(viewer, changeset, new Set(), calendarQuery),\ncreateMessages([messageData]),\n]);\n@@ -606,7 +606,7 @@ async function joinThread(\nlet userInfos = {\n...fetchMessagesResult.userInfos,\n- ...fetchThreadsResult.userInfos,\n+ ...membershipResult.userInfos,\n};\nlet rawEntryInfos;\nif (fetchEntriesResult) {\n@@ -618,12 +618,12 @@ async function joinThread(\n}\nconst response: ThreadJoinResult = {\n- threadInfos: fetchThreadsResult.threadInfos,\n+ threadInfos: membershipResult.threadInfos,\nrawMessageInfos: fetchMessagesResult.rawMessageInfos,\ntruncationStatuses: fetchMessagesResult.truncationStatuses,\nuserInfos,\nupdatesResult: {\n- newUpdates: fetchThreadsResult.viewerUpdates,\n+ newUpdates: membershipResult.viewerUpdates,\n},\n};\nif (rawEntryInfos) {\n" }, { "change_type": "MODIFY", "old_path": "web/calendar/entry.react.js", "new_path": "web/calendar/entry.react.js", "diff": "import {\ntype EntryInfo,\nentryInfoPropType,\n- type CreateEntryRequest,\n- type SaveEntryRequest,\n+ type CreateEntryInfo,\n+ type SaveEntryInfo,\ntype SaveEntryResponse,\n+ type DeleteEntryInfo,\ntype DeleteEntryResponse,\n+ type CalendarQuery,\n} from 'lib/types/entry-types';\nimport type { ThreadInfo } from 'lib/types/thread-types';\nimport { threadInfoPropType } from 'lib/types/thread-types';\n@@ -42,6 +44,7 @@ import {\n} from 'lib/selectors/session-selectors';\nimport { dateString } from 'lib/utils/date-utils';\nimport { threadInfoSelector } from 'lib/selectors/thread-selectors';\n+import { nonThreadCalendarQuery } from 'lib/selectors/nav-selectors';\nimport css from '../style.css';\nimport LoadingIndicator from '../loading-indicator.react';\n@@ -63,17 +66,14 @@ type Props = {\nnextSessionID: () => ?string,\nsessionStartingPayload: () => { newSessionID?: string },\nloggedIn: bool,\n+ calendarQuery: () => CalendarQuery,\n// Redux dispatch functions\ndispatchActionPayload: DispatchActionPayload,\ndispatchActionPromise: DispatchActionPromise,\n// async functions that hit server APIs\n- createEntry: (request: CreateEntryRequest) => Promise<SaveEntryResponse>,\n- saveEntry: (request: SaveEntryRequest) => Promise<SaveEntryResponse>,\n- deleteEntry: (\n- entryID: string,\n- prevText: string,\n- sessionID: string,\n- ) => Promise<DeleteEntryResponse>,\n+ createEntry: (info: CreateEntryInfo) => Promise<SaveEntryResponse>,\n+ saveEntry: (info: SaveEntryInfo) => Promise<SaveEntryResponse>,\n+ deleteEntry: (info: DeleteEntryInfo) => Promise<DeleteEntryResponse>,\n};\ntype State = {\nfocused: bool,\n@@ -323,6 +323,7 @@ class Entry extends React.PureComponent<Props, State> {\nthis.props.entryInfo.day,\n),\nthreadID: this.props.entryInfo.threadID,\n+ calendarQuery: this.props.calendarQuery(),\n});\nif (curSaveAttempt + 1 === this.nextSaveAttemptIndex) {\nthis.guardedSetState({ loadingStatus: \"inactive\" });\n@@ -355,6 +356,7 @@ class Entry extends React.PureComponent<Props, State> {\nprevText: this.props.entryInfo.text,\nsessionID: this.props.sessionID(),\ntimestamp: Date.now(),\n+ calendarQuery: this.props.calendarQuery(),\n});\nif (curSaveAttempt + 1 === this.nextSaveAttemptIndex) {\nthis.guardedSetState({ loadingStatus: \"inactive\" });\n@@ -427,11 +429,12 @@ class Entry extends React.PureComponent<Props, State> {\nthis.props.focusOnFirstEntryNewerThan(this.props.entryInfo.creationTime);\n}\nif (serverID) {\n- return await this.props.deleteEntry(\n- serverID,\n- this.props.entryInfo.text,\n- this.props.sessionID(),\n- );\n+ return await this.props.deleteEntry({\n+ entryID: serverID,\n+ prevText: this.props.entryInfo.text,\n+ sessionID: this.props.sessionID(),\n+ calendarQuery: this.props.calendarQuery(),\n+ });\n} else if (this.creating) {\nthis.needsDeleteAfterCreation = true;\n}\n@@ -473,6 +476,7 @@ Entry.propTypes = {\nnextSessionID: PropTypes.func.isRequired,\nsessionStartingPayload: PropTypes.func.isRequired,\nloggedIn: PropTypes.bool.isRequired,\n+ calendarQuery: PropTypes.func.isRequired,\ndispatchActionPayload: PropTypes.func.isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\ncreateEntry: PropTypes.func.isRequired,\n@@ -491,6 +495,7 @@ export default connect(\nsessionStartingPayload: sessionStartingPayload(state),\nloggedIn: !!(state.currentUserInfo &&\n!state.currentUserInfo.anonymous && true),\n+ calendarQuery: nonThreadCalendarQuery(state),\n}),\n{ createEntry, saveEntry, deleteEntry },\n)(Entry);\n" }, { "change_type": "MODIFY", "old_path": "web/modals/history/history-entry.react.js", "new_path": "web/modals/history/history-entry.react.js", "diff": "@@ -5,7 +5,9 @@ import { threadInfoPropType } from 'lib/types/thread-types';\nimport {\ntype EntryInfo,\nentryInfoPropType,\n+ type RestoreEntryInfo,\ntype RestoreEntryResponse,\n+ type CalendarQuery,\n} from 'lib/types/entry-types';\nimport type { AppState } from '../../redux-setup';\nimport type { LoadingStatus } from 'lib/types/loading-types';\n@@ -29,6 +31,7 @@ import {\nsessionStartingPayload,\n} from 'lib/selectors/session-selectors';\nimport { threadInfoSelector } from 'lib/selectors/thread-selectors';\n+import { nonThreadCalendarQuery } from 'lib/selectors/nav-selectors';\nimport css from '../../style.css';\nimport LoadingIndicator from '../../loading-indicator.react';\n@@ -43,13 +46,11 @@ type Props = {\nloggedIn: bool,\nrestoreLoadingStatus: LoadingStatus,\nsessionStartingPayload: () => { newSessionID?: string },\n+ calendarQuery: () => CalendarQuery,\n// Redux dispatch functions\ndispatchActionPromise: DispatchActionPromise,\n// async functions that hit server APIs\n- restoreEntry: (\n- entryID: string,\n- sessionID: string,\n- ) => Promise<RestoreEntryResponse>,\n+ restoreEntry: (info: RestoreEntryInfo) => Promise<RestoreEntryResponse>,\n};\nclass HistoryEntry extends React.PureComponent<Props> {\n@@ -143,10 +144,11 @@ class HistoryEntry extends React.PureComponent<Props> {\nasync restoreEntryAction() {\nconst entryID = this.props.entryInfo.id;\ninvariant(entryID, \"entry should have ID\");\n- const result = await this.props.restoreEntry(\n+ const result = await this.props.restoreEntry({\nentryID,\n- this.props.sessionID(),\n- );\n+ sessionID: this.props.sessionID(),\n+ calendarQuery: this.props.calendarQuery(),\n+ });\nthis.props.animateAndLoadEntry(entryID);\nreturn result;\n}\n@@ -162,6 +164,7 @@ HistoryEntry.propTypes = {\nloggedIn: PropTypes.bool.isRequired,\nrestoreLoadingStatus: PropTypes.string.isRequired,\nsessionStartingPayload: PropTypes.func.isRequired,\n+ calendarQuery: PropTypes.func.isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\nrestoreEntry: PropTypes.func.isRequired,\n}\n@@ -180,6 +183,7 @@ export default connect(\n`${restoreEntryActionTypes.started}:${entryID}`,\n)(state),\nsessionStartingPayload: sessionStartingPayload(state),\n+ calendarQuery: nonThreadCalendarQuery(state),\n};\n},\n{ restoreEntry },\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Code to create new updateTypes.UPDATE_ENTRY updates
129,187
06.08.2018 11:08:15
14,400
42cc71f29df26dd19c025495b08b2fa5df5b3557
Don't set thread to unread for expired SAVE_MESSAGES Apparently, sometimes push notifs can get delivered after a ping delivers the corresponding updates, leading to update inconsistency. With this commit we'll be checking to see if the message in the push notif has a timestamp that has already been passed by the update checkpoint.
[ { "change_type": "MODIFY", "old_path": "lib/reducers/thread-reducer.js", "new_path": "lib/reducers/thread-reducer.js", "diff": "@@ -330,15 +330,20 @@ export default function reduceThreadInfos(\ninconsistencyResponses: state.inconsistencyResponses,\n};\n} else if (action.type === saveMessagesActionType) {\n- const threadIDs = new Set();\n+ const threadIDToMostRecentTime = new Map();\nfor (let messageInfo of action.payload.rawMessageInfos) {\n- threadIDs.add(messageInfo.threadID);\n+ const current = threadIDToMostRecentTime.get(messageInfo.threadID);\n+ if (!current || current < messageInfo.time) {\n+ threadIDToMostRecentTime.set(messageInfo.threadID, messageInfo.time);\n+ }\n}\nconst changedThreadInfos = {};\n- for (let threadID of threadIDs) {\n+ for (let [threadID, mostRecentTime] of threadIDToMostRecentTime) {\n+ const threadInfo = state.threadInfos[threadID];\nif (\n- !state.threadInfos[threadID] ||\n- state.threadInfos[threadID].currentUser.unread\n+ !threadInfo ||\n+ threadInfo.currentUser.unread ||\n+ action.payload.updatesCurrentAsOf > mostRecentTime\n) {\ncontinue;\n}\n" }, { "change_type": "MODIFY", "old_path": "lib/types/message-types.js", "new_path": "lib/types/message-types.js", "diff": "@@ -565,4 +565,5 @@ export type GenericMessagesResult = {|\nexport type SaveMessagesPayload = {|\nrawMessageInfos: $ReadOnlyArray<RawMessageInfo>,\n+ updatesCurrentAsOf: number,\n|};\n" }, { "change_type": "MODIFY", "old_path": "native/app.react.js", "new_path": "native/app.react.js", "diff": "@@ -133,7 +133,6 @@ type NativeDispatch = Dispatch & ((action: NavigationAction) => boolean);\ntype Props = {\n// Redux state\n- cookie: ?string,\nnavigationState: NavigationState,\npingStartingPayload: () => PingStartingPayload,\npingActionInput: (\n@@ -152,6 +151,7 @@ type Props = {\nsessionTimeLeft: () => number,\nnextSessionID: () => ?string,\nactiveServerRequests: $ReadOnlyArray<ServerRequest>,\n+ updatesCurrentAsOf: number,\n// Redux dispatch functions\ndispatch: NativeDispatch,\ndispatchActionPayload: DispatchActionPayload,\n@@ -169,7 +169,6 @@ type Props = {\nclass AppWithNavigationState extends React.PureComponent<Props> {\nstatic propTypes = {\n- cookie: PropTypes.string,\nnavigationState: PropTypes.object.isRequired,\npingStartingPayload: PropTypes.func.isRequired,\npingActionInput: PropTypes.func.isRequired,\n@@ -185,6 +184,7 @@ class AppWithNavigationState extends React.PureComponent<Props> {\nsessionTimeLeft: PropTypes.func.isRequired,\nnextSessionID: PropTypes.func.isRequired,\nactiveServerRequests: PropTypes.arrayOf(serverRequestPropType).isRequired,\n+ updatesCurrentAsOf: PropTypes.number.isRequired,\ndispatch: PropTypes.func.isRequired,\ndispatchActionPayload: PropTypes.func.isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\n@@ -691,9 +691,10 @@ class AppWithNavigationState extends React.PureComponent<Props> {\nsaveMessageInfos(messageInfosString: string) {\nconst messageInfos: $ReadOnlyArray<RawMessageInfo> =\nJSON.parse(messageInfosString);\n+ const { updatesCurrentAsOf } = this.props;\nthis.props.dispatchActionPayload(\nsaveMessagesActionType,\n- { rawMessageInfos: messageInfos },\n+ { rawMessageInfos: messageInfos, updatesCurrentAsOf },\n);\n}\n@@ -918,7 +919,7 @@ const ConnectedAppWithNavigationState = connect(\nsessionTimeLeft: sessionTimeLeft(state),\nnextSessionID: nextSessionID(state),\nactiveServerRequests: state.activeServerRequests,\n- cookie: state.cookie,\n+ updatesCurrentAsOf: state.updatesCurrentAsOf,\n};\n},\n{ ping, updateActivity, setDeviceToken },\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Don't set thread to unread for expired SAVE_MESSAGES Apparently, sometimes push notifs can get delivered after a ping delivers the corresponding updates, leading to update inconsistency. With this commit we'll be checking to see if the message in the push notif has a timestamp that has already been passed by the update checkpoint.
129,187
07.08.2018 17:22:50
14,400
e31dd3b28aa20e04380bb4ee11db4acd6ccb512d
[native] Use ... instead of manually listing every property in redux-setup Thank for Flow for finally fixing this.
[ { "change_type": "MODIFY", "old_path": "native/redux-setup.js", "new_path": "native/redux-setup.js", "diff": "@@ -362,12 +362,9 @@ function validateState(oldState: AppState, state: AppState): AppState {\n) {\n// Makes sure a currently focused thread is never unread\nstate = {\n- navInfo: state.navInfo,\n- currentUserInfo: state.currentUserInfo,\n- sessionID: state.sessionID,\n- entryStore: state.entryStore,\n- lastUserInteraction: state.lastUserInteraction,\n+ ...state,\nthreadStore: {\n+ ...state.threadStore,\nthreadInfos: {\n...state.threadStore.threadInfos,\n[activeThread]: {\n@@ -378,24 +375,7 @@ function validateState(oldState: AppState, state: AppState): AppState {\n},\n},\n},\n- inconsistencyResponses: state.threadStore.inconsistencyResponses,\n},\n- userInfos: state.userInfos,\n- messageStore: state.messageStore,\n- drafts: state.drafts,\n- updatesCurrentAsOf: state.updatesCurrentAsOf,\n- loadingStatuses: state.loadingStatuses,\n- pingTimestamps: state.pingTimestamps,\n- activeServerRequests: state.activeServerRequests,\n- calendarFilters: state.calendarFilters,\n- cookie: state.cookie,\n- deviceToken: state.deviceToken,\n- urlPrefix: state.urlPrefix,\n- customServer: state.customServer,\n- threadIDsToNotifIDs: state.threadIDsToNotifIDs,\n- notifPermissionAlertInfo: state.notifPermissionAlertInfo,\n- messageSentFromRoute: state.messageSentFromRoute,\n- _persist: state._persist,\n};\n}\n@@ -407,15 +387,9 @@ function validateState(oldState: AppState, state: AppState): AppState {\n) {\n// Update messageStore.threads[activeThread].lastNavigatedTo\nstate = {\n- navInfo: state.navInfo,\n- currentUserInfo: state.currentUserInfo,\n- sessionID: state.sessionID,\n- entryStore: state.entryStore,\n- lastUserInteraction: state.lastUserInteraction,\n- threadStore: state.threadStore,\n- userInfos: state.userInfos,\n+ ...state,\nmessageStore: {\n- messages: state.messageStore.messages,\n+ ...state.messageStore,\nthreads: {\n...state.messageStore.threads,\n[activeThread]: {\n@@ -423,22 +397,7 @@ function validateState(oldState: AppState, state: AppState): AppState {\nlastNavigatedTo: Date.now(),\n},\n},\n- currentAsOf: state.messageStore.currentAsOf,\n},\n- drafts: state.drafts,\n- updatesCurrentAsOf: state.updatesCurrentAsOf,\n- loadingStatuses: state.loadingStatuses,\n- pingTimestamps: state.pingTimestamps,\n- activeServerRequests: state.activeServerRequests,\n- calendarFilters: state.calendarFilters,\n- cookie: state.cookie,\n- deviceToken: state.deviceToken,\n- urlPrefix: state.urlPrefix,\n- customServer: state.customServer,\n- threadIDsToNotifIDs: state.threadIDsToNotifIDs,\n- notifPermissionAlertInfo: state.notifPermissionAlertInfo,\n- messageSentFromRoute: state.messageSentFromRoute,\n- _persist: state._persist,\n};\n}\n@@ -449,28 +408,8 @@ function validateState(oldState: AppState, state: AppState): AppState {\n);\nif (messageSentFromRoute.length !== state.messageSentFromRoute.length) {\nstate = {\n- navInfo: state.navInfo,\n- currentUserInfo: state.currentUserInfo,\n- sessionID: state.sessionID,\n- entryStore: state.entryStore,\n- lastUserInteraction: state.lastUserInteraction,\n- threadStore: state.threadStore,\n- userInfos: state.userInfos,\n- messageStore: state.messageStore,\n- drafts: state.drafts,\n- updatesCurrentAsOf: state.updatesCurrentAsOf,\n- loadingStatuses: state.loadingStatuses,\n- pingTimestamps: state.pingTimestamps,\n- activeServerRequests: state.activeServerRequests,\n- calendarFilters: state.calendarFilters,\n- cookie: state.cookie,\n- deviceToken: state.deviceToken,\n- urlPrefix: state.urlPrefix,\n- customServer: state.customServer,\n- threadIDsToNotifIDs: state.threadIDsToNotifIDs,\n- notifPermissionAlertInfo: state.notifPermissionAlertInfo,\n+ ...state,\nmessageSentFromRoute,\n- _persist: state._persist,\n};\n}\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
[native] Use ... instead of manually listing every property in redux-setup Thank for Flow for finally fixing this.
129,187
07.08.2018 17:51:13
14,400
0639b7628833dd318f58fb7ed36538dac75336a4
Fix behavior when first load of ChatMessageList has only one screen of items Also keep `messageStore` from changing every ping. Also properly center the notif badge text.
[ { "change_type": "MODIFY", "old_path": "lib/reducers/message-reducer.js", "new_path": "lib/reducers/message-reducer.js", "diff": "@@ -355,6 +355,13 @@ function reduceMessageStore(\n);\n} else if (action.type === pingActionTypes.success) {\nlet messagesResult = action.payload.messagesResult;\n+ if (\n+ messagesResult.messageInfos.length === 0 &&\n+ (!action.payload.updatesResult ||\n+ action.payload.updatesResult.newUpdates.length === 0)\n+ ) {\n+ return messageStore;\n+ }\nif (action.payload.updatesResult) {\nmessagesResult = mergeUpdatesIntoMessagesResult(\nmessagesResult,\n" }, { "change_type": "MODIFY", "old_path": "web/chat/chat-message-list.react.js", "new_path": "web/chat/chat-message-list.react.js", "diff": "@@ -104,6 +104,9 @@ class ChatMessageList extends React.PureComponent<Props, State> {\n) {\nthis.loadingFromScroll = false;\n}\n+ if (prevProps.messageListData !== this.props.messageListData) {\n+ this.onScroll();\n+ }\n}\nscrollToBottom() {\n" }, { "change_type": "MODIFY", "old_path": "web/style.css", "new_path": "web/style.css", "diff": "@@ -97,12 +97,12 @@ div.chatBadge {\nbox-sizing: border-box;\nwidth: 25px;\nheight: 25px;\n- padding-left: 7px;\nmargin-left: 8px;\ncolor: white;\nbackground-color: red;\nborder-radius: 13px;\nfont-size: 18px;\n+ text-align: center;\n}\ndiv.main-content-container {\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Fix behavior when first load of ChatMessageList has only one screen of items Also keep `messageStore` from changing every ping. Also properly center the notif badge text.
129,187
07.08.2018 17:59:39
14,400
1297431e722eeca5403a7552f7ef63a6d824b763
Actually fix single-screen-isnt-enough on web
[ { "change_type": "MODIFY", "old_path": "web/chat/chat-message-list.react.js", "new_path": "web/chat/chat-message-list.react.js", "diff": "@@ -70,6 +70,10 @@ class ChatMessageList extends React.PureComponent<Props, State> {\nloadingFromScroll = false;\ncomponentDidMount() {\n+ // In case we already have all the most recent messages,\n+ // but they're not enough\n+ this.onScroll();\n+\nconst { threadInfo } = this.props;\nif (!threadInfo || threadInChatList(threadInfo)) {\nreturn;\n" } ]
JavaScript
BSD 3-Clause New or Revised License
comme2e/comm
Actually fix single-screen-isnt-enough on web