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 | 16.04.2020 23:07:29 | 14,400 | 567e460ce203ccfd0fca5dda6378fd2bbb629bf1 | [native] identifier-utils.js and getFetchableURI | [
{
"change_type": "MODIFY",
"old_path": "native/media/blob-utils.js",
"new_path": "native/media/blob-utils.js",
"diff": "@@ -11,6 +11,8 @@ import {\ntype FileDataInfo,\n} from 'lib/utils/file-utils';\n+import { getFetchableURI } from './identifier-utils';\n+\nexport type ReactNativeBlob = Blob & {\ndata: { type: string, name: string, size: number },\n};\n@@ -74,18 +76,20 @@ type FetchBlobResponse = {|\nreportedMediaType: ?string,\n|};\nasync function fetchBlob(\n- uri: string,\n+ inputURI: string,\ntype: MediaType,\n): Promise<{|\nsteps: $ReadOnlyArray<MediaMissionStep>,\nresult: ?FetchBlobResponse,\n|}> {\n+ const uri = getFetchableURI(inputURI);\nconst blobFetchStart = Date.now();\nlet blob, reportedMIME, reportedMediaType, exceptionMessage;\ntry {\n- blob = await getBlobFromURI(uri, type);\n+ const response = await fetch(uri);\n+ blob = await response.blob();\nreportedMIME =\n- uri.startsWith('ph://') && blob.type === 'application/octet-stream'\n+ uri.startsWith('ph-upload://') && blob.type === 'application/octet-stream'\n? 'video/quicktime'\n: blob.type;\nreportedMediaType = mimeTypesToMediaTypes[reportedMIME];\n@@ -125,19 +129,4 @@ async function fetchBlob(\nreturn { steps: [compareTypesStep], result };\n}\n-async function getBlobFromURI(\n- uri: string,\n- type: MediaType,\n-): Promise<ReactNativeBlob> {\n- // React Native always resolves FBMediaKit's ph:// scheme as an image so that\n- // the Image component can render thumbnails of videos. In order to force\n- // fetch() to return a blob of the video, we need to use the ph-upload://\n- // scheme. https://git.io/Jerlh\n- const fbMediaKitURL = uri.startsWith('ph://');\n- const fixedURI =\n- fbMediaKitURL && type === 'video' ? uri.replace(/^ph:/, 'ph-upload:') : uri;\n- const response = await fetch(fixedURI);\n- return await response.blob();\n-}\n-\nexport { getBlobDataInfo, blobToDataURI, dataURIToIntArray, fetchBlob };\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "native/media/identifier-utils.js",
"diff": "+// @flow\n+\n+function getCompatibleMediaURI(uri: string, ext: ?string): string {\n+ if (!ext) {\n+ return uri;\n+ }\n+ if (!uri.startsWith('ph://') && !uri.startsWith('ph-upload://')) {\n+ return uri;\n+ }\n+ const photoKitLocalIdentifier = uri.split('/')[2];\n+ if (!photoKitLocalIdentifier) {\n+ return uri;\n+ }\n+ // While the ph:// scheme is a Facebook hack used by FBMediaKit, the\n+ // assets-library:// scheme is a legacy Apple identifier. We map to the former\n+ // because:\n+ // (1) Some libraries (namely react-native-video) don't know how to handle the\n+ // ph:// scheme yet\n+ // (2) In RN0.60, uploading ph:// JPEGs leads to recompression and often\n+ // increases file size! It has the nice side effect of rotating image data\n+ // based on EXIF orientation, but this isn't worth it for us\n+ // https://github.com/facebook/react-native/issues/27099#issuecomment-602016225\n+ // https://github.com/expo/expo/issues/3177\n+ // https://github.com/react-native-community/react-native-video/issues/1572\n+ return (\n+ `assets-library://asset/asset.${ext}` +\n+ `?id=${photoKitLocalIdentifier}&ext=${ext}`\n+ );\n+}\n+\n+const mediaLibraryIdentifierRegex = new RegExp(\n+ '^assets-library:\\\\/\\\\/asset\\\\/asset.[a-z0-9]+\\\\?id=([a-z0-9-]+)',\n+ 'i',\n+);\n+function getMediaLibraryIdentifier(inputURI: string): ?string {\n+ const uri = getCompatibleMediaURI(inputURI);\n+ const matches = uri.match(mediaLibraryIdentifierRegex);\n+ if (!matches) {\n+ return null;\n+ }\n+ return matches[1];\n+}\n+\n+function getFetchableURI(inputURI: string): string {\n+ // React Native always resolves Apple's assets-library:// and FBMediaKit's\n+ // ph:// scheme as an image so that the Image component can render thumbnails\n+ // of videos. In order to force fetch() to return a blob of the video, we need\n+ // to use the ph-upload:// scheme. https://git.io/Jerlh\n+ let uri = inputURI;\n+ if (uri.startsWith('assets-library://')) {\n+ const mediaNativeID = getMediaLibraryIdentifier(uri);\n+ if (mediaNativeID) {\n+ uri = `ph-upload://${mediaNativeID}/L0/001`;\n+ }\n+ }\n+ if (uri.startsWith('ph://')) {\n+ uri = uri.replace(/^ph:/, 'ph-upload:');\n+ }\n+ return uri;\n+}\n+\n+export { getCompatibleMediaURI, getMediaLibraryIdentifier, getFetchableURI };\n"
},
{
"change_type": "MODIFY",
"old_path": "native/media/media-gallery-keyboard.react.js",
"new_path": "native/media/media-gallery-keyboard.react.js",
"diff": "@@ -42,7 +42,7 @@ import {\n} from '../themes/colors';\nimport { getAndroidPermission } from '../utils/android-permissions';\nimport SendMediaButton from './send-media-button.react';\n-import { getCompatibleMediaURI } from './media-utils';\n+import { getCompatibleMediaURI } from './identifier-utils';\nconst animationSpec = {\nduration: 400,\n"
},
{
"change_type": "MODIFY",
"old_path": "native/media/media-utils.js",
"new_path": "native/media/media-utils.js",
"diff": "@@ -238,51 +238,4 @@ function getDimensions(uri: string): Promise<Dimensions> {\n});\n}\n-function getCompatibleMediaURI(uri: string, ext: ?string): string {\n- if (!ext) {\n- return uri;\n- }\n- if (!uri.startsWith('ph://') && !uri.startsWith('ph-upload://')) {\n- return uri;\n- }\n- const photoKitLocalIdentifier = uri.split('/')[2];\n- if (!photoKitLocalIdentifier) {\n- return uri;\n- }\n- // While the ph:// scheme is a Facebook hack used by FBMediaKit, the\n- // assets-library:// scheme is a legacy Apple identifier. We map to the former\n- // because:\n- // (1) Some libraries (namely react-native-video) don't know how to handle the\n- // ph:// scheme yet\n- // (2) In RN0.60, uploading ph:// JPEGs leads to recompression and often\n- // increases file size! It has the nice side effect of rotating image data\n- // based on EXIF orientation, but this isn't worth it for us\n- // https://github.com/facebook/react-native/issues/27099#issuecomment-602016225\n- // https://github.com/expo/expo/issues/3177\n- // https://github.com/react-native-community/react-native-video/issues/1572\n- return (\n- `assets-library://asset/asset.${ext}` +\n- `?id=${photoKitLocalIdentifier}&ext=${ext}`\n- );\n-}\n-\n-const mediaLibraryIdentifierRegex = new RegExp(\n- '^assets-library:\\\\/\\\\/asset\\\\/asset.[a-z0-9]+\\\\?id=([a-z0-9-]+)',\n- 'i',\n-);\n-\n-function getMediaLibraryIdentifier(inputURI: string): ?string {\n- const uri = getCompatibleMediaURI(inputURI);\n- const matches = uri.match(mediaLibraryIdentifierRegex);\n- if (!matches) {\n- return null;\n- }\n- return matches[1];\n-}\n-\n-export {\n- processMedia,\n- getDimensions,\n- getCompatibleMediaURI,\n- getMediaLibraryIdentifier,\n-};\n+export { processMedia, getDimensions };\n"
},
{
"change_type": "MODIFY",
"old_path": "native/media/save-image.js",
"new_path": "native/media/save-image.js",
"diff": "@@ -9,7 +9,7 @@ import md5 from 'md5';\nimport { fileInfoFromData, readableFilename } from 'lib/utils/file-utils';\nimport { blobToDataURI, dataURIToIntArray } from './blob-utils';\n-import { getMediaLibraryIdentifier } from './media-utils';\n+import { getMediaLibraryIdentifier } from './identifier-utils';\nimport { displayActionResultModal } from '../navigation/action-result-modal';\nimport { getAndroidPermission } from '../utils/android-permissions';\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] identifier-utils.js and getFetchableURI |
129,187 | 16.04.2020 23:27:46 | 14,400 | 2532899846d2d2d62308252f6e7971545043299e | [server] Rework saveToDisk | [
{
"change_type": "MODIFY",
"old_path": "native/media/save-image.js",
"new_path": "native/media/save-image.js",
"diff": "@@ -9,7 +9,7 @@ import md5 from 'md5';\nimport { fileInfoFromData, readableFilename } from 'lib/utils/file-utils';\nimport { blobToDataURI, dataURIToIntArray } from './blob-utils';\n-import { getMediaLibraryIdentifier } from './identifier-utils';\n+import { getMediaLibraryIdentifier, getFetchableURI } from './identifier-utils';\nimport { displayActionResultModal } from '../navigation/action-result-modal';\nimport { getAndroidPermission } from '../utils/android-permissions';\n@@ -73,8 +73,13 @@ async function saveImageAndroid(\nconst saveFolder = `${filesystem.PicturesDirectoryPath}/SquadCal`;\nawait filesystem.mkdir(saveFolder);\n- const filePath = await saveToDisk(mediaInfo.uri, saveFolder);\n- await filesystem.scanFile(filePath);\n+\n+ const saveResult = await saveToDisk(mediaInfo.uri, saveFolder);\n+ if (!saveResult.success) {\n+ return saveResult.error;\n+ }\n+ await filesystem.scanFile(saveResult.path);\n+\nreturn null;\n}\n@@ -83,7 +88,11 @@ async function saveImageIOS(mediaInfo: SaveImageInfo) {\nlet { uri } = mediaInfo;\nlet tempFile;\nif (uri.startsWith('http')) {\n- tempFile = await saveToDisk(uri, filesystem.TemporaryDirectoryPath);\n+ const saveResult = await saveToDisk(uri, filesystem.TemporaryDirectoryPath);\n+ if (!saveResult.success) {\n+ return saveResult.error;\n+ }\n+ tempFile = saveResult.path;\nuri = `file://${tempFile}`;\n} else if (!uri.startsWith('file://')) {\nconst mediaNativeID = getMediaLibraryIdentifier(uri);\n@@ -108,12 +117,30 @@ async function saveImageIOS(mediaInfo: SaveImageInfo) {\nreturn null;\n}\n-// only works on file: and http[s]: schemes\n-async function saveToDisk(uri: string, directory: string) {\n+type SaveResult =\n+ | {| success: true, path: string |}\n+ | {| success: false, error: string |};\n+async function saveToDisk(\n+ inputURI: string,\n+ directory: string,\n+): Promise<SaveResult> {\n+ const uri = getFetchableURI(inputURI);\n+\n+ let blob;\n+ try {\nconst response = await fetch(uri);\n- const blob = await response.blob();\n+ blob = await response.blob();\n+ } catch {\n+ return { success: false, error: 'failed to resolve :(' };\n+ }\n+\n+ let dataURI;\n+ try {\n+ dataURI = await blobToDataURI(blob);\n+ } catch {\n+ return { success: false, error: 'failed to resolve :(' };\n+ }\n- const dataURI = await blobToDataURI(blob);\nconst firstComma = dataURI.indexOf(',');\ninvariant(firstComma > 4, 'malformed data-URI');\nconst base64 = dataURI.substring(firstComma + 1);\n@@ -123,14 +150,23 @@ async function saveToDisk(uri: string, directory: string) {\nconst intArray = dataURIToIntArray(dataURI);\n({ mime } = fileInfoFromData(intArray));\n}\n- invariant(mime, `unsupported media type in saveToDisk`);\n+ if (!mime) {\n+ return { success: false, error: 'failed to save :(' };\n+ }\nconst name = readableFilename(md5(dataURI), mime);\n- invariant(name, `unsupported mime type ${mime} in saveToDisk`);\n- const filePath = `${directory}/${name}`;\n+ if (!name) {\n+ return { success: false, error: 'failed to save :(' };\n+ }\n+ const path = `${directory}/${name}`;\n+\n+ try {\n+ await filesystem.writeFile(path, base64, 'base64');\n+ } catch {\n+ return { success: false, error: 'failed to save :(' };\n+ }\n- await filesystem.writeFile(filePath, base64, 'base64');\n- return filePath;\n+ return { success: true, path };\n}\nexport { intentionalSaveImage, saveImage };\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [server] Rework saveToDisk |
129,187 | 16.04.2020 23:31:31 | 14,400 | b23ab011eb822a611f21b0f392ac26ddd92fef93 | [native] Deal with react-native-fs platform inconsistencies in reporting dirs | [
{
"change_type": "MODIFY",
"old_path": "native/media/save-image.js",
"new_path": "native/media/save-image.js",
"diff": "@@ -71,7 +71,7 @@ async function saveImageAndroid(\nreturn \"don't have permission :(\";\n}\n- const saveFolder = `${filesystem.PicturesDirectoryPath}/SquadCal`;\n+ const saveFolder = `${filesystem.PicturesDirectoryPath}/SquadCal/`;\nawait filesystem.mkdir(saveFolder);\nconst saveResult = await saveToDisk(mediaInfo.uri, saveFolder);\n@@ -117,6 +117,7 @@ async function saveImageIOS(mediaInfo: SaveImageInfo) {\nreturn null;\n}\n+// path to directory should end with a /\ntype SaveResult =\n| {| success: true, path: string |}\n| {| success: false, error: string |};\n@@ -158,7 +159,7 @@ async function saveToDisk(\nif (!name) {\nreturn { success: false, error: 'failed to save :(' };\n}\n- const path = `${directory}/${name}`;\n+ const path = `${directory}${name}`;\ntry {\nawait filesystem.writeFile(path, base64, 'base64');\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Deal with react-native-fs platform inconsistencies in reporting dirs |
129,187 | 17.04.2020 13:21:22 | 14,400 | 1bc139968f5ec6787afa52288b69ca18418fd8e6 | [native] Reassign localUploadIDs on retry if not in pendingUploads | [
{
"change_type": "MODIFY",
"old_path": "native/input/input-state-container.react.js",
"new_path": "native/input/input-state-container.react.js",
"diff": "@@ -72,6 +72,10 @@ import { displayActionResultModal } from '../navigation/action-result-modal';\nimport { fetchFileSize } from '../media/file-utils';\nlet nextLocalUploadID = 0;\n+function getNewLocalID() {\n+ return `localUpload${nextLocalUploadID++}`;\n+}\n+\ntype SelectionWithID = {|\nselection: MediaSelection,\nlocalID: string,\n@@ -361,7 +365,7 @@ class InputStateContainer extends React.PureComponent<Props, State> {\nconst localMessageID = `local${this.props.nextLocalID}`;\nconst selectionsWithIDs = selections.map(selection => ({\nselection,\n- localID: `localUpload${nextLocalUploadID++}`,\n+ localID: getNewLocalID(),\n}));\nconst pendingUploads = {};\n@@ -584,7 +588,7 @@ class InputStateContainer extends React.PureComponent<Props, State> {\nuri: uploadResult.uri,\ntype: mediaType,\ndimensions: processedMedia.dimensions,\n- localMediaCreationInfo: undefined,\n+ localMediaSelection: undefined,\n},\n});\nuserTime = Date.now() - start;\n@@ -830,17 +834,79 @@ class InputStateContainer extends React.PureComponent<Props, State> {\nretryMultimediaMessage = async (localMessageID: string) => {\nconst rawMessageInfo = this.props.messageStoreMessages[localMessageID];\ninvariant(rawMessageInfo, `rawMessageInfo ${localMessageID} should exist`);\n+\n+ let pendingUploads = this.state.pendingUploads[localMessageID];\n+ if (!pendingUploads) {\n+ pendingUploads = {};\n+ }\n+\n+ const now = Date.now();\n+\n+ const updateMedia = <T: Media>(media: $ReadOnlyArray<T>): T[] =>\n+ media.map(singleMedia => {\n+ const oldID = singleMedia.id;\n+ if (!oldID.startsWith('localUpload')) {\n+ // already uploaded\n+ return singleMedia;\n+ }\n+ if (pendingUploads[oldID] && !pendingUploads[oldID].failed) {\n+ // still being uploaded\n+ return singleMedia;\n+ }\n+\n+ // If we have an incomplete upload that isn't in pendingUploads, that\n+ // indicates the app has restarted. We'll reassign a new localID to\n+ // avoid collisions. Note that this isn't necessary for the message ID\n+ // since the localID reducer prevents collisions there\n+ const id = pendingUploads[oldID] ? oldID : getNewLocalID();\n+\n+ const oldSelection = singleMedia.localMediaSelection;\n+ invariant(\n+ oldSelection,\n+ 'localMediaSelection should be set on locally created Media',\n+ );\n+ const retries = oldSelection.retries ? oldSelection.retries + 1 : 1;\n+\n+ // We switch for Flow\n+ let selection;\n+ if (oldSelection.step === 'photo_capture') {\n+ selection = { ...oldSelection, sendTime: now, retries };\n+ } else if (oldSelection.step === 'photo_library') {\n+ selection = { ...oldSelection, sendTime: now, retries };\n+ } else {\n+ selection = { ...oldSelection, sendTime: now, retries };\n+ }\n+\n+ if (singleMedia.type === 'photo') {\n+ return {\n+ type: 'photo',\n+ ...singleMedia,\n+ id,\n+ localMediaSelection: selection,\n+ };\n+ } else {\n+ return {\n+ type: 'video',\n+ ...singleMedia,\n+ id,\n+ localMediaSelection: selection,\n+ };\n+ }\n+ });\n+\nlet newRawMessageInfo;\n// This conditional is for Flow\nif (rawMessageInfo.type === messageTypes.MULTIMEDIA) {\nnewRawMessageInfo = ({\n...rawMessageInfo,\n- time: Date.now(),\n+ time: now,\n+ media: updateMedia(rawMessageInfo.media),\n}: RawMediaMessageInfo);\n} else if (rawMessageInfo.type === messageTypes.IMAGES) {\nnewRawMessageInfo = ({\n...rawMessageInfo,\n- time: Date.now(),\n+ time: now,\n+ media: updateMedia(rawMessageInfo.media),\n}: RawImagesMessageInfo);\n} else {\ninvariant(false, `rawMessageInfo ${localMessageID} should be multimedia`);\n@@ -863,11 +929,6 @@ class InputStateContainer extends React.PureComponent<Props, State> {\nreturn;\n}\n- let pendingUploads = this.state.pendingUploads[localMessageID];\n- if (!pendingUploads) {\n- pendingUploads = {};\n- }\n-\nconst retryMedia = incompleteMedia.filter(\n({ id }) => !pendingUploads[id] || pendingUploads[id].failed,\n);\n@@ -877,7 +938,7 @@ class InputStateContainer extends React.PureComponent<Props, State> {\n}\n// We're not actually starting the send here,\n- // we just use this action to update the message's timestamp in Redux\n+ // we just use this action to update the message in Redux\nthis.props.dispatchActionPayload(\nsendMultimediaMessageActionTypes.started,\nnewRawMessageInfo,\n@@ -898,27 +959,13 @@ class InputStateContainer extends React.PureComponent<Props, State> {\n},\n}));\n- const now = Date.now();\nconst selectionsWithIDs = retryMedia.map(singleMedia => {\nconst { id, localMediaSelection } = singleMedia;\ninvariant(\nlocalMediaSelection,\n'localMediaSelection should be set on locally created Media',\n);\n- const retries = localMediaSelection.retries\n- ? localMediaSelection.retries + 1\n- : 1;\n-\n- // We switch for Flow\n- let selection;\n- if (localMediaSelection.step === 'photo_capture') {\n- selection = { ...localMediaSelection, sendTime: now, retries };\n- } else if (localMediaSelection.step === 'photo_library') {\n- selection = { ...localMediaSelection, sendTime: now, retries };\n- } else {\n- selection = { ...localMediaSelection, sendTime: now, retries };\n- }\n- return { selection, localID: id };\n+ return { selection: localMediaSelection, localID: id };\n});\nawait this.uploadFiles(localMessageID, selectionsWithIDs);\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Reassign localUploadIDs on retry if not in pendingUploads |
129,187 | 17.04.2020 13:29:48 | 14,400 | 040133c345f9bc94790667ad2dd050613ff60989 | [server] Delete uploads in a message when deleting the message | [
{
"change_type": "MODIFY",
"old_path": "server/src/deleters/message-deleters.js",
"new_path": "server/src/deleters/message-deleters.js",
"diff": "@@ -4,10 +4,12 @@ import { dbQuery, SQL } from '../database';\nasync function deleteOrphanedMessages(): Promise<void> {\nawait dbQuery(SQL`\n- DELETE m, i\n+ DELETE m, i, up, iu\nFROM messages m\nLEFT JOIN ids i ON i.id = m.id\nLEFT JOIN threads t ON t.id = m.thread\n+ LEFT JOIN uploads up ON up.container = m.id\n+ LEFT JOIN ids iu ON iu.id = up.id\nWHERE t.id IS NULL\n`);\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/deleters/thread-deleters.js",
"new_path": "server/src/deleters/thread-deleters.js",
"diff": "@@ -81,7 +81,7 @@ async function deleteThread(\n// TODO: handle descendant thread permission update correctly.\n// thread-permission-updaters should be used for descendant threads.\nconst query = SQL`\n- DELETE t, ic, d, id, e, ie, re, ire, mm, r, ms, im, f, n, ino\n+ DELETE t, ic, d, id, e, ie, re, ire, mm, r, ms, im, up, iu, f, n, ino\nFROM threads t\nLEFT JOIN ids ic ON ic.id = t.id\nLEFT JOIN days d ON d.thread = t.id\n@@ -95,6 +95,8 @@ async function deleteThread(\nLEFT 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\n+ LEFT JOIN uploads up ON up.container = ms.id\n+ LEFT JOIN ids iu ON iu.id = up.id\nLEFT JOIN focused f ON f.thread = t.id\nLEFT JOIN notifications n ON n.thread = t.id\nLEFT JOIN ids ino ON ino.id = n.id\n@@ -129,7 +131,7 @@ async function deleteThread(\nasync function deleteInaccessibleThreads(): Promise<void> {\nawait dbQuery(SQL`\n- DELETE t, i, d, id, e, ie, re, ire, r, ir, ms, im, f, n, ino\n+ DELETE t, i, d, id, e, ie, re, ire, r, ir, ms, im, up, iu, f, n, ino\nFROM threads t\nLEFT JOIN ids i ON i.id = t.id\nLEFT JOIN memberships m ON m.thread = t.id\n@@ -143,6 +145,8 @@ async function deleteInaccessibleThreads(): Promise<void> {\nLEFT 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\n+ LEFT JOIN uploads up ON up.container = ms.id\n+ LEFT JOIN ids iu ON iu.id = up.id\nLEFT JOIN focused f ON f.thread = t.id\nLEFT JOIN notifications n ON n.thread = t.id\nLEFT JOIN ids ino ON ino.id = n.id\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [server] Delete uploads in a message when deleting the message |
129,187 | 17.04.2020 17:23:12 | 14,400 | f15f8a1ca9a07b80d77cccd85c254e229fc23b80 | [server] Update server image processing to match native | [
{
"change_type": "MODIFY",
"old_path": "server/package.json",
"new_path": "server/package.json",
"diff": "\"dependencies\": {\n\"JSONStream\": \"^1.3.5\",\n\"apn\": \"git+https://github.com/node-apn/node-apn.git#3.0.0\",\n- \"buffer-image-size\": \"^0.6.4\",\n\"common-tags\": \"^1.7.2\",\n\"cookie-parser\": \"^1.4.3\",\n\"dateformat\": \"^3.0.3\",\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/uploads/media-utils.js",
"new_path": "server/src/uploads/media-utils.js",
"diff": "@@ -4,20 +4,13 @@ import type { UploadInput } from '../creators/upload-creator';\nimport type { Dimensions } from 'lib/types/media-types';\nimport sharp from 'sharp';\n-import sizeOf from 'buffer-image-size';\nimport invariant from 'invariant';\nimport { fileInfoFromData, readableFilename } from 'lib/utils/file-utils';\n-\n-const fiveMegabytes = 5 * 1024 * 1024;\n+import { getImageProcessingPlan } from 'lib/utils/image-utils';\nconst allowedMimeTypes = new Set(['image/png', 'image/jpeg', 'image/gif']);\n-function getDimensions(buffer: Buffer): Dimensions {\n- const { height, width } = sizeOf(buffer);\n- return { height, width };\n-}\n-\nasync function validateAndConvert(\ninitialBuffer: Buffer,\ninitialName: string,\n@@ -28,15 +21,35 @@ async function validateAndConvert(\nif (!mime || !mediaType) {\nreturn null;\n}\n-\nif (!allowedMimeTypes.has(mime)) {\n// This should've gotten converted on the client\nreturn null;\n}\n- if (size < fiveMegabytes && (mime === 'image/png' || mime === 'image/jpeg')) {\n- const dimensions = inputDimensions\n- ? inputDimensions\n- : getDimensions(initialBuffer);\n+\n+ let sharpImage, metadata;\n+ try {\n+ sharpImage = sharp(initialBuffer);\n+ metadata = await sharpImage.metadata();\n+ } catch (e) {\n+ return null;\n+ }\n+\n+ let initialDimensions = inputDimensions;\n+ if (!initialDimensions) {\n+ if (metadata.orientation && metadata.orientation > 4) {\n+ initialDimensions = { width: metadata.height, height: metadata.width };\n+ } else {\n+ initialDimensions = { width: metadata.width, height: metadata.height };\n+ }\n+ }\n+\n+ const plan = getImageProcessingPlan(\n+ mime,\n+ initialDimensions,\n+ size,\n+ metadata.orientation,\n+ );\n+ if (!plan) {\nconst name = readableFilename(initialName, mime);\ninvariant(name, `should be able to construct filename for ${mime}`);\nreturn {\n@@ -44,50 +57,58 @@ async function validateAndConvert(\nmediaType,\nname,\nbuffer: initialBuffer,\n- dimensions,\n+ dimensions: initialDimensions,\n};\n}\n+ console.log(`processing image with ${JSON.stringify(plan)}`);\n+ const { targetMIME, compressionRatio, fitInside, shouldRotate } = plan;\n- let sharpImage;\n- try {\n- sharpImage = sharp(initialBuffer);\n- } catch (e) {\n- return null;\n+ if (shouldRotate) {\n+ sharpImage = sharpImage.rotate();\n}\n- sharpImage = sharpImage.resize(3000, 2000, {\n+\n+ if (fitInside) {\n+ sharpImage = sharpImage.resize(fitInside.width, fitInside.height, {\nfit: 'inside',\nwithoutEnlargement: true,\n});\n+ }\n- if (mime === 'image/png' || mime === 'image/gif') {\n+ if (targetMIME === 'image/png') {\nsharpImage = sharpImage.png();\n} else {\n- sharpImage = sharpImage.jpeg({ quality: 92 });\n+ sharpImage = sharpImage.jpeg({ quality: compressionRatio * 100 });\n}\n- const convertedBuffer = await sharpImage.toBuffer();\n+ const { data: convertedBuffer, info } = await sharpImage.toBuffer({\n+ resolveWithObject: true,\n+ });\n+ const convertedDimensions = { width: info.width, height: info.height };\n+\nconst {\nmime: convertedMIME,\nmediaType: convertedMediaType,\n} = fileInfoFromData(convertedBuffer);\n- if (!convertedMIME || !convertedMediaType) {\n+ if (\n+ !convertedMIME ||\n+ !convertedMediaType ||\n+ convertedMIME !== targetMIME ||\n+ convertedMediaType !== mediaType\n+ ) {\nreturn null;\n}\n- const convertedName = readableFilename(initialName, convertedMIME);\n+ const convertedName = readableFilename(initialName, targetMIME);\nif (!convertedName) {\nreturn null;\n}\n- const dimensions = inputDimensions\n- ? inputDimensions\n- : getDimensions(convertedBuffer);\nreturn {\n- mime: convertedMIME,\n- mediaType: convertedMediaType,\n+ mime: targetMIME,\n+ mediaType,\nname: convertedName,\nbuffer: convertedBuffer,\n- dimensions,\n+ dimensions: convertedDimensions,\n};\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "yarn.lock",
"new_path": "yarn.lock",
"diff": "@@ -3573,13 +3573,6 @@ buffer-from@^1.0.0:\nresolved \"https://registry.yarnpkg.com/buffer-from/-/buffer-from-1.1.1.tgz#32713bc028f75c02fdb710d7c7bcec1f2c6070ef\"\nintegrity sha512-MQcXEUbCKtEo7bhqEs6560Hyd4XaovZlO/k9V3hjVUF/zwW7KBVdSK4gIt/bzwS9MbR5qob+F5jusZsb0YQK2A==\n-buffer-image-size@^0.6.4:\n- version \"0.6.4\"\n- resolved \"https://registry.yarnpkg.com/buffer-image-size/-/buffer-image-size-0.6.4.tgz#357e8173e951ced3b5a2785c695993aa29dbcac4\"\n- integrity sha512-nEh+kZOPY1w+gcCMobZ6ETUp9WfibndnosbpwB1iJk/8Gt5ZF2bhS6+B6bPYz424KtwsR6Rflc3tCz1/ghX2dQ==\n- dependencies:\n- \"@types/node\" \"*\"\n-\nbuffer-indexof-polyfill@~1.0.0:\nversion \"1.0.1\"\nresolved \"https://registry.yarnpkg.com/buffer-indexof-polyfill/-/buffer-indexof-polyfill-1.0.1.tgz#a9fb806ce8145d5428510ce72f278bb363a638bf\"\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [server] Update server image processing to match native |
129,187 | 17.04.2020 17:48:02 | 14,400 | 63fc41e1705cb61c133b648330d975532a71fbfc | Return new Dimensions back from uploadMultimedia | [
{
"change_type": "MODIFY",
"old_path": "lib/actions/upload-actions.js",
"new_path": "lib/actions/upload-actions.js",
"diff": "@@ -33,7 +33,11 @@ async function uploadMultimedia(\n},\n);\nconst [uploadResult] = response.results;\n- return { id: uploadResult.id, uri: uploadResult.uri };\n+ return {\n+ id: uploadResult.id,\n+ uri: uploadResult.uri,\n+ dimensions: uploadResult.dimensions,\n+ };\n}\nconst updateMultimediaMessageMediaActionType =\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/types/media-types.js",
"new_path": "lib/types/media-types.js",
"diff": "@@ -81,6 +81,7 @@ export const mediaInfoPropType = PropTypes.shape({\nexport type UploadMultimediaResult = {|\nid: string,\nuri: string,\n+ dimensions: Dimensions,\n|};\nexport type UpdateMultimediaMessageMediaPayload = {|\n"
},
{
"change_type": "MODIFY",
"old_path": "native/input/input-state-container.react.js",
"new_path": "native/input/input-state-container.react.js",
"diff": "@@ -553,7 +553,7 @@ class InputStateContainer extends React.PureComponent<Props, State> {\ntry {\nuploadResult = await this.props.uploadMultimedia(\n{ uri: uploadURI, name: filename, type: mime },\n- selection.dimensions,\n+ processedMedia.dimensions,\n{\nonProgress: (percent: number) =>\nthis.setProgress(localMessageID, localID, percent),\n@@ -587,7 +587,7 @@ class InputStateContainer extends React.PureComponent<Props, State> {\nid: serverID,\nuri: uploadResult.uri,\ntype: mediaType,\n- dimensions: processedMedia.dimensions,\n+ dimensions: uploadResult.dimensions,\nlocalMediaSelection: undefined,\n},\n});\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/creators/upload-creator.js",
"new_path": "server/src/creators/upload-creator.js",
"diff": "@@ -32,9 +32,15 @@ async function createUploads(\n}\nconst ids = await createIDs('uploads', uploadInfos.length);\n+ const uploadRows = uploadInfos.map(uploadInfo => {\n+ const id = ids.shift();\nconst secret = crypto.randomBytes(8).toString('hex');\n- const uploadRows = uploadInfos.map(uploadInfo => [\n- ids.shift(),\n+ return {\n+ id,\n+ secret,\n+ dimensions: uploadInfo.dimensions,\n+ insert: [\n+ id,\nviewer.userID,\nuploadInfo.mediaType,\nuploadInfo.name,\n@@ -43,18 +49,24 @@ async function createUploads(\nsecret,\nDate.now(),\nJSON.stringify(uploadInfo.dimensions),\n- ]);\n+ ],\n+ };\n+ });\nconst insertQuery = SQL`\nINSERT INTO uploads(id, uploader, type, filename,\nmime, content, secret, creation_time, extra)\n- VALUES ${uploadRows}\n+ VALUES ${uploadRows.map(({ insert }) => insert)}\n`;\nawait dbQuery(insertQuery);\nreturn uploadRows.map(row => ({\n- id: row[0],\n- uri: shimUploadURI(getUploadURL(row[0], row[6]), viewer.platformDetails),\n+ id: row.id,\n+ uri: shimUploadURI(\n+ getUploadURL(row.id, row.secret),\n+ viewer.platformDetails,\n+ ),\n+ dimensions: row.dimensions,\n}));\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "web/chat/chat-input-state-container.react.js",
"new_path": "web/chat/chat-input-state-container.react.js",
"diff": "@@ -441,7 +441,6 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\ncurrentMediaID: upload.localID,\nmediaUpdate: {\nid: result.id,\n- filename: undefined,\n},\n});\n}\n@@ -487,6 +486,7 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\n: uploadAfterPreload.localID,\nmediaUpdate: {\nuri: result.uri,\n+ dimensions: result.dimensions,\n},\n});\n}\n@@ -517,6 +517,7 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\n[upload.localID]: {\n...currentUpload,\nuri: result.uri,\n+ dimensions: result.dimensions,\nuriIsReal: true,\n},\n},\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | Return new Dimensions back from uploadMultimedia |
129,187 | 17.04.2020 20:33:18 | 14,400 | d31a8d4df0dc757a9be7cc9691c5ad7a44f27fdf | [web] Display EXIF-oriented images correctly | [
{
"change_type": "MODIFY",
"old_path": "web/chat/chat-input-state-container.react.js",
"new_path": "web/chat/chat-input-state-container.react.js",
"diff": "@@ -27,6 +27,7 @@ import _omit from 'lodash/fp/omit';\nimport _groupBy from 'lodash/fp/groupBy';\nimport _partition from 'lodash/fp/partition';\nimport invariant from 'invariant';\n+import { detect as detectBrowser } from 'detect-browser';\nimport { connect } from 'lib/utils/redux-utils';\nimport {\n@@ -57,6 +58,7 @@ type Props = {|\nviewerID: ?string,\nnextLocalID: number,\nmessageStoreMessages: { [id: string]: RawMessageInfo },\n+ exifRotate: boolean,\n// Redux dispatch functions\ndispatchActionPayload: DispatchActionPayload,\ndispatchActionPromise: DispatchActionPromise,\n@@ -91,6 +93,7 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\nviewerID: PropTypes.string,\nnextLocalID: PropTypes.number.isRequired,\nmessageStoreMessages: PropTypes.object.isRequired,\n+ exifRotate: PropTypes.bool.isRequired,\ndispatchActionPayload: PropTypes.func.isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\nuploadMultimedia: PropTypes.func.isRequired,\n@@ -351,7 +354,9 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\n);\nasync appendFiles(threadID: string, files: $ReadOnlyArray<File>) {\n- const validationResults = await Promise.all(files.map(validateFile));\n+ const validationResults = await Promise.all(\n+ files.map(file => validateFile(file, this.props.exifRotate)),\n+ );\nconst newUploads = [];\nconst { setModal } = this.props;\nfor (let result of validationResults) {\n@@ -372,7 +377,7 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\nfile,\nmediaType,\ndimensions,\n- uri: URL.createObjectURL(file),\n+ uri: result.uri,\nuriIsReal: false,\nprogressPercent: 0,\nabort: null,\n@@ -846,11 +851,16 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\n}\nexport default connect(\n- (state: AppState) => ({\n+ (state: AppState) => {\n+ const browser = detectBrowser(state.userAgent);\n+ const exifRotate = !browser || browser.name !== 'safari';\n+ return {\nactiveChatThreadID: state.navInfo.activeChatThreadID,\nviewerID: state.currentUserInfo && state.currentUserInfo.id,\nnextLocalID: state.nextLocalID,\nmessageStoreMessages: state.messageStore.messages,\n- }),\n+ exifRotate,\n+ };\n+ },\n{ uploadMultimedia, deleteUpload, sendMultimediaMessage, sendTextMessage },\n)(ChatInputStateContainer);\n"
},
{
"change_type": "MODIFY",
"old_path": "web/package.json",
"new_path": "web/package.json",
"diff": "\"classnames\": \"^2.2.5\",\n\"dateformat\": \"^3.0.3\",\n\"detect-browser\": \"^4.0.4\",\n+ \"exif-js\": \"^2.3.0\",\n\"history\": \"^4.6.3\",\n\"invariant\": \"^2.2.4\",\n\"isomorphic-fetch\": \"^2.2.1\",\n"
},
{
"change_type": "MODIFY",
"old_path": "web/utils/media-utils.js",
"new_path": "web/utils/media-utils.js",
"diff": "@@ -4,6 +4,7 @@ import type { MediaType, Dimensions } from 'lib/types/media-types';\nimport { fileInfoFromData, readableFilename } from 'lib/utils/file-utils';\nimport invariant from 'invariant';\n+import EXIF from 'exif-js';\nfunction blobToArrayBuffer(blob: Blob): Promise<ArrayBuffer> {\nconst fileReader = new FileReader();\n@@ -23,32 +24,88 @@ function blobToArrayBuffer(blob: Blob): Promise<ArrayBuffer> {\n});\n}\n-function getPhotoDimensions(blob: File): Promise<Dimensions> {\n- const fileReader = new FileReader();\n- return new Promise((resolve, reject) => {\n- fileReader.onerror = error => {\n- fileReader.abort();\n- reject(error);\n- };\n- fileReader.onload = () => {\n- invariant(\n- typeof fileReader.result === 'string',\n- 'FileReader.readAsDataURL should result in string',\n+function getOrientation(file: File): Promise<?number> {\n+ return new Promise(resolve => {\n+ EXIF.getData(file, function() {\n+ resolve(EXIF.getTag(this, 'Orientation'));\n+ });\n+ });\n+}\n+\n+type ProcessFileResult = {|\n+ uri: string,\n+ dimensions: Dimensions,\n+|};\n+async function processFile(\n+ file: File,\n+ exifRotate: boolean,\n+): Promise<ProcessFileResult> {\n+ const initialURI = URL.createObjectURL(file);\n+\n+ const [image, orientation] = await Promise.all([\n+ preloadImage(initialURI),\n+ (async () => {\n+ if (!exifRotate) {\n+ return 1;\n+ }\n+ return await getOrientation(file);\n+ })(),\n+ ]);\n+\n+ const dimensions =\n+ !!orientation && orientation > 4\n+ ? { width: image.height, height: image.width }\n+ : { width: image.width, height: image.height };\n+\n+ const canvas = document.createElement('canvas');\n+ const context = canvas.getContext('2d');\n+ canvas.height = dimensions.height;\n+ canvas.width = dimensions.width;\n+\n+ if (orientation === 2) {\n+ context.transform(-1, 0, 0, 1, dimensions.width, 0);\n+ } else if (orientation === 3) {\n+ context.transform(-1, 0, 0, -1, dimensions.width, dimensions.height);\n+ } else if (orientation === 4) {\n+ context.transform(1, 0, 0, -1, 0, dimensions.height);\n+ } else if (orientation === 5) {\n+ context.transform(0, 1, 1, 0, 0, 0);\n+ } else if (orientation === 6) {\n+ context.transform(0, 1, -1, 0, dimensions.width, 0);\n+ } else if (orientation === 7) {\n+ context.transform(0, -1, -1, 0, dimensions.width, dimensions.height);\n+ } else if (orientation === 8) {\n+ context.transform(0, -1, 1, 0, 0, dimensions.height);\n+ } else {\n+ context.transform(1, 0, 0, 1, 0, 0);\n+ }\n+\n+ context.drawImage(image, 0, 0);\n+ const blob = await new Promise(resolve =>\n+ canvas.toBlob(blobResult => resolve(blobResult)),\n);\n- resolve(fileReader.result);\n- };\n- fileReader.readAsDataURL(blob);\n- }).then(uri => preloadImage(uri));\n+\n+ URL.revokeObjectURL(initialURI);\n+ const uri = URL.createObjectURL(blob);\n+ return { uri, dimensions };\n}\n// Returns null if unsupported\ntype FileValidationResult = {|\nfile: File,\nmediaType: MediaType,\n+ uri: string,\ndimensions: ?Dimensions,\n|};\n-async function validateFile(file: File): Promise<?FileValidationResult> {\n- const arrayBuffer = await blobToArrayBuffer(file);\n+async function validateFile(\n+ file: File,\n+ exifRotate: boolean,\n+): Promise<?FileValidationResult> {\n+ const [arrayBuffer, processResult] = await Promise.all([\n+ blobToArrayBuffer(file),\n+ processFile(file, exifRotate),\n+ ]);\n+\nconst { mime, mediaType } = fileInfoFromData(new Uint8Array(arrayBuffer));\nif (!mime || !mediaType || !allowedMimeTypes.has(mime)) {\nreturn null;\n@@ -57,28 +114,26 @@ async function validateFile(file: File): Promise<?FileValidationResult> {\nif (!name) {\nreturn null;\n}\n- let dimensions = null;\n- if (mediaType === 'photo') {\n- dimensions = await getPhotoDimensions(file);\n- }\n+\n+ const { dimensions, uri } = processResult;\nconst fixedFile =\nname !== file.name || mime !== file.type\n? new File([file], name, { type: mime })\n: file;\n- return { file: fixedFile, mediaType, dimensions };\n+\n+ return { file: fixedFile, mediaType, uri, dimensions };\n}\nconst allowedMimeTypeArray = ['image/png', 'image/jpeg', 'image/gif'];\nconst allowedMimeTypes = new Set(allowedMimeTypeArray);\nconst allowedMimeTypeString = allowedMimeTypeArray.join(',');\n-function preloadImage(uri: string): Promise<Dimensions> {\n+function preloadImage(uri: string): Promise<Image> {\nreturn new Promise((resolve, reject) => {\nconst img = new Image();\nimg.src = uri;\nimg.onload = () => {\n- const { width, height } = img;\n- resolve({ width, height });\n+ resolve(img);\n};\nimg.onerror = reject;\n});\n"
},
{
"change_type": "MODIFY",
"old_path": "yarn.lock",
"new_path": "yarn.lock",
"diff": "@@ -5684,6 +5684,11 @@ execa@^1.0.0:\nsignal-exit \"^3.0.0\"\nstrip-eof \"^1.0.0\"\n+exif-js@^2.3.0:\n+ version \"2.3.0\"\n+ resolved \"https://registry.yarnpkg.com/exif-js/-/exif-js-2.3.0.tgz#9d10819bf571f873813e7640241255ab9ce1a814\"\n+ integrity sha1-nRCBm/Vx+HOBPnZAJBJVq5zhqBQ=\n+\nexit@^0.1.2:\nversion \"0.1.2\"\nresolved \"https://registry.yarnpkg.com/exit/-/exit-0.1.2.tgz#0632638f8d877cc82107d30a0fff1a17cba1cd0c\"\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [web] Display EXIF-oriented images correctly |
129,187 | 17.04.2020 21:04:24 | 14,400 | 1c57b0e194aa84fb0b1b62e68bfb8e4b0254cc44 | [web] Update Flow | [
{
"change_type": "MODIFY",
"old_path": "web/package.json",
"new_path": "web/package.json",
"diff": "\"clean-webpack-plugin\": \"^3.0.0\",\n\"concurrently\": \"^5.0.0\",\n\"css-loader\": \"^3.2.0\",\n- \"flow-bin\": \"^0.98.0\",\n+ \"flow-bin\": \"^0.105.0\",\n\"mini-css-extract-plugin\": \"^0.8.0\",\n\"optimize-css-assets-webpack-plugin\": \"^5.0.1\",\n\"style-loader\": \"^1.0.0\",\n"
},
{
"change_type": "MODIFY",
"old_path": "yarn.lock",
"new_path": "yarn.lock",
"diff": "@@ -6174,11 +6174,6 @@ flow-bin@^0.105.0:\nresolved \"https://registry.yarnpkg.com/flow-bin/-/flow-bin-0.105.2.tgz#9d03d5ae3e1d011e311f309cb8786b3b3695fec2\"\nintegrity sha512-VCHt0SCjFPviv/Ze/W7AgkcE0uH4TocypSFA8wR3ZH1P7BSjny4l3uhHyOjzU3Qo1i0jO4NyaU6q3Y5IaQ6xng==\n-flow-bin@^0.98.0:\n- version \"0.98.1\"\n- resolved \"https://registry.yarnpkg.com/flow-bin/-/flow-bin-0.98.1.tgz#a8d781621c91703df69928acc83c9777e2fcbb49\"\n- integrity sha512-y1YzQgbFUX4EG6h2EO8PhyJeS0VxNgER8XsTwU8IXw4KozfneSmGVgw8y3TwAOza7rVhTlHEoli1xNuNW1rhPw==\n-\nflow-mono-cli@^1.5.0:\nversion \"1.5.3\"\nresolved \"https://registry.yarnpkg.com/flow-mono-cli/-/flow-mono-cli-1.5.3.tgz#ff162cfcd4a67bf9aa350872c2a35109408f5553\"\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [web] Update Flow |
129,187 | 17.04.2020 21:05:04 | 14,400 | d3391e90ec18db4c3f0ff159c99eedb04b56cb60 | [web] Handle ChatMessageList inverted scrolling better | [
{
"change_type": "MODIFY",
"old_path": "web/chat/chat-message-list.css",
"new_path": "web/chat/chat-message-list.css",
"diff": "@@ -10,6 +10,10 @@ div.activeContainer {\nborder: 2px solid #5989D6;\nmargin-left: 402px;\n}\n+div.firefoxMessageContainer {\n+ overflow-y: scroll;\n+ height: 100%;\n+}\ndiv.messageContainer {\nflex-grow: 1;\nflex: 1;\n@@ -21,14 +25,6 @@ div.messageContainer > div {\ntransform: translateZ(0);\n}\n-div.invertedMessageContainer {\n- flex-grow: 1;\n- flex: 1;\n- overflow-y: auto;\n- display: flex;\n- flex-direction: column;\n-}\n-\ndiv.message {\ndisplay: flex;\nflex-direction: column;\n"
},
{
"change_type": "MODIFY",
"old_path": "web/chat/chat-message-list.react.js",
"new_path": "web/chat/chat-message-list.react.js",
"diff": "@@ -53,7 +53,7 @@ type PassedProps = {|\nmessageListData: ?$ReadOnlyArray<ChatMessageItem>,\nstartReached: boolean,\ntimeZone: ?string,\n- usingFlexDirectionColumnReverse: boolean,\n+ firefox: boolean,\n// Redux dispatch functions\ndispatchActionPromise: DispatchActionPromise,\n// async functions that hit server APIs\n@@ -85,7 +85,7 @@ class ChatMessageList extends React.PureComponent<Props, State> {\nmessageListData: PropTypes.arrayOf(chatMessageItemPropType),\nstartReached: PropTypes.bool.isRequired,\ntimeZone: PropTypes.string,\n- usingFlexDirectionColumnReverse: PropTypes.bool.isRequired,\n+ firefox: PropTypes.bool.isRequired,\ndispatchActionPromise: PropTypes.func.isRequired,\nfetchMessagesBeforeCursor: PropTypes.func.isRequired,\nfetchMostRecentMessages: PropTypes.func.isRequired,\n@@ -118,43 +118,7 @@ class ChatMessageList extends React.PureComponent<Props, State> {\nthreadWatcher.removeID(threadInfo.id);\n}\n- getSnapshotBeforeUpdate(prevProps: Props): ?number {\n- if (this.props.usingFlexDirectionColumnReverse) {\n- return null;\n- }\n-\n- const { messageListData } = this.props;\n- const prevMessageListData = prevProps.messageListData;\n- const { messageContainer } = this;\n- if (\n- !messageListData ||\n- !prevMessageListData ||\n- !messageContainer ||\n- messageListData.length <= prevMessageListData.length\n- ) {\n- return null;\n- }\n-\n- // We only get here if new messages are being added. If they are being\n- // appended, ie. the user scrolled up to load older messages, we should\n- // always increase scroll position to compensate for the new height. On the\n- // other hand, if they are being prepended because they are new messages,\n- // we should only increase the scroll position if we were already scrolled\n- // to the newest message.\n- if (\n- prevMessageListData.length > 0 &&\n- ChatMessageList.keyExtractor(messageListData[0]) !==\n- ChatMessageList.keyExtractor(prevMessageListData[0]) &&\n- messageContainer.scrollTop !==\n- messageContainer.scrollHeight - messageContainer.offsetHeight\n- ) {\n- return null;\n- }\n-\n- return messageContainer.scrollHeight;\n- }\n-\n- componentDidUpdate(prevProps: Props, prevState: State, snapshot: ?number) {\n+ componentDidUpdate(prevProps: Props) {\nconst { messageListData } = this.props;\nconst prevMessageListData = prevProps.messageListData;\n@@ -190,12 +154,6 @@ class ChatMessageList extends React.PureComponent<Props, State> {\nmessageListData[0].messageInfo.localID)\n) {\nthis.scrollToBottom();\n- } else if (\n- snapshot !== null &&\n- snapshot !== undefined &&\n- messageContainer\n- ) {\n- messageContainer.scrollTop += messageContainer.scrollHeight - snapshot;\n}\n}\n@@ -289,15 +247,17 @@ class ChatMessageList extends React.PureComponent<Props, State> {\n);\nlet content;\n- if (!this.props.usingFlexDirectionColumnReverse) {\n+ if (this.props.firefox) {\ncontent = (\n<div\n- className={css.invertedMessageContainer}\n+ className={css.firefoxMessageContainer}\nref={this.messageContainerRef}\n>\n- {[...messages].reverse()}\n+ <div className={css.messageContainer}>\n+ {messages}\n{tooltip}\n</div>\n+ </div>\n);\n} else {\ncontent = (\n@@ -399,8 +359,7 @@ const ReduxConnectedChatMessageList = connect(\n(state: AppState, ownProps: { activeChatThreadID: ?string }) => {\nconst { activeChatThreadID } = ownProps;\nconst browser = detectBrowser(state.userAgent);\n- const usingFlexDirectionColumnReverse =\n- browser && browser.name === 'chrome';\n+ const firefox = browser && browser.name === 'firefox';\nreturn {\nthreadInfo: activeChatThreadID\n? threadInfoSelector(state)[activeChatThreadID]\n@@ -411,7 +370,7 @@ const ReduxConnectedChatMessageList = connect(\nstate.messageStore.threads[activeChatThreadID].startReached\n),\ntimeZone: state.timeZone,\n- usingFlexDirectionColumnReverse,\n+ firefox,\n};\n},\n{ fetchMessagesBeforeCursor, fetchMostRecentMessages },\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [web] Handle ChatMessageList inverted scrolling better |
129,187 | 17.04.2020 23:04:30 | 14,400 | 56484f93dde8515a755bb598cdff20b976338273 | [native] Fix width of single image messages | [
{
"change_type": "MODIFY",
"old_path": "native/chat/composed-message.react.js",
"new_path": "native/chat/composed-message.react.js",
"diff": "@@ -107,9 +107,8 @@ const styles = StyleSheet.create({\nmarginRight: 7,\n},\ncontent: {\n- flex: 1,\n- flexDirection: 'row',\nalignItems: 'center',\n+ flexDirection: 'row',\n},\nicon: {\nfontSize: 16,\n@@ -123,7 +122,6 @@ const styles = StyleSheet.create({\njustifyContent: 'flex-start',\n},\nmessageBox: {\n- flex: 1,\nflexDirection: 'row',\nmarginRight: 5,\n},\n"
},
{
"change_type": "MODIFY",
"old_path": "native/chat/message-list-container.react.js",
"new_path": "native/chat/message-list-container.react.js",
"diff": "@@ -36,7 +36,7 @@ import ThreadSettingsButton from './thread-settings-button.react';\nimport { registerChatScreen } from './chat-screen-registry';\nimport TextHeightMeasurer from '../text-height-measurer.react';\nimport ChatInputBar from './chat-input-bar.react';\n-import { multimediaMessageContentHeights } from './multimedia-message.react';\n+import { multimediaMessageContentSizes } from './multimedia-message.react';\nimport {\ntextMessageMaxWidthSelector,\ncomposedMessageMaxWidthSelector,\n@@ -269,7 +269,7 @@ class MessageListContainer extends React.PureComponent<Props, State> {\ninputState &&\ninputState.pendingUploads &&\ninputState.pendingUploads[id];\n- const heights = multimediaMessageContentHeights(\n+ const sizes = multimediaMessageContentSizes(\nmessageInfo,\nthis.props.composedMessageMaxWidth,\n);\n@@ -283,7 +283,7 @@ class MessageListContainer extends React.PureComponent<Props, State> {\nstartsCluster: item.startsCluster,\nendsCluster: item.endsCluster,\npendingUploads,\n- ...heights,\n+ ...sizes,\n};\n}\ninvariant(textHeights, 'textHeights not set');\n"
},
{
"change_type": "MODIFY",
"old_path": "native/chat/multimedia-message.react.js",
"new_path": "native/chat/multimedia-message.react.js",
"diff": "@@ -36,12 +36,13 @@ import { authorNameHeight } from './message-header.react';\nimport { failedSendHeight } from './failed-send.react';\nimport sendFailed from './multimedia-message-send-failed';\n-type ContentHeights = {|\n+type ContentSizes = {|\nimageHeight: number,\ncontentHeight: number,\n+ contentWidth: number,\n|};\nexport type ChatMultimediaMessageInfoItem = {|\n- ...ContentHeights,\n+ ...ContentSizes,\nitemType: 'message',\nmessageShapeType: 'multimedia',\nmessageInfo: MultimediaMessageInfo,\n@@ -71,14 +72,16 @@ function getMediaPerRow(mediaCount: number) {\n// Called by MessageListContainer\n// The results are merged into ChatMultimediaMessageInfoItem\n-function multimediaMessageContentHeights(\n+function multimediaMessageContentSizes(\nmessageInfo: MultimediaMessageInfo,\ncomposedMessageMaxWidth: number,\n-): ContentHeights {\n+): ContentSizes {\ninvariant(messageInfo.media.length > 0, 'should have media');\n+\nif (messageInfo.media.length === 1) {\nconst [media] = messageInfo.media;\nconst { height, width } = media.dimensions;\n+\nlet imageHeight =\ncomposedMessageMaxWidth >= width\n? height\n@@ -86,18 +89,26 @@ function multimediaMessageContentHeights(\nif (imageHeight < 50) {\nimageHeight = 50;\n}\n- return { imageHeight, contentHeight: imageHeight };\n+\n+ let contentWidth = (width / height) * imageHeight;\n+ if (contentWidth > composedMessageMaxWidth) {\n+ contentWidth = composedMessageMaxWidth;\n+ }\n+\n+ return { imageHeight, contentHeight: imageHeight, contentWidth };\n}\n+ const contentWidth = composedMessageMaxWidth;\n+\nconst mediaPerRow = getMediaPerRow(messageInfo.media.length);\nconst marginSpace = spaceBetweenImages * (mediaPerRow - 1);\n- const imageHeight = (composedMessageMaxWidth - marginSpace) / mediaPerRow;\n+ const imageHeight = (contentWidth - marginSpace) / mediaPerRow;\nconst numRows = Math.ceil(messageInfo.media.length / mediaPerRow);\nconst contentHeight =\nnumRows * imageHeight + (numRows - 1) * spaceBetweenImages;\n- return { imageHeight, contentHeight };\n+ return { imageHeight, contentHeight, contentWidth };\n}\n// Called by Message\n@@ -142,14 +153,17 @@ class MultimediaMessage extends React.PureComponent<Props> {\nrender() {\nconst { item, focused } = this.props;\n- const heightStyle = { height: item.contentHeight };\n+ const containerStyle = {\n+ height: item.contentHeight,\n+ width: item.contentWidth,\n+ };\nreturn (\n<ComposedMessage\nitem={item}\nsendFailed={sendFailed(item)}\nfocused={focused}\n>\n- <View style={[heightStyle, styles.container]}>\n+ <View style={[containerStyle, styles.container]}>\n{this.renderContent()}\n</View>\n</ComposedMessage>\n@@ -258,7 +272,6 @@ class MultimediaMessage extends React.PureComponent<Props> {\nconst spaceBetweenImages = 4;\nconst styles = StyleSheet.create({\ncontainer: {\n- flex: 1,\nflexDirection: 'row',\njustifyContent: 'center',\n},\n@@ -287,7 +300,7 @@ const WrappedMultimediaMessage = withOverlayPositionContext(MultimediaMessage);\nexport {\nborderRadius as multimediaMessageBorderRadius,\nWrappedMultimediaMessage as MultimediaMessage,\n- multimediaMessageContentHeights,\n+ multimediaMessageContentSizes,\nmultimediaMessageItemHeight,\nsendFailed as multimediaMessageSendFailed,\n};\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Fix width of single image messages |
129,187 | 17.04.2020 23:19:04 | 14,400 | c759e0069bd70de1fcd39ddfb74a64e2cfe5e7b0 | [native] Don't try fetching ph-upload blobs
Misreports TIFF as JPEG on iOS | [
{
"change_type": "MODIFY",
"old_path": "native/media/media-utils.js",
"new_path": "native/media/media-utils.js",
"diff": "@@ -12,7 +12,6 @@ import { Image } from 'react-native';\nimport invariant from 'invariant';\nimport { pathFromURI, readableFilename } from 'lib/utils/file-utils';\n-import { promiseAll } from 'lib/utils/promises';\nimport { fetchFileInfo } from './file-utils';\nimport { processVideo } from './video-utils';\n@@ -109,18 +108,11 @@ async function processMedia(\n};\n};\n- const promises = {};\n- promises.fileInfoResponse = fetchFileInfo(\n+ const { steps: fileInfoSteps, result: fileInfoResult } = await fetchFileInfo(\nmediaInput.uri,\nmediaInput.type,\nmediaInput.mediaNativeID,\n);\n- if (mediaInput.type === 'photo' || config.initialBlobCheck) {\n- promises.fetchBlobResponse = fetchBlob(mediaInput.uri, mediaType);\n- }\n- const { fileInfoResponse, fetchBlobResponse } = await promiseAll(promises);\n-\n- const { steps: fileInfoSteps, result: fileInfoResult } = fileInfoResponse;\nsteps.push(...fileInfoSteps);\nif (!fileInfoResult.success) {\nreturn { steps, result: fileInfoResult };\n@@ -129,8 +121,11 @@ async function processMedia(\ninitialURI = fileInfoResult.uri;\nlet blobResponse;\n- if (fetchBlobResponse) {\n- const { steps: blobSteps, result: blobResult } = fetchBlobResponse;\n+ if (mediaInput.type === 'photo' || config.initialBlobCheck) {\n+ const { steps: blobSteps, result: blobResult } = await fetchBlob(\n+ initialURI,\n+ mediaType,\n+ );\nsteps.push(...blobSteps);\nblobResponse = blobResult;\n}\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Don't try fetching ph-upload blobs
Misreports TIFF as JPEG on iOS |
129,187 | 18.04.2020 00:00:20 | 14,400 | ce471ab5afeae1fbf92eba473caaa8a063213914 | Add webp and tiff support | [
{
"change_type": "MODIFY",
"old_path": "lib/utils/file-utils.js",
"new_path": "lib/utils/file-utils.js",
"diff": "@@ -9,6 +9,8 @@ const mimeTypesToMediaTypes = Object.freeze({\n'image/jpeg': 'photo',\n'image/gif': 'photo',\n'image/heic': 'photo',\n+ 'image/webp': 'photo',\n+ 'image/tiff': 'photo',\n'video/mp4': 'video',\n'video/quicktime': 'video',\n});\n@@ -18,6 +20,8 @@ const mimeTypesToExtensions = Object.freeze({\n'image/jpeg': 'jpg',\n'image/gif': 'gif',\n'image/heic': 'heic',\n+ 'image/webp': 'webp',\n+ 'image/tiff': 'tiff',\n'video/mp4': 'mp4',\n'video/quicktime': 'mp4',\n});\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/uploads/media-utils.js",
"new_path": "server/src/uploads/media-utils.js",
"diff": "@@ -9,7 +9,13 @@ import invariant from 'invariant';\nimport { fileInfoFromData, readableFilename } from 'lib/utils/file-utils';\nimport { getImageProcessingPlan } from 'lib/utils/image-utils';\n-const allowedMimeTypes = new Set(['image/png', 'image/jpeg', 'image/gif']);\n+const allowedMimeTypes = new Set([\n+ 'image/png',\n+ 'image/jpeg',\n+ 'image/gif',\n+ 'image/webp',\n+ 'image/tiff',\n+]);\nasync function validateAndConvert(\ninitialBuffer: Buffer,\n"
},
{
"change_type": "MODIFY",
"old_path": "web/utils/media-utils.js",
"new_path": "web/utils/media-utils.js",
"diff": "@@ -124,7 +124,13 @@ async function validateFile(\nreturn { file: fixedFile, mediaType, uri, dimensions };\n}\n-const allowedMimeTypeArray = ['image/png', 'image/jpeg', 'image/gif'];\n+const allowedMimeTypeArray = [\n+ 'image/png',\n+ 'image/jpeg',\n+ 'image/gif',\n+ 'image/webp',\n+ 'image/tiff',\n+];\nconst allowedMimeTypes = new Set(allowedMimeTypeArray);\nconst allowedMimeTypeString = allowedMimeTypeArray.join(',');\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | Add webp and tiff support |
129,187 | 18.04.2020 00:00:35 | 14,400 | 7fe0df59a91e6b1a77e47d394c78a89fbdc523e5 | [web] Catch exceptions in validateFile | [
{
"change_type": "MODIFY",
"old_path": "web/chat/chat-input-state-container.react.js",
"new_path": "web/chat/chat-input-state-container.react.js",
"diff": "@@ -354,11 +354,19 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\n);\nasync appendFiles(threadID: string, files: $ReadOnlyArray<File>) {\n- const validationResults = await Promise.all(\n+ const { setModal } = this.props;\n+\n+ let validationResults;\n+ try {\n+ validationResults = await Promise.all(\nfiles.map(file => validateFile(file, this.props.exifRotate)),\n);\n+ } catch (e) {\n+ setModal(<InvalidUploadModal setModal={setModal} />);\n+ return;\n+ }\n+\nconst newUploads = [];\n- const { setModal } = this.props;\nfor (let result of validationResults) {\nif (!result) {\nsetModal(<InvalidUploadModal setModal={setModal} />);\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [web] Catch exceptions in validateFile |
129,187 | 18.04.2020 02:19:28 | 14,400 | 9fbe415077838675e2ea6a59e4784046bb291d48 | [web] Consistent order for pendingUploads | [
{
"change_type": "MODIFY",
"old_path": "web/chat/chat-input-state-container.react.js",
"new_path": "web/chat/chat-input-state-container.react.js",
"diff": "@@ -26,6 +26,7 @@ import _keyBy from 'lodash/fp/keyBy';\nimport _omit from 'lodash/fp/omit';\nimport _groupBy from 'lodash/fp/groupBy';\nimport _partition from 'lodash/fp/partition';\n+import _sortBy from 'lodash/fp/sortBy';\nimport invariant from 'invariant';\nimport { detect as detectBrowser } from 'detect-browser';\n@@ -324,7 +325,7 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\nconst [uploadsWithMessageIDs, uploadsWithoutMessageIDs] = _partition(\n'messageID',\n)(pendingUploads);\n- threadPendingUploads = uploadsWithoutMessageIDs;\n+ threadPendingUploads = _sortBy('localID')(uploadsWithoutMessageIDs);\nthreadAssignedUploads = _groupBy('messageID')(uploadsWithMessageIDs);\n}\nreturn {\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [web] Consistent order for pendingUploads |
129,187 | 18.04.2020 02:19:53 | 14,400 | f731d64eb3da9f657dc3682d042d131bc8ffb89f | [native] Fix resize config passed to expo-image-manipulator | [
{
"change_type": "MODIFY",
"old_path": "native/media/image-utils.js",
"new_path": "native/media/image-utils.js",
"diff": "@@ -46,9 +46,9 @@ async function processImage(\nif (fitInside) {\nconst fitInsideRatio = fitInside.width / fitInside.height;\nif (dimensions.width / dimensions.height > fitInsideRatio) {\n- transforms.push({ width: fitInside.width });\n+ transforms.push({ resize: { width: fitInside.width } });\n} else {\n- transforms.push({ height: fitInside.height });\n+ transforms.push({ resize: { height: fitInside.height } });\n}\n}\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Fix resize config passed to expo-image-manipulator |
129,187 | 18.04.2020 14:58:04 | 14,400 | 4a364e038e40bce1ed129329a42abd574a5970aa | [native] Don't crash when encountering images with a 0 dimension | [
{
"change_type": "MODIFY",
"old_path": "native/chat/multimedia-message.react.js",
"new_path": "native/chat/multimedia-message.react.js",
"diff": "@@ -82,15 +82,15 @@ function multimediaMessageContentSizes(\nconst [media] = messageInfo.media;\nconst { height, width } = media.dimensions;\n- let imageHeight =\n- composedMessageMaxWidth >= width\n- ? height\n- : (height * composedMessageMaxWidth) / width;\n+ let imageHeight = height;\n+ if (width > composedMessageMaxWidth) {\n+ imageHeight = (height * composedMessageMaxWidth) / width;\n+ }\nif (imageHeight < 50) {\nimageHeight = 50;\n}\n- let contentWidth = (width / height) * imageHeight;\n+ let contentWidth = height ? (width * imageHeight) / height : 0;\nif (contentWidth > composedMessageMaxWidth) {\ncontentWidth = composedMessageMaxWidth;\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "native/media/media-gallery-media.react.js",
"new_path": "native/media/media-gallery-media.react.js",
"diff": "@@ -173,12 +173,10 @@ class MediaGalleryMedia extends React.PureComponent<Props> {\nstep,\n} = selection;\nconst active = MediaGalleryMedia.isActive(this.props);\n+ const scaledWidth = height ? (width * containerHeight) / height : 0;\nconst dimensionsStyle = {\nheight: containerHeight,\n- width: Math.max(\n- Math.min((width / height) * containerHeight, this.props.screenWidth),\n- 150,\n- ),\n+ width: Math.max(Math.min(scaledWidth, this.props.screenWidth), 150),\n};\nlet buttons = null;\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Don't crash when encountering images with a 0 dimension |
129,187 | 18.04.2020 16:30:45 | 14,400 | c01a07fe7df500d1d8d4237b992b257e61975487 | Use react-native-fs to read MIME type | [
{
"change_type": "MODIFY",
"old_path": "lib/types/media-types.js",
"new_path": "lib/types/media-types.js",
"diff": "@@ -105,14 +105,14 @@ export type VideoProbeMediaMissionStep = {|\nformat: ?string,\n|};\n-export type BlobDataAnalysisMediaMissionStep = {|\n- step: 'blob_data_analysis',\n+export type ReadFileHeaderMediaMissionStep = {|\n+ step: 'read_file_header',\nsuccess: boolean,\nexceptionMessage: ?string,\ntime: number, // ms\nuri: string,\n- detectedMIME: ?string,\n- detectedMediaType: ?MediaType,\n+ mime: ?string,\n+ mediaType: ?MediaType,\n|};\nexport type MediaLibrarySelection =\n@@ -181,18 +181,6 @@ export type MediaSelection = MediaLibrarySelection | PhotoCapture;\nexport type MediaMissionStep =\n| MediaSelection\n- | {|\n- step: 'compare_blob_mime_to_media_type',\n- type: MediaType,\n- success: boolean,\n- exceptionMessage: ?string,\n- time: number, // ms\n- blobFetched: boolean,\n- blobMIME: ?string,\n- reportedMIME: ?string,\n- blobName: ?string,\n- size: ?number,\n- |}\n| {|\nstep: 'asset_info_fetch',\nsuccess: boolean,\n@@ -206,8 +194,10 @@ export type MediaMissionStep =\nsuccess: boolean,\nexceptionMessage: ?string,\ntime: number, // ms\n+ uri: string,\nfileSize: ?number,\n|}\n+ | ReadFileHeaderMediaMissionStep\n| {|\nstep: 'photo_manipulation',\nsuccess: boolean,\n@@ -227,7 +217,6 @@ export type MediaMissionStep =\nreturnCode: ?number,\nnewPath: ?string,\n|}\n- | BlobDataAnalysisMediaMissionStep\n| {|\nstep: 'dispose_uploaded_local_file',\nsuccess: boolean,\n@@ -256,6 +245,7 @@ export type MediaMissionFailure =\n| {|\nsuccess: false,\nreason: 'file_stat_failed',\n+ uri: string,\n|}\n| {|\nsuccess: false,\n@@ -264,16 +254,22 @@ export type MediaMissionFailure =\n|}\n| {|\nsuccess: false,\n- reason: 'blob_reported_mime_issue',\n- mime: ?string,\n+ reason: 'media_type_mismatch',\n+ reportedMediaType: MediaType,\n+ detectedMediaType: MediaType,\n+ detectedMIME: ?string,\n|}\n| {|\nsuccess: false,\n- reason: 'blob_data_mime_type_mismatch',\n- reportedMIME: string,\n+ reason: 'mime_fetch_failed',\n+ |}\n+ | {|\n+ success: false,\n+ reason: 'mime_type_mismatch',\nreportedMediaType: MediaType,\n- detectedMIME: ?string,\n+ reportedMIME: string,\ndetectedMediaType: ?MediaType,\n+ detectedMIME: string,\n|}\n| {|\nsuccess: false,\n@@ -315,18 +311,6 @@ export const mediaMissionPropType = PropTypes.shape({\nsendTime: PropTypes.number.isRequired,\nretries: PropTypes.number.isRequired,\n}),\n- PropTypes.shape({\n- step: PropTypes.oneOf(['compare_blob_mime_to_media_type']).isRequired,\n- type: mediaTypePropType.isRequired,\n- success: PropTypes.bool.isRequired,\n- exceptionMessage: PropTypes.string,\n- time: PropTypes.number.isRequired,\n- blobFetched: PropTypes.bool.isRequired,\n- blobMIME: PropTypes.string,\n- reportedMIME: PropTypes.string,\n- blobName: PropTypes.string,\n- size: PropTypes.number,\n- }),\nPropTypes.shape({\nstep: PropTypes.oneOf(['asset_info_fetch']).isRequired,\nsuccess: PropTypes.bool.isRequired,\n@@ -340,8 +324,18 @@ export const mediaMissionPropType = PropTypes.shape({\nsuccess: PropTypes.bool.isRequired,\nexceptionMessage: PropTypes.string,\ntime: PropTypes.number.isRequired,\n+ uri: PropTypes.string.isRequired,\nfileSize: PropTypes.number,\n}),\n+ PropTypes.shape({\n+ step: PropTypes.oneOf(['read_file_header']).isRequired,\n+ success: PropTypes.bool.isRequired,\n+ exceptionMessage: PropTypes.string,\n+ time: PropTypes.number.isRequired,\n+ uri: PropTypes.string.isRequired,\n+ mime: PropTypes.string,\n+ mediaType: mediaTypePropType,\n+ }),\nPropTypes.shape({\nstep: PropTypes.oneOf(['photo_manipulation']).isRequired,\nsuccess: PropTypes.bool.isRequired,\n@@ -370,15 +364,6 @@ export const mediaMissionPropType = PropTypes.shape({\nreturnCode: PropTypes.number,\nnewPath: PropTypes.string,\n}),\n- PropTypes.shape({\n- step: PropTypes.oneOf(['blob_data_analysis']).isRequired,\n- success: PropTypes.bool.isRequired,\n- exceptionMessage: PropTypes.string,\n- time: PropTypes.number.isRequired,\n- uri: PropTypes.string.isRequired,\n- detectedMIME: PropTypes.string,\n- detectedMediaType: mediaTypePropType,\n- }),\nPropTypes.shape({\nstep: PropTypes.oneOf(['dispose_uploaded_local_file']).isRequired,\nsuccess: PropTypes.bool.isRequired,\n@@ -411,6 +396,7 @@ export const mediaMissionPropType = PropTypes.shape({\nPropTypes.shape({\nsuccess: PropTypes.oneOf([false]).isRequired,\nreason: PropTypes.oneOf(['file_stat_failed']).isRequired,\n+ uri: PropTypes.string.isRequired,\n}),\nPropTypes.shape({\nsuccess: PropTypes.oneOf([false]).isRequired,\n@@ -419,16 +405,22 @@ export const mediaMissionPropType = PropTypes.shape({\n}),\nPropTypes.shape({\nsuccess: PropTypes.oneOf([false]).isRequired,\n- reason: PropTypes.oneOf(['blob_reported_mime_issue']).isRequired,\n- mime: PropTypes.string,\n+ reason: PropTypes.oneOf(['media_type_mismatch']).isRequired,\n+ reportedMediaType: mediaTypePropType.isRequired,\n+ detectedMediaType: mediaTypePropType.isRequired,\n+ detectedMIME: PropTypes.string,\n}),\nPropTypes.shape({\nsuccess: PropTypes.oneOf([false]).isRequired,\n- reason: PropTypes.oneOf(['blob_data_mime_type_mismatch']).isRequired,\n- reportedMIME: PropTypes.string.isRequired,\n+ reason: PropTypes.oneOf(['mime_fetch_failed']).isRequired,\n+ }),\n+ PropTypes.shape({\n+ success: PropTypes.oneOf([false]).isRequired,\n+ reason: PropTypes.oneOf(['mime_type_mismatch']).isRequired,\nreportedMediaType: mediaTypePropType.isRequired,\n- detectedMIME: PropTypes.string,\n+ reportedMIME: PropTypes.string.isRequired,\ndetectedMediaType: mediaTypePropType,\n+ detectedMIME: PropTypes.string.isRequired,\n}),\nPropTypes.shape({\nsuccess: PropTypes.oneOf([false]).isRequired,\n"
},
{
"change_type": "MODIFY",
"old_path": "native/input/input-state-container.react.js",
"new_path": "native/input/input-state-container.react.js",
"diff": "@@ -642,9 +642,8 @@ class InputStateContainer extends React.PureComponent<Props, State> {\nconst { viewerID } = this.props;\nif (__DEV__ || (viewerID && isStaff(viewerID))) {\nreturn {\n- initialBlobCheck: true,\n- finalBlobCheck: true,\n- blobDataAnalysis: true,\n+ initialFileHeaderCheck: true,\n+ finalFileHeaderCheck: true,\n};\n}\nreturn {};\n"
},
{
"change_type": "MODIFY",
"old_path": "native/media/blob-utils.js",
"new_path": "native/media/blob-utils.js",
"diff": "// @flow\n-import type { MediaType, MediaMissionStep } from 'lib/types/media-types';\n-\nimport base64 from 'base-64';\nimport invariant from 'invariant';\n-import {\n- fileInfoFromData,\n- mimeTypesToMediaTypes,\n- type FileDataInfo,\n-} from 'lib/utils/file-utils';\n-\n-import { getFetchableURI } from './identifier-utils';\n-\n-export type ReactNativeBlob = Blob & {\n- data: { type: string, name: string, size: number },\n-};\n-\n-// Processes the contents of the blob, looking at \"magic numbers\" to determine\n-// MIME type\n-async function getBlobDataInfo(blob: ReactNativeBlob): Promise<FileDataInfo> {\n- const dataURI = await blobToDataURI(blob);\n- const intArray = dataURIToIntArray(dataURI);\n- return fileInfoFromData(intArray);\n-}\n-\nfunction blobToDataURI(blob: Blob): Promise<string> {\nconst fileReader = new FileReader();\nreturn new Promise((resolve, reject) => {\n@@ -70,63 +48,4 @@ function stringToIntArray(str: string): Uint8Array {\nreturn array;\n}\n-type FetchBlobResponse = {|\n- blob: ReactNativeBlob,\n- reportedMIME: ?string,\n- reportedMediaType: ?string,\n-|};\n-async function fetchBlob(\n- inputURI: string,\n- type: MediaType,\n-): Promise<{|\n- steps: $ReadOnlyArray<MediaMissionStep>,\n- result: ?FetchBlobResponse,\n-|}> {\n- const uri = getFetchableURI(inputURI);\n- const blobFetchStart = Date.now();\n- let blob, reportedMIME, reportedMediaType, exceptionMessage;\n- try {\n- const response = await fetch(uri);\n- blob = await response.blob();\n- reportedMIME =\n- uri.startsWith('ph-upload://') && blob.type === 'application/octet-stream'\n- ? 'video/quicktime'\n- : blob.type;\n- reportedMediaType = mimeTypesToMediaTypes[reportedMIME];\n- } catch (e) {\n- if (\n- e &&\n- typeof e === 'object' &&\n- e.message &&\n- typeof e.message === 'string'\n- ) {\n- exceptionMessage = e.message;\n- }\n- }\n-\n- const compareTypesStep = {\n- step: 'compare_blob_mime_to_media_type',\n- type,\n- success: type === reportedMediaType,\n- exceptionMessage,\n- time: Date.now() - blobFetchStart,\n- blobFetched: !!blob,\n- blobMIME: blob ? blob.type : null,\n- reportedMIME,\n- blobName: blob && blob.data ? blob.data.name : null,\n- size: blob ? blob.size : null,\n- };\n-\n- if (!blob) {\n- return { steps: [compareTypesStep], result: null };\n- }\n-\n- const result = {\n- blob,\n- reportedMIME,\n- reportedMediaType,\n- };\n- return { steps: [compareTypesStep], result };\n-}\n-\n-export { getBlobDataInfo, blobToDataURI, dataURIToIntArray, fetchBlob };\n+export { blobToDataURI, dataURIToIntArray };\n"
},
{
"change_type": "MODIFY",
"old_path": "native/media/file-utils.js",
"new_path": "native/media/file-utils.js",
"diff": "@@ -4,61 +4,15 @@ import type {\nMediaMissionStep,\nMediaMissionFailure,\nMediaType,\n+ ReadFileHeaderMediaMissionStep,\n} from 'lib/types/media-types';\nimport { Platform } from 'react-native';\nimport * as MediaLibrary from 'expo-media-library';\nimport filesystem from 'react-native-fs';\n+import base64 from 'base-64';\n-import { pathFromURI } from 'lib/utils/file-utils';\n-\n-async function fetchAssetInfo(\n- mediaNativeID: string,\n-): Promise<{|\n- steps: $ReadOnlyArray<MediaMissionStep>,\n- result: {| localURI: ?string, orientation: ?number |},\n-|}> {\n- let localURI,\n- orientation,\n- success = false,\n- exceptionMessage;\n- const start = Date.now();\n- try {\n- const assetInfo = await MediaLibrary.getAssetInfoAsync(mediaNativeID);\n- success = true;\n- localURI = assetInfo.localUri;\n- if (Platform.OS === 'ios') {\n- orientation = assetInfo.orientation;\n- } else {\n- orientation = assetInfo.exif && assetInfo.exif.Orientation;\n- }\n- } catch (e) {\n- if (\n- e &&\n- typeof e === 'object' &&\n- e.message &&\n- typeof e.message === 'string'\n- ) {\n- exceptionMessage = e.message;\n- }\n- }\n- return {\n- steps: [\n- {\n- step: 'asset_info_fetch',\n- success,\n- exceptionMessage,\n- time: Date.now() - start,\n- localURI,\n- orientation,\n- },\n- ],\n- result: {\n- localURI,\n- orientation,\n- },\n- };\n-}\n+import { pathFromURI, fileInfoFromData } from 'lib/utils/file-utils';\nasync function fetchFileSize(\nuri: string,\n@@ -91,6 +45,7 @@ async function fetchFileSize(\nsuccess,\nexceptionMessage,\ntime: Date.now() - statStart,\n+ uri,\nfileSize,\n},\n],\n@@ -145,6 +100,7 @@ async function fetchFileInfo(\nresult: {\nsuccess: false,\nreason: 'file_stat_failed',\n+ uri,\n},\n};\n}\n@@ -160,4 +116,97 @@ async function fetchFileInfo(\n};\n}\n-export { fetchFileInfo, fetchFileSize };\n+async function fetchAssetInfo(\n+ mediaNativeID: string,\n+): Promise<{|\n+ steps: $ReadOnlyArray<MediaMissionStep>,\n+ result: {| localURI: ?string, orientation: ?number |},\n+|}> {\n+ let localURI,\n+ orientation,\n+ success = false,\n+ exceptionMessage;\n+ const start = Date.now();\n+ try {\n+ const assetInfo = await MediaLibrary.getAssetInfoAsync(mediaNativeID);\n+ success = true;\n+ localURI = assetInfo.localUri;\n+ if (Platform.OS === 'ios') {\n+ orientation = assetInfo.orientation;\n+ } else {\n+ orientation = assetInfo.exif && assetInfo.exif.Orientation;\n+ }\n+ } catch (e) {\n+ if (\n+ e &&\n+ typeof e === 'object' &&\n+ e.message &&\n+ typeof e.message === 'string'\n+ ) {\n+ exceptionMessage = e.message;\n+ }\n+ }\n+ return {\n+ steps: [\n+ {\n+ step: 'asset_info_fetch',\n+ success,\n+ exceptionMessage,\n+ time: Date.now() - start,\n+ localURI,\n+ orientation,\n+ },\n+ ],\n+ result: {\n+ localURI,\n+ orientation,\n+ },\n+ };\n+}\n+\n+async function readFileHeader(\n+ localURI: string,\n+ fileSize: number,\n+): Promise<ReadFileHeaderMediaMissionStep> {\n+ const fetchBytes = Math.min(fileSize, 64);\n+\n+ const start = Date.now();\n+ let fileData,\n+ success = false,\n+ exceptionMessage;\n+ try {\n+ fileData = await filesystem.read(localURI, fetchBytes, 0, 'base64');\n+ success = true;\n+ } catch (e) {\n+ if (\n+ e &&\n+ typeof e === 'object' &&\n+ e.message &&\n+ typeof e.message === 'string'\n+ ) {\n+ exceptionMessage = e.message;\n+ }\n+ }\n+\n+ let mime, mediaType;\n+ if (fileData) {\n+ const utf8 = base64.decode(fileData);\n+ const intArray = new Uint8Array(utf8.length);\n+ for (var i = 0; i < utf8.length; i++) {\n+ intArray[i] = utf8.charCodeAt(i);\n+ }\n+ ({ mime, mediaType } = fileInfoFromData(intArray));\n+ }\n+\n+ return {\n+ step: 'read_file_header',\n+ success,\n+ exceptionMessage,\n+ time: Date.now() - start,\n+ uri: localURI,\n+ mime,\n+ mediaType,\n+ };\n+}\n+\n+export { fetchFileSize, fetchFileInfo, readFileHeader };\n"
},
{
"change_type": "MODIFY",
"old_path": "native/media/media-utils.js",
"new_path": "native/media/media-utils.js",
"diff": "@@ -5,7 +5,6 @@ import type {\nMediaType,\nMediaMissionStep,\nMediaMissionFailure,\n- BlobDataAnalysisMediaMissionStep,\n} from 'lib/types/media-types';\nimport { Image } from 'react-native';\n@@ -13,40 +12,9 @@ import invariant from 'invariant';\nimport { pathFromURI, readableFilename } from 'lib/utils/file-utils';\n-import { fetchFileInfo } from './file-utils';\n+import { fetchFileSize, fetchFileInfo, readFileHeader } from './file-utils';\nimport { processVideo } from './video-utils';\nimport { processImage } from './image-utils';\n-import { getBlobDataInfo, fetchBlob, type ReactNativeBlob } from './blob-utils';\n-\n-async function checkBlobData(\n- uploadURI: string,\n- blob: ReactNativeBlob,\n- expectedMIME: string,\n-): Promise<BlobDataAnalysisMediaMissionStep> {\n- let mime, mediaType, exceptionMessage;\n- const start = Date.now();\n- try {\n- ({ mime, mediaType } = await getBlobDataInfo(blob));\n- } catch (e) {\n- if (\n- e &&\n- typeof e === 'object' &&\n- e.message &&\n- typeof e.message === 'string'\n- ) {\n- exceptionMessage = e.message;\n- }\n- }\n- return {\n- step: 'blob_data_analysis',\n- success: !!mime && mime === expectedMIME,\n- exceptionMessage,\n- time: Date.now() - start,\n- uri: uploadURI,\n- detectedMIME: mime,\n- detectedMediaType: mediaType,\n- };\n-}\ntype MediaInput = {|\ntype: MediaType,\n@@ -56,9 +24,8 @@ type MediaInput = {|\nmediaNativeID?: string,\n|};\ntype MediaProcessConfig = $Shape<{|\n- initialBlobCheck: boolean,\n- finalBlobCheck: boolean,\n- blobDataAnalysis: boolean,\n+ initialFileHeaderCheck: boolean,\n+ finalFileHeaderCheck: boolean,\n|}>;\ntype MediaResult = {|\nsuccess: true,\n@@ -115,30 +82,24 @@ async function processMedia(\n);\nsteps.push(...fileInfoSteps);\nif (!fileInfoResult.success) {\n- return { steps, result: fileInfoResult };\n+ return finish(fileInfoResult);\n}\nconst { orientation, fileSize } = fileInfoResult;\ninitialURI = fileInfoResult.uri;\n- let blobResponse;\n- if (mediaInput.type === 'photo' || config.initialBlobCheck) {\n- const { steps: blobSteps, result: blobResult } = await fetchBlob(\n- initialURI,\n- mediaType,\n- );\n- steps.push(...blobSteps);\n- blobResponse = blobResult;\n- }\n- if (blobResponse) {\n- const { reportedMIME, reportedMediaType } = blobResponse;\n- if (reportedMIME) {\n- mime = reportedMIME;\n+ if (mediaInput.type === 'photo' || config.initialFileHeaderCheck) {\n+ const readFileStep = await readFileHeader(initialURI, fileSize);\n+ steps.push(readFileStep);\n+ if (readFileStep.mime) {\n+ mime = readFileStep.mime;\n}\n- if (reportedMediaType && reportedMediaType !== mediaType) {\n+ if (readFileStep.mediaType && readFileStep.mediaType !== mediaType) {\nreturn finish({\nsuccess: false,\n- reason: 'blob_reported_mime_issue',\n- mime: reportedMIME,\n+ reason: 'media_type_mismatch',\n+ reportedMediaType: mediaType,\n+ detectedMediaType: readFileStep.mediaType,\n+ detectedMIME: readFileStep.mime,\n});\n}\n}\n@@ -158,8 +119,7 @@ async function processMedia(\nif (!mime) {\nreturn finish({\nsuccess: false,\n- reason: 'blob_reported_mime_issue',\n- mime,\n+ reason: 'mime_fetch_failed',\n});\n}\nconst { steps: imageSteps, result: imageResult } = await processImage({\n@@ -180,42 +140,29 @@ async function processMedia(\ninvariant(false, `unknown mediaType ${mediaInput.type}`);\n}\n- if (blobResponse && uploadURI !== initialURI) {\n- blobResponse = null;\n- }\n- if (!blobResponse && (config.finalBlobCheck || config.blobDataAnalysis)) {\n- const { steps: blobSteps, result: blobResult } = await fetchBlob(\n+ if (uploadURI !== initialURI && config.finalFileHeaderCheck) {\n+ const { steps: fileSizeSteps, result: newFileSize } = await fetchFileSize(\nuploadURI,\n- mediaType,\n);\n- steps.push(...blobSteps);\n- blobResponse = blobResult;\n- const reportedMIME = blobResponse && blobResponse.reportedMIME;\n- if (config.finalBlobCheck && reportedMIME && reportedMIME !== mime) {\n+ steps.push(...fileSizeSteps);\n+ if (!newFileSize) {\nreturn finish({\nsuccess: false,\n- reason: 'blob_reported_mime_issue',\n- mime: reportedMIME,\n+ reason: 'file_stat_failed',\n+ uri: uploadURI,\n});\n}\n- }\n- if (blobResponse && config.blobDataAnalysis) {\n- const blobDataCheckStep = await checkBlobData(\n- uploadURI,\n- blobResponse.blob,\n- mime,\n- );\n- steps.push(blobDataCheckStep);\n- const { detectedMIME, detectedMediaType } = blobDataCheckStep;\n- if (!blobDataCheckStep.success) {\n+ const readNewFileStep = await readFileHeader(uploadURI, newFileSize);\n+ steps.push(readNewFileStep);\n+ if (readNewFileStep.mime && readNewFileStep.mime !== mime) {\nreturn finish({\nsuccess: false,\n- reason: 'blob_data_mime_type_mismatch',\n- reportedMIME: mime,\n+ reason: 'mime_type_mismatch',\nreportedMediaType: mediaType,\n- detectedMIME,\n- detectedMediaType,\n+ reportedMIME: mime,\n+ detectedMediaType: readNewFileStep.mediaType,\n+ detectedMIME: readNewFileStep.mime,\n});\n}\n}\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | Use react-native-fs to read MIME type |
129,187 | 18.04.2020 16:58:42 | 14,400 | 5824ad6bf1f37a25eaf3db7d636834680dc1333f | [native] Return two Promises from processMedia
Makes it easier to do post-processing for the `MediaMissionReport` | [
{
"change_type": "MODIFY",
"old_path": "native/input/input-state-container.react.js",
"new_path": "native/input/input-state-container.react.js",
"diff": "@@ -69,7 +69,6 @@ import {\n} from './input-state';\nimport { processMedia } from '../media/media-utils';\nimport { displayActionResultModal } from '../navigation/action-result-modal';\n-import { fetchFileSize } from '../media/file-utils';\nlet nextLocalUploadID = 0;\nfunction getNewLocalID() {\n@@ -457,7 +456,13 @@ class InputStateContainer extends React.PureComponent<Props, State> {\nserverID,\nuserTime,\nerrorMessage;\n- const finish = (result: MediaMissionResult) => {\n+ let reportPromise;\n+\n+ const finish = async (result: MediaMissionResult) => {\n+ if (reportPromise) {\n+ const finalSteps = await reportPromise;\n+ steps.push(...finalSteps);\n+ }\nconst totalTime = Date.now() - start;\nuserTime = userTime ? userTime : totalTime;\nthis.queueMediaMissionReport(\n@@ -503,14 +508,15 @@ class InputStateContainer extends React.PureComponent<Props, State> {\nlet processedMedia;\nconst processingStart = Date.now();\ntry {\n- const { result: processResult, steps: processSteps } = await processMedia(\n+ const processMediaReturn = processMedia(\nmediaInfo,\nthis.mediaProcessConfig(),\n);\n- steps = [...steps, ...processSteps];\n+ reportPromise = processMediaReturn.reportPromise;\n+ const processResult = await processMediaReturn.resultPromise;\nif (!processResult.success) {\nfail('processing failed');\n- return finish(processResult);\n+ return await finish(processResult);\n}\nprocessedMedia = processResult;\n} catch (e) {\n@@ -532,7 +538,7 @@ class InputStateContainer extends React.PureComponent<Props, State> {\nfail(\nprocessExceptionMessage ? processExceptionMessage : 'processing threw',\n);\n- return finish({\n+ return await finish({\nsuccess: false,\nreason: 'processing_exception',\ntime,\n@@ -593,6 +599,10 @@ class InputStateContainer extends React.PureComponent<Props, State> {\n});\nuserTime = Date.now() - start;\n}\n+\n+ const processSteps = await reportPromise;\n+ reportPromise = null;\n+ steps.push(...processSteps);\nsteps.push({\nstep: 'upload',\nsuccess: !!uploadResult,\n@@ -602,14 +612,9 @@ class InputStateContainer extends React.PureComponent<Props, State> {\n});\nif (!shouldDisposePath) {\n- return finish(mediaMissionResult);\n+ return await finish(mediaMissionResult);\n}\n- // If shouldDisposePath is set, uploadURI represents a new file whose size\n- // hasn't been checked. Let's add the file size to our MediaMission report\n- const { steps: fileSizeSteps } = await fetchFileSize(uploadURI);\n- steps.push(...fileSizeSteps);\n-\nlet disposeSuccess = false,\ndisposeExceptionMessage;\nconst disposeStart = Date.now();\n@@ -635,7 +640,7 @@ class InputStateContainer extends React.PureComponent<Props, State> {\npath: shouldDisposePath,\n});\n- return finish(mediaMissionResult);\n+ return await finish(mediaMissionResult);\n}\nmediaProcessConfig() {\n"
},
{
"change_type": "MODIFY",
"old_path": "native/media/media-utils.js",
"new_path": "native/media/media-utils.js",
"diff": "@@ -36,22 +36,46 @@ type MediaResult = {|\nmediaType: MediaType,\ndimensions: Dimensions,\n|};\n-async function processMedia(\n+function processMedia(\nmediaInput: MediaInput,\nconfig: MediaProcessConfig,\n-): Promise<{|\n- steps: $ReadOnlyArray<MediaMissionStep>,\n- result: MediaMissionFailure | MediaResult,\n-|}> {\n+): {|\n+ resultPromise: Promise<MediaMissionFailure | MediaResult>,\n+ reportPromise: Promise<$ReadOnlyArray<MediaMissionStep>>,\n+|} {\n+ let resolveResult;\n+ const sendResult = result => {\n+ if (resolveResult) {\n+ resolveResult(result);\n+ }\n+ };\n+\n+ const reportPromise = processMediaMission(mediaInput, config, sendResult);\n+ const resultPromise = new Promise(resolve => {\n+ resolveResult = resolve;\n+ });\n+\n+ return { reportPromise, resultPromise };\n+}\n+\n+async function processMediaMission(\n+ mediaInput: MediaInput,\n+ config: MediaProcessConfig,\n+ sendResult: (MediaMissionFailure | MediaResult) => void,\n+): Promise<$ReadOnlyArray<MediaMissionStep>> {\nconst steps = [];\nlet initialURI = null,\nuploadURI = null,\ndimensions = mediaInput.dimensions,\nmime = null,\n- mediaType = mediaInput.type;\n+ mediaType = mediaInput.type,\n+ finished = false;\nconst finish = (failure?: MediaMissionFailure) => {\n+ invariant(!finished, 'finish called twice in processMediaMission');\n+ finished = true;\nif (failure) {\n- return { steps, result: failure };\n+ sendResult(failure);\n+ return;\n}\ninvariant(\nuploadURI && mime,\n@@ -61,9 +85,7 @@ async function processMedia(\ninitialURI !== uploadURI ? pathFromURI(uploadURI) : null;\nconst filename = readableFilename(mediaInput.filename, mime);\ninvariant(filename, `could not construct filename for ${mime}`);\n- return {\n- steps,\n- result: {\n+ sendResult({\nsuccess: true,\nuploadURI,\nshouldDisposePath,\n@@ -71,8 +93,7 @@ async function processMedia(\nmime,\nmediaType,\ndimensions,\n- },\n- };\n+ });\n};\nconst { steps: fileInfoSteps, result: fileInfoResult } = await fetchFileInfo(\n@@ -82,7 +103,8 @@ async function processMedia(\n);\nsteps.push(...fileInfoSteps);\nif (!fileInfoResult.success) {\n- return finish(fileInfoResult);\n+ finish(fileInfoResult);\n+ return steps;\n}\nconst { orientation, fileSize } = fileInfoResult;\ninitialURI = fileInfoResult.uri;\n@@ -94,13 +116,14 @@ async function processMedia(\nmime = readFileStep.mime;\n}\nif (readFileStep.mediaType && readFileStep.mediaType !== mediaType) {\n- return finish({\n+ finish({\nsuccess: false,\nreason: 'media_type_mismatch',\nreportedMediaType: mediaType,\ndetectedMediaType: readFileStep.mediaType,\ndetectedMIME: readFileStep.mime,\n});\n+ return steps;\n}\n}\n@@ -111,16 +134,18 @@ async function processMedia(\n});\nsteps.push(...videoSteps);\nif (!videoResult.success) {\n- return finish(videoResult);\n+ finish(videoResult);\n+ return steps;\n}\nuploadURI = videoResult.uri;\nmime = videoResult.mime;\n} else if (mediaInput.type === 'photo') {\nif (!mime) {\n- return finish({\n+ finish({\nsuccess: false,\nreason: 'mime_fetch_failed',\n});\n+ return steps;\n}\nconst { steps: imageSteps, result: imageResult } = await processImage({\nuri: initialURI,\n@@ -131,7 +156,8 @@ async function processMedia(\n});\nsteps.push(...imageSteps);\nif (!imageResult.success) {\n- return finish(imageResult);\n+ finish(imageResult);\n+ return steps;\n}\nuploadURI = imageResult.uri;\ndimensions = imageResult.dimensions;\n@@ -140,23 +166,35 @@ async function processMedia(\ninvariant(false, `unknown mediaType ${mediaInput.type}`);\n}\n- if (uploadURI !== initialURI && config.finalFileHeaderCheck) {\n+ if (uploadURI === initialURI) {\n+ finish();\n+ return steps;\n+ }\n+\n+ if (!config.finalFileHeaderCheck) {\n+ finish();\n+ }\n+\nconst { steps: fileSizeSteps, result: newFileSize } = await fetchFileSize(\nuploadURI,\n);\nsteps.push(...fileSizeSteps);\nif (!newFileSize) {\n- return finish({\n+ if (config.finalFileHeaderCheck) {\n+ finish({\nsuccess: false,\nreason: 'file_stat_failed',\nuri: uploadURI,\n});\n}\n+ return steps;\n+ }\nconst readNewFileStep = await readFileHeader(uploadURI, newFileSize);\nsteps.push(readNewFileStep);\nif (readNewFileStep.mime && readNewFileStep.mime !== mime) {\n- return finish({\n+ if (config.finalFileHeaderCheck) {\n+ finish({\nsuccess: false,\nreason: 'mime_type_mismatch',\nreportedMediaType: mediaType,\n@@ -165,9 +203,14 @@ async function processMedia(\ndetectedMIME: readNewFileStep.mime,\n});\n}\n+ return steps;\n+ }\n+\n+ if (config.finalFileHeaderCheck) {\n+ finish();\n}\n- return finish();\n+ return steps;\n}\nfunction getDimensions(uri: string): Promise<Dimensions> {\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Return two Promises from processMedia
Makes it easier to do post-processing for the `MediaMissionReport` |
129,187 | 18.04.2020 17:19:14 | 14,400 | 6f6a6436eed8d15a455ce7fde96303c53451994e | [native] Fix ThreadEntity linking in RobotextMessage | [
{
"change_type": "MODIFY",
"old_path": "native/chat/message.react.js",
"new_path": "native/chat/message.react.js",
"diff": "@@ -107,6 +107,7 @@ class Message extends React.PureComponent<Props> {\nmessage = (\n<RobotextMessage\nitem={this.props.item}\n+ navigation={this.props.navigation}\nfocused={this.props.focused}\ntoggleFocus={this.props.toggleFocus}\n/>\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 { chatMessageItemPropType } from 'lib/selectors/chat-selectors';\n-import type { Dispatch } from 'lib/types/redux-types';\nimport type { AppState } from '../redux/redux-setup';\nimport type { RobotextMessageInfo } from 'lib/types/message-types';\nimport {\n@@ -10,6 +9,10 @@ import {\nkeyboardStatePropType,\nwithKeyboardState,\n} from '../keyboard/keyboard-state';\n+import {\n+ type MessageListNavProp,\n+ messageListNavPropType,\n+} from './message-list-types';\nimport * as React from 'react';\nimport { Text, TouchableWithoutFeedback, View } from 'react-native';\n@@ -49,6 +52,7 @@ function robotextMessageItemHeight(\ntype Props = {|\nitem: ChatRobotextMessageInfoItemWithHeight,\n+ navigation: MessageListNavProp,\nfocused: boolean,\ntoggleFocus: (messageKey: string) => void,\n// withKeyboardState\n@@ -59,6 +63,7 @@ type Props = {|\nclass RobotextMessage extends React.PureComponent<Props> {\nstatic propTypes = {\nitem: chatMessageItemPropType.isRequired,\n+ navigation: messageListNavPropType.isRequired,\nfocused: PropTypes.bool.isRequired,\ntoggleFocus: PropTypes.func.isRequired,\nkeyboardState: keyboardStatePropType,\n@@ -84,7 +89,7 @@ class RobotextMessage extends React.PureComponent<Props> {\n}\nlinkedRobotext() {\n- const { item } = this.props;\n+ const { item, navigation } = this.props;\nconst robotext = item.robotext;\nconst robotextParts = splitRobotext(robotext);\nconst textParts = [];\n@@ -100,7 +105,14 @@ class RobotextMessage extends React.PureComponent<Props> {\nconst { rawText, entityType, id } = parseRobotextEntity(splitPart);\nif (entityType === 't' && id !== this.props.item.messageInfo.threadID) {\n- textParts.push(<ThreadEntity key={id} id={id} name={rawText} />);\n+ textParts.push(\n+ <ThreadEntity\n+ key={id}\n+ id={id}\n+ name={rawText}\n+ navigation={navigation}\n+ />,\n+ );\n} else if (entityType === 'c') {\ntextParts.push(<ColorEntity key={id} color={rawText} />);\n} else {\n@@ -131,19 +143,18 @@ const WrappedRobotextMessage = connect((state: AppState) => ({\ntype InnerThreadEntityProps = {\nid: string,\nname: string,\n+ navigation: MessageListNavProp,\n// Redux state\nthreadInfo: ?ThreadInfo,\nstyles: typeof styles,\n- // Redux dispatch functions\n- dispatch: Dispatch,\n};\nclass InnerThreadEntity extends React.PureComponent<InnerThreadEntityProps> {\nstatic propTypes = {\nid: PropTypes.string.isRequired,\nname: PropTypes.string.isRequired,\n+ navigation: messageListNavPropType.isRequired,\nthreadInfo: threadInfoPropType,\nstyles: PropTypes.objectOf(PropTypes.object).isRequired,\n- dispatch: PropTypes.func.isRequired,\n};\nrender() {\n@@ -158,24 +169,19 @@ class InnerThreadEntity extends React.PureComponent<InnerThreadEntityProps> {\n}\nonPressThread = () => {\n- const { threadInfo, dispatch } = this.props;\n+ const { threadInfo, navigation } = this.props;\ninvariant(threadInfo, 'onPressThread should have threadInfo');\n- dispatch({\n- type: 'Navigation/NAVIGATE',\n+ navigation.navigate({\nrouteName: MessageListRouteName,\nparams: { threadInfo },\nkey: `${MessageListRouteName}${threadInfo.id}`,\n});\n};\n}\n-const ThreadEntity = connect(\n- (state: AppState, ownProps: { id: string }) => ({\n+const ThreadEntity = connect((state: AppState, ownProps: { id: string }) => ({\nthreadInfo: threadInfoSelector(state)[ownProps.id],\nstyles: stylesSelector(state),\n- }),\n- null,\n- true,\n-)(InnerThreadEntity);\n+}))(InnerThreadEntity);\nfunction ColorEntity(props: {| color: string |}) {\nconst colorStyle = { color: props.color };\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Fix ThreadEntity linking in RobotextMessage |
129,187 | 19.04.2020 15:02:53 | 14,400 | 141aa2cc5cc7963ec6012913c3e89383a25f8768 | [native] Don't block file size check on asset info fetch if we already have localURI | [
{
"change_type": "MODIFY",
"old_path": "native/media/file-utils.js",
"new_path": "native/media/file-utils.js",
"diff": "@@ -68,48 +68,85 @@ async function fetchFileInfo(\nresult: MediaMissionFailure | FetchFileInfoResult,\n|}> {\nconst steps = [];\n- let uri = inputURI,\n- orientation;\n+ let assetInfoPromise, newLocalURI;\nconst needsLocalURI = !pathFromURI(inputURI);\nconst needsOrientation = mediaType === 'photo';\nif (mediaNativeID && (needsLocalURI || needsOrientation)) {\n+ assetInfoPromise = (async () => {\nconst {\nsteps: assetInfoSteps,\nresult: assetInfoResult,\n} = await fetchAssetInfo(mediaNativeID);\nsteps.push(...assetInfoSteps);\n- if (assetInfoResult.localURI) {\n- uri = assetInfoResult.localURI;\n+ newLocalURI = assetInfoResult.localURI;\n+ return assetInfoResult;\n+ })();\n}\n- if (assetInfoResult.orientation) {\n- orientation = assetInfoResult.orientation;\n+\n+ const getLocalURIPromise = (async () => {\n+ if (!needsLocalURI) {\n+ return inputURI;\n+ }\n+ if (!assetInfoPromise) {\n+ return null;\n}\n+ const { localURI } = await assetInfoPromise;\n+ if (!localURI || !pathFromURI(localURI)) {\n+ return null;\n}\n+ return localURI;\n+ })();\n- const path = pathFromURI(uri);\n- if (!path) {\n- return { steps, result: { success: false, reason: 'no_file_path' } };\n+ const getOrientationPromise = (async () => {\n+ if (!needsOrientation || !assetInfoPromise) {\n+ return null;\n}\n+ const { orientation } = await assetInfoPromise;\n+ return orientation;\n+ })();\n- const { steps: fileSizeSteps, result: fileSize } = await fetchFileSize(uri);\n+ const getFileSizePromise = (async () => {\n+ const localURI = await getLocalURIPromise;\n+ if (!localURI) {\n+ return null;\n+ }\n+ const { steps: fileSizeSteps, result: fileSize } = await fetchFileSize(\n+ localURI,\n+ );\nsteps.push(...fileSizeSteps);\n+ return fileSize;\n+ })();\n+\n+ const [uri, orientation, fileSize] = await Promise.all([\n+ getLocalURIPromise,\n+ getOrientationPromise,\n+ getFileSizePromise,\n+ ]);\n+ if (!uri) {\n+ return { steps, result: { success: false, reason: 'no_file_path' } };\n+ }\nif (!fileSize) {\nreturn {\nsteps,\n- result: {\n- success: false,\n- reason: 'file_stat_failed',\n- uri,\n- },\n+ result: { success: false, reason: 'file_stat_failed', uri },\n};\n}\n+ let finalURI = uri;\n+ if (newLocalURI && newLocalURI !== uri) {\n+ console.log(\n+ 'fetchAssetInfo returned localURI ' +\n+ `${newLocalURI} when we already had ${uri}`,\n+ );\n+ finalURI = newLocalURI;\n+ }\n+\nreturn {\nsteps,\nresult: {\nsuccess: true,\n- uri,\n+ uri: finalURI,\norientation,\nfileSize,\n},\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Don't block file size check on asset info fetch if we already have localURI |
129,187 | 19.04.2020 15:23:39 | 14,400 | fb9c862b0e07a2e28b85bc965669ca7ba07dbd7c | [native] Allow fetchFileInfo to handle MIME | [
{
"change_type": "MODIFY",
"old_path": "native/media/file-utils.js",
"new_path": "native/media/file-utils.js",
"diff": "@@ -14,55 +14,18 @@ import base64 from 'base-64';\nimport { pathFromURI, fileInfoFromData } from 'lib/utils/file-utils';\n-async function fetchFileSize(\n- uri: string,\n-): Promise<{|\n- steps: $ReadOnlyArray<MediaMissionStep>,\n- result: ?number,\n-|}> {\n- let fileSize,\n- success = false,\n- exceptionMessage;\n- const statStart = Date.now();\n- try {\n- const result = await filesystem.stat(uri);\n- success = true;\n- fileSize = result.size;\n- } catch (e) {\n- if (\n- e &&\n- typeof e === 'object' &&\n- e.message &&\n- typeof e.message === 'string'\n- ) {\n- exceptionMessage = e.message;\n- }\n- }\n- return {\n- steps: [\n- {\n- step: 'stat_file',\n- success,\n- exceptionMessage,\n- time: Date.now() - statStart,\n- uri,\n- fileSize,\n- },\n- ],\n- result: fileSize,\n- };\n-}\n-\ntype FetchFileInfoResult = {|\nsuccess: true,\nuri: string,\norientation: ?number,\nfileSize: number,\n+ mime: ?string,\n+ mediaType: ?MediaType,\n|};\nasync function fetchFileInfo(\ninputURI: string,\n- mediaType: MediaType,\nmediaNativeID: ?string,\n+ optionalFields: $Shape<{| orientation: boolean, mime: boolean |}>,\n): Promise<{|\nsteps: $ReadOnlyArray<MediaMissionStep>,\nresult: MediaMissionFailure | FetchFileInfoResult,\n@@ -71,8 +34,7 @@ async function fetchFileInfo(\nlet assetInfoPromise, newLocalURI;\nconst needsLocalURI = !pathFromURI(inputURI);\n- const needsOrientation = mediaType === 'photo';\n- if (mediaNativeID && (needsLocalURI || needsOrientation)) {\n+ if (mediaNativeID && (needsLocalURI || optionalFields.orientation)) {\nassetInfoPromise = (async () => {\nconst {\nsteps: assetInfoSteps,\n@@ -99,7 +61,7 @@ async function fetchFileInfo(\n})();\nconst getOrientationPromise = (async () => {\n- if (!needsOrientation || !assetInfoPromise) {\n+ if (!optionalFields.orientation || !assetInfoPromise) {\nreturn null;\n}\nconst { orientation } = await assetInfoPromise;\n@@ -118,10 +80,30 @@ async function fetchFileInfo(\nreturn fileSize;\n})();\n- const [uri, orientation, fileSize] = await Promise.all([\n+ const getTypesPromise = (async () => {\n+ if (!optionalFields.mime) {\n+ return { mime: null, mediaType: null };\n+ }\n+ const [localURI, fileSize] = await Promise.all([\n+ getLocalURIPromise,\n+ getFileSizePromise,\n+ ]);\n+ if (!localURI || !fileSize) {\n+ return { mime: null, mediaType: null };\n+ }\n+ const readFileStep = await readFileHeader(localURI, fileSize);\n+ steps.push(readFileStep);\n+ return {\n+ mime: readFileStep.mime,\n+ mediaType: readFileStep.mediaType,\n+ };\n+ })();\n+\n+ const [uri, orientation, fileSize, types] = await Promise.all([\ngetLocalURIPromise,\ngetOrientationPromise,\ngetFileSizePromise,\n+ getTypesPromise,\n]);\nif (!uri) {\nreturn { steps, result: { success: false, reason: 'no_file_path' } };\n@@ -149,6 +131,8 @@ async function fetchFileInfo(\nuri: finalURI,\norientation,\nfileSize,\n+ mime: types.mime,\n+ mediaType: types.mediaType,\n},\n};\n}\n@@ -201,6 +185,45 @@ async function fetchAssetInfo(\n};\n}\n+async function fetchFileSize(\n+ uri: string,\n+): Promise<{|\n+ steps: $ReadOnlyArray<MediaMissionStep>,\n+ result: ?number,\n+|}> {\n+ let fileSize,\n+ success = false,\n+ exceptionMessage;\n+ const statStart = Date.now();\n+ try {\n+ const result = await filesystem.stat(uri);\n+ success = true;\n+ fileSize = result.size;\n+ } catch (e) {\n+ if (\n+ e &&\n+ typeof e === 'object' &&\n+ e.message &&\n+ typeof e.message === 'string'\n+ ) {\n+ exceptionMessage = e.message;\n+ }\n+ }\n+ return {\n+ steps: [\n+ {\n+ step: 'stat_file',\n+ success,\n+ exceptionMessage,\n+ time: Date.now() - statStart,\n+ uri,\n+ fileSize,\n+ },\n+ ],\n+ result: fileSize,\n+ };\n+}\n+\nasync function readFileHeader(\nlocalURI: string,\nfileSize: number,\n@@ -246,4 +269,4 @@ async function readFileHeader(\n};\n}\n-export { fetchFileSize, fetchFileInfo, readFileHeader };\n+export { fetchFileInfo };\n"
},
{
"change_type": "MODIFY",
"old_path": "native/media/media-utils.js",
"new_path": "native/media/media-utils.js",
"diff": "@@ -12,7 +12,7 @@ import invariant from 'invariant';\nimport { pathFromURI, readableFilename } from 'lib/utils/file-utils';\n-import { fetchFileSize, fetchFileInfo, readFileHeader } from './file-utils';\n+import { fetchFileInfo } from './file-utils';\nimport { processVideo } from './video-utils';\nimport { processImage } from './image-utils';\n@@ -68,7 +68,6 @@ async function processMediaMission(\nuploadURI = null,\ndimensions = mediaInput.dimensions,\nmime = null,\n- mediaType = mediaInput.type,\nfinished = false;\nconst finish = (failure?: MediaMissionFailure) => {\ninvariant(!finished, 'finish called twice in processMediaMission');\n@@ -91,15 +90,18 @@ async function processMediaMission(\nshouldDisposePath,\nfilename,\nmime,\n- mediaType,\n+ mediaType: mediaInput.type,\ndimensions,\n});\n};\nconst { steps: fileInfoSteps, result: fileInfoResult } = await fetchFileInfo(\nmediaInput.uri,\n- mediaInput.type,\nmediaInput.mediaNativeID,\n+ {\n+ orientation: mediaInput.type === 'photo',\n+ mime: mediaInput.type === 'photo' || config.initialFileHeaderCheck,\n+ },\n);\nsteps.push(...fileInfoSteps);\nif (!fileInfoResult.success) {\n@@ -108,24 +110,21 @@ async function processMediaMission(\n}\nconst { orientation, fileSize } = fileInfoResult;\ninitialURI = fileInfoResult.uri;\n+ mime = fileInfoResult.mime;\n- if (mediaInput.type === 'photo' || config.initialFileHeaderCheck) {\n- const readFileStep = await readFileHeader(initialURI, fileSize);\n- steps.push(readFileStep);\n- if (readFileStep.mime) {\n- mime = readFileStep.mime;\n- }\n- if (readFileStep.mediaType && readFileStep.mediaType !== mediaType) {\n+ if (\n+ fileInfoResult.mediaType &&\n+ fileInfoResult.mediaType !== mediaInput.type\n+ ) {\nfinish({\nsuccess: false,\nreason: 'media_type_mismatch',\n- reportedMediaType: mediaType,\n- detectedMediaType: readFileStep.mediaType,\n- detectedMIME: readFileStep.mime,\n+ reportedMediaType: mediaInput.type,\n+ detectedMediaType: fileInfoResult.mediaType,\n+ detectedMIME: fileInfoResult.mime,\n});\nreturn steps;\n}\n- }\nif (mediaInput.type === 'video') {\nconst { steps: videoSteps, result: videoResult } = await processVideo({\n@@ -175,32 +174,29 @@ async function processMediaMission(\nfinish();\n}\n- const { steps: fileSizeSteps, result: newFileSize } = await fetchFileSize(\n- uploadURI,\n- );\n- steps.push(...fileSizeSteps);\n- if (!newFileSize) {\n- if (config.finalFileHeaderCheck) {\n- finish({\n- success: false,\n- reason: 'file_stat_failed',\n- uri: uploadURI,\n+ const {\n+ steps: finalFileInfoSteps,\n+ result: finalFileInfoResult,\n+ } = await fetchFileInfo(mediaInput.uri, mediaInput.mediaNativeID, {\n+ mime: true,\n});\n+ steps.push(...finalFileInfoSteps);\n+ if (!finalFileInfoResult.success) {\n+ if (config.finalFileHeaderCheck) {\n+ finish(finalFileInfoResult);\n}\nreturn steps;\n}\n- const readNewFileStep = await readFileHeader(uploadURI, newFileSize);\n- steps.push(readNewFileStep);\n- if (readNewFileStep.mime && readNewFileStep.mime !== mime) {\n+ if (finalFileInfoResult.mime && finalFileInfoResult.mime !== mime) {\nif (config.finalFileHeaderCheck) {\nfinish({\nsuccess: false,\nreason: 'mime_type_mismatch',\n- reportedMediaType: mediaType,\n+ reportedMediaType: mediaInput.type,\nreportedMIME: mime,\n- detectedMediaType: readNewFileStep.mediaType,\n- detectedMIME: readNewFileStep.mime,\n+ detectedMediaType: finalFileInfoResult.mediaType,\n+ detectedMIME: finalFileInfoResult.mime,\n});\n}\nreturn steps;\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Allow fetchFileInfo to handle MIME |
129,187 | 19.04.2020 22:37:55 | 14,400 | 2734516e005d70eef961da2b6eff6fcbc41661ee | [native] Refactor saveImage logic for performance | [
{
"change_type": "MODIFY",
"old_path": "native/media/blob-utils.js",
"new_path": "native/media/blob-utils.js",
"diff": "@@ -48,4 +48,4 @@ function stringToIntArray(str: string): Uint8Array {\nreturn array;\n}\n-export { blobToDataURI, dataURIToIntArray };\n+export { blobToDataURI, dataURIToIntArray, stringToIntArray };\n"
},
{
"change_type": "MODIFY",
"old_path": "native/media/file-utils.js",
"new_path": "native/media/file-utils.js",
"diff": "@@ -13,6 +13,9 @@ import filesystem from 'react-native-fs';\nimport base64 from 'base-64';\nimport { pathFromURI, fileInfoFromData } from 'lib/utils/file-utils';\n+import { stringToIntArray } from './blob-utils';\n+\n+const defaultOptionalFields = Object.freeze({});\ntype FetchFileInfoResult = {|\nsuccess: true,\n@@ -22,10 +25,11 @@ type FetchFileInfoResult = {|\nmime: ?string,\nmediaType: ?MediaType,\n|};\n+type OptionalFields = $Shape<{| orientation: boolean, mime: boolean |}>;\nasync function fetchFileInfo(\ninputURI: string,\n- mediaNativeID: ?string,\n- optionalFields: $Shape<{| orientation: boolean, mime: boolean |}>,\n+ mediaNativeID?: ?string,\n+ optionalFields?: OptionalFields = defaultOptionalFields,\n): Promise<{|\nsteps: $ReadOnlyArray<MediaMissionStep>,\nresult: MediaMissionFailure | FetchFileInfoResult,\n@@ -251,10 +255,7 @@ async function readFileHeader(\nlet mime, mediaType;\nif (fileData) {\nconst utf8 = base64.decode(fileData);\n- const intArray = new Uint8Array(utf8.length);\n- for (var i = 0; i < utf8.length; i++) {\n- intArray[i] = utf8.charCodeAt(i);\n- }\n+ const intArray = stringToIntArray(utf8);\n({ mime, mediaType } = fileInfoFromData(intArray));\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "native/media/save-image.js",
"new_path": "native/media/save-image.js",
"diff": "@@ -4,12 +4,17 @@ import { Platform, PermissionsAndroid } from 'react-native';\nimport filesystem from 'react-native-fs';\nimport invariant from 'invariant';\nimport * as MediaLibrary from 'expo-media-library';\n-import md5 from 'md5';\n-import { fileInfoFromData, readableFilename } from 'lib/utils/file-utils';\n+import {\n+ fileInfoFromData,\n+ readableFilename,\n+ pathFromURI,\n+} from 'lib/utils/file-utils';\n+import { promiseAll } from 'lib/utils/promises';\nimport { blobToDataURI, dataURIToIntArray } from './blob-utils';\nimport { getMediaLibraryIdentifier, getFetchableURI } from './identifier-utils';\n+import { fetchFileInfo } from './file-utils';\nimport { displayActionResultModal } from '../navigation/action-result-modal';\nimport { getAndroidPermission } from '../utils/android-permissions';\n@@ -71,15 +76,44 @@ async function saveImageAndroid(\nreturn \"don't have permission :(\";\n}\n+ const promises = [];\nconst saveFolder = `${filesystem.PicturesDirectoryPath}/SquadCal/`;\n- await filesystem.mkdir(saveFolder);\n+ promises.push(filesystem.mkdir(saveFolder));\n- const saveResult = await saveToDisk(mediaInfo.uri, saveFolder);\n+ let { uri } = mediaInfo;\n+ let tempFile, mime, error;\n+ if (uri.startsWith('http')) {\n+ promises.push(\n+ (async () => {\n+ const tempSaveResult = await saveRemoteMediaToDisk(\n+ uri,\n+ `${filesystem.TemporaryDirectoryPath}/`,\n+ );\n+ if (!tempSaveResult.success) {\n+ error = tempSaveResult.error;\n+ } else {\n+ tempFile = tempSaveResult.path;\n+ uri = `file://${tempFile}`;\n+ mime = tempSaveResult.mime;\n+ }\n+ })(),\n+ );\n+ }\n+\n+ await Promise.all(promises);\n+ if (error) {\n+ return error;\n+ }\n+\n+ const saveResult = await copyToSortedDirectory(uri, saveFolder, mime);\nif (!saveResult.success) {\nreturn saveResult.error;\n}\n- await filesystem.scanFile(saveResult.path);\n+ filesystem.scanFile(saveResult.path);\n+ if (tempFile) {\n+ filesystem.unlink(tempFile);\n+ }\nreturn null;\n}\n@@ -88,7 +122,10 @@ async function saveImageIOS(mediaInfo: SaveImageInfo) {\nlet { uri } = mediaInfo;\nlet tempFile;\nif (uri.startsWith('http')) {\n- const saveResult = await saveToDisk(uri, filesystem.TemporaryDirectoryPath);\n+ const saveResult = await saveRemoteMediaToDisk(\n+ uri,\n+ filesystem.TemporaryDirectoryPath,\n+ );\nif (!saveResult.success) {\nreturn saveResult.error;\n}\n@@ -112,18 +149,17 @@ async function saveImageIOS(mediaInfo: SaveImageInfo) {\nawait MediaLibrary.saveToLibraryAsync(uri);\nif (tempFile) {\n- await filesystem.unlink(tempFile);\n+ filesystem.unlink(tempFile);\n}\nreturn null;\n}\n-// path to directory should end with a /\ntype SaveResult =\n- | {| success: true, path: string |}\n+ | {| success: true, path: string, mime: string |}\n| {| success: false, error: string |};\n-async function saveToDisk(\n+async function saveRemoteMediaToDisk(\ninputURI: string,\n- directory: string,\n+ directory: string, // should end with a /\n): Promise<SaveResult> {\nconst uri = getFetchableURI(inputURI);\n@@ -155,19 +191,63 @@ async function saveToDisk(\nreturn { success: false, error: 'failed to save :(' };\n}\n- const name = readableFilename(md5(dataURI), mime);\n+ const tempName = readableFilename('', mime);\n+ if (!tempName) {\n+ return { success: false, error: 'failed to save :(' };\n+ }\n+ const tempPath = `${directory}tempsave.${tempName}`;\n+\n+ try {\n+ await filesystem.writeFile(tempPath, base64, 'base64');\n+ } catch {\n+ return { success: false, error: 'failed to save :(' };\n+ }\n+\n+ return { success: true, path: tempPath, mime };\n+}\n+\n+async function copyToSortedDirectory(\n+ localURI: string,\n+ directory: string, // should end with a /\n+ inputMIME: ?string,\n+): Promise<SaveResult> {\n+ const path = pathFromURI(localURI);\n+ if (!path) {\n+ return { success: false, error: 'failed to save :(' };\n+ }\n+ let mime = inputMIME;\n+\n+ const promises = {};\n+ promises.hash = filesystem.hash(path, 'md5');\n+ if (!mime) {\n+ promises.fileInfoResult = fetchFileInfo(localURI, null, { mime: true });\n+ }\n+ const { hash, fileInfoResult } = await promiseAll(promises);\n+\n+ if (\n+ fileInfoResult &&\n+ fileInfoResult.result.success &&\n+ fileInfoResult.result.mime\n+ ) {\n+ mime = fileInfoResult.result.mime;\n+ }\n+ if (!mime) {\n+ return { success: false, error: 'failed to save :(' };\n+ }\n+\n+ const name = readableFilename(hash, mime);\nif (!name) {\nreturn { success: false, error: 'failed to save :(' };\n}\n- const path = `${directory}${name}`;\n+ const newPath = `${directory}${name}`;\ntry {\n- await filesystem.writeFile(path, base64, 'base64');\n+ await filesystem.copyFile(path, newPath);\n} catch {\nreturn { success: false, error: 'failed to save :(' };\n}\n- return { success: true, path };\n+ return { success: true, path: newPath, mime };\n}\nexport { intentionalSaveImage, saveImage };\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Refactor saveImage logic for performance |
129,187 | 19.04.2020 23:19:34 | 14,400 | 6fb2c9f80f11a70f1bb441dd83b0ac54607b2537 | [web] Skip canvas draw if no EXIF rotation needed | [
{
"change_type": "MODIFY",
"old_path": "web/utils/media-utils.js",
"new_path": "web/utils/media-utils.js",
"diff": "@@ -41,15 +41,15 @@ async function processFile(\nexifRotate: boolean,\n): Promise<ProcessFileResult> {\nconst initialURI = URL.createObjectURL(file);\n+ if (!exifRotate) {\n+ const { width, height } = await preloadImage(initialURI);\n+ const dimensions = { width, height };\n+ return { uri: initialURI, dimensions };\n+ }\nconst [image, orientation] = await Promise.all([\npreloadImage(initialURI),\n- (async () => {\n- if (!exifRotate) {\n- return 1;\n- }\n- return await getOrientation(file);\n- })(),\n+ getOrientation(file),\n]);\nconst dimensions =\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [web] Skip canvas draw if no EXIF rotation needed |
129,187 | 20.04.2020 00:17:18 | 14,400 | 4eb08408fb26aab713d352915a7c192b7cc4886e | [web] Fix chat scrolling behavior for Firefox
Using ugly CSS hack | [
{
"change_type": "MODIFY",
"old_path": "web/chat/chat-message-list.css",
"new_path": "web/chat/chat-message-list.css",
"diff": "@@ -10,10 +10,6 @@ div.activeContainer {\nborder: 2px solid #5989D6;\nmargin-left: 402px;\n}\n-div.firefoxMessageContainer {\n- overflow-y: scroll;\n- height: 100%;\n-}\ndiv.messageContainer {\nflex-grow: 1;\nflex: 1;\n@@ -21,9 +17,16 @@ div.messageContainer {\ndisplay: flex;\nflex-direction: column-reverse;\n}\n+div.firefoxMessageContainer {\n+ flex-direction: column !important;\n+ transform: scaleY(-1);\n+}\ndiv.messageContainer > div {\ntransform: translateZ(0);\n}\n+div.firefoxMessageContainer > div {\n+ transform: translateZ(0) scaleY(-1) !important;\n+}\ndiv.message {\ndisplay: flex;\n"
},
{
"change_type": "MODIFY",
"old_path": "web/chat/chat-message-list.react.js",
"new_path": "web/chat/chat-message-list.react.js",
"diff": "@@ -158,8 +158,14 @@ class ChatMessageList extends React.PureComponent<Props, State> {\n}\nscrollToBottom() {\n- if (this.messageContainer) {\n- this.messageContainer.scrollTop = this.messageContainer.scrollHeight;\n+ const { messageContainer } = this;\n+ if (!messageContainer) {\n+ return;\n+ }\n+ if (this.props.firefox) {\n+ messageContainer.scrollTop = 0;\n+ } else {\n+ messageContainer.scrollTop = messageContainer.scrollHeight;\n}\n}\n@@ -246,31 +252,16 @@ class ChatMessageList extends React.PureComponent<Props, State> {\n/>\n);\n- let content;\n- if (this.props.firefox) {\n- content = (\n- <div\n- className={css.firefoxMessageContainer}\n- ref={this.messageContainerRef}\n- >\n- <div className={css.messageContainer}>\n- {messages}\n- {tooltip}\n- </div>\n- </div>\n- );\n- } else {\n- content = (\n- <div className={css.messageContainer} ref={this.messageContainerRef}>\n+ const messageContainerStyle = classNames({\n+ [css.messageContainer]: true,\n+ [css.firefoxMessageContainer]: this.props.firefox,\n+ });\n+ return connectDropTarget(\n+ <div className={containerStyle} ref={this.containerRef}>\n+ <div className={messageContainerStyle} ref={this.messageContainerRef}>\n{messages}\n{tooltip}\n</div>\n- );\n- }\n-\n- return connectDropTarget(\n- <div className={containerStyle} ref={this.containerRef}>\n- {content}\n<ChatInputBar threadInfo={threadInfo} chatInputState={chatInputState} />\n</div>,\n);\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [web] Fix chat scrolling behavior for Firefox
Using ugly CSS hack
https://github.com/philipwalton/flexbugs/issues/108
https://bugzilla.mozilla.org/show_bug.cgi?id=1042151 |
129,187 | 20.04.2020 14:12:27 | 14,400 | de29fbbb3017bb60e3f0602b1214112625d1d156 | [native] OverlayableScrollViewState -> ScrollViewModalState | [
{
"change_type": "MODIFY",
"old_path": "native/chat/message-list.react.js",
"new_path": "native/chat/message-list.react.js",
"diff": "@@ -13,10 +13,10 @@ import {\nmessageListNavPropType,\n} from './message-list-types';\nimport {\n- type OverlayableScrollViewState,\n- overlayableScrollViewStatePropType,\n- withOverlayableScrollViewState,\n-} from '../navigation/overlayable-scroll-view-state';\n+ type ScrollViewModalState,\n+ scrollViewModalStatePropType,\n+ withScrollViewModalState,\n+} from '../navigation/scroll-view-modal-state';\nimport {\ntype KeyboardState,\nkeyboardStatePropType,\n@@ -63,8 +63,8 @@ type Props = {|\nstartReached: boolean,\nscrollBlockingModalsClosed: boolean,\nstyles: typeof styles,\n- // withOverlayableScrollViewState\n- overlayableScrollViewState: ?OverlayableScrollViewState,\n+ // withScrollViewModalState\n+ scrollViewModalState: ?ScrollViewModalState,\n// withKeyboardState\nkeyboardState: ?KeyboardState,\n// Redux dispatch functions\n@@ -99,7 +99,7 @@ class MessageList extends React.PureComponent<Props, State> {\nstartReached: PropTypes.bool.isRequired,\nscrollBlockingModalsClosed: PropTypes.bool.isRequired,\nstyles: PropTypes.objectOf(PropTypes.object).isRequired,\n- overlayableScrollViewState: overlayableScrollViewStatePropType,\n+ scrollViewModalState: scrollViewModalStatePropType,\nkeyboardState: keyboardStatePropType,\ndispatchActionPromise: PropTypes.func.isRequired,\nfetchMessagesBeforeCursor: PropTypes.func.isRequired,\n@@ -150,10 +150,8 @@ class MessageList extends React.PureComponent<Props, State> {\n}\nstatic scrollDisabled(props: Props) {\n- const { overlayableScrollViewState } = props;\n- return !!(\n- overlayableScrollViewState && overlayableScrollViewState.scrollDisabled\n- );\n+ const { scrollViewModalState } = props;\n+ return !!(scrollViewModalState && scrollViewModalState.scrollDisabled);\n}\ncomponentDidUpdate(prevProps: Props) {\n@@ -395,5 +393,5 @@ export default connect(\n)(\nconnectNav((context: ?NavContextType) => ({\nscrollBlockingModalsClosed: scrollBlockingChatModalsClosedSelector(context),\n- }))(withKeyboardState(withOverlayableScrollViewState(MessageList))),\n+ }))(withKeyboardState(withScrollViewModalState(MessageList))),\n);\n"
},
{
"change_type": "MODIFY",
"old_path": "native/chat/multimedia-message-multimedia.react.js",
"new_path": "native/chat/multimedia-message-multimedia.react.js",
"diff": "@@ -20,10 +20,10 @@ import {\nmessageListNavPropType,\n} from './message-list-types';\nimport {\n- type OverlayableScrollViewState,\n- overlayableScrollViewStatePropType,\n- withOverlayableScrollViewState,\n-} from '../navigation/overlayable-scroll-view-state';\n+ type ScrollViewModalState,\n+ scrollViewModalStatePropType,\n+ withScrollViewModalState,\n+} from '../navigation/scroll-view-modal-state';\nimport {\ntype KeyboardState,\nkeyboardStatePropType,\n@@ -58,8 +58,8 @@ type Props = {|\ntoggleMessageFocus: (messageKey: string) => void,\n// Redux state\ncolors: Colors,\n- // withOverlayableScrollViewState\n- overlayableScrollViewState: ?OverlayableScrollViewState,\n+ // withScrollViewModalState\n+ scrollViewModalState: ?ScrollViewModalState,\n// withKeyboardState\nkeyboardState: ?KeyboardState,\n|};\n@@ -80,7 +80,7 @@ class MultimediaMessageMultimedia extends React.PureComponent<Props, State> {\nmessageFocused: PropTypes.bool.isRequired,\ntoggleMessageFocus: PropTypes.func.isRequired,\ncolors: colorsPropType.isRequired,\n- overlayableScrollViewState: overlayableScrollViewStatePropType,\n+ scrollViewModalState: scrollViewModalStatePropType,\nkeyboardState: keyboardStatePropType,\n};\nview: ?View;\n@@ -115,10 +115,8 @@ class MultimediaMessageMultimedia extends React.PureComponent<Props, State> {\n}\nstatic scrollDisabled(props: Props) {\n- const { overlayableScrollViewState } = props;\n- return !!(\n- overlayableScrollViewState && overlayableScrollViewState.scrollDisabled\n- );\n+ const { scrollViewModalState } = props;\n+ return !!(scrollViewModalState && scrollViewModalState.scrollDisabled);\n}\ncomponentDidUpdate(prevProps: Props) {\n@@ -185,9 +183,9 @@ class MultimediaMessageMultimedia extends React.PureComponent<Props, State> {\n}\nthis.clickable = false;\n- const { overlayableScrollViewState, mediaInfo } = this.props;\n- if (overlayableScrollViewState) {\n- overlayableScrollViewState.setScrollDisabled(true);\n+ const { scrollViewModalState, mediaInfo } = this.props;\n+ if (scrollViewModalState) {\n+ scrollViewModalState.setScrollDisabled(true);\n}\nview.measure((x, y, width, height, pageX, pageY) => {\n@@ -234,9 +232,9 @@ class MultimediaMessageMultimedia extends React.PureComponent<Props, State> {\ntoggleMessageFocus(messageKey(item.messageInfo));\n}\n- const { overlayableScrollViewState } = this.props;\n- if (overlayableScrollViewState) {\n- overlayableScrollViewState.setScrollDisabled(true);\n+ const { scrollViewModalState } = this.props;\n+ if (scrollViewModalState) {\n+ scrollViewModalState.setScrollDisabled(true);\n}\nview.measure((x, y, width, height, pageX, pageY) => {\n@@ -298,8 +296,4 @@ const styles = StyleSheet.create({\nexport default connect((state: AppState) => ({\ncolors: colorsSelector(state),\n-}))(\n- withKeyboardState(\n- withOverlayableScrollViewState(MultimediaMessageMultimedia),\n- ),\n-);\n+}))(withKeyboardState(withScrollViewModalState(MultimediaMessageMultimedia)));\n"
},
{
"change_type": "MODIFY",
"old_path": "native/chat/settings/thread-settings-member.react.js",
"new_path": "native/chat/settings/thread-settings-member.react.js",
"diff": "@@ -11,10 +11,10 @@ import type { AppState } from '../../redux/redux-setup';\nimport type { LoadingStatus } from 'lib/types/loading-types';\nimport { loadingStatusPropType } from 'lib/types/loading-types';\nimport {\n- type OverlayableScrollViewState,\n- overlayableScrollViewStatePropType,\n- withOverlayableScrollViewState,\n-} from '../../navigation/overlayable-scroll-view-state';\n+ type ScrollViewModalState,\n+ scrollViewModalStatePropType,\n+ withScrollViewModalState,\n+} from '../../navigation/scroll-view-modal-state';\nimport {\ntype VerticalBounds,\nverticalBoundsPropType,\n@@ -69,8 +69,8 @@ type Props = {|\nchangeRoleLoadingStatus: LoadingStatus,\ncolors: Colors,\nstyles: typeof styles,\n- // withOverlayableScrollViewState\n- overlayableScrollViewState: ?OverlayableScrollViewState,\n+ // withScrollViewModalState\n+ scrollViewModalState: ?ScrollViewModalState,\n// withKeyboardState\nkeyboardState: ?KeyboardState,\n|};\n@@ -87,7 +87,7 @@ class ThreadSettingsMember extends React.PureComponent<Props> {\nchangeRoleLoadingStatus: loadingStatusPropType.isRequired,\ncolors: colorsPropType.isRequired,\nstyles: PropTypes.objectOf(PropTypes.object).isRequired,\n- overlayableScrollViewState: overlayableScrollViewStatePropType,\n+ scrollViewModalState: scrollViewModalStatePropType,\nkeyboardState: keyboardStatePropType,\n};\neditButton: ?View;\n@@ -232,9 +232,9 @@ class ThreadSettingsMember extends React.PureComponent<Props> {\nreturn;\n}\n- const { overlayableScrollViewState } = this.props;\n- if (overlayableScrollViewState) {\n- overlayableScrollViewState.setScrollDisabled(true);\n+ const { scrollViewModalState } = this.props;\n+ if (scrollViewModalState) {\n+ scrollViewModalState.setScrollDisabled(true);\n}\neditButton.measure((x, y, width, height, pageX, pageY) => {\n@@ -315,4 +315,4 @@ export default connect(\ncolors: colorsSelector(state),\nstyles: stylesSelector(state),\n}),\n-)(withKeyboardState(withOverlayableScrollViewState(ThreadSettingsMember)));\n+)(withKeyboardState(withScrollViewModalState(ThreadSettingsMember)));\n"
},
{
"change_type": "MODIFY",
"old_path": "native/chat/settings/thread-settings.react.js",
"new_path": "native/chat/settings/thread-settings.react.js",
"diff": "@@ -16,10 +16,10 @@ import type { CategoryType } from './thread-settings-category.react';\nimport type { Navigate } from '../../navigation/route-names';\nimport type { VerticalBounds } from '../../types/layout-types';\nimport {\n- type OverlayableScrollViewState,\n- overlayableScrollViewStatePropType,\n- withOverlayableScrollViewState,\n-} from '../../navigation/overlayable-scroll-view-state';\n+ type ScrollViewModalState,\n+ scrollViewModalStatePropType,\n+ withScrollViewModalState,\n+} from '../../navigation/scroll-view-modal-state';\nimport React from 'react';\nimport PropTypes from 'prop-types';\n@@ -196,8 +196,8 @@ type Props = {|\nsomethingIsSaving: boolean,\ntabActive: boolean,\nstyles: typeof styles,\n- // withOverlayableScrollViewState\n- overlayableScrollViewState: ?OverlayableScrollViewState,\n+ // withScrollViewModalState\n+ scrollViewModalState: ?ScrollViewModalState,\n|};\ntype State = {|\nshowMaxMembers: number,\n@@ -228,7 +228,7 @@ class ThreadSettings extends React.PureComponent<Props, State> {\nsomethingIsSaving: PropTypes.bool.isRequired,\ntabActive: PropTypes.bool.isRequired,\nstyles: PropTypes.objectOf(PropTypes.object).isRequired,\n- overlayableScrollViewState: overlayableScrollViewStatePropType,\n+ scrollViewModalState: scrollViewModalStatePropType,\n};\nstatic navigationOptions = ({ navigation }) => ({\ntitle: navigation.state.params.threadInfo.uiName,\n@@ -258,10 +258,8 @@ class ThreadSettings extends React.PureComponent<Props, State> {\n}\nstatic scrollDisabled(props: Props) {\n- const { overlayableScrollViewState } = props;\n- return !!(\n- overlayableScrollViewState && overlayableScrollViewState.scrollDisabled\n- );\n+ const { scrollViewModalState } = props;\n+ return !!(scrollViewModalState && scrollViewModalState.scrollDisabled);\n}\ncomponentDidMount() {\n@@ -852,7 +850,7 @@ const WrappedThreadSettings = connect(\n)(\nconnectNav((context: ?NavContextType) => ({\ntabActive: activeTabSelector(context),\n- }))(withOverlayableScrollViewState(ThreadSettings)),\n+ }))(withScrollViewModalState(ThreadSettings)),\n);\nhoistNonReactStatics(WrappedThreadSettings, ThreadSettings);\n"
},
{
"change_type": "MODIFY",
"old_path": "native/chat/text-message.react.js",
"new_path": "native/chat/text-message.react.js",
"diff": "@@ -15,10 +15,10 @@ import {\nmessageListNavPropType,\n} from './message-list-types';\nimport {\n- type OverlayableScrollViewState,\n- overlayableScrollViewStatePropType,\n- withOverlayableScrollViewState,\n-} from '../navigation/overlayable-scroll-view-state';\n+ type ScrollViewModalState,\n+ scrollViewModalStatePropType,\n+ withScrollViewModalState,\n+} from '../navigation/scroll-view-modal-state';\nimport {\ntype KeyboardState,\nkeyboardStatePropType,\n@@ -73,8 +73,8 @@ type Props = {|\nfocused: boolean,\ntoggleFocus: (messageKey: string) => void,\nverticalBounds: ?VerticalBounds,\n- // withOverlayableScrollViewState\n- overlayableScrollViewState: ?OverlayableScrollViewState,\n+ // withScrollViewModalState\n+ scrollViewModalState: ?ScrollViewModalState,\n// withKeyboardState\nkeyboardState: ?KeyboardState,\n|};\n@@ -85,7 +85,7 @@ class TextMessage extends React.PureComponent<Props> {\nfocused: PropTypes.bool.isRequired,\ntoggleFocus: PropTypes.func.isRequired,\nverticalBounds: verticalBoundsPropType,\n- overlayableScrollViewState: overlayableScrollViewStatePropType,\n+ scrollViewModalState: scrollViewModalStatePropType,\nkeyboardState: keyboardStatePropType,\n};\nmessage: ?View;\n@@ -129,9 +129,9 @@ class TextMessage extends React.PureComponent<Props> {\ntoggleFocus(messageKey(item.messageInfo));\n}\n- const { overlayableScrollViewState } = this.props;\n- if (overlayableScrollViewState) {\n- overlayableScrollViewState.setScrollDisabled(true);\n+ const { scrollViewModalState } = this.props;\n+ if (scrollViewModalState) {\n+ scrollViewModalState.setScrollDisabled(true);\n}\nmessage.measure((x, y, width, height, pageX, pageY) => {\n@@ -179,7 +179,7 @@ class TextMessage extends React.PureComponent<Props> {\n}\nconst WrappedTextMessage = withKeyboardState(\n- withOverlayableScrollViewState(TextMessage),\n+ withScrollViewModalState(TextMessage),\n);\nexport { WrappedTextMessage as TextMessage, textMessageItemHeight };\n"
},
{
"change_type": "MODIFY",
"old_path": "native/navigation/app-navigator.react.js",
"new_path": "native/navigation/app-navigator.react.js",
"diff": "@@ -33,7 +33,7 @@ import ActionResultModal from './action-result-modal.react';\nimport { TextMessageTooltipModal } from '../chat/text-message-tooltip-modal.react';\nimport ThreadSettingsMemberTooltipModal from '../chat/settings/thread-settings-member-tooltip-modal.react';\nimport CameraModal from '../media/camera-modal.react';\n-import OverlayableScrollViewStateContainer from './overlayable-scroll-view-state-container.react';\n+import ScrollViewModalStateContainer from './scroll-view-modal-state-container.react';\nimport KeyboardStateContainer from '../keyboard/keyboard-state-container.react';\nimport PushHandler from '../push/push-handler.react';\nimport { getPersistor } from '../redux/persist';\n@@ -86,14 +86,14 @@ function WrappedAppNavigator(props: Props) {\nconst { navigation } = props;\nreturn (\n- <OverlayableScrollViewStateContainer>\n+ <ScrollViewModalStateContainer>\n<KeyboardStateContainer>\n<AppNavigator navigation={navigation} />\n<PersistGate persistor={getPersistor()}>\n<PushHandler navigation={navigation} />\n</PersistGate>\n</KeyboardStateContainer>\n- </OverlayableScrollViewStateContainer>\n+ </ScrollViewModalStateContainer>\n);\n}\nhoistNonReactStatics(WrappedAppNavigator, AppNavigator);\n"
},
{
"change_type": "DELETE",
"old_path": "native/navigation/overlayable-scroll-view-state.js",
"new_path": null,
"diff": "-// @flow\n-\n-import * as React from 'react';\n-import PropTypes from 'prop-types';\n-\n-export type OverlayableScrollViewState = {|\n- scrollDisabled: boolean,\n- setScrollDisabled: (scrollDisabled: boolean) => void,\n-|};\n-\n-const overlayableScrollViewStatePropType = PropTypes.shape({\n- scrollDisabled: PropTypes.bool.isRequired,\n- setScrollDisabled: PropTypes.func.isRequired,\n-});\n-\n-const OverlayableScrollViewContext = React.createContext<?OverlayableScrollViewState>(\n- null,\n-);\n-\n-function withOverlayableScrollViewState<\n- AllProps: {},\n- ComponentType: React.ComponentType<AllProps>,\n->(\n- Component: ComponentType,\n-): React.ComponentType<\n- $Diff<\n- React.ElementConfig<ComponentType>,\n- { overlayableScrollViewState: ?OverlayableScrollViewState },\n- >,\n-> {\n- class OverlayableScrollViewStateHOC extends React.PureComponent<\n- $Diff<\n- React.ElementConfig<ComponentType>,\n- { overlayableScrollViewState: ?OverlayableScrollViewState },\n- >,\n- > {\n- render() {\n- return (\n- <OverlayableScrollViewContext.Consumer>\n- {value => (\n- <Component {...this.props} overlayableScrollViewState={value} />\n- )}\n- </OverlayableScrollViewContext.Consumer>\n- );\n- }\n- }\n- return OverlayableScrollViewStateHOC;\n-}\n-\n-export {\n- overlayableScrollViewStatePropType,\n- OverlayableScrollViewContext,\n- withOverlayableScrollViewState,\n-};\n"
},
{
"change_type": "RENAME",
"old_path": "native/navigation/overlayable-scroll-view-state-container.react.js",
"new_path": "native/navigation/scroll-view-modal-state-container.react.js",
"diff": "@@ -7,7 +7,7 @@ import {\nscrollBlockingChatModalsClosedSelector,\noverlayTransitioningSelector,\n} from './nav-selectors';\n-import { OverlayableScrollViewContext } from './overlayable-scroll-view-state';\n+import { ScrollViewModalContext } from './scroll-view-modal-state';\nimport { connectNav, type NavContextType } from './navigation-context';\ntype Props = {|\n@@ -19,10 +19,7 @@ type Props = {|\ntype State = {|\nscrollDisabled: boolean,\n|};\n-class OverlayableScrollViewStateContainer extends React.PureComponent<\n- Props,\n- State,\n-> {\n+class ScrollViewModalStateContainer extends React.PureComponent<Props, State> {\nstatic propTypes = {\nchildren: PropTypes.node.isRequired,\nscrollBlockingModalsClosed: PropTypes.bool.isRequired,\n@@ -57,14 +54,14 @@ class OverlayableScrollViewStateContainer extends React.PureComponent<\n};\nrender() {\n- const overlayableScrollViewState = {\n+ const scrollViewModalState = {\nscrollDisabled: this.state.scrollDisabled,\nsetScrollDisabled: this.setScrollDisabled,\n};\nreturn (\n- <OverlayableScrollViewContext.Provider value={overlayableScrollViewState}>\n+ <ScrollViewModalContext.Provider value={scrollViewModalState}>\n{this.props.children}\n- </OverlayableScrollViewContext.Provider>\n+ </ScrollViewModalContext.Provider>\n);\n}\n}\n@@ -78,4 +75,4 @@ export default connectNav((context: ?NavContextType) => {\nscrollBlockingModalsGone:\nscrollBlockingModalsClosed && !overlayTransitioningSelector(context),\n};\n-})(OverlayableScrollViewStateContainer);\n+})(ScrollViewModalStateContainer);\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "native/navigation/scroll-view-modal-state.js",
"diff": "+// @flow\n+\n+import * as React from 'react';\n+import PropTypes from 'prop-types';\n+\n+export type ScrollViewModalState = {|\n+ scrollDisabled: boolean,\n+ setScrollDisabled: (scrollDisabled: boolean) => void,\n+|};\n+\n+const scrollViewModalStatePropType = PropTypes.shape({\n+ scrollDisabled: PropTypes.bool.isRequired,\n+ setScrollDisabled: PropTypes.func.isRequired,\n+});\n+\n+const ScrollViewModalContext = React.createContext<?ScrollViewModalState>(null);\n+\n+function withScrollViewModalState<\n+ AllProps: {},\n+ ComponentType: React.ComponentType<AllProps>,\n+>(\n+ Component: ComponentType,\n+): React.ComponentType<\n+ $Diff<\n+ React.ElementConfig<ComponentType>,\n+ { scrollViewModalState: ?ScrollViewModalState },\n+ >,\n+> {\n+ class ScrollViewModalStateHOC extends React.PureComponent<\n+ $Diff<\n+ React.ElementConfig<ComponentType>,\n+ { scrollViewModalState: ?ScrollViewModalState },\n+ >,\n+ > {\n+ render() {\n+ return (\n+ <ScrollViewModalContext.Consumer>\n+ {value => <Component {...this.props} scrollViewModalState={value} />}\n+ </ScrollViewModalContext.Consumer>\n+ );\n+ }\n+ }\n+ return ScrollViewModalStateHOC;\n+}\n+\n+export {\n+ scrollViewModalStatePropType,\n+ ScrollViewModalContext,\n+ withScrollViewModalState,\n+};\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] OverlayableScrollViewState -> ScrollViewModalState |
129,187 | 20.04.2020 15:29:05 | 14,400 | 5e631e00f84b6d35b445edcaadb027765b8b8bb0 | [native] scrollDisabled -> scrollViewModalState | [
{
"change_type": "MODIFY",
"old_path": "native/chat/message-list.react.js",
"new_path": "native/chat/message-list.react.js",
"diff": "@@ -48,12 +48,7 @@ import {\ntype ChatMessageInfoItemWithHeight,\n} from './message.react';\nimport ListLoadingIndicator from '../components/list-loading-indicator.react';\n-import { scrollBlockingChatModalsClosedSelector } from '../navigation/nav-selectors';\nimport { styleSelector } from '../themes/colors';\n-import {\n- connectNav,\n- type NavContextType,\n-} from '../navigation/navigation-context';\ntype Props = {|\nthreadInfo: ThreadInfo,\n@@ -61,7 +56,6 @@ type Props = {|\nnavigation: MessageListNavProp,\n// Redux state\nstartReached: boolean,\n- scrollBlockingModalsClosed: boolean,\nstyles: typeof styles,\n// withScrollViewModalState\nscrollViewModalState: ?ScrollViewModalState,\n@@ -97,7 +91,6 @@ class MessageList extends React.PureComponent<Props, State> {\nmessageListData: PropTypes.arrayOf(chatMessageItemPropType).isRequired,\nnavigation: messageListNavPropType.isRequired,\nstartReached: PropTypes.bool.isRequired,\n- scrollBlockingModalsClosed: PropTypes.bool.isRequired,\nstyles: PropTypes.objectOf(PropTypes.object).isRequired,\nscrollViewModalState: scrollViewModalStatePropType,\nkeyboardState: keyboardStatePropType,\n@@ -151,7 +144,14 @@ class MessageList extends React.PureComponent<Props, State> {\nstatic scrollDisabled(props: Props) {\nconst { scrollViewModalState } = props;\n- return !!(scrollViewModalState && scrollViewModalState.scrollDisabled);\n+ return (\n+ !!scrollViewModalState && scrollViewModalState.modalState !== 'closed'\n+ );\n+ }\n+\n+ static modalOpen(props: Props) {\n+ const { scrollViewModalState } = props;\n+ return !!scrollViewModalState && scrollViewModalState.modalState === 'open';\n}\ncomponentDidUpdate(prevProps: Props) {\n@@ -175,10 +175,9 @@ class MessageList extends React.PureComponent<Props, State> {\nthis.loadingFromScroll = false;\n}\n- if (\n- this.props.scrollBlockingModalsClosed &&\n- !prevProps.scrollBlockingModalsClosed\n- ) {\n+ const modalIsOpen = MessageList.modalOpen(this.props);\n+ const modalWasOpen = MessageList.modalOpen(prevProps);\n+ if (!modalIsOpen && modalWasOpen) {\nthis.setState({ focusedMessageKey: null });\n}\n@@ -390,8 +389,4 @@ export default connect(\n};\n},\n{ fetchMessagesBeforeCursor, fetchMostRecentMessages },\n-)(\n- connectNav((context: ?NavContextType) => ({\n- scrollBlockingModalsClosed: scrollBlockingChatModalsClosedSelector(context),\n- }))(withKeyboardState(withScrollViewModalState(MessageList))),\n-);\n+)(withKeyboardState(withScrollViewModalState(MessageList)));\n"
},
{
"change_type": "MODIFY",
"old_path": "native/chat/multimedia-message-multimedia.react.js",
"new_path": "native/chat/multimedia-message-multimedia.react.js",
"diff": "@@ -116,7 +116,9 @@ class MultimediaMessageMultimedia extends React.PureComponent<Props, State> {\nstatic scrollDisabled(props: Props) {\nconst { scrollViewModalState } = props;\n- return !!(scrollViewModalState && scrollViewModalState.scrollDisabled);\n+ return (\n+ !!scrollViewModalState && scrollViewModalState.modalState !== 'closed'\n+ );\n}\ncomponentDidUpdate(prevProps: Props) {\n@@ -185,7 +187,7 @@ class MultimediaMessageMultimedia extends React.PureComponent<Props, State> {\nconst { scrollViewModalState, mediaInfo } = this.props;\nif (scrollViewModalState) {\n- scrollViewModalState.setScrollDisabled(true);\n+ scrollViewModalState.setModalState('open');\n}\nview.measure((x, y, width, height, pageX, pageY) => {\n@@ -234,7 +236,7 @@ class MultimediaMessageMultimedia extends React.PureComponent<Props, State> {\nconst { scrollViewModalState } = this.props;\nif (scrollViewModalState) {\n- scrollViewModalState.setScrollDisabled(true);\n+ scrollViewModalState.setModalState('open');\n}\nview.measure((x, y, width, height, pageX, pageY) => {\n"
},
{
"change_type": "MODIFY",
"old_path": "native/chat/settings/thread-settings-member.react.js",
"new_path": "native/chat/settings/thread-settings-member.react.js",
"diff": "@@ -234,7 +234,7 @@ class ThreadSettingsMember extends React.PureComponent<Props> {\nconst { scrollViewModalState } = this.props;\nif (scrollViewModalState) {\n- scrollViewModalState.setScrollDisabled(true);\n+ scrollViewModalState.setModalState('open');\n}\neditButton.measure((x, y, width, height, pageX, pageY) => {\n"
},
{
"change_type": "MODIFY",
"old_path": "native/chat/settings/thread-settings.react.js",
"new_path": "native/chat/settings/thread-settings.react.js",
"diff": "@@ -259,7 +259,9 @@ class ThreadSettings extends React.PureComponent<Props, State> {\nstatic scrollDisabled(props: Props) {\nconst { scrollViewModalState } = props;\n- return !!(scrollViewModalState && scrollViewModalState.scrollDisabled);\n+ return (\n+ !!scrollViewModalState && scrollViewModalState.modalState !== 'closed'\n+ );\n}\ncomponentDidMount() {\n"
},
{
"change_type": "MODIFY",
"old_path": "native/chat/text-message.react.js",
"new_path": "native/chat/text-message.react.js",
"diff": "@@ -131,7 +131,7 @@ class TextMessage extends React.PureComponent<Props> {\nconst { scrollViewModalState } = this.props;\nif (scrollViewModalState) {\n- scrollViewModalState.setScrollDisabled(true);\n+ scrollViewModalState.setModalState('open');\n}\nmessage.measure((x, y, width, height, pageX, pageY) => {\n"
},
{
"change_type": "MODIFY",
"old_path": "native/navigation/scroll-view-modal-state-container.react.js",
"new_path": "native/navigation/scroll-view-modal-state-container.react.js",
"diff": "@@ -7,7 +7,10 @@ import {\nscrollBlockingChatModalsClosedSelector,\noverlayTransitioningSelector,\n} from './nav-selectors';\n-import { ScrollViewModalContext } from './scroll-view-modal-state';\n+import {\n+ ScrollViewModalContext,\n+ type ScrollViewModalStatus,\n+} from './scroll-view-modal-state';\nimport { connectNav, type NavContextType } from './navigation-context';\ntype Props = {|\n@@ -17,7 +20,7 @@ type Props = {|\nscrollBlockingModalsGone: boolean,\n|};\ntype State = {|\n- scrollDisabled: boolean,\n+ modalState: ScrollViewModalStatus,\n|};\nclass ScrollViewModalStateContainer extends React.PureComponent<Props, State> {\nstatic propTypes = {\n@@ -29,34 +32,40 @@ class ScrollViewModalStateContainer extends React.PureComponent<Props, State> {\nconstructor(props: Props) {\nsuper(props);\nthis.state = {\n- scrollDisabled: !props.scrollBlockingModalsClosed,\n+ modalState: props.scrollBlockingModalsClosed ? 'closed' : 'open',\n};\n}\ncomponentDidUpdate(prevProps: Props) {\nif (\n- this.state.scrollDisabled &&\n+ this.state.modalState !== 'closed' &&\nthis.props.scrollBlockingModalsGone &&\n!prevProps.scrollBlockingModalsGone\n) {\n- this.setScrollDisabled(false);\n+ this.setModalState('closed');\n} else if (\n- !this.state.scrollDisabled &&\n+ this.state.modalState !== 'open' &&\n!this.props.scrollBlockingModalsClosed &&\nprevProps.scrollBlockingModalsClosed\n) {\n- this.setScrollDisabled(true);\n+ this.setModalState('open');\n+ } else if (\n+ this.state.modalState === 'open' &&\n+ this.props.scrollBlockingModalsClosed &&\n+ !prevProps.scrollBlockingModalsClosed\n+ ) {\n+ this.setModalState('closing');\n}\n}\n- setScrollDisabled = (scrollDisabled: boolean) => {\n- this.setState({ scrollDisabled });\n+ setModalState = (modalState: ScrollViewModalStatus) => {\n+ this.setState({ modalState });\n};\nrender() {\nconst scrollViewModalState = {\n- scrollDisabled: this.state.scrollDisabled,\n- setScrollDisabled: this.setScrollDisabled,\n+ modalState: this.state.modalState,\n+ setModalState: this.setModalState,\n};\nreturn (\n<ScrollViewModalContext.Provider value={scrollViewModalState}>\n"
},
{
"change_type": "MODIFY",
"old_path": "native/navigation/scroll-view-modal-state.js",
"new_path": "native/navigation/scroll-view-modal-state.js",
"diff": "import * as React from 'react';\nimport PropTypes from 'prop-types';\n+export type ScrollViewModalStatus = 'open' | 'closed' | 'closing';\n+\nexport type ScrollViewModalState = {|\n- scrollDisabled: boolean,\n- setScrollDisabled: (scrollDisabled: boolean) => void,\n+ modalState: ScrollViewModalStatus,\n+ setModalState: (modalState: ScrollViewModalStatus) => void,\n|};\nconst scrollViewModalStatePropType = PropTypes.shape({\n- scrollDisabled: PropTypes.bool.isRequired,\n- setScrollDisabled: PropTypes.func.isRequired,\n+ modalState: PropTypes.oneOf(['open', 'closed', 'closing']).isRequired,\n+ setModalState: PropTypes.func.isRequired,\n});\nconst ScrollViewModalContext = React.createContext<?ScrollViewModalState>(null);\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] scrollDisabled -> scrollViewModalState |
129,187 | 20.04.2020 21:29:47 | 14,400 | 47f7e619af218366b7ffbef00afa091ebacc0a6a | [native]
Corresponding bugfix in `MultimediaModal` to avoid starting values at 0 and then dividing by them | [
{
"change_type": "MODIFY",
"old_path": "native/ios/Podfile.lock",
"new_path": "native/ios/Podfile.lock",
"diff": "@@ -311,7 +311,7 @@ PODS:\n- React\n- RNKeychain (4.0.1):\n- React\n- - RNReanimated (1.3.0):\n+ - RNReanimated (1.8.0):\n- React\n- RNScreens (1.0.0-alpha.17):\n- React\n@@ -638,7 +638,7 @@ SPEC CHECKSUMS:\nRNFS: 54da03c2b7d862c42ea3ca8c7f86f892760a535a\nRNGestureHandler: 8f09cd560f8d533eb36da5a6c5a843af9f056b38\nRNKeychain: 45dbd50d1ac4bd42c3740f76ffb135abf05746d0\n- RNReanimated: 6abbbae2e5e72609d85aabd92a982a94566885f1\n+ RNReanimated: 955cf4068714003d2f1a6e2bae3fb1118f359aff\nRNScreens: 000c9e6e31c9a483688943155107e4ca9394d37a\nRNVectorIcons: 0bb4def82230be1333ddaeee9fcba45f0b288ed4\nSDWebImage: d9ea4959d99c52276dfada481987018fcaea3d58\n"
},
{
"change_type": "MODIFY",
"old_path": "native/media/multimedia-modal.react.js",
"new_path": "native/media/multimedia-modal.react.js",
"diff": "@@ -56,6 +56,7 @@ import {\n} from '../utils/animation-utils';\nimport { intentionalSaveImage } from './save-image';\n+/* eslint-disable import/no-named-as-default-member */\nconst {\nValue,\nClock,\n@@ -87,6 +88,7 @@ const {\ntiming,\ndecay,\n} = Animated;\n+/* eslint-enable import/no-named-as-default-member */\nfunction scaleDelta(value: Value, gestureActive: Value) {\nconst diffThisFrame = new Value(1);\n@@ -239,12 +241,12 @@ class MultimediaModal extends React.PureComponent<Props, State> {\nsaveButtonHeight = new Value(0);\nactionLinksLastState = new Value(1);\n- centerX = new Value(0);\n- centerY = new Value(0);\n- screenWidth = new Value(0);\n- screenHeight = new Value(0);\n- imageWidth = new Value(0);\n- imageHeight = new Value(0);\n+ centerX: Value;\n+ centerY: Value;\n+ screenWidth: Value;\n+ screenHeight: Value;\n+ imageWidth: Value;\n+ imageHeight: Value;\npinchHandler = React.createRef();\npanHandler = React.createRef();\n@@ -930,15 +932,41 @@ class MultimediaModal extends React.PureComponent<Props, State> {\nupdateDimensions() {\nconst { width: screenWidth, height: screenHeight } = this.screenDimensions;\n+ if (this.screenWidth) {\nthis.screenWidth.setValue(screenWidth);\n+ } else {\n+ this.screenWidth = new Value(screenWidth);\n+ }\n+ if (this.screenHeight) {\nthis.screenHeight.setValue(screenHeight);\n+ } else {\n+ this.screenHeight = new Value(screenHeight);\n+ }\n- this.centerX.setValue(screenWidth / 2);\n- this.centerY.setValue(screenHeight / 2 + this.props.contentVerticalOffset);\n+ const centerX = screenWidth / 2;\n+ const centerY = screenHeight / 2 + this.props.contentVerticalOffset;\n+ if (this.centerX) {\n+ this.centerX.setValue(centerX);\n+ } else {\n+ this.centerX = new Value(centerX);\n+ }\n+ if (this.centerY) {\n+ this.centerY.setValue(centerY);\n+ } else {\n+ this.centerY = new Value(centerY);\n+ }\nconst { width, height } = this.imageDimensions;\n+ if (this.imageWidth) {\nthis.imageWidth.setValue(width);\n+ } else {\n+ this.imageWidth = new Value(width);\n+ }\n+ if (this.imageHeight) {\nthis.imageHeight.setValue(height);\n+ } else {\n+ this.imageHeight = new Value(height);\n+ }\n}\ncomponentDidMount() {\n@@ -1161,7 +1189,9 @@ class MultimediaModal extends React.PureComponent<Props, State> {\n}\n};\n- closeButtonRef = (closeButton: ?React.ElementRef<typeof TouchableOpacity>) => {\n+ closeButtonRef = (\n+ closeButton: ?React.ElementRef<typeof TouchableOpacity>,\n+ ) => {\nthis.closeButton = (closeButton: any);\n};\n"
},
{
"change_type": "MODIFY",
"old_path": "native/package.json",
"new_path": "native/package.json",
"diff": "\"react-native-onepassword\": \"git+https://git@github.com/DriveWealth/react-native-onepassword.git#aed794d8c6f0f2560b62a0012449abf6f1b3576c\",\n\"react-native-orientation-locker\": \"^1.1.6\",\n\"react-native-progress\": \"^4.0.3\",\n- \"react-native-reanimated\": \"^1.3.0\",\n+ \"react-native-reanimated\": \"^1.8.0\",\n\"react-native-screens\": \"1.0.0-alpha.17\",\n\"react-native-splash-screen\": \"^3.2.0\",\n\"react-native-unimodules\": \"^0.9.0\",\n"
},
{
"change_type": "MODIFY",
"old_path": "yarn.lock",
"new_path": "yarn.lock",
"diff": "@@ -11693,10 +11693,12 @@ react-native-progress@^4.0.3:\n\"@react-native-community/art\" \"^1.0.3\"\nprop-types \"^15.7.2\"\n-react-native-reanimated@^1.3.0:\n- version \"1.3.0\"\n- resolved \"https://registry.yarnpkg.com/react-native-reanimated/-/react-native-reanimated-1.3.0.tgz#581cdb0bd1ff05e7304b116af712ded0c7665ede\"\n- integrity sha512-KFno6D0q09kx71IDuPa4qeC1t1msALsCMuli3/EN3YDf8XoM2CG53yzhVHMFtmcW0IUCySugHgxQiuT5BzwOPA==\n+react-native-reanimated@^1.8.0:\n+ version \"1.8.0\"\n+ resolved \"https://registry.yarnpkg.com/react-native-reanimated/-/react-native-reanimated-1.8.0.tgz#0b5719b20c1fed9aaf8afd9a12e21c9bd46ee428\"\n+ integrity sha512-vGTt94lE5fsZmfMwERWFIsCr5LHsyllOESeNvlKryLgAg7h4cnJ5XSmVSy4L3qogdgFYCL6HEgY+s7tQmKXiiQ==\n+ dependencies:\n+ fbjs \"^1.0.0\"\nreact-native-safe-area-view@^0.14.1, react-native-safe-area-view@^0.14.6:\nversion \"0.14.8\"\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] react-native-reanimated@1.8.0
Corresponding bugfix in `MultimediaModal` to avoid starting values at 0 and then dividing by them |
129,187 | 20.04.2020 22:24:29 | 14,400 | c2ca0318f933c566e1e5e99f5c1c185f44cd91cc | [native] Consider scrollBlockingChatModal anywhere in stack in scrollBlockingChatModalsClosedSelector | [
{
"change_type": "MODIFY",
"old_path": "native/navigation/nav-selectors.js",
"new_path": "native/navigation/nav-selectors.js",
"diff": "@@ -109,8 +109,13 @@ const scrollBlockingChatModalsClosedSelector: (\nreturn true;\n}\nconst appRoute = assertNavigationRouteNotLeafNode(currentRootSubroute);\n- const currentAppSubroute = appRoute.routes[appRoute.index];\n- return !scrollBlockingChatModals.includes(currentAppSubroute.routeName);\n+ for (let i = appRoute.index; i >= 0; i--) {\n+ const route = appRoute.routes[i];\n+ if (scrollBlockingChatModals.includes(route.routeName)) {\n+ return false;\n+ }\n+ }\n+ return true;\n},\n);\n@@ -142,7 +147,7 @@ const backgroundIsDarkSelector: (\n},\n);\n-const overlayTransitioningSelector: (\n+const overlayModalClosingSelector: (\ncontext: ?NavContextType,\n) => boolean = createSelector(\n(context: ?NavContextType) => context && context.state,\n@@ -282,7 +287,7 @@ export {\ncreateActiveTabSelector,\nscrollBlockingChatModalsClosedSelector,\nbackgroundIsDarkSelector,\n- overlayTransitioningSelector,\n+ overlayModalClosingSelector,\nactiveThreadSelector,\nactiveMessageListSelector,\nuseActiveThread,\n"
},
{
"change_type": "MODIFY",
"old_path": "native/navigation/scroll-view-modal-state-container.react.js",
"new_path": "native/navigation/scroll-view-modal-state-container.react.js",
"diff": "@@ -5,7 +5,7 @@ import PropTypes from 'prop-types';\nimport {\nscrollBlockingChatModalsClosedSelector,\n- overlayTransitioningSelector,\n+ overlayModalClosingSelector,\n} from './nav-selectors';\nimport {\nScrollViewModalContext,\n@@ -82,6 +82,6 @@ export default connectNav((context: ?NavContextType) => {\nreturn {\nscrollBlockingModalsClosed,\nscrollBlockingModalsGone:\n- scrollBlockingModalsClosed && !overlayTransitioningSelector(context),\n+ scrollBlockingModalsClosed && !overlayModalClosingSelector(context),\n};\n})(ScrollViewModalStateContainer);\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Consider scrollBlockingChatModal anywhere in stack in scrollBlockingChatModalsClosedSelector |
129,187 | 20.04.2020 22:25:04 | 14,400 | f047e37fdcb01c9bbaf06edb7f9076b2aa433d86 | [native] Handle ActionResultModal after MultimediaModal dismiss in MultimediaMessageMultimedia | [
{
"change_type": "MODIFY",
"old_path": "native/chat/multimedia-message-multimedia.react.js",
"new_path": "native/chat/multimedia-message-multimedia.react.js",
"diff": "@@ -44,6 +44,32 @@ import InlineMultimedia from './inline-multimedia.react';\nimport { multimediaTooltipHeight } from './multimedia-tooltip-modal.react';\nimport { type Colors, colorsPropType, colorsSelector } from '../themes/colors';\n+/* eslint-disable import/no-named-as-default-member */\n+const {\n+ Value,\n+ set,\n+ block,\n+ cond,\n+ eq,\n+ greaterThan,\n+ and,\n+ sub,\n+ multiply,\n+ interpolate,\n+ Extrapolate,\n+} = Animated;\n+/* eslint-enable import/no-named-as-default-member */\n+\n+function overlayJustCleared(overlayPosition: Value) {\n+ const justCleared = new Value(0);\n+ const prevValue = new Value(0);\n+ return [\n+ set(justCleared, and(greaterThan(prevValue, 0), eq(overlayPosition, 0))),\n+ set(prevValue, overlayPosition),\n+ justCleared,\n+ ];\n+}\n+\ntype Props = {|\nmediaInfo: MediaInfo,\nitem: ChatMultimediaMessageInfoItem,\n@@ -51,7 +77,7 @@ type Props = {|\nverticalBounds: ?VerticalBounds,\nverticalOffset: number,\nstyle: ImageStyle,\n- overlayPosition: ?Animated.Value,\n+ overlayPosition: ?Value,\npostInProgress: boolean,\npendingUpload: ?PendingMultimediaUpload,\nmessageFocused: boolean,\n@@ -63,18 +89,14 @@ type Props = {|\n// withKeyboardState\nkeyboardState: ?KeyboardState,\n|};\n-type State = {|\n- hidden: boolean,\n- opacity: ?Animated.Value,\n-|};\n-class MultimediaMessageMultimedia extends React.PureComponent<Props, State> {\n+class MultimediaMessageMultimedia extends React.PureComponent<Props> {\nstatic propTypes = {\nmediaInfo: mediaInfoPropType.isRequired,\nitem: chatMessageItemPropType.isRequired,\nnavigation: messageListNavPropType.isRequired,\nverticalBounds: verticalBoundsPropType,\nverticalOffset: PropTypes.number.isRequired,\n- overlayPosition: PropTypes.instanceOf(Animated.Value),\n+ overlayPosition: PropTypes.instanceOf(Value),\npostInProgress: PropTypes.bool.isRequired,\npendingUpload: pendingMultimediaUploadPropType,\nmessageFocused: PropTypes.bool.isRequired,\n@@ -85,21 +107,12 @@ class MultimediaMessageMultimedia extends React.PureComponent<Props, State> {\n};\nview: ?View;\nclickable = true;\n+ hidden = new Value(0);\n+ opacity: Value;\nconstructor(props: Props) {\nsuper(props);\n- this.state = {\n- hidden: false,\n- opacity: this.getOpacity(),\n- };\n- }\n-\n- static getDerivedStateFromProps(props: Props, state: State) {\n- const scrollIsDisabled = MultimediaMessageMultimedia.scrollDisabled(props);\n- if (!scrollIsDisabled && state.hidden) {\n- return { hidden: false };\n- }\n- return null;\n+ this.getOpacity();\n}\ngetOpacity() {\n@@ -107,11 +120,20 @@ class MultimediaMessageMultimedia extends React.PureComponent<Props, State> {\nif (!overlayPosition) {\nreturn null;\n}\n- return Animated.interpolate(this.props.overlayPosition, {\n+ this.opacity = block([\n+ cond(overlayJustCleared(overlayPosition), set(this.hidden, 0)),\n+ sub(\n+ 1,\n+ multiply(\n+ this.hidden,\n+ interpolate(overlayPosition, {\ninputRange: [0.1, 0.11],\n- outputRange: [1, 0],\n- extrapolate: Animated.Extrapolate.CLAMP,\n- });\n+ outputRange: [0, 1],\n+ extrapolate: Extrapolate.CLAMP,\n+ }),\n+ ),\n+ ),\n+ ]);\n}\nstatic scrollDisabled(props: Props) {\n@@ -123,7 +145,7 @@ class MultimediaMessageMultimedia extends React.PureComponent<Props, State> {\ncomponentDidUpdate(prevProps: Props) {\nif (this.props.overlayPosition !== prevProps.overlayPosition) {\n- this.setState({ opacity: this.getOpacity() });\n+ this.getOpacity();\n}\nconst scrollIsDisabled = MultimediaMessageMultimedia.scrollDisabled(\n@@ -134,15 +156,13 @@ class MultimediaMessageMultimedia extends React.PureComponent<Props, State> {\n);\nif (!scrollIsDisabled && scrollWasDisabled) {\nthis.clickable = true;\n+ this.hidden.setValue(0);\n}\n}\nrender() {\n- const wrapperStyles = [styles.container];\n- if (this.state.hidden && this.state.opacity) {\n- wrapperStyles.push({ opacity: this.state.opacity });\n- }\n- wrapperStyles.push(this.props.style);\n+ const { opacity } = this;\n+ const wrapperStyles = [styles.container, { opacity }, this.props.style];\nconst { mediaInfo, pendingUpload, postInProgress } = this.props;\nreturn (\n@@ -201,7 +221,7 @@ class MultimediaMessageMultimedia extends React.PureComponent<Props, State> {\nverticalBounds,\n},\n});\n- this.setState({ hidden: true });\n+ this.hidden.setValue(1);\n});\n};\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Handle ActionResultModal after MultimediaModal dismiss in MultimediaMessageMultimedia |
129,187 | 20.04.2020 22:44:21 | 14,400 | baf51ce07f7f2fd20a118f1183171496424dde0a | [native] Fix tap gestures in MultimediaModal on Android | [
{
"change_type": "MODIFY",
"old_path": "native/media/multimedia-modal.react.js",
"new_path": "native/media/multimedia-modal.react.js",
"diff": "@@ -258,12 +258,8 @@ class MultimediaModal extends React.PureComponent<Props, State> {\nthis.singleTapHandler,\nthis.doubleTapHandler,\n];\n- beforeDoubleTapRefs = [this.pinchHandler, this.panHandler];\n- beforeSingleTapRefs = [\n- this.pinchHandler,\n- this.panHandler,\n- this.doubleTapHandler,\n- ];\n+ beforeDoubleTapRefs;\n+ beforeSingleTapRefs;\npinchEvent;\npanEvent;\n@@ -525,6 +521,15 @@ class MultimediaModal extends React.PureComponent<Props, State> {\nbuttonOpacity,\nupdatedActionLinksOpacity,\n);\n+\n+ this.beforeDoubleTapRefs = Platform.select({\n+ android: [],\n+ default: [this.pinchHandler, this.panHandler],\n+ });\n+ this.beforeSingleTapRefs = [\n+ ...this.beforeDoubleTapRefs,\n+ this.doubleTapHandler,\n+ ];\n}\n// How much space do we have to pan the image horizontally?\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Fix tap gestures in MultimediaModal on Android |
129,187 | 20.04.2020 23:29:49 | 14,400 | 94f82b19f54bcb803b7cf7e94d98e4f80ee9859f | [native] Fetch final URI in final processMedia check | [
{
"change_type": "MODIFY",
"old_path": "native/media/media-utils.js",
"new_path": "native/media/media-utils.js",
"diff": "@@ -177,7 +177,7 @@ async function processMediaMission(\nconst {\nsteps: finalFileInfoSteps,\nresult: finalFileInfoResult,\n- } = await fetchFileInfo(mediaInput.uri, mediaInput.mediaNativeID, {\n+ } = await fetchFileInfo(uploadURI, mediaInput.mediaNativeID, {\nmime: true,\n});\nsteps.push(...finalFileInfoSteps);\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Fetch final URI in final processMedia check |
129,187 | 21.04.2020 13:05:25 | 14,400 | dece3045e1e5aeaee7916a09f7db4d8e54137262 | Support ArrayBuffer in fileInfoFromData | [
{
"change_type": "MODIFY",
"old_path": "lib/utils/file-utils.js",
"new_path": "lib/utils/file-utils.js",
"diff": "@@ -30,7 +30,9 @@ export type FileDataInfo = {|\nmime: ?string,\nmediaType: ?MediaType,\n|};\n-function fileInfoFromData(data: Uint8Array | Buffer): FileDataInfo {\n+function fileInfoFromData(\n+ data: Uint8Array | Buffer | ArrayBuffer,\n+): FileDataInfo {\nconst fileTypeResult = fileType(data);\nif (!fileTypeResult) {\nreturn { mime: null, mediaType: null };\n"
},
{
"change_type": "MODIFY",
"old_path": "web/utils/media-utils.js",
"new_path": "web/utils/media-utils.js",
"diff": "@@ -106,7 +106,7 @@ async function validateFile(\nprocessFile(file, exifRotate),\n]);\n- const { mime, mediaType } = fileInfoFromData(new Uint8Array(arrayBuffer));\n+ const { mime, mediaType } = fileInfoFromData(arrayBuffer);\nif (!mime || !mediaType || !allowedMimeTypes.has(mime)) {\nreturn null;\n}\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | Support ArrayBuffer in fileInfoFromData |
129,187 | 21.04.2020 15:04:31 | 14,400 | 27fb2e89ab8ea3a8e79a68dc128270584e8c5aea | [web] Unset upload if it fails | [
{
"change_type": "MODIFY",
"old_path": "web/chat/chat-input-bar.react.js",
"new_path": "web/chat/chat-input-bar.react.js",
"diff": "@@ -301,8 +301,15 @@ class ChatInputBar extends React.PureComponent<Props> {\n}\n};\n- onMultimediaFileChange = (event: SyntheticInputEvent<HTMLInputElement>) => {\n- this.props.chatInputState.appendFiles([...event.target.files]);\n+ onMultimediaFileChange = async (\n+ event: SyntheticInputEvent<HTMLInputElement>,\n+ ) => {\n+ const result = await this.props.chatInputState.appendFiles([\n+ ...event.target.files,\n+ ]);\n+ if (!result && this.multimediaInput) {\n+ this.multimediaInput.value = '';\n+ }\n};\nonClickJoin = (event: SyntheticEvent<HTMLAnchorElement>) => {\n"
},
{
"change_type": "MODIFY",
"old_path": "web/chat/chat-input-state-container.react.js",
"new_path": "web/chat/chat-input-state-container.react.js",
"diff": "@@ -354,7 +354,10 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\n),\n);\n- async appendFiles(threadID: string, files: $ReadOnlyArray<File>) {\n+ async appendFiles(\n+ threadID: string,\n+ files: $ReadOnlyArray<File>,\n+ ): Promise<boolean> {\nconst { setModal } = this.props;\nlet validationResults;\n@@ -364,19 +367,19 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\n);\n} catch (e) {\nsetModal(<InvalidUploadModal setModal={setModal} />);\n- return;\n+ return false;\n}\nconst newUploads = [];\nfor (let result of validationResults) {\nif (!result) {\nsetModal(<InvalidUploadModal setModal={setModal} />);\n- return;\n+ return false;\n}\nconst { file, mediaType, dimensions } = result;\nif (!dimensions) {\nsetModal(<InvalidUploadModal setModal={setModal} />);\n- return;\n+ return false;\n}\nnewUploads.push({\nlocalID: `localUpload${nextLocalUploadID++}`,\n@@ -394,7 +397,7 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\n}\nif (newUploads.length === 0) {\nsetModal(<InvalidUploadModal setModal={setModal} />);\n- return;\n+ return false;\n}\nconst newUploadsObject = _keyBy('localID')(newUploads);\nthis.setState(\n@@ -412,6 +415,7 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\n},\n() => this.uploadFiles(threadID, newUploads),\n);\n+ return true;\n}\nuploadFiles(\n"
},
{
"change_type": "MODIFY",
"old_path": "web/chat/chat-input-state.js",
"new_path": "web/chat/chat-input-state.js",
"diff": "@@ -51,7 +51,7 @@ export type ChatInputState = {|\n[messageID: string]: $ReadOnlyArray<PendingMultimediaUpload>,\n},\ndraft: string,\n- appendFiles: (files: $ReadOnlyArray<File>) => Promise<void>,\n+ appendFiles: (files: $ReadOnlyArray<File>) => Promise<boolean>,\ncancelPendingUpload: (localUploadID: string) => void,\nsendTextMessage: (messageInfo: RawTextMessageInfo) => void,\ncreateMultimediaMessage: (localID?: number) => void,\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [web] Unset upload if it fails |
129,187 | 21.04.2020 16:30:12 | 14,400 | 6c345059b9f5c3a39812b414d765f427248375dd | [native] Fix MediaGalleryKeyboard eslint errors
Introduced by `react-native-reanimated` upgrade | [
{
"change_type": "MODIFY",
"old_path": "native/media/media-gallery-keyboard.react.js",
"new_path": "native/media/media-gallery-keyboard.react.js",
"diff": "@@ -77,6 +77,7 @@ class MediaGalleryKeyboard extends React.PureComponent<Props, State> {\nfetchingPhotos = false;\nflatList: ?FlatList<MediaLibrarySelection>;\nviewableIndices: number[] = [];\n+ // eslint-disable-next-line import/no-named-as-default-member\nqueueModeProgress = new Animated.Value(0);\nsendButtonStyle: ViewStyle;\nmediaSelected = false;\n@@ -122,11 +123,13 @@ class MediaGalleryKeyboard extends React.PureComponent<Props, State> {\nconst { queuedMediaURIs } = this.state;\nconst prevQueuedMediaURIs = prevState.queuedMediaURIs;\nif (queuedMediaURIs && !prevQueuedMediaURIs) {\n+ // eslint-disable-next-line import/no-named-as-default-member\nAnimated.timing(this.queueModeProgress, {\n...animationSpec,\ntoValue: 1,\n}).start();\n} else if (!queuedMediaURIs && prevQueuedMediaURIs) {\n+ // eslint-disable-next-line import/no-named-as-default-member\nAnimated.timing(this.queueModeProgress, {\n...animationSpec,\ntoValue: 0,\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Fix MediaGalleryKeyboard eslint errors
Introduced by `react-native-reanimated` upgrade |
129,187 | 21.04.2020 16:30:38 | 14,400 | bfbaa382f02e73935a6618cedac5c96401a54962 | [native] Temporary expo-media-library changes for release
Don't include videos and sort by creation time | [
{
"change_type": "MODIFY",
"old_path": "native/media/media-gallery-keyboard.react.js",
"new_path": "native/media/media-gallery-keyboard.react.js",
"diff": "@@ -212,8 +212,8 @@ class MediaGalleryKeyboard extends React.PureComponent<Props, State> {\n} = await MediaLibrary.getAssetsAsync({\nfirst: 20,\nafter,\n- mediaType: [MediaLibrary.MediaType.photo, MediaLibrary.MediaType.video],\n- sortBy: [MediaLibrary.SortBy.modificationTime],\n+ mediaType: [MediaLibrary.MediaType.photo],\n+ sortBy: [MediaLibrary.SortBy.creationTime],\n});\nlet firstRemoved = false,\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Temporary expo-media-library changes for release
Don't include videos and sort by creation time |
129,187 | 21.04.2020 16:33:18 | 14,400 | 8c6079a0145cd0f4475b75a5848f77d4ee2ad6e9 | [native] codeVersion -> 48 | [
{
"change_type": "MODIFY",
"old_path": "native/android/app/build.gradle",
"new_path": "native/android/app/build.gradle",
"diff": "@@ -131,8 +131,8 @@ android {\napplicationId \"org.squadcal\"\nminSdkVersion rootProject.ext.minSdkVersion\ntargetSdkVersion rootProject.ext.targetSdkVersion\n- versionCode 47\n- versionName \"0.0.47\"\n+ versionCode 48\n+ versionName \"0.0.48\"\nmissingDimensionStrategy 'react-native-camera', 'general'\nmultiDexEnabled true\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "native/ios/SquadCal/Info.debug.plist",
"new_path": "native/ios/SquadCal/Info.debug.plist",
"diff": "<key>CFBundlePackageType</key>\n<string>APPL</string>\n<key>CFBundleShortVersionString</key>\n- <string>0.0.47</string>\n+ <string>0.0.48</string>\n<key>CFBundleSignature</key>\n<string>????</string>\n<key>CFBundleVersion</key>\n- <string>47</string>\n+ <string>48</string>\n<key>LSApplicationQueriesSchemes</key>\n<array>\n<string>org-appextension-feature-password-management</string>\n"
},
{
"change_type": "MODIFY",
"old_path": "native/ios/SquadCal/Info.release.plist",
"new_path": "native/ios/SquadCal/Info.release.plist",
"diff": "<key>CFBundlePackageType</key>\n<string>APPL</string>\n<key>CFBundleShortVersionString</key>\n- <string>0.0.47</string>\n+ <string>0.0.48</string>\n<key>CFBundleSignature</key>\n<string>????</string>\n<key>CFBundleVersion</key>\n- <string>47</string>\n+ <string>48</string>\n<key>LSApplicationQueriesSchemes</key>\n<array>\n<string>org-appextension-feature-password-management</string>\n"
},
{
"change_type": "MODIFY",
"old_path": "native/redux/persist.js",
"new_path": "native/redux/persist.js",
"diff": "@@ -178,7 +178,7 @@ const persistConfig = {\ntimeout: __DEV__ ? 0 : undefined,\n};\n-const codeVersion = 47;\n+const codeVersion = 48;\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 -> 48 |
129,187 | 22.04.2020 11:44:34 | 14,400 | dcbd73ddf0043097a1a602fdaf3c11e1e254d974 | Measure photo_capture totalTime/userTime from selection instead of capture | [
{
"change_type": "MODIFY",
"old_path": "lib/types/media-types.js",
"new_path": "lib/types/media-types.js",
"diff": "@@ -172,6 +172,7 @@ export type PhotoCapture = {|\ndimensions: Dimensions,\nfilename: string,\nuri: string,\n+ captureTime: number, // ms timestamp\nselectTime: number, // ms timestamp\nsendTime: number, // ms timestamp\nretries: number,\n@@ -307,6 +308,7 @@ export const mediaMissionPropType = PropTypes.shape({\ndimensions: dimensionsPropType.isRequired,\nfilename: PropTypes.string.isRequired,\nuri: PropTypes.string.isRequired,\n+ captureTime: PropTypes.number.isRequired,\nselectTime: PropTypes.number.isRequired,\nsendTime: PropTypes.number.isRequired,\nretries: PropTypes.number.isRequired,\n"
},
{
"change_type": "MODIFY",
"old_path": "native/media/camera-modal.react.js",
"new_path": "native/media/camera-modal.react.js",
"diff": "@@ -64,6 +64,7 @@ import { colors } from '../themes/colors';\nimport { saveImage } from './save-image';\nimport SendMediaButton from './send-media-button.react';\n+/* eslint-disable import/no-named-as-default-member */\nconst {\nValue,\nClock,\n@@ -92,6 +93,8 @@ const {\nspring,\nSpringUtils,\n} = Animated;\n+/* eslint-enable import/no-named-as-default-member */\n+\nconst maxZoom = 16;\nconst zoomUpdateFactor = (() => {\nif (Platform.OS === 'ios') {\n@@ -105,6 +108,7 @@ const zoomUpdateFactor = (() => {\n}\nreturn 0.03;\n})();\n+\nconst permissionRationale = {\ntitle: 'Access Your Camera',\nmessage: 'Requesting access to your device camera',\n@@ -928,8 +932,9 @@ class CameraModal extends React.PureComponent<Props, State> {\ndimensions: { width, height },\nfilename,\ntime: now - startTime,\n- selectTime: now,\n- sendTime: now,\n+ captureTime: now,\n+ selectTime: 0,\n+ sendTime: 0,\nretries: 0,\n};\n@@ -945,13 +950,23 @@ class CameraModal extends React.PureComponent<Props, State> {\nif (!pendingPhotoCapture) {\nreturn;\n}\n+\n+ const now = Date.now();\n+ const capture = {\n+ ...pendingPhotoCapture,\n+ selectTime: now,\n+ sendTime: now,\n+ };\n+\n+ this.close();\n+\nconst { inputState } = this.props;\ninvariant(inputState, 'inputState should be set');\n- this.close();\ninputState.sendMultimediaMessage(\nthis.props.navigation.state.params.threadID,\n- [pendingPhotoCapture],\n+ [capture],\n);\n+\nsaveImage({ uri: pendingPhotoCapture.uri, type: 'photo' });\n};\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | Measure photo_capture totalTime/userTime from selection instead of capture |
129,187 | 22.04.2020 14:40:02 | 14,400 | b1604abbb93e79a77ebbd5a3b99c681335956bd3 | getImageProcessingPlan takes object as input | [
{
"change_type": "MODIFY",
"old_path": "lib/utils/image-utils.js",
"new_path": "lib/utils/image-utils.js",
"diff": "@@ -11,30 +11,39 @@ const convertToPNG = new Set([\n'image/bmp',\n]);\n-type ImageProcessingPlan = {|\n+type Input = {|\n+ inputMIME: string,\n+ inputDimensions: Dimensions, // post EXIF orientation\n+ inputFileSize: number, // in bytes\n+ inputOrientation: ?number,\n+|};\n+type Plan = {|\ntargetMIME: 'image/png' | 'image/jpeg',\ncompressionRatio: number,\nfitInside: ?Dimensions,\nshouldRotate: boolean,\n|};\n-function getImageProcessingPlan(\n- mime: string,\n- dimensions: Dimensions, // post EXIF orientation\n- fileSize: number, // in bytes\n- orientation: ?number,\n-): ?ImageProcessingPlan {\n- const unsupportedMIME = mime !== 'image/png' && mime !== 'image/jpeg';\n- const needsRotation = !!orientation && orientation > 1;\n+function getImageProcessingPlan(input: Input): ?Plan {\n+ const {\n+ inputMIME,\n+ inputDimensions: { width: inputWidth, height: inputHeight },\n+ inputFileSize,\n+ inputOrientation,\n+ } = input;\n+\n+ const unsupportedMIME =\n+ inputMIME !== 'image/png' && inputMIME !== 'image/jpeg';\n+ const needsRotation = !!inputOrientation && inputOrientation > 1;\nconst needsCompression =\n- fileSize > 5e6 || (unsupportedMIME && fileSize > 3e6);\n+ inputFileSize > 5e6 || (unsupportedMIME && inputFileSize > 3e6);\nconst needsResize =\n- fileSize > 5e5 && (dimensions.width > 3000 || dimensions.height > 2000);\n+ inputFileSize > 5e5 && (inputWidth > 3000 || inputHeight > 2000);\nif (!unsupportedMIME && !needsRotation && !needsCompression && !needsResize) {\nreturn null;\n}\n- const targetMIME = convertToPNG.has(mime) ? 'image/png' : 'image/jpeg';\n+ const targetMIME = convertToPNG.has(inputMIME) ? 'image/png' : 'image/jpeg';\nlet compressionRatio = 1;\nif (targetMIME === 'image/jpeg') {\nif (needsCompression) {\n"
},
{
"change_type": "MODIFY",
"old_path": "native/media/image-utils.js",
"new_path": "native/media/image-utils.js",
"diff": "@@ -33,7 +33,12 @@ async function processImage(\nlet { uri, dimensions, mime } = input;\nconst { fileSize, orientation } = input;\n- const plan = getImageProcessingPlan(mime, dimensions, fileSize, orientation);\n+ const plan = getImageProcessingPlan({\n+ inputMIME: mime,\n+ inputDimensions: dimensions,\n+ inputFileSize: fileSize,\n+ inputOrientation: orientation,\n+ });\nif (!plan) {\nreturn {\nsteps,\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/uploads/media-utils.js",
"new_path": "server/src/uploads/media-utils.js",
"diff": "@@ -68,12 +68,12 @@ async function validateAndConvert(\n}\n}\n- const plan = getImageProcessingPlan(\n- mime,\n- initialDimensions,\n- size,\n- metadata.orientation,\n- );\n+ const plan = getImageProcessingPlan({\n+ inputMIME: mime,\n+ inputDimensions: initialDimensions,\n+ inputFileSize: size,\n+ inputOrientation: metadata.orientation,\n+ });\nif (!plan) {\nconst name = readableFilename(initialName, mime);\ninvariant(name, `should be able to construct filename for ${mime}`);\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | getImageProcessingPlan takes object as input |
129,187 | 22.04.2020 15:36:00 | 14,400 | 58325478fbb2dccae982cc06e0a90151ca395839 | [lib] Fix VideoProbeMediaMissionStep format property | [
{
"change_type": "MODIFY",
"old_path": "lib/types/media-types.js",
"new_path": "lib/types/media-types.js",
"diff": "@@ -102,7 +102,7 @@ export type VideoProbeMediaMissionStep = {|\npath: string,\next: ?string,\ncodec: ?string,\n- format: ?string,\n+ format: ?$ReadOnlyArray<string>,\n|};\nexport type ReadFileHeaderMediaMissionStep = {|\n@@ -356,7 +356,7 @@ export const mediaMissionPropType = PropTypes.shape({\npath: PropTypes.string.isRequired,\next: PropTypes.string,\ncodec: PropTypes.string,\n- format: PropTypes.string,\n+ format: PropTypes.arrayOf(PropTypes.string),\n}),\nPropTypes.shape({\nstep: PropTypes.oneOf(['video_ffmpeg_transcode']).isRequired,\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [lib] Fix VideoProbeMediaMissionStep format property |
129,187 | 22.04.2020 15:36:57 | 14,400 | 0c12c225941bfc89ff08f94b097b50844e8fa7dc | [native] Include x264/x265 in Android ffmpeg build
iOS doesn't need it because it has hardware-accelerated support via VideoToolbox | [
{
"change_type": "MODIFY",
"old_path": "native/android/app/build.gradle",
"new_path": "native/android/app/build.gradle",
"diff": "@@ -173,6 +173,13 @@ android {\n}\n}\n+\n+ packagingOptions {\n+ pickFirst 'lib/x86/libc++_shared.so'\n+ pickFirst 'lib/x86_64/libc++_shared.so'\n+ pickFirst 'lib/armeabi-v7a/libc++_shared.so'\n+ pickFirst 'lib/arm64-v8a/libc++_shared.so'\n+ }\n}\napply from: '../../../node_modules/react-native-unimodules/gradle.groovy'\n"
},
{
"change_type": "MODIFY",
"old_path": "native/android/build.gradle",
"new_path": "native/android/build.gradle",
"diff": "@@ -22,7 +22,7 @@ buildscript {\n}\next {\n- reactNativeFFmpegPackage = \"min-lts\"\n+ reactNativeFFmpegPackage = \"min-gpl-lts\"\n}\nallprojects {\n"
},
{
"change_type": "MODIFY",
"old_path": "native/media/video-utils.js",
"new_path": "native/media/video-utils.js",
"diff": "@@ -52,13 +52,12 @@ async function processVideo(\nios: filesystem.TemporaryDirectoryPath,\ndefault: `${filesystem.TemporaryDirectoryPath}/`,\n}),\n- // This tells ffmpeg to use the hardware-accelerated encoders. Since we're\n- // using the min-lts builds of react-native-ffmpeg we actually don't need\n- // to specify this, but we would if we were using any build that provides\n- // alternate encoders (for instance, min-gpl-lts)\n+ // We want ffmpeg to use hardware-accelerated encoders. On iOS we can do\n+ // this using VideoToolbox, but ffmpeg on Android is still missing\n+ // MediaCodec encoding support: https://trac.ffmpeg.org/ticket/6407\noutputCodec: Platform.select({\nios: 'h264_videotoolbox',\n- android: 'h264_mediacodec',\n+ //android: 'h264_mediacodec',\ndefault: 'h264',\n}),\n});\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Include x264/x265 in Android ffmpeg build
iOS doesn't need it because it has hardware-accelerated support via VideoToolbox |
129,187 | 22.04.2020 15:39:45 | 14,400 | bc09eb68122d4171ad36e50ef7a19df07c2a9512 | [lib] Cap ffmpeg transcode outputPath to 255 chars | [
{
"change_type": "MODIFY",
"old_path": "lib/utils/video-utils.js",
"new_path": "lib/utils/video-utils.js",
"diff": "@@ -28,9 +28,11 @@ function getVideoProcessingPlan(input: Input): ?Plan {\nreturn null;\n}\n- const mp4Name = replaceExtension(inputFilename, 'mp4');\n- const uuid = getUUID();\n- const outputPath = `${outputDirectory}transcode.${uuid}.${mp4Name}`;\n+ const outputFilename = replaceExtension(\n+ `transcode.${getUUID()}.${inputFilename}`,\n+ 'mp4',\n+ );\n+ const outputPath = `${outputDirectory}${outputFilename}`;\nconst ffmpegCommand = `-i ${inputPath} -c:v ${outputCodec} -c:a copy ${outputPath}`;\nreturn { outputPath, ffmpegCommand };\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [lib] Cap ffmpeg transcode outputPath to 255 chars |
129,187 | 22.04.2020 17:06:18 | 14,400 | 58aacd4bad7f6cd257e96a245dbb0642376ae49f | [native] ffmpeg class | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "native/media/ffmpeg.js",
"diff": "+// @flow\n+\n+import { RNFFmpeg, RNFFprobe, RNFFmpegConfig } from 'react-native-ffmpeg';\n+\n+if (!__DEV__) {\n+ RNFFmpegConfig.disableLogs();\n+ RNFFmpegConfig.disableStatistics();\n+}\n+\n+class FFmpeg {\n+ async getVideoFormat(path: string) {\n+ const info = await RNFFprobe.getMediaInformation(path);\n+ const codec = FFmpeg.getVideoCodec(info);\n+ const format = info.format.split(',');\n+ return { codec, format };\n+ }\n+\n+ static getVideoCodec(info: Object): ?string {\n+ if (!info.streams) {\n+ return null;\n+ }\n+ for (let stream of info.streams) {\n+ if (stream.type === 'video') {\n+ return stream.codec;\n+ }\n+ }\n+ return null;\n+ }\n+\n+ process(ffmpegCommand: string) {\n+ return RNFFmpeg.execute(ffmpegCommand);\n+ }\n+}\n+\n+const ffmpeg = new FFmpeg();\n+\n+export { ffmpeg };\n"
},
{
"change_type": "MODIFY",
"old_path": "native/media/video-utils.js",
"new_path": "native/media/video-utils.js",
"diff": "@@ -7,17 +7,13 @@ import type {\n} from 'lib/types/media-types';\nimport filesystem from 'react-native-fs';\n-import { RNFFmpeg, RNFFprobe, RNFFmpegConfig } from 'react-native-ffmpeg';\nimport { Platform } from 'react-native';\nimport invariant from 'invariant';\nimport { pathFromURI, extensionFromFilename } from 'lib/utils/file-utils';\nimport { getVideoProcessingPlan } from 'lib/utils/video-utils';\n-if (!__DEV__) {\n- RNFFmpegConfig.disableLogs();\n- RNFFmpegConfig.disableStatistics();\n-}\n+import { ffmpeg } from './ffmpeg';\ntype ProcessVideoInfo = {|\nuri: string,\n@@ -79,7 +75,7 @@ async function processVideo(\nexceptionMessage;\nconst start = Date.now();\ntry {\n- const { rc } = await RNFFmpeg.execute(ffmpegCommand);\n+ const { rc } = await ffmpeg.process(ffmpegCommand);\nsuccess = rc === 0;\nif (success) {\nreturnCode = rc;\n@@ -143,9 +139,7 @@ async function checkVideoCodec(\nconst start = Date.now();\nif (ext === 'mp4' || ext === 'mov') {\ntry {\n- const videoInfo = await RNFFprobe.getMediaInformation(path);\n- codec = getVideoCodec(videoInfo);\n- format = videoInfo.format.split(',');\n+ ({ codec, format } = await ffmpeg.getVideoFormat(path));\nsuccess = codec === 'h264' && format.includes('mp4');\n} catch (e) {\nif (\n@@ -171,16 +165,4 @@ async function checkVideoCodec(\n};\n}\n-function getVideoCodec(info): ?string {\n- if (!info.streams) {\n- return null;\n- }\n- for (let stream of info.streams) {\n- if (stream.type === 'video') {\n- return stream.codec;\n- }\n- }\n- return null;\n-}\n-\nexport { processVideo };\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] ffmpeg class |
129,187 | 22.04.2020 18:08:12 | 14,400 | 4e84524dd41dbe124edf6b119db1405ee276cc04 | [native] Limit simultaneous ffmpeg calls | [
{
"change_type": "MODIFY",
"old_path": "native/media/ffmpeg.js",
"new_path": "native/media/ffmpeg.js",
"diff": "@@ -7,8 +7,86 @@ if (!__DEV__) {\nRNFFmpegConfig.disableStatistics();\n}\n+const maxSimultaneousCalls = {\n+ process: 4,\n+ probe: 1,\n+};\n+\n+type CallCounter = typeof maxSimultaneousCalls;\n+type QueuedCommandType = $Keys<CallCounter>;\n+type QueuedCommand = {|\n+ type: QueuedCommandType,\n+ runCommand: () => Promise<void>,\n+|};\n+\nclass FFmpeg {\n- async getVideoFormat(path: string) {\n+ queue: QueuedCommand[] = [];\n+ currentCalls: CallCounter = { process: 0, probe: 0 };\n+\n+ queueCommand<R>(\n+ type: QueuedCommandType,\n+ wrappedCommand: () => Promise<R>,\n+ ): Promise<R> {\n+ return new Promise((resolve, reject) => {\n+ const runCommand = async () => {\n+ try {\n+ const result = await wrappedCommand();\n+ this.currentCalls[type]--;\n+ this.possiblyRunCommands();\n+ resolve(result);\n+ } catch (e) {\n+ reject(e);\n+ }\n+ };\n+ this.queue.push({ type, runCommand });\n+ this.possiblyRunCommands();\n+ });\n+ }\n+\n+ possiblyRunCommands() {\n+ let openSlots: $Shape<CallCounter> = {};\n+ for (let type in this.currentCalls) {\n+ const currentCalls = this.currentCalls[type];\n+ const maxCalls = maxSimultaneousCalls[type];\n+ const callsLeft = maxCalls - currentCalls;\n+ if (!callsLeft) {\n+ return;\n+ } else if (currentCalls) {\n+ openSlots = { [type]: callsLeft };\n+ break;\n+ } else {\n+ openSlots[type] = callsLeft;\n+ }\n+ }\n+\n+ const toDefer = [],\n+ toRun = [];\n+ for (let command of this.queue) {\n+ const { type } = command;\n+ if (openSlots[type]) {\n+ openSlots = { [type]: openSlots[type] - 1 };\n+ this.currentCalls[type]++;\n+ toRun.push(command);\n+ } else {\n+ toDefer.push(command);\n+ }\n+ }\n+\n+ this.queue = toDefer;\n+ toRun.forEach(({ runCommand }) => runCommand());\n+ }\n+\n+ process(ffmpegCommand: string) {\n+ const wrappedCommand = () => RNFFmpeg.execute(ffmpegCommand);\n+ return this.queueCommand('process', wrappedCommand);\n+ }\n+\n+ getVideoFormat(path: string) {\n+ const wrappedCommand = () => FFmpeg.innerGetVideoFormat(path);\n+ return this.queueCommand('probe', wrappedCommand);\n+ }\n+\n+ static async innerGetVideoFormat(path: string) {\nconst info = await RNFFprobe.getMediaInformation(path);\nconst codec = FFmpeg.getVideoCodec(info);\nconst format = info.format.split(',');\n@@ -26,10 +104,6 @@ class FFmpeg {\n}\nreturn null;\n}\n-\n- process(ffmpegCommand: string) {\n- return RNFFmpeg.execute(ffmpegCommand);\n- }\n}\nconst ffmpeg = new FFmpeg();\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Limit simultaneous ffmpeg calls |
129,187 | 22.04.2020 18:45:55 | 14,400 | 41c2fad8860620e90f677e722942828de05c108c | [lib] Get the ffmpeg command right | [
{
"change_type": "MODIFY",
"old_path": "lib/utils/video-utils.js",
"new_path": "lib/utils/video-utils.js",
"diff": "@@ -33,7 +33,18 @@ function getVideoProcessingPlan(input: Input): ?Plan {\n'mp4',\n);\nconst outputPath = `${outputDirectory}${outputFilename}`;\n- const ffmpegCommand = `-i ${inputPath} -c:v ${outputCodec} -c:a copy ${outputPath}`;\n+ const crf = 25;\n+\n+ const ffmpegCommand =\n+ `-i ${inputPath} ` +\n+ `-c:a copy -c:v ${outputCodec} ` +\n+ `-crf ${crf} ` +\n+ '-vsync 2 -r 30 ' +\n+ '-vf scale=1920:1920:force_original_aspect_ratio=decrease ' +\n+ '-preset ultrafast ' +\n+ '-movflags +faststart ' +\n+ '-pix_fmt yuv420p ' +\n+ outputPath;\nreturn { outputPath, ffmpegCommand };\n}\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [lib] Get the ffmpeg command right |
129,187 | 22.04.2020 18:54:08 | 14,400 | e6a6f3d2ab1650dbc05e35271435ed118f57bbf0 | [lib] Shared maxDimensions for all media | [
{
"change_type": "MODIFY",
"old_path": "lib/utils/image-utils.js",
"new_path": "lib/utils/image-utils.js",
"diff": "import type { Dimensions } from '../types/media-types';\n-const maxDimensions = Object.freeze({ width: 3000, height: 2000 });\n+import { maxDimensions } from './media-utils';\n+const { height: maxHeight, width: maxWidth } = maxDimensions;\nconst convertToPNG = new Set([\n'image/png',\n'image/gif',\n@@ -37,7 +38,7 @@ function getImageProcessingPlan(input: Input): ?Plan {\nconst needsCompression =\ninputFileSize > 5e6 || (unsupportedMIME && inputFileSize > 3e6);\nconst needsResize =\n- inputFileSize > 5e5 && (inputWidth > 3000 || inputHeight > 2000);\n+ inputFileSize > 5e5 && (inputWidth > maxWidth || inputHeight > maxHeight);\nif (!unsupportedMIME && !needsRotation && !needsCompression && !needsResize) {\nreturn null;\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "lib/utils/media-utils.js",
"diff": "+// @flow\n+\n+const maxDimensions = Object.freeze({ width: 1920, height: 1920 });\n+\n+export { maxDimensions };\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/utils/video-utils.js",
"new_path": "lib/utils/video-utils.js",
"diff": "import { replaceExtension } from './file-utils';\nimport { getUUID } from './uuid';\n+import { maxDimensions } from './media-utils';\n+\n+const { height: maxHeight, width: maxWidth } = maxDimensions;\ntype Input = {|\ninputPath: string,\n@@ -40,7 +43,7 @@ function getVideoProcessingPlan(input: Input): ?Plan {\n`-c:a copy -c:v ${outputCodec} ` +\n`-crf ${crf} ` +\n'-vsync 2 -r 30 ' +\n- '-vf scale=1920:1920:force_original_aspect_ratio=decrease ' +\n+ `-vf scale=${maxWidth}:${maxHeight}:force_original_aspect_ratio=decrease ` +\n'-preset ultrafast ' +\n'-movflags +faststart ' +\n'-pix_fmt yuv420p ' +\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [lib] Shared maxDimensions for all media |
129,187 | 22.04.2020 19:00:27 | 14,400 | 6a981cc59acb97d6bedd23e7a22484d121696a20 | [lib] Only skip video processing if file is less than 10MB | [
{
"change_type": "MODIFY",
"old_path": "lib/utils/video-utils.js",
"new_path": "lib/utils/video-utils.js",
"diff": "@@ -9,7 +9,7 @@ const { height: maxHeight, width: maxWidth } = maxDimensions;\ntype Input = {|\ninputPath: string,\ninputHasCorrectContainerAndCodec: boolean,\n- inputFileSize: number,\n+ inputFileSize: number, // in bytes\ninputFilename: string,\noutputDirectory: string,\noutputCodec: string,\n@@ -22,12 +22,13 @@ function getVideoProcessingPlan(input: Input): ?Plan {\nconst {\ninputPath,\ninputHasCorrectContainerAndCodec,\n+ inputFileSize,\ninputFilename,\noutputDirectory,\noutputCodec,\n} = input;\n- if (inputHasCorrectContainerAndCodec) {\n+ if (inputHasCorrectContainerAndCodec && inputFileSize < 1e7) {\nreturn null;\n}\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [lib] Only skip video processing if file is less than 10MB |
129,187 | 22.04.2020 19:29:21 | 14,400 | e49bded95bf2ad559d046a958181ff8a648ca56b | [native] Pass MediaSelection directly into processMedia | [
{
"change_type": "MODIFY",
"old_path": "native/input/input-state-container.react.js",
"new_path": "native/input/input-state-container.react.js",
"diff": "@@ -477,39 +477,11 @@ class InputStateContainer extends React.PureComponent<Props, State> {\nuserTime = Date.now() - start;\n};\n- let mediaInfo;\n- if (selection.step === 'photo_library') {\n- mediaInfo = {\n- type: 'photo',\n- uri: selection.uri,\n- dimensions: selection.dimensions,\n- filename: selection.filename,\n- mediaNativeID: selection.mediaNativeID,\n- };\n- } else if (selection.step === 'photo_capture') {\n- mediaInfo = {\n- type: 'photo',\n- uri: selection.uri,\n- dimensions: selection.dimensions,\n- filename: selection.filename,\n- };\n- } else if (selection.step === 'video_library') {\n- mediaInfo = {\n- type: 'video',\n- uri: selection.uri,\n- dimensions: selection.dimensions,\n- filename: selection.filename,\n- mediaNativeID: selection.mediaNativeID,\n- };\n- } else {\n- invariant(false, `invalid selection ${JSON.stringify(selection)}`);\n- }\n-\nlet processedMedia;\nconst processingStart = Date.now();\ntry {\nconst processMediaReturn = processMedia(\n- mediaInfo,\n+ selection,\nthis.mediaProcessConfig(),\n);\nreportPromise = processMediaReturn.reportPromise;\n"
},
{
"change_type": "MODIFY",
"old_path": "native/media/media-utils.js",
"new_path": "native/media/media-utils.js",
"diff": "@@ -5,6 +5,7 @@ import type {\nMediaType,\nMediaMissionStep,\nMediaMissionFailure,\n+ MediaSelection,\n} from 'lib/types/media-types';\nimport { Image } from 'react-native';\n@@ -16,13 +17,6 @@ import { fetchFileInfo } from './file-utils';\nimport { processVideo } from './video-utils';\nimport { processImage } from './image-utils';\n-type MediaInput = {|\n- type: MediaType,\n- uri: string,\n- dimensions: Dimensions,\n- filename: string,\n- mediaNativeID?: string,\n-|};\ntype MediaProcessConfig = $Shape<{|\ninitialFileHeaderCheck: boolean,\nfinalFileHeaderCheck: boolean,\n@@ -37,7 +31,7 @@ type MediaResult = {|\ndimensions: Dimensions,\n|};\nfunction processMedia(\n- mediaInput: MediaInput,\n+ selection: MediaSelection,\nconfig: MediaProcessConfig,\n): {|\nresultPromise: Promise<MediaMissionFailure | MediaResult>,\n@@ -50,7 +44,7 @@ function processMedia(\n}\n};\n- const reportPromise = processMediaMission(mediaInput, config, sendResult);\n+ const reportPromise = processMediaMission(selection, config, sendResult);\nconst resultPromise = new Promise(resolve => {\nresolveResult = resolve;\n});\n@@ -59,16 +53,17 @@ function processMedia(\n}\nasync function processMediaMission(\n- mediaInput: MediaInput,\n+ selection: MediaSelection,\nconfig: MediaProcessConfig,\nsendResult: (MediaMissionFailure | MediaResult) => void,\n): Promise<$ReadOnlyArray<MediaMissionStep>> {\nconst steps = [];\nlet initialURI = null,\nuploadURI = null,\n- dimensions = mediaInput.dimensions,\n+ dimensions = selection.dimensions,\nmime = null,\nfinished = false;\n+ const mediaType = selection.step.startsWith('photo_') ? 'photo' : 'video';\nconst finish = (failure?: MediaMissionFailure) => {\ninvariant(!finished, 'finish called twice in processMediaMission');\nfinished = true;\n@@ -82,7 +77,7 @@ async function processMediaMission(\n);\nconst shouldDisposePath =\ninitialURI !== uploadURI ? pathFromURI(uploadURI) : null;\n- const filename = readableFilename(mediaInput.filename, mime);\n+ const filename = readableFilename(selection.filename, mime);\ninvariant(filename, `could not construct filename for ${mime}`);\nsendResult({\nsuccess: true,\n@@ -90,17 +85,20 @@ async function processMediaMission(\nshouldDisposePath,\nfilename,\nmime,\n- mediaType: mediaInput.type,\n+ mediaType,\ndimensions,\n});\n};\n+ const mediaNativeID = selection.mediaNativeID\n+ ? selection.mediaNativeID\n+ : null;\nconst { steps: fileInfoSteps, result: fileInfoResult } = await fetchFileInfo(\n- mediaInput.uri,\n- mediaInput.mediaNativeID,\n+ selection.uri,\n+ mediaNativeID,\n{\n- orientation: mediaInput.type === 'photo',\n- mime: mediaInput.type === 'photo' || config.initialFileHeaderCheck,\n+ orientation: mediaType === 'photo',\n+ mime: mediaType === 'photo' || config.initialFileHeaderCheck,\n},\n);\nsteps.push(...fileInfoSteps);\n@@ -112,24 +110,21 @@ async function processMediaMission(\ninitialURI = fileInfoResult.uri;\nmime = fileInfoResult.mime;\n- if (\n- fileInfoResult.mediaType &&\n- fileInfoResult.mediaType !== mediaInput.type\n- ) {\n+ if (fileInfoResult.mediaType && fileInfoResult.mediaType !== mediaType) {\nfinish({\nsuccess: false,\nreason: 'media_type_mismatch',\n- reportedMediaType: mediaInput.type,\n+ reportedMediaType: mediaType,\ndetectedMediaType: fileInfoResult.mediaType,\ndetectedMIME: fileInfoResult.mime,\n});\nreturn steps;\n}\n- if (mediaInput.type === 'video') {\n+ if (selection.step === 'video_library') {\nconst { steps: videoSteps, result: videoResult } = await processVideo({\nuri: initialURI,\n- filename: mediaInput.filename,\n+ filename: selection.filename,\nfileSize,\n});\nsteps.push(...videoSteps);\n@@ -139,7 +134,10 @@ async function processMediaMission(\n}\nuploadURI = videoResult.uri;\nmime = videoResult.mime;\n- } else if (mediaInput.type === 'photo') {\n+ } else if (\n+ selection.step === 'photo_capture' ||\n+ selection.step === 'photo_library'\n+ ) {\nif (!mime) {\nfinish({\nsuccess: false,\n@@ -163,7 +161,7 @@ async function processMediaMission(\ndimensions = imageResult.dimensions;\nmime = imageResult.mime;\n} else {\n- invariant(false, `unknown mediaType ${mediaInput.type}`);\n+ invariant(false, `unknown mediaType ${mediaType}`);\n}\nif (uploadURI === initialURI) {\n@@ -178,7 +176,7 @@ async function processMediaMission(\nconst {\nsteps: finalFileInfoSteps,\nresult: finalFileInfoResult,\n- } = await fetchFileInfo(uploadURI, mediaInput.mediaNativeID, {\n+ } = await fetchFileInfo(uploadURI, null, {\nmime: true,\n});\nsteps.push(...finalFileInfoSteps);\n@@ -194,7 +192,7 @@ async function processMediaMission(\nfinish({\nsuccess: false,\nreason: 'mime_type_mismatch',\n- reportedMediaType: mediaInput.type,\n+ reportedMediaType: mediaType,\nreportedMIME: mime,\ndetectedMediaType: finalFileInfoResult.mediaType,\ndetectedMIME: finalFileInfoResult.mime,\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Pass MediaSelection directly into processMedia |
129,187 | 22.04.2020 19:38:43 | 14,400 | 4bc5917a831eb4d6ebebc86c256333354c82d26e | Decide ffmpeg output video CRF based on duration | [
{
"change_type": "MODIFY",
"old_path": "lib/types/media-types.js",
"new_path": "lib/types/media-types.js",
"diff": "@@ -135,7 +135,7 @@ export type MediaLibrarySelection =\nselectTime: number, // ms timestamp\nsendTime: number, // ms timestamp\nretries: number,\n- playableDuration: number,\n+ duration: number,\n|};\nconst photoLibrarySelectionPropType = PropTypes.shape({\n@@ -158,7 +158,7 @@ const videoLibrarySelectionPropType = PropTypes.shape({\nselectTime: PropTypes.number.isRequired,\nsendTime: PropTypes.number.isRequired,\nretries: PropTypes.number.isRequired,\n- playableDuration: PropTypes.number.isRequired,\n+ duration: PropTypes.number.isRequired,\n});\nexport const mediaLibrarySelectionPropType = PropTypes.oneOfType([\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/utils/video-utils.js",
"new_path": "lib/utils/video-utils.js",
"diff": "@@ -11,6 +11,7 @@ type Input = {|\ninputHasCorrectContainerAndCodec: boolean,\ninputFileSize: number, // in bytes\ninputFilename: string,\n+ inputDuration: number,\noutputDirectory: string,\noutputCodec: string,\n|};\n@@ -24,6 +25,7 @@ function getVideoProcessingPlan(input: Input): ?Plan {\ninputHasCorrectContainerAndCodec,\ninputFileSize,\ninputFilename,\n+ inputDuration,\noutputDirectory,\noutputCodec,\n} = input;\n@@ -37,7 +39,9 @@ function getVideoProcessingPlan(input: Input): ?Plan {\n'mp4',\n);\nconst outputPath = `${outputDirectory}${outputFilename}`;\n- const crf = 25;\n+\n+ const { floor, min, max, log2 } = Math;\n+ const crf = floor(min(5, max(0, log2(inputDuration / 5)))) + 23;\nconst ffmpegCommand =\n`-i ${inputPath} ` +\n"
},
{
"change_type": "MODIFY",
"old_path": "native/media/media-gallery-keyboard.react.js",
"new_path": "native/media/media-gallery-keyboard.react.js",
"diff": "@@ -252,7 +252,7 @@ class MediaGalleryKeyboard extends React.PureComponent<Props, State> {\nuri,\nfilename,\nmediaNativeID: id,\n- playableDuration: duration,\n+ duration,\nselectTime: 0,\nsendTime: 0,\nretries: 0,\n"
},
{
"change_type": "MODIFY",
"old_path": "native/media/media-utils.js",
"new_path": "native/media/media-utils.js",
"diff": "@@ -126,6 +126,7 @@ async function processMediaMission(\nuri: initialURI,\nfilename: selection.filename,\nfileSize,\n+ duration: selection.duration,\n});\nsteps.push(...videoSteps);\nif (!videoResult.success) {\n"
},
{
"change_type": "MODIFY",
"old_path": "native/media/video-utils.js",
"new_path": "native/media/video-utils.js",
"diff": "@@ -19,6 +19,7 @@ type ProcessVideoInfo = {|\nuri: string,\nfilename: string,\nfileSize: number,\n+ duration: number,\n|};\ntype ProcessVideoResponse = {|\nsuccess: true,\n@@ -44,6 +45,7 @@ async function processVideo(\ninputHasCorrectContainerAndCodec: initialCheckStep.success,\ninputFileSize: input.fileSize,\ninputFilename: input.filename,\n+ inputDuration: input.duration,\noutputDirectory: Platform.select({\nios: filesystem.TemporaryDirectoryPath,\ndefault: `${filesystem.TemporaryDirectoryPath}/`,\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | Decide ffmpeg output video CRF based on duration |
129,187 | 23.04.2020 14:31:25 | 14,400 | 153a3537ab097d01a8cff6b1cc742e18799e13d6 | [native] ClearableTextInput | [
{
"change_type": "MODIFY",
"old_path": "native/chat/chat-input-bar.react.js",
"new_path": "native/chat/chat-input-bar.react.js",
"diff": "@@ -71,6 +71,7 @@ import {\nconnectNav,\ntype NavContextType,\n} from '../navigation/navigation-context';\n+import ClearableTextInput from '../components/clearable-text-input.react';\nconst draftKeyFromThreadID = (threadID: string) =>\n`${threadID}/message_composer`;\n@@ -118,6 +119,7 @@ class ChatInputBar extends React.PureComponent<Props, State> {\ninputState: inputStatePropType,\n};\ntextInput: ?TextInput;\n+ clearableTextInput: ?ClearableTextInput;\nexpandOpacity: Animated.Value;\nexpandoButtonsOpacity: Animated.Value;\nexpandoButtonsWidth: Animated.Value;\n@@ -128,6 +130,7 @@ class ChatInputBar extends React.PureComponent<Props, State> {\ntext: props.draft,\nbuttonsExpanded: true,\n};\n+ // eslint-disable-next-line import/no-named-as-default-member\nthis.expandoButtonsOpacity = new Animated.Value(1);\nthis.expandOpacity = Animated.sub(1, this.expandoButtonsOpacity);\nthis.expandoButtonsWidth = Animated.interpolate(\n@@ -330,18 +333,18 @@ class ChatInputBar extends React.PureComponent<Props, State> {\n{this.state.buttonsExpanded ? null : expandoButton}\n</View>\n</Animated.View>\n- <View style={this.props.styles.textInputContainer}>\n- <TextInput\n+ <ClearableTextInput\nvalue={this.state.text}\n+ sendMessage={this.sendMessage}\nonChangeText={this.updateText}\nunderlineColorAndroid=\"transparent\"\nplaceholder=\"Send a message...\"\nplaceholderTextColor={this.props.colors.listInputButton}\nmultiline={true}\nstyle={this.props.styles.textInput}\n- ref={this.textInputRef}\n+ textInputRef={this.textInputRef}\n+ ref={this.clearableTextInputRef}\n/>\n- </View>\n{button}\n</View>\n</TouchableWithoutFeedback>\n@@ -397,6 +400,10 @@ class ChatInputBar extends React.PureComponent<Props, State> {\nthis.textInput = textInput;\n};\n+ clearableTextInputRef = (clearableTextInput: ?ClearableTextInput) => {\n+ this.clearableTextInput = clearableTextInput;\n+ };\n+\nupdateText = (text: string) => {\nthis.setState({ text });\nthis.saveDraft(text);\n@@ -415,6 +422,16 @@ class ChatInputBar extends React.PureComponent<Props, State> {\nreturn;\n}\nthis.updateText('');\n+\n+ const { clearableTextInput } = this;\n+ invariant(\n+ clearableTextInput,\n+ 'clearableTextInput should be sent in onSend',\n+ );\n+ clearableTextInput.clear();\n+ };\n+\n+ sendMessage = (text: string) => {\nconst localID = `local${this.props.nextLocalID}`;\nconst creatorID = this.props.viewerID;\ninvariant(creatorID, 'should have viewer ID in order to send a message');\n@@ -455,6 +472,7 @@ class ChatInputBar extends React.PureComponent<Props, State> {\nif (this.state.buttonsExpanded) {\nreturn;\n}\n+ // eslint-disable-next-line import/no-named-as-default-member\nAnimated.timing(this.expandoButtonsOpacity, {\nduration: 500,\ntoValue: 1,\n@@ -471,6 +489,7 @@ class ChatInputBar extends React.PureComponent<Props, State> {\n) {\nreturn;\n}\n+ // eslint-disable-next-line import/no-named-as-default-member\nAnimated.timing(this.expandoButtonsOpacity, {\nduration: 500,\ntoValue: 0,\n@@ -580,9 +599,6 @@ const styles = {\npaddingHorizontal: 10,\npaddingVertical: 5,\n},\n- textInputContainer: {\n- flex: 1,\n- },\n};\nconst stylesSelector = styleSelector(styles);\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "native/components/clearable-text-input.react.js",
"diff": "+// @flow\n+\n+import type { KeyPressEvent } from '../types/react-native';\n+\n+import * as React from 'react';\n+import { TextInput, View, Platform, StyleSheet } from 'react-native';\n+\n+import invariant from 'invariant';\n+\n+type Props = {|\n+ ...React.ElementConfig<typeof TextInput>,\n+ textInputRef: (textInput: ?TextInput) => mixed,\n+ sendMessage: (text: string) => mixed,\n+|};\n+type State = {|\n+ textInputKey: number,\n+|};\n+class ClearableTextInput extends React.PureComponent<Props, State> {\n+ state = {\n+ textInputKey: 0,\n+ };\n+ pendingMessage: ?string;\n+ lastKeyPressed: ?string;\n+ lastTextInputSent = -1;\n+\n+ onChangeText = (text: string) => {\n+ this.props.onChangeText && this.props.onChangeText(text);\n+ };\n+\n+ sendMessage() {\n+ if (this.lastMessageSent) {\n+ return;\n+ }\n+ const { pendingMessage } = this;\n+ invariant(pendingMessage, 'cannot send an empty message');\n+ this.props.sendMessage(pendingMessage);\n+ const textInputSent = this.state.textInputKey - 1;\n+ if (textInputSent > this.lastTextInputSent) {\n+ this.lastTextInputSent = textInputSent;\n+ }\n+ }\n+\n+ get lastMessageSent() {\n+ return this.lastTextInputSent >= this.state.textInputKey - 1;\n+ }\n+\n+ onOldInputChangeText = (text: string) => {\n+ const { pendingMessage, lastKeyPressed } = this;\n+ invariant(\n+ pendingMessage,\n+ 'onOldInputChangeText should have a pendingMessage',\n+ );\n+\n+ if (\n+ Platform.OS === 'ios' &&\n+ !this.lastMessageSent &&\n+ lastKeyPressed &&\n+ lastKeyPressed.length > 1\n+ ) {\n+ // This represents an autocorrect event on blur\n+ this.pendingMessage = text;\n+ }\n+ this.lastKeyPressed = null;\n+\n+ this.sendMessage();\n+ this.updateTextFromOldInput(text);\n+ };\n+\n+ updateTextFromOldInput(text: string) {\n+ const { pendingMessage } = this;\n+ invariant(\n+ pendingMessage,\n+ 'updateTextFromOldInput should have a pendingMessage',\n+ );\n+ // TODO more sophisticated\n+ if (text.startsWith(pendingMessage)) {\n+ this.onChangeText(text.substring(pendingMessage.length));\n+ }\n+ }\n+\n+ onOldInputKeyPress = (event: KeyPressEvent) => {\n+ const { key } = event.nativeEvent;\n+ if (this.lastKeyPressed && this.lastKeyPressed.length > key.length) {\n+ return;\n+ }\n+ this.lastKeyPressed = key;\n+ this.props.onKeyPress && this.props.onKeyPress(event);\n+ };\n+\n+ onOldInputBlur = () => {\n+ this.sendMessage();\n+ };\n+\n+ textInputRef = (textInput: ?TextInput) => {\n+ if (this.state.textInputKey > 0 && textInput) {\n+ textInput.focus();\n+ }\n+ this.props.textInputRef(textInput);\n+ };\n+\n+ clear() {\n+ this.pendingMessage = this.props.value;\n+ this.setState(prevState => ({ textInputKey: prevState.textInputKey + 1 }));\n+ }\n+\n+ render() {\n+ const { textInputRef, sendMessage, ...props } = this.props;\n+\n+ const textInputs = [];\n+ if (this.state.textInputKey > 0 && this.pendingMessage) {\n+ textInputs.push(\n+ <TextInput\n+ {...props}\n+ style={[props.style, styles.invisibleTextInput]}\n+ onChangeText={this.onOldInputChangeText}\n+ onKeyPress={this.onOldInputKeyPress}\n+ onBlur={this.onOldInputBlur}\n+ key={this.state.textInputKey - 1}\n+ />,\n+ );\n+ }\n+ textInputs.push(\n+ <TextInput\n+ {...props}\n+ onChangeText={this.onChangeText}\n+ key={this.state.textInputKey}\n+ ref={this.textInputRef}\n+ />,\n+ );\n+\n+ return <View style={styles.textInputContainer}>{textInputs}</View>;\n+ }\n+}\n+\n+const styles = StyleSheet.create({\n+ invisibleTextInput: {\n+ opacity: 0,\n+ position: 'absolute',\n+ },\n+ textInputContainer: {\n+ flex: 1,\n+ },\n+});\n+\n+export default ClearableTextInput;\n"
},
{
"change_type": "MODIFY",
"old_path": "native/types/react-native.js",
"new_path": "native/types/react-native.js",
"diff": "export type { ViewToken } from 'react-native/Libraries/Lists/ViewabilityHelper';\n-export type { Layout, LayoutEvent } from 'react-native/Libraries/Types/CoreEventTypes';\n+export type {\n+ Layout,\n+ LayoutEvent,\n+} from 'react-native/Libraries/Types/CoreEventTypes';\n-export type { ContentSizeChangeEvent } from 'react-native/Libraries/Components/TextInput/TextInput';\n+export type {\n+ ContentSizeChangeEvent,\n+ KeyPressEvent,\n+} from 'react-native/Libraries/Components/TextInput/TextInput';\nexport type { Rationale } from 'react-native/Libraries/PermissionsAndroid/PermissionsAndroid';\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] ClearableTextInput |
129,187 | 23.04.2020 15:55:12 | 14,400 | 244a74e840b8dfbd709410cdf9bb41332fe3a717 | [native] Fix up ChatInputBar send button
Avoiding `LayoutAnimation` now that we have `ClearableTextInput` and increasing the tap target | [
{
"change_type": "MODIFY",
"old_path": "native/chat/chat-input-bar.react.js",
"new_path": "native/chat/chat-input-bar.react.js",
"diff": "@@ -36,7 +36,6 @@ import {\nView,\nTextInput,\nTouchableOpacity,\n- LayoutAnimation,\nPlatform,\nText,\nActivityIndicator,\n@@ -123,6 +122,8 @@ class ChatInputBar extends React.PureComponent<Props, State> {\nexpandOpacity: Animated.Value;\nexpandoButtonsOpacity: Animated.Value;\nexpandoButtonsWidth: Animated.Value;\n+ sendButtonContainerOpen: Animated.Value;\n+ sendButtonContainerWidth: Animated.Value;\nconstructor(props: Props) {\nsuper(props);\n@@ -130,6 +131,7 @@ class ChatInputBar extends React.PureComponent<Props, State> {\ntext: props.draft,\nbuttonsExpanded: true,\n};\n+\n// eslint-disable-next-line import/no-named-as-default-member\nthis.expandoButtonsOpacity = new Animated.Value(1);\nthis.expandOpacity = Animated.sub(1, this.expandoButtonsOpacity);\n@@ -140,6 +142,18 @@ class ChatInputBar extends React.PureComponent<Props, State> {\noutputRange: [22, 60],\n},\n);\n+\n+ // eslint-disable-next-line import/no-named-as-default-member\n+ this.sendButtonContainerOpen = new Animated.Value(\n+ props.draft.trim() ? 1 : 0,\n+ );\n+ this.sendButtonContainerWidth = Animated.interpolate(\n+ this.sendButtonContainerOpen,\n+ {\n+ inputRange: [0, 1],\n+ outputRange: [4, 38],\n+ },\n+ );\n}\nstatic mediaGalleryOpen(props: Props) {\n@@ -163,7 +177,12 @@ class ChatInputBar extends React.PureComponent<Props, State> {\n(currentText === '' && prevText !== '') ||\n(currentText !== '' && prevText === '')\n) {\n- LayoutAnimation.easeInEaseOut();\n+ // eslint-disable-next-line import/no-named-as-default-member\n+ Animated.timing(this.sendButtonContainerOpen, {\n+ duration: 150,\n+ toValue: currentText !== '' ? 1 : 0,\n+ easing: Easing.inOut(Easing.ease),\n+ }).start();\n}\nconst systemKeyboardIsShowing = ChatInputBar.systemKeyboardShowing(\n@@ -267,23 +286,55 @@ class ChatInputBar extends React.PureComponent<Props, State> {\nlet content;\nif (threadHasPermission(this.props.threadInfo, threadPermissions.VOICED)) {\n- let button = null;\n- if (this.state.text.trim()) {\n- button = (\n- <TouchableOpacity\n- onPress={this.onSend}\n- activeOpacity={0.4}\n- style={this.props.styles.bottomAligned}\n- >\n- <Icon\n- name=\"md-send\"\n- size={25}\n- style={this.props.styles.sendIcon}\n- color={this.props.colors.greenButton}\n- />\n- </TouchableOpacity>\n+ content = this.renderInput();\n+ } else if (isMember) {\n+ content = (\n+ <Text style={this.props.styles.explanation}>\n+ You don't have permission to send messages.\n+ </Text>\n+ );\n+ } else {\n+ const defaultRoleID = Object.keys(this.props.threadInfo.roles).find(\n+ roleID => this.props.threadInfo.roles[roleID].isDefault,\n+ );\n+ invariant(\n+ defaultRoleID !== undefined,\n+ 'all threads should have a default role',\n+ );\n+ const defaultRole = this.props.threadInfo.roles[defaultRoleID];\n+ const membersAreVoiced = !!defaultRole.permissions[\n+ threadPermissions.VOICED\n+ ];\n+ if (membersAreVoiced) {\n+ content = (\n+ <Text style={this.props.styles.explanation}>\n+ Join this thread to send messages.\n+ </Text>\n+ );\n+ } else {\n+ content = (\n+ <Text style={this.props.styles.explanation}>\n+ You don't have permission to send messages.\n+ </Text>\n+ );\n+ }\n+ }\n+\n+ const keyboardInputHost =\n+ Platform.OS === 'android' ? null : (\n+ <KeyboardInputHost textInputRef={this.textInput} />\n+ );\n+\n+ return (\n+ <View style={this.props.styles.container}>\n+ {joinButton}\n+ {content}\n+ {keyboardInputHost}\n+ </View>\n);\n}\n+\n+ renderInput() {\nconst expandoButton = (\n<TouchableOpacity\nonPress={this.expandButtons}\n@@ -299,7 +350,8 @@ class ChatInputBar extends React.PureComponent<Props, State> {\n</Animated.View>\n</TouchableOpacity>\n);\n- content = (\n+ const sendButtonContainerStyle = { width: this.sendButtonContainerWidth };\n+ return (\n<TouchableWithoutFeedback onPress={this.dismissKeyboard}>\n<View style={this.props.styles.inputContainer}>\n<Animated.View style={this.expandoButtonsStyle}>\n@@ -345,55 +397,24 @@ class ChatInputBar extends React.PureComponent<Props, State> {\ntextInputRef={this.textInputRef}\nref={this.clearableTextInputRef}\n/>\n- {button}\n+ <Animated.View style={sendButtonContainerStyle}>\n+ <TouchableOpacity\n+ onPress={this.onSend}\n+ activeOpacity={0.4}\n+ style={this.props.styles.sendButton}\n+ disabled={this.state.text.trim() === ''}\n+ >\n+ <Icon\n+ name=\"md-send\"\n+ size={25}\n+ style={this.props.styles.sendIcon}\n+ color={this.props.colors.greenButton}\n+ />\n+ </TouchableOpacity>\n+ </Animated.View>\n</View>\n</TouchableWithoutFeedback>\n);\n- } else if (isMember) {\n- content = (\n- <Text style={this.props.styles.explanation}>\n- You don't have permission to send messages.\n- </Text>\n- );\n- } else {\n- const defaultRoleID = Object.keys(this.props.threadInfo.roles).find(\n- roleID => this.props.threadInfo.roles[roleID].isDefault,\n- );\n- invariant(\n- defaultRoleID !== undefined,\n- 'all threads should have a default role',\n- );\n- const defaultRole = this.props.threadInfo.roles[defaultRoleID];\n- const membersAreVoiced = !!defaultRole.permissions[\n- threadPermissions.VOICED\n- ];\n- if (membersAreVoiced) {\n- content = (\n- <Text style={this.props.styles.explanation}>\n- Join this thread to send messages.\n- </Text>\n- );\n- } else {\n- content = (\n- <Text style={this.props.styles.explanation}>\n- You don't have permission to send messages.\n- </Text>\n- );\n- }\n- }\n-\n- const keyboardInputHost =\n- Platform.OS === 'android' ? null : (\n- <KeyboardInputHost textInputRef={this.textInput} />\n- );\n-\n- return (\n- <View style={this.props.styles.container}>\n- {joinButton}\n- {content}\n- {keyboardInputHost}\n- </View>\n- );\n}\ntextInputRef = (textInput: ?TextInput) => {\n@@ -522,10 +543,6 @@ class ChatInputBar extends React.PureComponent<Props, State> {\n}\nconst styles = {\n- bottomAligned: {\n- alignSelf: 'flex-end',\n- paddingBottom: Platform.OS === 'ios' ? 7 : 9,\n- },\ncameraIcon: {\npaddingBottom: 10,\npaddingRight: 3,\n@@ -584,16 +601,22 @@ const styles = {\njoinThreadLoadingIndicator: {\npaddingVertical: 2,\n},\n+ sendButton: {\n+ position: 'absolute',\n+ bottom: Platform.OS === 'android' ? 3 : 0,\n+ left: 0,\n+ },\nsendIcon: {\n- paddingLeft: 5,\n+ paddingLeft: 9,\npaddingRight: 8,\n+ paddingVertical: 5,\n},\ntextInput: {\nbackgroundColor: 'listInputBackground',\nborderRadius: 10,\ncolor: 'listForegroundLabel',\nfontSize: 16,\n- marginHorizontal: 4,\n+ marginLeft: 4,\nmarginVertical: 5,\nmaxHeight: 250,\npaddingHorizontal: 10,\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Fix up ChatInputBar send button
Avoiding `LayoutAnimation` now that we have `ClearableTextInput` and increasing the tap target |
129,187 | 23.04.2020 16:59:11 | 14,400 | 247458919e21bd831b61519bbb642634415e90a0 | [native] ClearableTextInput.getValueAndReset | [
{
"change_type": "MODIFY",
"old_path": "native/chat/chat-input-bar.react.js",
"new_path": "native/chat/chat-input-bar.react.js",
"diff": "@@ -387,7 +387,6 @@ class ChatInputBar extends React.PureComponent<Props, State> {\n</Animated.View>\n<ClearableTextInput\nvalue={this.state.text}\n- sendMessage={this.sendMessage}\nonChangeText={this.updateText}\nunderlineColorAndroid=\"transparent\"\nplaceholder=\"Send a message...\"\n@@ -437,22 +436,21 @@ class ChatInputBar extends React.PureComponent<Props, State> {\n});\n}, 400);\n- onSend = () => {\n- const text = this.state.text.trim();\n- if (!text) {\n+ onSend = async () => {\n+ if (!this.state.text.trim()) {\nreturn;\n}\n- this.updateText('');\nconst { clearableTextInput } = this;\ninvariant(\nclearableTextInput,\n'clearableTextInput should be sent in onSend',\n);\n- clearableTextInput.clear();\n- };\n+ const text = await clearableTextInput.getValueAndReset();\n+ if (!text) {\n+ return;\n+ }\n- sendMessage = (text: string) => {\nconst localID = `local${this.props.nextLocalID}`;\nconst creatorID = this.props.viewerID;\ninvariant(creatorID, 'should have viewer ID in order to send a message');\n"
},
{
"change_type": "MODIFY",
"old_path": "native/components/clearable-text-input.react.js",
"new_path": "native/components/clearable-text-input.react.js",
"diff": "@@ -10,7 +10,6 @@ import invariant from 'invariant';\ntype Props = {|\n...React.ElementConfig<typeof TextInput>,\ntextInputRef: (textInput: ?TextInput) => mixed,\n- sendMessage: (text: string) => mixed,\n|};\ntype State = {|\ntextInputKey: number,\n@@ -19,7 +18,7 @@ class ClearableTextInput extends React.PureComponent<Props, State> {\nstate = {\ntextInputKey: 0,\n};\n- pendingMessage: ?string;\n+ pendingMessage: ?{| value: ?string, resolve: (value: ?string) => void |};\nlastKeyPressed: ?string;\nlastTextInputSent = -1;\n@@ -28,19 +27,20 @@ class ClearableTextInput extends React.PureComponent<Props, State> {\n};\nsendMessage() {\n- if (this.lastMessageSent) {\n+ if (this.pendingMessageSent) {\nreturn;\n}\nconst { pendingMessage } = this;\ninvariant(pendingMessage, 'cannot send an empty message');\n- this.props.sendMessage(pendingMessage);\n+ pendingMessage.resolve(pendingMessage.value);\n+\nconst textInputSent = this.state.textInputKey - 1;\nif (textInputSent > this.lastTextInputSent) {\nthis.lastTextInputSent = textInputSent;\n}\n}\n- get lastMessageSent() {\n+ get pendingMessageSent() {\nreturn this.lastTextInputSent >= this.state.textInputKey - 1;\n}\n@@ -53,12 +53,12 @@ class ClearableTextInput extends React.PureComponent<Props, State> {\nif (\nPlatform.OS === 'ios' &&\n- !this.lastMessageSent &&\n+ !this.pendingMessageSent &&\nlastKeyPressed &&\nlastKeyPressed.length > 1\n) {\n// This represents an autocorrect event on blur\n- this.pendingMessage = text;\n+ pendingMessage.value = text;\n}\nthis.lastKeyPressed = null;\n@@ -72,10 +72,15 @@ class ClearableTextInput extends React.PureComponent<Props, State> {\npendingMessage,\n'updateTextFromOldInput should have a pendingMessage',\n);\n- // TODO more sophisticated\n- if (text.startsWith(pendingMessage)) {\n- this.onChangeText(text.substring(pendingMessage.length));\n+ const pendingValue = pendingMessage.value;\n+ if (!pendingValue || !text.startsWith(pendingValue)) {\n+ return;\n+ }\n+ const newValue = text.substring(pendingValue.length);\n+ if (this.props.value === newValue) {\n+ return;\n}\n+ this.onChangeText(newValue);\n}\nonOldInputKeyPress = (event: KeyPressEvent) => {\n@@ -98,16 +103,24 @@ class ClearableTextInput extends React.PureComponent<Props, State> {\nthis.props.textInputRef(textInput);\n};\n- clear() {\n- this.pendingMessage = this.props.value;\n- this.setState(prevState => ({ textInputKey: prevState.textInputKey + 1 }));\n+ getValueAndReset(): Promise<?string> {\n+ this.onChangeText('');\n+ return new Promise(resolve => {\n+ this.pendingMessage = {\n+ value: this.props.value,\n+ resolve,\n+ };\n+ this.setState(prevState => ({\n+ textInputKey: prevState.textInputKey + 1,\n+ }));\n+ });\n}\nrender() {\n- const { textInputRef, sendMessage, ...props } = this.props;\n+ const { textInputRef, ...props } = this.props;\nconst textInputs = [];\n- if (this.state.textInputKey > 0 && this.pendingMessage) {\n+ if (this.state.textInputKey > 0) {\ntextInputs.push(\n<TextInput\n{...props}\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] ClearableTextInput.getValueAndReset |
129,187 | 23.04.2020 17:11:35 | 14,400 | 96038f35fba41b7e32a933fe51929ca5ddee1249 | [native] Start hiding send button immediately onSend | [
{
"change_type": "MODIFY",
"old_path": "native/chat/chat-input-bar.react.js",
"new_path": "native/chat/chat-input-bar.react.js",
"diff": "@@ -170,6 +170,15 @@ class ChatInputBar extends React.PureComponent<Props, State> {\nreturn ChatInputBar.systemKeyboardShowing(this.props);\n}\n+ updateSendButton(currentText: string) {\n+ // eslint-disable-next-line import/no-named-as-default-member\n+ Animated.timing(this.sendButtonContainerOpen, {\n+ duration: 150,\n+ toValue: currentText === '' ? 0 : 1,\n+ easing: Easing.inOut(Easing.ease),\n+ }).start();\n+ }\n+\ncomponentDidUpdate(prevProps: Props, prevState: State) {\nconst currentText = this.state.text.trim();\nconst prevText = prevState.text.trim();\n@@ -177,12 +186,7 @@ class ChatInputBar extends React.PureComponent<Props, State> {\n(currentText === '' && prevText !== '') ||\n(currentText !== '' && prevText === '')\n) {\n- // eslint-disable-next-line import/no-named-as-default-member\n- Animated.timing(this.sendButtonContainerOpen, {\n- duration: 150,\n- toValue: currentText !== '' ? 1 : 0,\n- easing: Easing.inOut(Easing.ease),\n- }).start();\n+ this.updateSendButton(currentText);\n}\nconst systemKeyboardIsShowing = ChatInputBar.systemKeyboardShowing(\n@@ -440,6 +444,7 @@ class ChatInputBar extends React.PureComponent<Props, State> {\nif (!this.state.text.trim()) {\nreturn;\n}\n+ this.updateSendButton('');\nconst { clearableTextInput } = this;\ninvariant(\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Start hiding send button immediately onSend |
129,187 | 23.04.2020 17:28:47 | 14,400 | be5607801378717be088349a9fb619fff4b8d22d | [native] ClearableTextInput for Android | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "native/components/clearable-text-input.react.ios.js",
"diff": "+// @flow\n+\n+import type { KeyPressEvent } from '../types/react-native';\n+\n+import * as React from 'react';\n+import { TextInput, View, StyleSheet } from 'react-native';\n+\n+import invariant from 'invariant';\n+\n+type Props = {|\n+ ...React.ElementConfig<typeof TextInput>,\n+ textInputRef: (textInput: ?TextInput) => mixed,\n+|};\n+type State = {|\n+ textInputKey: number,\n+|};\n+class ClearableTextInput extends React.PureComponent<Props, State> {\n+ state = {\n+ textInputKey: 0,\n+ };\n+ pendingMessage: ?{| value: ?string, resolve: (value: ?string) => void |};\n+ lastKeyPressed: ?string;\n+ lastTextInputSent = -1;\n+\n+ onChangeText = (text: string) => {\n+ this.props.onChangeText && this.props.onChangeText(text);\n+ };\n+\n+ sendMessage() {\n+ if (this.pendingMessageSent) {\n+ return;\n+ }\n+ const { pendingMessage } = this;\n+ invariant(pendingMessage, 'cannot send an empty message');\n+ pendingMessage.resolve(pendingMessage.value);\n+\n+ const textInputSent = this.state.textInputKey - 1;\n+ if (textInputSent > this.lastTextInputSent) {\n+ this.lastTextInputSent = textInputSent;\n+ }\n+ }\n+\n+ get pendingMessageSent() {\n+ return this.lastTextInputSent >= this.state.textInputKey - 1;\n+ }\n+\n+ onOldInputChangeText = (text: string) => {\n+ const { pendingMessage, lastKeyPressed } = this;\n+ invariant(\n+ pendingMessage,\n+ 'onOldInputChangeText should have a pendingMessage',\n+ );\n+\n+ if (\n+ !this.pendingMessageSent &&\n+ lastKeyPressed &&\n+ lastKeyPressed.length > 1\n+ ) {\n+ // This represents an autocorrect event on blur\n+ pendingMessage.value = text;\n+ }\n+ this.lastKeyPressed = null;\n+\n+ this.sendMessage();\n+ this.updateTextFromOldInput(text);\n+ };\n+\n+ updateTextFromOldInput(text: string) {\n+ const { pendingMessage } = this;\n+ invariant(\n+ pendingMessage,\n+ 'updateTextFromOldInput should have a pendingMessage',\n+ );\n+ const pendingValue = pendingMessage.value;\n+ if (!pendingValue || !text.startsWith(pendingValue)) {\n+ return;\n+ }\n+ const newValue = text.substring(pendingValue.length);\n+ if (this.props.value === newValue) {\n+ return;\n+ }\n+ this.onChangeText(newValue);\n+ }\n+\n+ onOldInputKeyPress = (event: KeyPressEvent) => {\n+ const { key } = event.nativeEvent;\n+ if (this.lastKeyPressed && this.lastKeyPressed.length > key.length) {\n+ return;\n+ }\n+ this.lastKeyPressed = key;\n+ this.props.onKeyPress && this.props.onKeyPress(event);\n+ };\n+\n+ onOldInputBlur = () => {\n+ this.sendMessage();\n+ };\n+\n+ textInputRef = (textInput: ?TextInput) => {\n+ if (this.state.textInputKey > 0 && textInput) {\n+ textInput.focus();\n+ }\n+ this.props.textInputRef(textInput);\n+ };\n+\n+ getValueAndReset(): Promise<?string> {\n+ this.onChangeText('');\n+ return new Promise(resolve => {\n+ this.pendingMessage = {\n+ value: this.props.value,\n+ resolve,\n+ };\n+ this.setState(prevState => ({\n+ textInputKey: prevState.textInputKey + 1,\n+ }));\n+ });\n+ }\n+\n+ render() {\n+ const { textInputRef, ...props } = this.props;\n+\n+ const textInputs = [];\n+ if (this.state.textInputKey > 0) {\n+ textInputs.push(\n+ <TextInput\n+ {...props}\n+ style={[props.style, styles.invisibleTextInput]}\n+ onChangeText={this.onOldInputChangeText}\n+ onKeyPress={this.onOldInputKeyPress}\n+ onBlur={this.onOldInputBlur}\n+ key={this.state.textInputKey - 1}\n+ />,\n+ );\n+ }\n+ textInputs.push(\n+ <TextInput\n+ {...props}\n+ onChangeText={this.onChangeText}\n+ key={this.state.textInputKey}\n+ ref={this.textInputRef}\n+ />,\n+ );\n+\n+ return <View style={styles.textInputContainer}>{textInputs}</View>;\n+ }\n+}\n+\n+const styles = StyleSheet.create({\n+ invisibleTextInput: {\n+ opacity: 0,\n+ position: 'absolute',\n+ },\n+ textInputContainer: {\n+ flex: 1,\n+ },\n+});\n+\n+export default ClearableTextInput;\n"
},
{
"change_type": "MODIFY",
"old_path": "native/components/clearable-text-input.react.js",
"new_path": "native/components/clearable-text-input.react.js",
"diff": "// @flow\n-import type { KeyPressEvent } from '../types/react-native';\n-\nimport * as React from 'react';\n-import { TextInput, View, Platform, StyleSheet } from 'react-native';\n-\n-import invariant from 'invariant';\n+import { TextInput, View, StyleSheet } from 'react-native';\ntype Props = {|\n...React.ElementConfig<typeof TextInput>,\ntextInputRef: (textInput: ?TextInput) => mixed,\n|};\n-type State = {|\n- textInputKey: number,\n-|};\n-class ClearableTextInput extends React.PureComponent<Props, State> {\n- state = {\n- textInputKey: 0,\n- };\n- pendingMessage: ?{| value: ?string, resolve: (value: ?string) => void |};\n- lastKeyPressed: ?string;\n- lastTextInputSent = -1;\n-\n- onChangeText = (text: string) => {\n- this.props.onChangeText && this.props.onChangeText(text);\n- };\n-\n- sendMessage() {\n- if (this.pendingMessageSent) {\n- return;\n- }\n- const { pendingMessage } = this;\n- invariant(pendingMessage, 'cannot send an empty message');\n- pendingMessage.resolve(pendingMessage.value);\n-\n- const textInputSent = this.state.textInputKey - 1;\n- if (textInputSent > this.lastTextInputSent) {\n- this.lastTextInputSent = textInputSent;\n- }\n- }\n-\n- get pendingMessageSent() {\n- return this.lastTextInputSent >= this.state.textInputKey - 1;\n- }\n+class ClearableTextInput extends React.PureComponent<Props> {\n+ textInput: ?TextInput;\n+ lastMessageSent: ?string;\n- onOldInputChangeText = (text: string) => {\n- const { pendingMessage, lastKeyPressed } = this;\n- invariant(\n- pendingMessage,\n- 'onOldInputChangeText should have a pendingMessage',\n- );\n-\n- if (\n- Platform.OS === 'ios' &&\n- !this.pendingMessageSent &&\n- lastKeyPressed &&\n- lastKeyPressed.length > 1\n- ) {\n- // This represents an autocorrect event on blur\n- pendingMessage.value = text;\n- }\n- this.lastKeyPressed = null;\n-\n- this.sendMessage();\n- this.updateTextFromOldInput(text);\n- };\n-\n- updateTextFromOldInput(text: string) {\n- const { pendingMessage } = this;\n- invariant(\n- pendingMessage,\n- 'updateTextFromOldInput should have a pendingMessage',\n- );\n- const pendingValue = pendingMessage.value;\n- if (!pendingValue || !text.startsWith(pendingValue)) {\n- return;\n- }\n- const newValue = text.substring(pendingValue.length);\n- if (this.props.value === newValue) {\n+ onChangeText = (inputText: string) => {\n+ const { onChangeText } = this.props;\n+ if (!onChangeText) {\nreturn;\n}\n- this.onChangeText(newValue);\n- }\n- onOldInputKeyPress = (event: KeyPressEvent) => {\n- const { key } = event.nativeEvent;\n- if (this.lastKeyPressed && this.lastKeyPressed.length > key.length) {\n- return;\n+ let text;\n+ if (this.lastMessageSent && inputText.startsWith(this.lastMessageSent)) {\n+ text = inputText.substring(this.lastMessageSent.length);\n+ } else {\n+ text = inputText;\n+ this.lastMessageSent = null;\n}\n- this.lastKeyPressed = key;\n- this.props.onKeyPress && this.props.onKeyPress(event);\n+ onChangeText(text);\n};\n- onOldInputBlur = () => {\n- this.sendMessage();\n- };\n-\n- textInputRef = (textInput: ?TextInput) => {\n- if (this.state.textInputKey > 0 && textInput) {\n- textInput.focus();\n+ async getValueAndReset(): Promise<?string> {\n+ this.lastMessageSent = this.props.value;\n+ this.props.onChangeText && this.props.onChangeText('');\n+ if (this.textInput) {\n+ this.textInput.clear();\n}\n- this.props.textInputRef(textInput);\n- };\n-\n- getValueAndReset(): Promise<?string> {\n- this.onChangeText('');\n- return new Promise(resolve => {\n- this.pendingMessage = {\n- value: this.props.value,\n- resolve,\n- };\n- this.setState(prevState => ({\n- textInputKey: prevState.textInputKey + 1,\n- }));\n- });\n+ return this.props.value;\n}\nrender() {\nconst { textInputRef, ...props } = this.props;\n-\n- const textInputs = [];\n- if (this.state.textInputKey > 0) {\n- textInputs.push(\n- <TextInput\n- {...props}\n- style={[props.style, styles.invisibleTextInput]}\n- onChangeText={this.onOldInputChangeText}\n- onKeyPress={this.onOldInputKeyPress}\n- onBlur={this.onOldInputBlur}\n- key={this.state.textInputKey - 1}\n- />,\n- );\n- }\n- textInputs.push(\n+ return (\n+ <View style={styles.textInputContainer}>\n<TextInput\n{...props}\nonChangeText={this.onChangeText}\n- key={this.state.textInputKey}\nref={this.textInputRef}\n- />,\n+ />\n+ </View>\n);\n-\n- return <View style={styles.textInputContainer}>{textInputs}</View>;\n}\n+\n+ textInputRef = (textInput: ?TextInput) => {\n+ this.textInput = textInput;\n+ this.props.textInputRef(textInput);\n+ };\n}\nconst styles = StyleSheet.create({\n- invisibleTextInput: {\n- opacity: 0,\n- position: 'absolute',\n- },\ntextInputContainer: {\nflex: 1,\n},\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] ClearableTextInput for Android |
129,187 | 23.04.2020 20:06:51 | 14,400 | 5efbbc8e3fbca8f738cec1b6074e6457fb0a9125 | [native] Final ClearableTextInput fixes | [
{
"change_type": "MODIFY",
"old_path": "native/chat/chat-input-bar.react.js",
"new_path": "native/chat/chat-input-bar.react.js",
"diff": "@@ -451,7 +451,8 @@ class ChatInputBar extends React.PureComponent<Props, State> {\nclearableTextInput,\n'clearableTextInput should be sent in onSend',\n);\n- const text = await clearableTextInput.getValueAndReset();\n+ let text = await clearableTextInput.getValueAndReset();\n+ text = text.trim();\nif (!text) {\nreturn;\n}\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "native/components/clearable-text-input.js",
"diff": "+// @flow\n+\n+import * as React from 'react';\n+import { TextInput } from 'react-native';\n+\n+type TextInputProps = React.ElementConfig<typeof TextInput>;\n+export type ClearableTextInputProps = {|\n+ ...TextInputProps,\n+ textInputRef: (textInput: ?TextInput) => mixed,\n+ onChangeText: $NonMaybeType<$PropertyType<TextInputProps, 'onChangeText'>>,\n+ value: $NonMaybeType<$PropertyType<TextInputProps, 'value'>>,\n+|};\n"
},
{
"change_type": "MODIFY",
"old_path": "native/components/clearable-text-input.react.ios.js",
"new_path": "native/components/clearable-text-input.react.ios.js",
"diff": "// @flow\n+import type { ClearableTextInputProps } from './clearable-text-input';\nimport type { KeyPressEvent } from '../types/react-native';\nimport * as React from 'react';\n@@ -7,25 +8,20 @@ import { TextInput, View, StyleSheet } from 'react-native';\nimport invariant from 'invariant';\n-type Props = {|\n- ...React.ElementConfig<typeof TextInput>,\n- textInputRef: (textInput: ?TextInput) => mixed,\n-|};\ntype State = {|\ntextInputKey: number,\n|};\n-class ClearableTextInput extends React.PureComponent<Props, State> {\n+class ClearableTextInput extends React.PureComponent<\n+ ClearableTextInputProps,\n+ State,\n+> {\nstate = {\ntextInputKey: 0,\n};\n- pendingMessage: ?{| value: ?string, resolve: (value: ?string) => void |};\n+ pendingMessage: ?{| value: string, resolve: (value: string) => void |};\nlastKeyPressed: ?string;\nlastTextInputSent = -1;\n- onChangeText = (text: string) => {\n- this.props.onChangeText && this.props.onChangeText(text);\n- };\n-\nsendMessage() {\nif (this.pendingMessageSent) {\nreturn;\n@@ -79,7 +75,7 @@ class ClearableTextInput extends React.PureComponent<Props, State> {\nif (this.props.value === newValue) {\nreturn;\n}\n- this.onChangeText(newValue);\n+ this.props.onChangeText(newValue);\n}\nonOldInputKeyPress = (event: KeyPressEvent) => {\n@@ -102,13 +98,11 @@ class ClearableTextInput extends React.PureComponent<Props, State> {\nthis.props.textInputRef(textInput);\n};\n- getValueAndReset(): Promise<?string> {\n- this.onChangeText('');\n+ getValueAndReset(): Promise<string> {\n+ const { value } = this.props;\n+ this.props.onChangeText('');\nreturn new Promise(resolve => {\n- this.pendingMessage = {\n- value: this.props.value,\n- resolve,\n- };\n+ this.pendingMessage = { value, resolve };\nthis.setState(prevState => ({\ntextInputKey: prevState.textInputKey + 1,\n}));\n@@ -134,7 +128,7 @@ class ClearableTextInput extends React.PureComponent<Props, State> {\ntextInputs.push(\n<TextInput\n{...props}\n- onChangeText={this.onChangeText}\n+ onChangeText={this.props.onChangeText}\nkey={this.state.textInputKey}\nref={this.textInputRef}\n/>,\n"
},
{
"change_type": "MODIFY",
"old_path": "native/components/clearable-text-input.react.js",
"new_path": "native/components/clearable-text-input.react.js",
"diff": "// @flow\n+import type { ClearableTextInputProps } from './clearable-text-input';\n+\nimport * as React from 'react';\nimport { TextInput, View, StyleSheet } from 'react-native';\n-type Props = {|\n- ...React.ElementConfig<typeof TextInput>,\n- textInputRef: (textInput: ?TextInput) => mixed,\n-|};\n-class ClearableTextInput extends React.PureComponent<Props> {\n+import sleep from 'lib/utils/sleep';\n+\n+import { waitForInteractions } from '../utils/interactions';\n+\n+class ClearableTextInput extends React.PureComponent<ClearableTextInputProps> {\ntextInput: ?TextInput;\nlastMessageSent: ?string;\n+ queuedResolve: ?() => mixed;\nonChangeText = (inputText: string) => {\n- const { onChangeText } = this.props;\n- if (!onChangeText) {\n- return;\n- }\n-\nlet text;\nif (this.lastMessageSent && inputText.startsWith(this.lastMessageSent)) {\ntext = inputText.substring(this.lastMessageSent.length);\n@@ -24,16 +22,31 @@ class ClearableTextInput extends React.PureComponent<Props> {\ntext = inputText;\nthis.lastMessageSent = null;\n}\n- onChangeText(text);\n+ this.props.onChangeText(text);\n};\n- async getValueAndReset(): Promise<?string> {\n- this.lastMessageSent = this.props.value;\n- this.props.onChangeText && this.props.onChangeText('');\n+ getValueAndReset(): Promise<string> {\n+ const { value } = this.props;\n+ this.lastMessageSent = value;\n+ this.props.onChangeText('');\nif (this.textInput) {\nthis.textInput.clear();\n}\n- return this.props.value;\n+ return new Promise(resolve => {\n+ this.queuedResolve = async () => {\n+ await waitForInteractions();\n+ await sleep(5);\n+ resolve(value);\n+ };\n+ });\n+ }\n+\n+ componentDidUpdate(prevProps: ClearableTextInputProps) {\n+ if (!this.props.value && prevProps.value && this.queuedResolve) {\n+ const resolve = this.queuedResolve;\n+ this.queuedResolve = null;\n+ resolve();\n+ }\n}\nrender() {\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "native/utils/interactions.js",
"diff": "+// @flow\n+\n+import { InteractionManager } from 'react-native';\n+\n+function waitForInteractions(): Promise<void> {\n+ return new Promise(resolve => {\n+ InteractionManager.runAfterInteractions(resolve);\n+ });\n+}\n+\n+export { waitForInteractions };\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Final ClearableTextInput fixes |
129,187 | 24.04.2020 19:28:45 | 14,400 | bb0578f2ccfe3ded96155a6a4939302945662dcf | [native] Don't change tabs when back button is pressed on Android | [
{
"change_type": "MODIFY",
"old_path": "native/navigation/app-navigator.react.js",
"new_path": "native/navigation/app-navigator.react.js",
"diff": "@@ -49,6 +49,7 @@ const TabNavigator = createBottomTabNavigator(\ninitialRouteName: CalendarRouteName,\nlazy: false,\ntabBarComponent: TabBar,\n+ backBehavior: 'none',\ntabBarOptions: {\nkeyboardHidesTabBar: false,\n},\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Don't change tabs when back button is pressed on Android |
129,187 | 24.04.2020 19:29:39 | 14,400 | b05f5df146f3f413e6bd58d3ecef3af65236dd85 | [native] Don't finish SplashActivity until MainActivity is started | [
{
"change_type": "MODIFY",
"old_path": "native/android/app/src/main/java/org/squadcal/SplashActivity.java",
"new_path": "native/android/app/src/main/java/org/squadcal/SplashActivity.java",
"diff": "@@ -22,8 +22,8 @@ public class SplashActivity extends AppCompatActivity {\nprivate void forwardIntent(Intent intent) {\nIntent mainIntent = new Intent(this, MainActivity.class);\nmainIntent.putExtras(intent);\n- finish();\nstartActivity(mainIntent);\n+ finish();\n}\n}\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Don't finish SplashActivity until MainActivity is started |
129,187 | 24.04.2020 19:31:11 | 14,400 | fa0ab162fb330e4a07a95df636806e9c06417e3d | [native] Add editTextBackground for all styles.xml | [
{
"change_type": "MODIFY",
"old_path": "native/android/app/src/main/res/values-w481dp-xxhdpi/styles.xml",
"new_path": "native/android/app/src/main/res/values-w481dp-xxhdpi/styles.xml",
"diff": "<resources>\n<style name=\"AppTheme\" parent=\"Theme.AppCompat.Light.NoActionBar\">\n+ <item name=\"android:editTextBackground\">@android:color/transparent</item>\n</style>\n<style name=\"SplashTheme\" parent=\"Theme.AppCompat.Light.NoActionBar\">\n<item name=\"android:windowNoTitle\">true</item>\n"
},
{
"change_type": "MODIFY",
"old_path": "native/android/app/src/main/res/values-w481dp-xxxhdpi/styles.xml",
"new_path": "native/android/app/src/main/res/values-w481dp-xxxhdpi/styles.xml",
"diff": "<resources>\n<style name=\"AppTheme\" parent=\"Theme.AppCompat.Light.NoActionBar\">\n+ <item name=\"android:editTextBackground\">@android:color/transparent</item>\n</style>\n<style name=\"SplashTheme\" parent=\"Theme.AppCompat.Light.NoActionBar\">\n<item name=\"android:windowNoTitle\">true</item>\n"
},
{
"change_type": "MODIFY",
"old_path": "native/android/app/src/main/res/values-w801dp-xhdpi/styles.xml",
"new_path": "native/android/app/src/main/res/values-w801dp-xhdpi/styles.xml",
"diff": "<resources>\n<style name=\"AppTheme\" parent=\"Theme.AppCompat.Light.NoActionBar\">\n+ <item name=\"android:editTextBackground\">@android:color/transparent</item>\n</style>\n<style name=\"SplashTheme\" parent=\"Theme.AppCompat.Light.NoActionBar\">\n<item name=\"android:windowNoTitle\">true</item>\n"
},
{
"change_type": "MODIFY",
"old_path": "native/android/app/src/main/res/values-w801dp/styles.xml",
"new_path": "native/android/app/src/main/res/values-w801dp/styles.xml",
"diff": "<resources>\n<style name=\"AppTheme\" parent=\"Theme.AppCompat.Light.NoActionBar\">\n+ <item name=\"android:editTextBackground\">@android:color/transparent</item>\n</style>\n<style name=\"SplashTheme\" parent=\"Theme.AppCompat.Light.NoActionBar\">\n<item name=\"android:windowNoTitle\">true</item>\n"
},
{
"change_type": "MODIFY",
"old_path": "native/android/app/src/main/res/values-w961dp-hdpi/styles.xml",
"new_path": "native/android/app/src/main/res/values-w961dp-hdpi/styles.xml",
"diff": "<resources>\n<style name=\"AppTheme\" parent=\"Theme.AppCompat.Light.NoActionBar\">\n+ <item name=\"android:editTextBackground\">@android:color/transparent</item>\n</style>\n<style name=\"SplashTheme\" parent=\"Theme.AppCompat.Light.NoActionBar\">\n<item name=\"android:windowNoTitle\">true</item>\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Add editTextBackground for all styles.xml |
129,187 | 24.04.2020 21:07:41 | 14,400 | 8f96d948843f2c2e9f1ace107cb9973177ba9bca | [native] Use waitForInteractions to decide when to hide SplashScreen on Android | [
{
"change_type": "MODIFY",
"old_path": "native/navigation/app-navigator.react.js",
"new_path": "native/navigation/app-navigator.react.js",
"diff": "@@ -38,6 +38,7 @@ import KeyboardStateContainer from '../keyboard/keyboard-state-container.react';\nimport PushHandler from '../push/push-handler.react';\nimport { getPersistor } from '../redux/persist';\nimport { RootContext } from '../root-context';\n+import { waitForInteractions } from '../utils/interactions';\nconst TabNavigator = createBottomTabNavigator(\n{\n@@ -79,7 +80,7 @@ function WrappedAppNavigator(props: Props) {\nReact.useEffect(() => {\nif (Platform.OS === 'android') {\n- setTimeout(SplashScreen.hide, 350);\n+ waitForInteractions().then(() => SplashScreen.hide());\n} else {\nSplashScreen.hide();\n}\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Use waitForInteractions to decide when to hide SplashScreen on Android |
129,187 | 25.04.2020 00:45:39 | 14,400 | fce34c1eb0212f30713d88b5a052bed70c0388d0 | [native] Update video dimensions after transcode | [
{
"change_type": "MODIFY",
"old_path": "lib/types/media-types.js",
"new_path": "lib/types/media-types.js",
"diff": "@@ -103,6 +103,7 @@ export type VideoProbeMediaMissionStep = {|\next: ?string,\ncodec: ?string,\nformat: ?$ReadOnlyArray<string>,\n+ dimensions: ?Dimensions,\n|};\nexport type ReadFileHeaderMediaMissionStep = {|\n@@ -357,6 +358,7 @@ export const mediaMissionPropType = PropTypes.shape({\next: PropTypes.string,\ncodec: PropTypes.string,\nformat: PropTypes.arrayOf(PropTypes.string),\n+ dimensions: dimensionsPropType,\n}),\nPropTypes.shape({\nstep: PropTypes.oneOf(['video_ffmpeg_transcode']).isRequired,\n"
},
{
"change_type": "MODIFY",
"old_path": "native/media/ffmpeg.js",
"new_path": "native/media/ffmpeg.js",
"diff": "@@ -81,25 +81,28 @@ class FFmpeg {\nreturn this.queueCommand('process', wrappedCommand);\n}\n- getVideoFormat(path: string) {\n- const wrappedCommand = () => FFmpeg.innerGetVideoFormat(path);\n+ getVideoInfo(path: string) {\n+ const wrappedCommand = () => FFmpeg.innerGetVideoInfo(path);\nreturn this.queueCommand('probe', wrappedCommand);\n}\n- static async innerGetVideoFormat(path: string) {\n+ static async innerGetVideoInfo(path: string) {\nconst info = await RNFFprobe.getMediaInformation(path);\n- const codec = FFmpeg.getVideoCodec(info);\n+ const videoStreamInfo = FFmpeg.getVideoStreamInfo(info);\n+ const codec = videoStreamInfo && videoStreamInfo.codec;\n+ const dimensions = videoStreamInfo && videoStreamInfo.dimensions;\nconst format = info.format.split(',');\n- return { codec, format };\n+ return { codec, format, dimensions };\n}\n- static getVideoCodec(info: Object): ?string {\n+ static getVideoStreamInfo(info: Object) {\nif (!info.streams) {\nreturn null;\n}\nfor (let stream of info.streams) {\nif (stream.type === 'video') {\n- return stream.codec;\n+ const { codec, width, height } = stream;\n+ return { codec, dimensions: { width, height } };\n}\n}\nreturn null;\n"
},
{
"change_type": "MODIFY",
"old_path": "native/media/media-utils.js",
"new_path": "native/media/media-utils.js",
"diff": "@@ -127,6 +127,7 @@ async function processMediaMission(\nfilename: selection.filename,\nfileSize,\nduration: selection.duration,\n+ dimensions,\n});\nsteps.push(...videoSteps);\nif (!videoResult.success) {\n@@ -135,6 +136,7 @@ async function processMediaMission(\n}\nuploadURI = videoResult.uri;\nmime = videoResult.mime;\n+ dimensions = videoResult.dimensions;\n} else if (\nselection.step === 'photo_capture' ||\nselection.step === 'photo_library'\n"
},
{
"change_type": "MODIFY",
"old_path": "native/media/video-utils.js",
"new_path": "native/media/video-utils.js",
"diff": "@@ -4,6 +4,7 @@ import type {\nMediaMissionStep,\nMediaMissionFailure,\nVideoProbeMediaMissionStep,\n+ Dimensions,\n} from 'lib/types/media-types';\nimport filesystem from 'react-native-fs';\n@@ -20,11 +21,13 @@ type ProcessVideoInfo = {|\nfilename: string,\nfileSize: number,\nduration: number,\n+ dimensions: Dimensions,\n|};\ntype ProcessVideoResponse = {|\nsuccess: true,\nuri: string,\nmime: string,\n+ dimensions: Dimensions,\n|};\nasync function processVideo(\ninput: ProcessVideoInfo,\n@@ -37,7 +40,7 @@ async function processVideo(\nconst path = pathFromURI(input.uri);\ninvariant(path, `could not extract path from ${input.uri}`);\n- const initialCheckStep = await checkVideoCodec(path);\n+ const initialCheckStep = await checkVideoInfo(path);\nsteps.push(initialCheckStep);\nconst plan = getVideoProcessingPlan({\n@@ -66,6 +69,7 @@ async function processVideo(\nsuccess: true,\nuri: input.uri,\nmime: 'video/mp4',\n+ dimensions: input.dimensions,\n},\n};\n}\n@@ -110,7 +114,7 @@ async function processVideo(\n};\n}\n- const transcodeProbeStep = await checkVideoCodec(outputPath);\n+ const transcodeProbeStep = await checkVideoInfo(outputPath);\nsteps.push(transcodeProbeStep);\nif (!transcodeProbeStep.success) {\nreturn {\n@@ -119,29 +123,34 @@ async function processVideo(\n};\n}\n+ const dimensions = transcodeProbeStep.dimensions\n+ ? transcodeProbeStep.dimensions\n+ : input.dimensions;\nreturn {\nsteps,\nresult: {\nsuccess: true,\nuri: `file://${outputPath}`,\nmime: 'video/mp4',\n+ dimensions,\n},\n};\n}\n-async function checkVideoCodec(\n+async function checkVideoInfo(\npath: string,\n): Promise<VideoProbeMediaMissionStep> {\nconst ext = extensionFromFilename(path);\nlet codec,\nformat,\n+ dimensions,\nsuccess = false,\nexceptionMessage;\nconst start = Date.now();\nif (ext === 'mp4' || ext === 'mov') {\ntry {\n- ({ codec, format } = await ffmpeg.getVideoFormat(path));\n+ ({ codec, format, dimensions } = await ffmpeg.getVideoInfo(path));\nsuccess = codec === 'h264' && format.includes('mp4');\n} catch (e) {\nif (\n@@ -164,6 +173,7 @@ async function checkVideoCodec(\next,\ncodec,\nformat,\n+ dimensions,\n};\n}\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Update video dimensions after transcode |
129,187 | 25.04.2020 00:46:10 | 14,400 | 0e76c06be63196f376ed328d351f9ec580edc579 | [native] ffmpeg options for h264_videotoolbox | [
{
"change_type": "MODIFY",
"old_path": "lib/utils/video-utils.js",
"new_path": "lib/utils/video-utils.js",
"diff": "// @flow\n+import invariant from 'invariant';\n+\nimport { replaceExtension } from './file-utils';\nimport { getUUID } from './uuid';\nimport { maxDimensions } from './media-utils';\n@@ -40,16 +42,26 @@ function getVideoProcessingPlan(input: Input): ?Plan {\n);\nconst outputPath = `${outputDirectory}${outputFilename}`;\n+ let quality, speed;\n+ if (outputCodec === 'h264') {\nconst { floor, min, max, log2 } = Math;\nconst crf = floor(min(5, max(0, log2(inputDuration / 5)))) + 23;\n+ quality = `-crf ${crf}`;\n+ speed = '-preset ultrafast';\n+ } else if (outputCodec === 'h264_videotoolbox') {\n+ quality = '-profile:v baseline';\n+ speed = '-realtime 1';\n+ } else {\n+ invariant(false, `unrecognized outputCodec ${outputCodec}`);\n+ }\nconst ffmpegCommand =\n`-i ${inputPath} ` +\n`-c:a copy -c:v ${outputCodec} ` +\n- `-crf ${crf} ` +\n+ `${quality} ` +\n'-vsync 2 -r 30 ' +\n`-vf scale=${maxWidth}:${maxHeight}:force_original_aspect_ratio=decrease ` +\n- '-preset ultrafast ' +\n+ `${speed} ` +\n'-movflags +faststart ' +\n'-pix_fmt yuv420p ' +\noutputPath;\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] ffmpeg options for h264_videotoolbox |
129,187 | 25.04.2020 15:41:28 | 14,400 | a8b3a12b25ce969e8199394ae493cabdfd27c133 | [native] Treat animated GIFs as videos
Also lets `ffprobe` determine duration for videos since `expo-media-library` won't have it for animated GIFs | [
{
"change_type": "MODIFY",
"old_path": "lib/types/media-types.js",
"new_path": "lib/types/media-types.js",
"diff": "@@ -100,7 +100,8 @@ export type VideoProbeMediaMissionStep = {|\nexceptionMessage: ?string,\ntime: number, // ms\npath: string,\n- ext: ?string,\n+ validFormat: boolean,\n+ duration: ?number, // seconds\ncodec: ?string,\nformat: ?$ReadOnlyArray<string>,\ndimensions: ?Dimensions,\n@@ -116,6 +117,16 @@ export type ReadFileHeaderMediaMissionStep = {|\nmediaType: ?MediaType,\n|};\n+export type FrameCountMediaMissionStep = {|\n+ step: 'frame_count',\n+ success: boolean,\n+ exceptionMessage: ?string,\n+ time: number,\n+ path: string,\n+ mime: string,\n+ hasMultipleFrames: ?boolean,\n+|};\n+\nexport type MediaLibrarySelection =\n| {|\nstep: 'photo_library',\n@@ -136,7 +147,7 @@ export type MediaLibrarySelection =\nselectTime: number, // ms timestamp\nsendTime: number, // ms timestamp\nretries: number,\n- duration: number,\n+ duration: number, // seconds\n|};\nconst photoLibrarySelectionPropType = PropTypes.shape({\n@@ -200,6 +211,7 @@ export type MediaMissionStep =\nfileSize: ?number,\n|}\n| ReadFileHeaderMediaMissionStep\n+ | FrameCountMediaMissionStep\n| {|\nstep: 'photo_manipulation',\nsuccess: boolean,\n@@ -256,21 +268,14 @@ export type MediaMissionFailure =\n|}\n| {|\nsuccess: false,\n- reason: 'media_type_mismatch',\n- reportedMediaType: MediaType,\n- detectedMediaType: MediaType,\n+ reason: 'media_type_fetch_failed',\ndetectedMIME: ?string,\n|}\n- | {|\n- success: false,\n- reason: 'mime_fetch_failed',\n- |}\n| {|\nsuccess: false,\nreason: 'mime_type_mismatch',\nreportedMediaType: MediaType,\nreportedMIME: string,\n- detectedMediaType: ?MediaType,\ndetectedMIME: string,\n|}\n| {|\n@@ -278,6 +283,10 @@ export type MediaMissionFailure =\nreason: 'http_upload_failed',\nexceptionMessage: ?string,\n|}\n+ | {|\n+ success: false,\n+ reason: 'video_probe_failed',\n+ |}\n| {|\nsuccess: false,\nreason: 'video_transcode_failed',\n@@ -339,6 +348,15 @@ export const mediaMissionPropType = PropTypes.shape({\nmime: PropTypes.string,\nmediaType: mediaTypePropType,\n}),\n+ PropTypes.shape({\n+ step: PropTypes.oneOf(['frame_count']).isRequired,\n+ success: PropTypes.bool.isRequired,\n+ exceptionMessage: PropTypes.string,\n+ time: PropTypes.number.isRequired,\n+ path: PropTypes.string.isRequired,\n+ mime: PropTypes.string.isRequired,\n+ hasMultipleFrames: PropTypes.bool,\n+ }),\nPropTypes.shape({\nstep: PropTypes.oneOf(['photo_manipulation']).isRequired,\nsuccess: PropTypes.bool.isRequired,\n@@ -355,7 +373,8 @@ export const mediaMissionPropType = PropTypes.shape({\nexceptionMessage: PropTypes.string,\ntime: PropTypes.number.isRequired,\npath: PropTypes.string.isRequired,\n- ext: PropTypes.string,\n+ validFormat: PropTypes.bool.isRequired,\n+ duration: PropTypes.number,\ncodec: PropTypes.string,\nformat: PropTypes.arrayOf(PropTypes.string),\ndimensions: dimensionsPropType,\n@@ -409,21 +428,14 @@ export const mediaMissionPropType = PropTypes.shape({\n}),\nPropTypes.shape({\nsuccess: PropTypes.oneOf([false]).isRequired,\n- reason: PropTypes.oneOf(['media_type_mismatch']).isRequired,\n- reportedMediaType: mediaTypePropType.isRequired,\n- detectedMediaType: mediaTypePropType.isRequired,\n+ reason: PropTypes.oneOf(['media_type_fetch_failed']).isRequired,\ndetectedMIME: PropTypes.string,\n}),\n- PropTypes.shape({\n- success: PropTypes.oneOf([false]).isRequired,\n- reason: PropTypes.oneOf(['mime_fetch_failed']).isRequired,\n- }),\nPropTypes.shape({\nsuccess: PropTypes.oneOf([false]).isRequired,\nreason: PropTypes.oneOf(['mime_type_mismatch']).isRequired,\nreportedMediaType: mediaTypePropType.isRequired,\nreportedMIME: PropTypes.string.isRequired,\n- detectedMediaType: mediaTypePropType,\ndetectedMIME: PropTypes.string.isRequired,\n}),\nPropTypes.shape({\n@@ -431,6 +443,10 @@ export const mediaMissionPropType = PropTypes.shape({\nreason: PropTypes.oneOf(['http_upload_failed']).isRequired,\nexceptionMessage: PropTypes.string,\n}),\n+ PropTypes.shape({\n+ success: PropTypes.oneOf([false]).isRequired,\n+ reason: PropTypes.oneOf(['video_probe_failed']).isRequired,\n+ }),\nPropTypes.shape({\nsuccess: PropTypes.oneOf([false]).isRequired,\nreason: PropTypes.oneOf(['video_transcode_failed']).isRequired,\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/utils/video-utils.js",
"new_path": "lib/utils/video-utils.js",
"diff": "@@ -69,4 +69,16 @@ function getVideoProcessingPlan(input: Input): ?Plan {\nreturn { outputPath, ffmpegCommand };\n}\n-export { getVideoProcessingPlan };\n+function getHasMultipleFramesProbeCommand(path: string) {\n+ const ffprobeCommand =\n+ '-v error ' +\n+ '-count_frames ' +\n+ '-select_streams v:0 ' +\n+ '-show_entries stream=nb_read_frames ' +\n+ '-of default=nokey=1:noprint_wrappers=1 ' +\n+ '-read_intervals \"%+#2\" ' +\n+ path;\n+ return ffprobeCommand;\n+}\n+\n+export { getVideoProcessingPlan, getHasMultipleFramesProbeCommand };\n"
},
{
"change_type": "MODIFY",
"old_path": "native/input/input-state-container.react.js",
"new_path": "native/input/input-state-container.react.js",
"diff": "@@ -608,7 +608,7 @@ class InputStateContainer extends React.PureComponent<Props, State> {\nstep: 'dispose_uploaded_local_file',\nsuccess: disposeSuccess,\nexceptionMessage: disposeExceptionMessage,\n- time: disposeStart - Date.now(),\n+ time: Date.now() - disposeStart,\npath: shouldDisposePath,\n});\n@@ -619,7 +619,6 @@ class InputStateContainer extends React.PureComponent<Props, State> {\nconst { viewerID } = this.props;\nif (__DEV__ || (viewerID && isStaff(viewerID))) {\nreturn {\n- initialFileHeaderCheck: true,\nfinalFileHeaderCheck: true,\n};\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "native/media/ffmpeg.js",
"new_path": "native/media/ffmpeg.js",
"diff": "import { RNFFmpeg, RNFFprobe, RNFFmpegConfig } from 'react-native-ffmpeg';\n+import { getHasMultipleFramesProbeCommand } from 'lib/utils/video-utils';\n+\nif (!__DEV__) {\nRNFFmpegConfig.disableLogs();\nRNFFmpegConfig.disableStatistics();\n@@ -92,7 +94,8 @@ class FFmpeg {\nconst codec = videoStreamInfo && videoStreamInfo.codec;\nconst dimensions = videoStreamInfo && videoStreamInfo.dimensions;\nconst format = info.format.split(',');\n- return { codec, format, dimensions };\n+ const duration = info.duration / 1000;\n+ return { codec, format, dimensions, duration };\n}\nstatic getVideoStreamInfo(info: Object) {\n@@ -107,6 +110,18 @@ class FFmpeg {\n}\nreturn null;\n}\n+\n+ hasMultipleFrames(path: string) {\n+ const wrappedCommand = () => FFmpeg.innerHasMultipleFrames(path);\n+ return this.queueCommand('probe', wrappedCommand);\n+ }\n+\n+ static async innerHasMultipleFrames(path: string) {\n+ await RNFFprobe.execute(getHasMultipleFramesProbeCommand(path));\n+ const probeOutput = await RNFFmpegConfig.getLastCommandOutput();\n+ const numFrames = parseInt(probeOutput.lastCommandOutput);\n+ return numFrames > 1;\n+ }\n}\nconst ffmpeg = new FFmpeg();\n"
},
{
"change_type": "MODIFY",
"old_path": "native/media/file-utils.js",
"new_path": "native/media/file-utils.js",
"diff": "@@ -13,9 +13,11 @@ import filesystem from 'react-native-fs';\nimport base64 from 'base-64';\nimport { pathFromURI, fileInfoFromData } from 'lib/utils/file-utils';\n+\nimport { stringToIntArray } from './blob-utils';\n+import { ffmpeg } from './ffmpeg';\n-const defaultOptionalFields = Object.freeze({});\n+const defaultOptionals = Object.freeze({});\ntype FetchFileInfoResult = {|\nsuccess: true,\n@@ -25,20 +27,26 @@ type FetchFileInfoResult = {|\nmime: ?string,\nmediaType: ?MediaType,\n|};\n-type OptionalFields = $Shape<{| orientation: boolean, mime: boolean |}>;\n+type OptionalInputs = $Shape<{| mediaNativeID: ?string |}>;\n+type OptionalFields = $Shape<{|\n+ orientation: boolean,\n+ mediaType: boolean,\n+ mime: boolean,\n+|}>;\nasync function fetchFileInfo(\ninputURI: string,\n- mediaNativeID?: ?string,\n- optionalFields?: OptionalFields = defaultOptionalFields,\n+ optionalInputs?: OptionalInputs = defaultOptionals,\n+ optionalFields?: OptionalFields = defaultOptionals,\n): Promise<{|\nsteps: $ReadOnlyArray<MediaMissionStep>,\nresult: MediaMissionFailure | FetchFileInfoResult,\n|}> {\n+ const { mediaNativeID } = optionalInputs;\nconst steps = [];\nlet assetInfoPromise, newLocalURI;\n- const needsLocalURI = !pathFromURI(inputURI);\n- if (mediaNativeID && (needsLocalURI || optionalFields.orientation)) {\n+ const inputPath = pathFromURI(inputURI);\n+ if (mediaNativeID && (!inputPath || optionalFields.orientation)) {\nassetInfoPromise = (async () => {\nconst {\nsteps: assetInfoSteps,\n@@ -51,17 +59,21 @@ async function fetchFileInfo(\n}\nconst getLocalURIPromise = (async () => {\n- if (!needsLocalURI) {\n- return inputURI;\n+ if (inputPath) {\n+ return { localURI: inputURI, path: inputPath };\n}\nif (!assetInfoPromise) {\nreturn null;\n}\nconst { localURI } = await assetInfoPromise;\n- if (!localURI || !pathFromURI(localURI)) {\n+ if (!localURI) {\n+ return null;\n+ }\n+ const path = pathFromURI(localURI);\n+ if (!path) {\nreturn null;\n}\n- return localURI;\n+ return { localURI, path };\n})();\nconst getOrientationPromise = (async () => {\n@@ -73,10 +85,11 @@ async function fetchFileInfo(\n})();\nconst getFileSizePromise = (async () => {\n- const localURI = await getLocalURIPromise;\n- if (!localURI) {\n+ const localURIResult = await getLocalURIPromise;\n+ if (!localURIResult) {\nreturn null;\n}\n+ const { localURI } = localURIResult;\nconst { steps: fileSizeSteps, result: fileSize } = await fetchFileSize(\nlocalURI,\n);\n@@ -85,33 +98,41 @@ async function fetchFileInfo(\n})();\nconst getTypesPromise = (async () => {\n- if (!optionalFields.mime) {\n+ if (!optionalFields.mime && !optionalFields.mediaType) {\nreturn { mime: null, mediaType: null };\n}\n- const [localURI, fileSize] = await Promise.all([\n+ const [localURIResult, fileSize] = await Promise.all([\ngetLocalURIPromise,\ngetFileSizePromise,\n]);\n- if (!localURI || !fileSize) {\n+ if (!localURIResult || !fileSize) {\nreturn { mime: null, mediaType: null };\n}\n+ const { localURI, path } = localURIResult;\nconst readFileStep = await readFileHeader(localURI, fileSize);\nsteps.push(readFileStep);\n- return {\n- mime: readFileStep.mime,\n- mediaType: readFileStep.mediaType,\n- };\n+ const { mime, mediaType: baseMediaType } = readFileStep;\n+ if (!optionalFields.mediaType || !mime || !baseMediaType) {\n+ return { mime, mediaType: null };\n+ }\n+ const {\n+ steps: getMediaTypeSteps,\n+ result: mediaType,\n+ } = await getMediaTypeInfo(path, mime, baseMediaType);\n+ steps.push(...getMediaTypeSteps);\n+ return { mime, mediaType };\n})();\n- const [uri, orientation, fileSize, types] = await Promise.all([\n+ const [localURIResult, orientation, fileSize, types] = await Promise.all([\ngetLocalURIPromise,\ngetOrientationPromise,\ngetFileSizePromise,\ngetTypesPromise,\n]);\n- if (!uri) {\n+ if (!localURIResult) {\nreturn { steps, result: { success: false, reason: 'no_file_path' } };\n}\n+ const uri = localURIResult.localURI;\nif (!fileSize) {\nreturn {\nsteps,\n@@ -270,4 +291,48 @@ async function readFileHeader(\n};\n}\n+async function getMediaTypeInfo(\n+ path: string,\n+ mime: string,\n+ baseMediaType: MediaType,\n+): Promise<{|\n+ steps: $ReadOnlyArray<MediaMissionStep>,\n+ result: ?MediaType,\n+|}> {\n+ if (mime !== 'image/gif') {\n+ return { steps: [], result: baseMediaType };\n+ }\n+\n+ let hasMultipleFrames,\n+ frameCountSuccess = false,\n+ frameCountExceptionMessage;\n+ const frameCountStart = Date.now();\n+ try {\n+ hasMultipleFrames = await ffmpeg.hasMultipleFrames(path);\n+ frameCountSuccess = true;\n+ } catch (e) {\n+ if (\n+ e &&\n+ typeof e === 'object' &&\n+ e.message &&\n+ typeof e.message === 'string'\n+ ) {\n+ frameCountExceptionMessage = e.message;\n+ }\n+ }\n+ const steps = [\n+ {\n+ step: 'frame_count',\n+ success: frameCountSuccess,\n+ exceptionMessage: frameCountExceptionMessage,\n+ time: Date.now() - frameCountStart,\n+ path,\n+ mime,\n+ hasMultipleFrames,\n+ },\n+ ];\n+ const result = hasMultipleFrames ? 'video' : 'photo';\n+ return { steps, result };\n+}\n+\nexport { fetchFileInfo };\n"
},
{
"change_type": "MODIFY",
"old_path": "native/media/media-utils.js",
"new_path": "native/media/media-utils.js",
"diff": "@@ -18,7 +18,6 @@ import { processVideo } from './video-utils';\nimport { processImage } from './image-utils';\ntype MediaProcessConfig = $Shape<{|\n- initialFileHeaderCheck: boolean,\nfinalFileHeaderCheck: boolean,\n|}>;\ntype MediaResult = {|\n@@ -63,7 +62,7 @@ async function processMediaMission(\ndimensions = selection.dimensions,\nmime = null,\nfinished = false;\n- const mediaType = selection.step.startsWith('photo_') ? 'photo' : 'video';\n+ let mediaType;\nconst finish = (failure?: MediaMissionFailure) => {\ninvariant(!finished, 'finish called twice in processMediaMission');\nfinished = true;\n@@ -72,8 +71,8 @@ async function processMediaMission(\nreturn;\n}\ninvariant(\n- uploadURI && mime,\n- \"if we're finishing successfully we should have a URI and MIME type\",\n+ uploadURI && mime && mediaType,\n+ 'missing required fields to finish',\n);\nconst shouldDisposePath =\ninitialURI !== uploadURI ? pathFromURI(uploadURI) : null;\n@@ -95,10 +94,11 @@ async function processMediaMission(\n: null;\nconst { steps: fileInfoSteps, result: fileInfoResult } = await fetchFileInfo(\nselection.uri,\n- mediaNativeID,\n+ { mediaNativeID },\n{\norientation: mediaType === 'photo',\n- mime: mediaType === 'photo' || config.initialFileHeaderCheck,\n+ mime: true,\n+ mediaType: true,\n},\n);\nsteps.push(...fileInfoSteps);\n@@ -107,26 +107,21 @@ async function processMediaMission(\nreturn steps;\n}\nconst { orientation, fileSize } = fileInfoResult;\n- initialURI = fileInfoResult.uri;\n- mime = fileInfoResult.mime;\n-\n- if (fileInfoResult.mediaType && fileInfoResult.mediaType !== mediaType) {\n+ ({ uri: initialURI, mime, mediaType } = fileInfoResult);\n+ if (!mime || !mediaType) {\nfinish({\nsuccess: false,\n- reason: 'media_type_mismatch',\n- reportedMediaType: mediaType,\n- detectedMediaType: fileInfoResult.mediaType,\n- detectedMIME: fileInfoResult.mime,\n+ reason: 'media_type_fetch_failed',\n+ detectedMIME: mime,\n});\nreturn steps;\n}\n- if (selection.step === 'video_library') {\n+ if (mediaType === 'video') {\nconst { steps: videoSteps, result: videoResult } = await processVideo({\nuri: initialURI,\nfilename: selection.filename,\nfileSize,\n- duration: selection.duration,\ndimensions,\n});\nsteps.push(...videoSteps);\n@@ -137,17 +132,7 @@ async function processMediaMission(\nuploadURI = videoResult.uri;\nmime = videoResult.mime;\ndimensions = videoResult.dimensions;\n- } else if (\n- selection.step === 'photo_capture' ||\n- selection.step === 'photo_library'\n- ) {\n- if (!mime) {\n- finish({\n- success: false,\n- reason: 'mime_fetch_failed',\n- });\n- return steps;\n- }\n+ } else if (mediaType === 'photo') {\nconst { steps: imageSteps, result: imageResult } = await processImage({\nuri: initialURI,\ndimensions,\n@@ -179,9 +164,7 @@ async function processMediaMission(\nconst {\nsteps: finalFileInfoSteps,\nresult: finalFileInfoResult,\n- } = await fetchFileInfo(uploadURI, null, {\n- mime: true,\n- });\n+ } = await fetchFileInfo(uploadURI, undefined, { mime: true });\nsteps.push(...finalFileInfoSteps);\nif (!finalFileInfoResult.success) {\nif (config.finalFileHeaderCheck) {\n@@ -197,7 +180,6 @@ async function processMediaMission(\nreason: 'mime_type_mismatch',\nreportedMediaType: mediaType,\nreportedMIME: mime,\n- detectedMediaType: finalFileInfoResult.mediaType,\ndetectedMIME: finalFileInfoResult.mime,\n});\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "native/media/save-image.js",
"new_path": "native/media/save-image.js",
"diff": "@@ -220,7 +220,9 @@ async function copyToSortedDirectory(\nconst promises = {};\npromises.hash = filesystem.hash(path, 'md5');\nif (!mime) {\n- promises.fileInfoResult = fetchFileInfo(localURI, null, { mime: true });\n+ promises.fileInfoResult = fetchFileInfo(localURI, undefined, {\n+ mime: true,\n+ });\n}\nconst { hash, fileInfoResult } = await promiseAll(promises);\n"
},
{
"change_type": "MODIFY",
"old_path": "native/media/video-utils.js",
"new_path": "native/media/video-utils.js",
"diff": "@@ -11,7 +11,7 @@ import filesystem from 'react-native-fs';\nimport { Platform } from 'react-native';\nimport invariant from 'invariant';\n-import { pathFromURI, extensionFromFilename } from 'lib/utils/file-utils';\n+import { pathFromURI } from 'lib/utils/file-utils';\nimport { getVideoProcessingPlan } from 'lib/utils/video-utils';\nimport { ffmpeg } from './ffmpeg';\n@@ -20,7 +20,6 @@ type ProcessVideoInfo = {|\nuri: string,\nfilename: string,\nfileSize: number,\n- duration: number,\ndimensions: Dimensions,\n|};\ntype ProcessVideoResponse = {|\n@@ -42,13 +41,16 @@ async function processVideo(\nconst initialCheckStep = await checkVideoInfo(path);\nsteps.push(initialCheckStep);\n+ if (!initialCheckStep.success || !initialCheckStep.duration) {\n+ return { steps, result: { success: false, reason: 'video_probe_failed' } };\n+ }\nconst plan = getVideoProcessingPlan({\ninputPath: path,\n- inputHasCorrectContainerAndCodec: initialCheckStep.success,\n+ inputHasCorrectContainerAndCodec: initialCheckStep.validFormat,\ninputFileSize: input.fileSize,\ninputFilename: input.filename,\n- inputDuration: input.duration,\n+ inputDuration: initialCheckStep.duration,\noutputDirectory: Platform.select({\nios: filesystem.TemporaryDirectoryPath,\ndefault: `${filesystem.TemporaryDirectoryPath}/`,\n@@ -116,7 +118,7 @@ async function processVideo(\nconst transcodeProbeStep = await checkVideoInfo(outputPath);\nsteps.push(transcodeProbeStep);\n- if (!transcodeProbeStep.success) {\n+ if (!transcodeProbeStep.validFormat) {\nreturn {\nsteps,\nresult: { success: false, reason: 'video_transcode_failed' },\n@@ -140,18 +142,18 @@ async function processVideo(\nasync function checkVideoInfo(\npath: string,\n): Promise<VideoProbeMediaMissionStep> {\n- const ext = extensionFromFilename(path);\n-\nlet codec,\nformat,\ndimensions,\n+ duration,\nsuccess = false,\n+ validFormat = false,\nexceptionMessage;\nconst start = Date.now();\n- if (ext === 'mp4' || ext === 'mov') {\ntry {\n- ({ codec, format, dimensions } = await ffmpeg.getVideoInfo(path));\n- success = codec === 'h264' && format.includes('mp4');\n+ ({ codec, format, dimensions, duration } = await ffmpeg.getVideoInfo(path));\n+ success = true;\n+ validFormat = codec === 'h264' && format.includes('mp4');\n} catch (e) {\nif (\ne &&\n@@ -162,15 +164,14 @@ async function checkVideoInfo(\nexceptionMessage = e.message;\n}\n}\n- }\n-\nreturn {\nstep: 'video_probe',\nsuccess,\nexceptionMessage,\ntime: Date.now() - start,\npath,\n- ext,\n+ validFormat,\n+ duration,\ncodec,\nformat,\ndimensions,\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Treat animated GIFs as videos
Also lets `ffprobe` determine duration for videos since `expo-media-library` won't have it for animated GIFs |
129,187 | 25.04.2020 19:11:30 | 14,400 | facc9e558a96b339199b79b29eb2ef8fb99c3363 | Limit videos to 180 seconds | [
{
"change_type": "MODIFY",
"old_path": "lib/types/media-types.js",
"new_path": "lib/types/media-types.js",
"diff": "@@ -283,6 +283,11 @@ export type MediaMissionFailure =\nreason: 'http_upload_failed',\nexceptionMessage: ?string,\n|}\n+ | {|\n+ success: false,\n+ reason: 'video_too_long',\n+ duration: number, // in seconds\n+ |}\n| {|\nsuccess: false,\nreason: 'video_probe_failed',\n@@ -443,6 +448,11 @@ export const mediaMissionPropType = PropTypes.shape({\nreason: PropTypes.oneOf(['http_upload_failed']).isRequired,\nexceptionMessage: PropTypes.string,\n}),\n+ PropTypes.shape({\n+ success: PropTypes.oneOf([false]).isRequired,\n+ reason: PropTypes.oneOf(['video_too_long']).isRequired,\n+ duration: PropTypes.number.isRequired,\n+ }),\nPropTypes.shape({\nsuccess: PropTypes.oneOf([false]).isRequired,\nreason: PropTypes.oneOf(['video_probe_failed']).isRequired,\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/utils/video-utils.js",
"new_path": "lib/utils/video-utils.js",
"diff": "@@ -81,4 +81,10 @@ function getHasMultipleFramesProbeCommand(path: string) {\nreturn ffprobeCommand;\n}\n-export { getVideoProcessingPlan, getHasMultipleFramesProbeCommand };\n+const videoDurationLimit = 3; // in minutes\n+\n+export {\n+ getVideoProcessingPlan,\n+ getHasMultipleFramesProbeCommand,\n+ videoDurationLimit,\n+};\n"
},
{
"change_type": "MODIFY",
"old_path": "native/input/input-state-container.react.js",
"new_path": "native/input/input-state-container.react.js",
"diff": "@@ -62,6 +62,7 @@ import {\n} from 'lib/selectors/loading-selectors';\nimport { pathFromURI } from 'lib/utils/file-utils';\nimport { isStaff } from 'lib/shared/user-utils';\n+import { videoDurationLimit } from 'lib/utils/video-utils';\nimport {\nInputStateContext,\n@@ -487,7 +488,11 @@ class InputStateContainer extends React.PureComponent<Props, State> {\nreportPromise = processMediaReturn.reportPromise;\nconst processResult = await processMediaReturn.resultPromise;\nif (!processResult.success) {\n- fail('processing failed');\n+ const message =\n+ processResult.reason === 'video_too_long'\n+ ? `can't do vids longer than ${videoDurationLimit}min`\n+ : 'processing failed';\n+ fail(message);\nreturn await finish(processResult);\n}\nprocessedMedia = processResult;\n@@ -507,9 +512,7 @@ class InputStateContainer extends React.PureComponent<Props, State> {\ntime,\nexceptionMessage: processExceptionMessage,\n});\n- fail(\n- processExceptionMessage ? processExceptionMessage : 'processing threw',\n- );\n+ fail('processing failed');\nreturn await finish({\nsuccess: false,\nreason: 'processing_exception',\n"
},
{
"change_type": "MODIFY",
"old_path": "native/media/video-utils.js",
"new_path": "native/media/video-utils.js",
"diff": "@@ -12,7 +12,10 @@ import { Platform } from 'react-native';\nimport invariant from 'invariant';\nimport { pathFromURI } from 'lib/utils/file-utils';\n-import { getVideoProcessingPlan } from 'lib/utils/video-utils';\n+import {\n+ getVideoProcessingPlan,\n+ videoDurationLimit,\n+} from 'lib/utils/video-utils';\nimport { ffmpeg } from './ffmpeg';\n@@ -44,13 +47,20 @@ async function processVideo(\nif (!initialCheckStep.success || !initialCheckStep.duration) {\nreturn { steps, result: { success: false, reason: 'video_probe_failed' } };\n}\n+ const { validFormat, duration } = initialCheckStep;\n+ if (duration > videoDurationLimit * 60) {\n+ return {\n+ steps,\n+ result: { success: false, reason: 'video_too_long', duration },\n+ };\n+ }\nconst plan = getVideoProcessingPlan({\ninputPath: path,\n- inputHasCorrectContainerAndCodec: initialCheckStep.validFormat,\n+ inputHasCorrectContainerAndCodec: validFormat,\ninputFileSize: input.fileSize,\ninputFilename: input.filename,\n- inputDuration: initialCheckStep.duration,\n+ inputDuration: duration,\noutputDirectory: Platform.select({\nios: filesystem.TemporaryDirectoryPath,\ndefault: `${filesystem.TemporaryDirectoryPath}/`,\n"
},
{
"change_type": "MODIFY",
"old_path": "native/navigation/action-result-modal.react.js",
"new_path": "native/navigation/action-result-modal.react.js",
"diff": "@@ -18,7 +18,9 @@ import { contentBottomOffset } from '../selectors/dimension-selectors';\nimport { overlayStyleSelector, type StyleSheetOf } from '../themes/colors';\nimport { connectNav, type NavContextType } from './navigation-context';\n+/* eslint-disable import/no-named-as-default-member */\nconst { Value, Extrapolate, interpolate } = Animated;\n+/* eslint-enable import/no-named-as-default-member */\ntype NavProp = NavigationStackProp<{|\n...NavigationLeafRoute,\n@@ -114,6 +116,7 @@ const styles = {\ntext: {\ncolor: 'modalContrastForegroundLabel',\nfontSize: 20,\n+ textAlign: 'center',\n},\n};\nconst stylesSelector = overlayStyleSelector(styles);\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | Limit videos to 180 seconds |
129,187 | 25.04.2020 19:24:45 | 14,400 | 1732de009df3331947fe81dd51d2d917eb0db404 | [native] Delete unused temporary files in processVideo | [
{
"change_type": "MODIFY",
"old_path": "native/media/video-utils.js",
"new_path": "native/media/video-utils.js",
"diff": "@@ -109,6 +109,9 @@ async function processVideo(\nexceptionMessage = e.message;\n}\n}\n+ if (!success) {\n+ filesystem.unlink(outputPath);\n+ }\nsteps.push({\nstep: 'video_ffmpeg_transcode',\n@@ -129,6 +132,7 @@ async function processVideo(\nconst transcodeProbeStep = await checkVideoInfo(outputPath);\nsteps.push(transcodeProbeStep);\nif (!transcodeProbeStep.validFormat) {\n+ filesystem.unlink(outputPath);\nreturn {\nsteps,\nresult: { success: false, reason: 'video_transcode_failed' },\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Delete unused temporary files in processVideo |
129,187 | 25.04.2020 19:33:20 | 14,400 | 92918d7af3e16215a6debb54ada7d6f05ee791b9 | [native] Avoid upscaling dimensions with h264_videotoolbox | [
{
"change_type": "MODIFY",
"old_path": "lib/utils/video-utils.js",
"new_path": "lib/utils/video-utils.js",
"diff": "// @flow\n+import type { Dimensions } from '../types/media-types';\n+\nimport invariant from 'invariant';\nimport { replaceExtension } from './file-utils';\n@@ -14,6 +16,7 @@ type Input = {|\ninputFileSize: number, // in bytes\ninputFilename: string,\ninputDuration: number,\n+ inputDimensions: Dimensions,\noutputDirectory: string,\noutputCodec: string,\n|};\n@@ -28,6 +31,7 @@ function getVideoProcessingPlan(input: Input): ?Plan {\ninputFileSize,\ninputFilename,\ninputDuration,\n+ inputDimensions,\noutputDirectory,\noutputCodec,\n} = input;\n@@ -42,15 +46,24 @@ function getVideoProcessingPlan(input: Input): ?Plan {\n);\nconst outputPath = `${outputDirectory}${outputFilename}`;\n- let quality, speed;\n+ let quality, speed, scale;\nif (outputCodec === 'h264') {\nconst { floor, min, max, log2 } = Math;\nconst crf = floor(min(5, max(0, log2(inputDuration / 5)))) + 23;\nquality = `-crf ${crf}`;\nspeed = '-preset ultrafast';\n+ scale = `-vf scale=${maxWidth}:${maxHeight}:force_original_aspect_ratio=decrease`;\n} else if (outputCodec === 'h264_videotoolbox') {\nquality = '-profile:v baseline';\nspeed = '-realtime 1';\n+ const { width, height } = inputDimensions;\n+ scale = '';\n+ const exceedsDimensions = width > maxWidth || height > maxHeight;\n+ if (exceedsDimensions && width / height > maxWidth / maxHeight) {\n+ scale = `-vf scale=${maxWidth}:-1`;\n+ } else if (exceedsDimensions) {\n+ scale = `-vf scale=-1:${maxHeight}`;\n+ }\n} else {\ninvariant(false, `unrecognized outputCodec ${outputCodec}`);\n}\n@@ -60,7 +73,7 @@ function getVideoProcessingPlan(input: Input): ?Plan {\n`-c:a copy -c:v ${outputCodec} ` +\n`${quality} ` +\n'-vsync 2 -r 30 ' +\n- `-vf scale=${maxWidth}:${maxHeight}:force_original_aspect_ratio=decrease ` +\n+ `${scale} ` +\n`${speed} ` +\n'-movflags +faststart ' +\n'-pix_fmt yuv420p ' +\n"
},
{
"change_type": "MODIFY",
"old_path": "native/media/video-utils.js",
"new_path": "native/media/video-utils.js",
"diff": "@@ -61,6 +61,7 @@ async function processVideo(\ninputFileSize: input.fileSize,\ninputFilename: input.filename,\ninputDuration: duration,\n+ inputDimensions: input.dimensions,\noutputDirectory: Platform.select({\nios: filesystem.TemporaryDirectoryPath,\ndefault: `${filesystem.TemporaryDirectoryPath}/`,\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Avoid upscaling dimensions with h264_videotoolbox |
129,187 | 25.04.2020 19:56:31 | 14,400 | 79ce38d184f647bf434a2c30433235075f7fb936 | [native] Unlink departingURI when Multimedia unmounted | [
{
"change_type": "MODIFY",
"old_path": "native/media/multimedia.react.js",
"new_path": "native/media/multimedia.react.js",
"diff": "@@ -72,6 +72,13 @@ class Multimedia extends React.PureComponent<Props, State> {\n}\n}\n+ componentWillUnmount() {\n+ const { departingURI, unlinkDepartingURI } = this.state;\n+ if (departingURI && unlinkDepartingURI) {\n+ Multimedia.unlinkURI(departingURI);\n+ }\n+ }\n+\nrender() {\nconst images = [];\nconst { currentURI, departingURI } = this.state;\n@@ -110,10 +117,6 @@ class Multimedia extends React.PureComponent<Props, State> {\n}\nonLoad = () => {\n- this.onLoadAsync();\n- };\n-\n- async onLoadAsync() {\nconst { departingURI, unlinkDepartingURI } = this.state;\nif (!departingURI && !unlinkDepartingURI) {\nreturn;\n@@ -124,15 +127,18 @@ class Multimedia extends React.PureComponent<Props, State> {\nreturn;\n}\n- const path = pathFromURI(departingURI);\n+ Multimedia.unlinkURI(departingURI);\n+ };\n+\n+ static unlinkURI(uri: string) {\n+ const path = pathFromURI(uri);\nif (!path) {\nreturn;\n}\n-\ntry {\n- await filesystem.unlink(path);\n+ filesystem.unlink(path);\n} catch (e) {}\n- };\n+ }\n}\nconst styles = StyleSheet.create({\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Unlink departingURI when Multimedia unmounted |
129,187 | 25.04.2020 23:25:57 | 14,400 | d56625e50bfc37e6dd2d7cd172c5ac6be037af56 | Add loop to Video MediaInfo | [
{
"change_type": "MODIFY",
"old_path": "lib/types/media-types.js",
"new_path": "lib/types/media-types.js",
"diff": "@@ -28,6 +28,7 @@ export type Video = {|\nuri: string,\ntype: 'video',\ndimensions: Dimensions,\n+ loop?: boolean,\n// stored on native only during creation in case retry needed after state lost\nlocalMediaSelection?: MediaSelection,\n|};\n"
},
{
"change_type": "MODIFY",
"old_path": "native/input/input-state-container.react.js",
"new_path": "native/input/input-state-container.react.js",
"diff": "@@ -412,6 +412,7 @@ class InputStateContainer extends React.PureComponent<Props, State> {\ntype: 'video',\ndimensions: selection.dimensions,\nlocalMediaSelection: selection,\n+ loop: false,\n};\n}\ninvariant(false, `invalid selection ${JSON.stringify(selection)}`);\n@@ -527,6 +528,7 @@ class InputStateContainer extends React.PureComponent<Props, State> {\nfilename,\nmime,\nmediaType,\n+ loop,\n} = processedMedia;\nconst uploadStart = Date.now();\n@@ -569,6 +571,7 @@ class InputStateContainer extends React.PureComponent<Props, State> {\nuri: uploadResult.uri,\ntype: mediaType,\ndimensions: uploadResult.dimensions,\n+ loop,\nlocalMediaSelection: undefined,\n},\n});\n"
},
{
"change_type": "MODIFY",
"old_path": "native/media/media-utils.js",
"new_path": "native/media/media-utils.js",
"diff": "@@ -28,6 +28,7 @@ type MediaResult = {|\nmime: string,\nmediaType: MediaType,\ndimensions: Dimensions,\n+ loop: boolean,\n|};\nfunction processMedia(\nselection: MediaSelection,\n@@ -61,6 +62,7 @@ async function processMediaMission(\nuploadURI = null,\ndimensions = selection.dimensions,\nmime = null,\n+ loop = false,\nfinished = false;\nlet mediaType;\nconst finish = (failure?: MediaMissionFailure) => {\n@@ -86,6 +88,7 @@ async function processMediaMission(\nmime,\nmediaType,\ndimensions,\n+ loop,\n});\n};\n@@ -120,6 +123,7 @@ async function processMediaMission(\nif (mediaType === 'video') {\nconst { steps: videoSteps, result: videoResult } = await processVideo({\nuri: initialURI,\n+ mime,\nfilename: selection.filename,\nfileSize,\ndimensions,\n@@ -129,9 +133,7 @@ async function processMediaMission(\nfinish(videoResult);\nreturn steps;\n}\n- uploadURI = videoResult.uri;\n- mime = videoResult.mime;\n- dimensions = videoResult.dimensions;\n+ ({ uri: uploadURI, mime, dimensions, loop } = videoResult);\n} else if (mediaType === 'photo') {\nconst { steps: imageSteps, result: imageResult } = await processImage({\nuri: initialURI,\n@@ -145,9 +147,7 @@ async function processMediaMission(\nfinish(imageResult);\nreturn steps;\n}\n- uploadURI = imageResult.uri;\n- dimensions = imageResult.dimensions;\n- mime = imageResult.mime;\n+ ({ uri: uploadURI, mime, dimensions } = imageResult);\n} else {\ninvariant(false, `unknown mediaType ${mediaType}`);\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "native/media/video-utils.js",
"new_path": "native/media/video-utils.js",
"diff": "@@ -21,6 +21,7 @@ import { ffmpeg } from './ffmpeg';\ntype ProcessVideoInfo = {|\nuri: string,\n+ mime: string,\nfilename: string,\nfileSize: number,\ndimensions: Dimensions,\n@@ -30,6 +31,7 @@ type ProcessVideoResponse = {|\nuri: string,\nmime: string,\ndimensions: Dimensions,\n+ loop: boolean,\n|};\nasync function processVideo(\ninput: ProcessVideoInfo,\n@@ -83,6 +85,7 @@ async function processVideo(\nuri: input.uri,\nmime: 'video/mp4',\ndimensions: input.dimensions,\n+ loop: false,\n},\n};\n}\n@@ -150,6 +153,7 @@ async function processVideo(\nuri: `file://${outputPath}`,\nmime: 'video/mp4',\ndimensions,\n+ loop: input.mime === 'image/gif',\n},\n};\n}\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | Add loop to Video MediaInfo |
129,187 | 26.04.2020 00:47:31 | 14,400 | cf23e490a7b3e8d2535797d50680e687f0bf16a1 | Pipe loop through server/client flow | [
{
"change_type": "MODIFY",
"old_path": "lib/actions/upload-actions.js",
"new_path": "lib/actions/upload-actions.js",
"diff": "@@ -9,22 +9,31 @@ export type MultimediaUploadCallbacks = $Shape<{|\nabortHandler: (abort: () => void) => void,\nuploadBlob: UploadBlob,\n|}>;\n+export type MultimediaUploadExtras = {| ...Dimensions, loop: boolean |};\nasync function uploadMultimedia(\nfetchJSON: FetchJSON,\nmultimedia: Object,\n- dimensions: Dimensions,\n+ extras: MultimediaUploadExtras,\ncallbacks?: MultimediaUploadCallbacks,\n): Promise<UploadMultimediaResult> {\nconst onProgress = callbacks && callbacks.onProgress;\nconst abortHandler = callbacks && callbacks.abortHandler;\nconst uploadBlob = callbacks && callbacks.uploadBlob;\n+\n+ const stringDimensions = {\n+ height: extras.height.toString(),\n+ width: extras.width.toString(),\n+ };\n+ const stringExtras = extras.loop\n+ ? stringDimensions\n+ : { ...stringDimensions, loop: '1' };\n+\nconst response = await fetchJSON(\n'upload_multimedia',\n{\nmultimedia: [multimedia],\n- height: dimensions.height.toString(),\n- width: dimensions.width.toString(),\n+ ...stringExtras,\n},\n{\nonProgress,\n@@ -37,6 +46,8 @@ async function uploadMultimedia(\nid: uploadResult.id,\nuri: uploadResult.uri,\ndimensions: uploadResult.dimensions,\n+ mediaType: uploadResult.mediaType,\n+ loop: uploadResult.loop,\n};\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "lib/types/media-types.js",
"new_path": "lib/types/media-types.js",
"diff": "@@ -83,6 +83,8 @@ export type UploadMultimediaResult = {|\nid: string,\nuri: string,\ndimensions: Dimensions,\n+ mediaType: MediaType,\n+ loop: boolean,\n|};\nexport type UpdateMultimediaMessageMediaPayload = {|\n"
},
{
"change_type": "MODIFY",
"old_path": "native/input/input-state-container.react.js",
"new_path": "native/input/input-state-container.react.js",
"diff": "@@ -11,7 +11,6 @@ import type {\nMediaSelection,\nMediaMissionResult,\nMediaMission,\n- Dimensions,\n} from 'lib/types/media-types';\nimport {\nmessageTypes,\n@@ -45,6 +44,7 @@ import {\nuploadMultimedia,\nupdateMultimediaMessageMediaActionType,\ntype MultimediaUploadCallbacks,\n+ type MultimediaUploadExtras,\n} from 'lib/actions/upload-actions';\nimport {\ncreateLocalMessageActionType,\n@@ -95,7 +95,7 @@ type Props = {|\n// async functions that hit server APIs\nuploadMultimedia: (\nmultimedia: Object,\n- dimensions: Dimensions,\n+ extras: MultimediaUploadExtras,\ncallbacks: MultimediaUploadCallbacks,\n) => Promise<UploadMultimediaResult>,\nsendMultimediaMessage: (\n@@ -522,21 +522,14 @@ class InputStateContainer extends React.PureComponent<Props, State> {\n});\n}\n- const {\n- uploadURI,\n- shouldDisposePath,\n- filename,\n- mime,\n- mediaType,\n- loop,\n- } = processedMedia;\n+ const { uploadURI, shouldDisposePath, filename, mime } = processedMedia;\nconst uploadStart = Date.now();\nlet uploadExceptionMessage, uploadResult, mediaMissionResult;\ntry {\nuploadResult = await this.props.uploadMultimedia(\n{ uri: uploadURI, name: filename, type: mime },\n- processedMedia.dimensions,\n+ { ...processedMedia.dimensions, loop: processedMedia.loop },\n{\nonProgress: (percent: number) =>\nthis.setProgress(localMessageID, localID, percent),\n@@ -562,17 +555,18 @@ class InputStateContainer extends React.PureComponent<Props, State> {\n}\nif (uploadResult) {\n- serverID = uploadResult.id;\n+ const { id, mediaType, uri, dimensions, loop } = uploadResult;\n+ serverID = id;\nthis.props.dispatchActionPayload(updateMultimediaMessageMediaActionType, {\nmessageID: localMessageID,\ncurrentMediaID: localID,\nmediaUpdate: {\n- id: serverID,\n- uri: uploadResult.uri,\n+ id,\ntype: mediaType,\n- dimensions: uploadResult.dimensions,\n- loop,\n+ uri,\n+ dimensions,\nlocalMediaSelection: undefined,\n+ loop,\n},\n});\nuserTime = Date.now() - start;\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/creators/upload-creator.js",
"new_path": "server/src/creators/upload-creator.js",
"diff": "@@ -22,6 +22,7 @@ export type UploadInput = {|\nmediaType: MediaType,\nbuffer: Buffer,\ndimensions: Dimensions,\n+ loop: boolean,\n|};\nasync function createUploads(\nviewer: Viewer,\n@@ -35,20 +36,23 @@ async function createUploads(\nconst uploadRows = uploadInfos.map(uploadInfo => {\nconst id = ids.shift();\nconst secret = crypto.randomBytes(8).toString('hex');\n+ const { dimensions, mediaType, loop } = uploadInfo;\nreturn {\nid,\nsecret,\n- dimensions: uploadInfo.dimensions,\n+ dimensions,\n+ mediaType,\n+ loop,\ninsert: [\nid,\nviewer.userID,\n- uploadInfo.mediaType,\n+ mediaType,\nuploadInfo.name,\nuploadInfo.mime,\nuploadInfo.buffer,\nsecret,\nDate.now(),\n- JSON.stringify(uploadInfo.dimensions),\n+ JSON.stringify({ ...dimensions, loop }),\n],\n};\n});\n@@ -67,6 +71,8 @@ async function createUploads(\nviewer.platformDetails,\n),\ndimensions: row.dimensions,\n+ mediaType: row.mediaType,\n+ loop: row.loop,\n}));\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/fetchers/message-fetchers.js",
"new_path": "server/src/fetchers/message-fetchers.js",
"diff": "@@ -30,7 +30,7 @@ import { ServerError } from 'lib/utils/errors';\nimport { dbQuery, SQL, mergeOrConditions } from '../database';\nimport { fetchUserInfos } from './user-fetchers';\nimport { creationString, localIDFromCreationString } from '../utils/idempotent';\n-import { getUploadURL } from './upload-fetchers';\n+import { mediaFromRow } from './upload-fetchers';\nexport type CollapsableNotifInfo = {|\ncollapseKey: ?string,\n@@ -364,28 +364,7 @@ function rawMessageInfoFromRows(\ntext: content.text,\n};\n} else if (type === messageTypes.IMAGES || type === messageTypes.MULTIMEDIA) {\n- const media = [];\n- for (let row of rows) {\n- if (!row.uploadID) {\n- continue;\n- }\n- const uploadID = row.uploadID.toString();\n- if (row.uploadType === 'photo') {\n- media.push({\n- id: uploadID,\n- uri: getUploadURL(uploadID, row.uploadSecret),\n- type: 'photo',\n- dimensions: row.uploadExtra,\n- });\n- } else {\n- media.push({\n- id: uploadID,\n- uri: getUploadURL(uploadID, row.uploadSecret),\n- type: 'video',\n- dimensions: row.uploadExtra,\n- });\n- }\n- }\n+ const media = rows.filter(row => row.uploadID).map(mediaFromRow);\nconst [row] = rows;\nreturn createMediaMessageInfo({\nthreadID: row.threadID.toString(),\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/fetchers/upload-fetchers.js",
"new_path": "server/src/fetchers/upload-fetchers.js",
"diff": "@@ -37,25 +37,33 @@ function getUploadURL(id: string, secret: string) {\nreturn `${baseDomain}${basePath}upload/${id}/${secret}`;\n}\n+function mediaFromRow(row: Object): Media {\n+ const { uploadType: type, uploadSecret: secret } = row;\n+ const { width, height, loop } = row.uploadExtra;\n+ const id = row.uploadID.toString();\n+ const dimensions = { width, height };\n+ const uri = getUploadURL(id, secret);\n+ if (type === 'photo') {\n+ return { id, type: 'photo', uri, dimensions };\n+ } else if (loop) {\n+ return { id, type: 'video', uri, dimensions, loop };\n+ } else {\n+ return { id, type: 'video', uri, dimensions };\n+ }\n+}\n+\nasync function fetchMedia(\nviewer: Viewer,\nmediaIDs: $ReadOnlyArray<string>,\n): Promise<$ReadOnlyArray<Media>> {\nconst query = SQL`\n- SELECT id, secret, type, extra\n+ SELECT id AS uploadID, secret AS uploadSecret,\n+ type AS uploadType, extra AS uploadExtra\nFROM uploads\nWHERE id IN (${mediaIDs}) AND uploader = ${viewer.id} AND container IS NULL\n`;\nconst [result] = await dbQuery(query);\n- return result.map(row => {\n- const id = row.id.toString();\n- return {\n- id,\n- uri: getUploadURL(id, row.secret),\n- type: row.type,\n- dimensions: row.extra,\n- };\n- });\n+ return result.map(mediaFromRow);\n}\n-export { fetchUpload, getUploadURL, fetchMedia };\n+export { fetchUpload, getUploadURL, mediaFromRow, fetchMedia };\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/uploads/media-utils.js",
"new_path": "server/src/uploads/media-utils.js",
"diff": "@@ -40,6 +40,7 @@ async function validateAndConvert(\ninitialBuffer: Buffer,\ninitialName: string,\ninputDimensions: ?Dimensions,\n+ inputLoop: boolean,\nsize: number, // in bytes\n): Promise<?UploadInput> {\nconst { mime, mediaType } = deepFileInfoFromData(initialBuffer);\n@@ -83,6 +84,7 @@ async function validateAndConvert(\nname,\nbuffer: initialBuffer,\ndimensions: initialDimensions,\n+ loop: inputLoop,\n};\n}\nconsole.log(`processing image with ${JSON.stringify(plan)}`);\n@@ -134,6 +136,7 @@ async function validateAndConvert(\nname: convertedName,\nbuffer: convertedBuffer,\ndimensions: convertedDimensions,\n+ loop: inputLoop,\n};\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/uploads/uploads.js",
"new_path": "server/src/uploads/uploads.js",
"diff": "@@ -46,24 +46,27 @@ async function multimediaUploadResponder(\nthrow new ServerError('invalid_parameters');\n}\n- const overrideHeight =\n+ const inputHeight =\nfiles.length === 1 && body.height ? parseInt(body.height) : null;\n- const overrideWidth =\n+ const inputWidth =\nfiles.length === 1 && body.width ? parseInt(body.width) : null;\n- if (!!overrideHeight !== !!overrideWidth) {\n+ if (!!inputHeight !== !!inputWidth) {\nthrow new ServerError('invalid_parameters');\n}\n- const overrideDimensions: ?Dimensions =\n- overrideHeight && overrideWidth\n- ? { height: overrideHeight, width: overrideWidth }\n+ const inputDimensions: ?Dimensions =\n+ inputHeight && inputWidth\n+ ? { height: inputHeight, width: inputWidth }\n: null;\n+ const inputLoop = !!(files.length === 1 && body.loop);\n+\nconst validationResults = await Promise.all(\nfiles.map(({ buffer, size, originalname }) =>\nvalidateAndConvert(\nbuffer,\noverrideFilename ? overrideFilename : originalname,\n- overrideDimensions,\n+ inputDimensions,\n+ inputLoop,\nsize,\n),\n),\n"
},
{
"change_type": "MODIFY",
"old_path": "web/chat/chat-input-state-container.react.js",
"new_path": "web/chat/chat-input-state-container.react.js",
"diff": "// @flow\nimport type { AppState } from '../redux-setup';\n-import type { UploadMultimediaResult, Dimensions } from 'lib/types/media-types';\n+import type { UploadMultimediaResult } from 'lib/types/media-types';\nimport type {\nDispatchActionPayload,\nDispatchActionPromise,\n@@ -36,6 +36,7 @@ import {\nupdateMultimediaMessageMediaActionType,\ndeleteUpload,\ntype MultimediaUploadCallbacks,\n+ type MultimediaUploadExtras,\n} from 'lib/actions/upload-actions';\nimport {\ncreateLocalMessageActionType,\n@@ -66,7 +67,7 @@ type Props = {|\n// async functions that hit server APIs\nuploadMultimedia: (\nmultimedia: Object,\n- dimensions: Dimensions,\n+ extras: MultimediaUploadExtras,\ncallbacks: MultimediaUploadCallbacks,\n) => Promise<UploadMultimediaResult>,\ndeleteUpload: (id: string) => Promise<void>,\n@@ -180,8 +181,7 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\nconst creatorID = this.props.viewerID;\ninvariant(creatorID, 'need viewer ID in order to send a message');\nconst media = uploads.map(\n- ({ localID, serverID, uri, mediaType, dimensions }) => {\n- // This conditional is for Flow\n+ ({ localID, serverID, uri, mediaType, dimensions, loop }) => {\nif (mediaType === 'photo') {\nreturn {\nid: serverID ? serverID : localID,\n@@ -195,6 +195,7 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\nuri,\ntype: 'video',\ndimensions,\n+ loop,\n};\n}\n},\n@@ -390,6 +391,7 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\nmediaType,\ndimensions,\nuri: result.uri,\n+ loop: false,\nuriIsReal: false,\nprogressPercent: 0,\nabort: null,\n@@ -432,7 +434,7 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\ntry {\nresult = await this.props.uploadMultimedia(\nupload.file,\n- upload.dimensions,\n+ { ...upload.dimensions, loop: false },\n{\nonProgress: (percent: number) =>\nthis.setProgress(threadID, upload.localID, percent),\n@@ -497,15 +499,13 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\n`after preload`,\n);\nif (uploadAfterPreload.messageID) {\n+ const { mediaType, uri, dimensions, loop } = result;\nthis.props.dispatchActionPayload(updateMultimediaMessageMediaActionType, {\nmessageID: uploadAfterPreload.messageID,\ncurrentMediaID: uploadAfterPreload.serverID\n? uploadAfterPreload.serverID\n: uploadAfterPreload.localID,\n- mediaUpdate: {\n- uri: result.uri,\n- dimensions: result.dimensions,\n- },\n+ mediaUpdate: { type: mediaType, uri, dimensions, loop },\n});\n}\n@@ -535,8 +535,10 @@ class ChatInputStateContainer extends React.PureComponent<Props, State> {\n[upload.localID]: {\n...currentUpload,\nuri: result.uri,\n+ mediaType: result.mediaType,\ndimensions: result.dimensions,\nuriIsReal: true,\n+ loop: result.loop,\n},\n},\n},\n"
},
{
"change_type": "MODIFY",
"old_path": "web/chat/chat-input-state.js",
"new_path": "web/chat/chat-input-state.js",
"diff": "@@ -22,6 +22,7 @@ export type PendingMultimediaUpload = {|\nmediaType: MediaType,\ndimensions: Dimensions,\nuri: string,\n+ loop: boolean,\n// URLs created with createObjectURL aren't considered \"real\". The distinction\n// is required because those \"fake\" URLs must be disposed properly\nuriIsReal: boolean,\n@@ -39,6 +40,7 @@ export const pendingMultimediaUploadPropType = PropTypes.shape({\nmediaType: mediaTypePropType.isRequired,\ndimensions: dimensionsPropType.isRequired,\nuri: PropTypes.string.isRequired,\n+ loop: PropTypes.bool.isRequired,\nuriIsReal: PropTypes.bool.isRequired,\nprogressPercent: PropTypes.number.isRequired,\nabort: PropTypes.func,\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | Pipe loop through server/client flow |
129,187 | 26.04.2020 16:05:15 | 14,400 | 2fb1d9373342269470e23bdab8fcc3a67eb87f68 | [native] Support for rendering animated GIFs on Android
Using Facebook Fresco | [
{
"change_type": "MODIFY",
"old_path": "native/android/app/build.gradle",
"new_path": "native/android/app/build.gradle",
"diff": "@@ -194,6 +194,11 @@ dependencies {\nimplementation \"com.facebook.react:react-native:+\" // From node_modules\nimplementation \"androidx.multidex:multidex:2.0.1\"\n+ implementation 'com.facebook.fresco:fresco:2.2.0'\n+ implementation 'com.facebook.fresco:animated-gif:2.2.0'\n+ implementation 'com.facebook.fresco:animated-webp:2.2.0'\n+ implementation 'com.facebook.fresco:webpsupport:2.2.0'\n+\nif (enableHermes) {\ndef hermesPath = \"../../../node_modules/hermes-engine/android/\";\ndebugImplementation files(hermesPath + \"hermes-debug.aar\")\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Support for rendering animated GIFs on Android
Using Facebook Fresco |
129,187 | 27.04.2020 12:47:56 | 14,400 | 89c0146c8ef43dd3a7dc2154d7b587c81244d6e3 | [native] Update expo-media-library patch | [
{
"change_type": "MODIFY",
"old_path": "patches/expo-media-library+8.1.0.patch",
"new_path": "patches/expo-media-library+8.1.0.patch",
"diff": "@@ -94,10 +94,10 @@ index bfe25f3..edde485 100644\nPermissions permissionsManager = mModuleRegistry.getModule(Permissions.class);\nif (permissionsManager == null) {\ndiff --git a/node_modules/expo-media-library/android/src/main/java/expo/modules/medialibrary/MediaLibraryUtils.java b/node_modules/expo-media-library/android/src/main/java/expo/modules/medialibrary/MediaLibraryUtils.java\n-index da5bd28..7d70a64 100644\n+index da5bd28..6861e02 100644\n--- a/node_modules/expo-media-library/android/src/main/java/expo/modules/medialibrary/MediaLibraryUtils.java\n+++ b/node_modules/expo-media-library/android/src/main/java/expo/modules/medialibrary/MediaLibraryUtils.java\n-@@ -1,14 +1,18 @@\n+@@ -1,17 +1,23 @@\npackage expo.modules.medialibrary;\nimport android.content.Context;\n@@ -113,10 +113,15 @@ index da5bd28..7d70a64 100644\nimport androidx.exifinterface.media.ExifInterface;\nimport android.text.TextUtils;\n+import android.net.Uri;\n++import android.util.Log;\nimport java.io.File;\nimport java.io.FileInputStream;\n-@@ -96,7 +100,8 @@ final class MediaLibraryUtils {\n++import java.io.FileNotFoundException;\n+ import java.io.FileOutputStream;\n+ import java.io.IOException;\n+ import java.nio.channels.FileChannel;\n+@@ -96,7 +102,8 @@ final class MediaLibraryUtils {\n}\nstatic void queryAssetInfo(Context context, final String selection, final String[] selectionArgs, boolean fullInfo, Promise promise) {\n@@ -126,7 +131,7 @@ index da5bd28..7d70a64 100644\nEXTERNAL_CONTENT,\nASSET_PROJECTION,\nselection,\n-@@ -109,7 +114,7 @@ final class MediaLibraryUtils {\n+@@ -109,7 +116,7 @@ final class MediaLibraryUtils {\nif (asset.getCount() == 1) {\nasset.moveToFirst();\nArrayList<Bundle> array = new ArrayList<>();\n@@ -135,7 +140,7 @@ index da5bd28..7d70a64 100644\n// actually we want to return just the first item, but array.getMap returns ReadableMap\n// which is not compatible with promise.resolve and there is no simple solution to convert\n// ReadableMap to WritableMap so it's easier to return an array and pick the first item on JS side\n-@@ -126,7 +131,7 @@ final class MediaLibraryUtils {\n+@@ -126,7 +133,7 @@ final class MediaLibraryUtils {\n}\n}\n@@ -144,7 +149,7 @@ index da5bd28..7d70a64 100644\nfinal int idIndex = cursor.getColumnIndex(Media._ID);\nfinal int filenameIndex = cursor.getColumnIndex(Media.DISPLAY_NAME);\nfinal int mediaTypeIndex = cursor.getColumnIndex(Files.FileColumns.MEDIA_TYPE);\n-@@ -142,9 +147,16 @@ final class MediaLibraryUtils {\n+@@ -142,9 +149,16 @@ final class MediaLibraryUtils {\nreturn;\n}\nfor (int i = 0; i < limit && !cursor.isAfterLast(); i++) {\n@@ -163,7 +168,7 @@ index da5bd28..7d70a64 100644\nBundle asset = new Bundle();\nasset.putString(\"id\", cursor.getString(idIndex));\n-@@ -159,8 +171,8 @@ final class MediaLibraryUtils {\n+@@ -159,8 +173,8 @@ final class MediaLibraryUtils {\nasset.putString(\"albumId\", cursor.getString(albumIdIndex));\nif (fullInfo) {\n@@ -174,20 +179,19 @@ index da5bd28..7d70a64 100644\n}\nasset.putString(\"localUri\", localUri);\n-@@ -213,25 +225,66 @@ final class MediaLibraryUtils {\n+@@ -213,25 +227,68 @@ final class MediaLibraryUtils {\nreturn MEDIA_TYPES.get(mediaType);\n}\n- static int[] getSizeFromCursor(Cursor cursor, int mediaType, int localUriIndex){\n-+ static int[] getSizeFromCursor(ContentResolver contentResolver, ExifInterface exifInterface, Cursor cursor, int mediaType, int localUriIndex) {\n++ static int[] getSizeFromCursor(ContentResolver contentResolver, ExifInterface exifInterface, Cursor cursor, int mediaType, int localUriIndex) throws IOException {\n+ final String uri = cursor.getString(localUriIndex);\n+\n+ if (mediaType == Files.FileColumns.MEDIA_TYPE_VIDEO) {\n-+ Uri photoUri = Uri.parse(\"file://\" + uri);\n-+ try {\n-+ AssetFileDescriptor photoDescriptor = contentResolver.openAssetFileDescriptor(photoUri, \"r\");\n-+ MediaMetadataRetriever retriever = new MediaMetadataRetriever();\n-+ try {\n++ Uri videoUri = Uri.parse(\"file://\" + uri);\n++ MediaMetadataRetriever retriever = null;\n++ try (AssetFileDescriptor photoDescriptor = contentResolver.openAssetFileDescriptor(videoUri, \"r\")) {\n++ retriever = new MediaMetadataRetriever();\n+ retriever.setDataSource(photoDescriptor.getFileDescriptor());\n+ int videoWidth = Integer.parseInt(\n+ retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_VIDEO_WIDTH)\n@@ -200,11 +204,13 @@ index da5bd28..7d70a64 100644\n+ );\n+ return maybeRotateAssetSize(videoWidth, videoHeight, videoOrientation);\n+ } catch (NumberFormatException e) {\n++ Log.e(\"expo-media-library\", \"MediaMetadataRetriever unexpectedly returned non-integer: \" + e.getMessage());\n++ } catch (FileNotFoundException e) {\n++ Log.e(\"expo-media-library\", String.format(\"ContentResolver failed to read %s: %s\", uri, e.getMessage()));\n+ } finally {\n++ if (retriever != null) {\n+ retriever.release();\n-+ photoDescriptor.close();\n+ }\n-+ } catch (Exception e) {\n+ }\n+ }\n+\n@@ -223,7 +229,8 @@ index da5bd28..7d70a64 100644\n+ int height = cursor.getInt(heightIndex);\n+ int orientation = cursor.getInt(orientationIndex);\n+\n-+ if (width <= 0 || height <= 0) {\n++ // If the image doesn't have the required information, we can get them from Bitmap.Options\n++ if (mediaType == Files.FileColumns.MEDIA_TYPE_IMAGE && (width <= 0 || height <= 0)) {\nBitmapFactory.Options options = new BitmapFactory.Options();\noptions.inJustDecodeBounds = true;\n+ BitmapFactory.decodeFile(uri, options);\n@@ -255,7 +262,7 @@ index da5bd28..7d70a64 100644\n}\nstatic int[] maybeRotateAssetSize(int width, int height, int orientation) {\n-@@ -265,9 +318,7 @@ final class MediaLibraryUtils {\n+@@ -265,9 +322,7 @@ final class MediaLibraryUtils {\nreturn TextUtils.join(\",\", result);\n}\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Update expo-media-library patch |
129,187 | 27.04.2020 14:44:37 | 14,400 | 26128e19380b59f9534700bb53565a36b8319637 | [native] Don't use mediaType before it's set in processMedia | [
{
"change_type": "MODIFY",
"old_path": "native/media/media-utils.js",
"new_path": "native/media/media-utils.js",
"diff": "@@ -92,6 +92,7 @@ async function processMediaMission(\n});\n};\n+ const possiblyPhoto = selection.step.startsWith('photo_');\nconst mediaNativeID = selection.mediaNativeID\n? selection.mediaNativeID\n: null;\n@@ -99,7 +100,7 @@ async function processMediaMission(\nselection.uri,\n{ mediaNativeID },\n{\n- orientation: mediaType === 'photo',\n+ orientation: possiblyPhoto,\nmime: true,\nmediaType: true,\n},\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Don't use mediaType before it's set in processMedia |
129,187 | 27.04.2020 14:50:24 | 14,400 | 90e941e5508d5972d35a87adc671a2a28720630e | [native] saveImage only needs URI | [
{
"change_type": "MODIFY",
"old_path": "native/chat/multimedia-tooltip-modal.react.js",
"new_path": "native/chat/multimedia-tooltip-modal.react.js",
"diff": "@@ -14,7 +14,7 @@ type CustomProps = {\n};\nfunction onPressSave(props: CustomProps) {\n- return intentionalSaveImage(props.mediaInfo);\n+ return intentionalSaveImage(props.mediaInfo.uri);\n}\nconst spec = {\n"
},
{
"change_type": "MODIFY",
"old_path": "native/media/camera-modal.react.js",
"new_path": "native/media/camera-modal.react.js",
"diff": "@@ -967,7 +967,7 @@ class CameraModal extends React.PureComponent<Props, State> {\n[capture],\n);\n- saveImage({ uri: pendingPhotoCapture.uri, type: 'photo' });\n+ saveImage(pendingPhotoCapture.uri);\n};\nclearPendingImage = () => {\n"
},
{
"change_type": "MODIFY",
"old_path": "native/media/multimedia-modal.react.js",
"new_path": "native/media/multimedia-modal.react.js",
"diff": "@@ -1177,7 +1177,8 @@ class MultimediaModal extends React.PureComponent<Props, State> {\n};\nsave = async () => {\n- await intentionalSaveImage(this.props.navigation.state.params.mediaInfo);\n+ const { mediaInfo } = this.props.navigation.state.params;\n+ await intentionalSaveImage(mediaInfo.uri);\n};\nsetCloseButtonEnabled = ([enabledNum]: [number]) => {\n"
},
{
"change_type": "MODIFY",
"old_path": "native/media/save-image.js",
"new_path": "native/media/save-image.js",
"diff": "@@ -18,24 +18,12 @@ import { fetchFileInfo } from './file-utils';\nimport { displayActionResultModal } from '../navigation/action-result-modal';\nimport { getAndroidPermission } from '../utils/android-permissions';\n-type SaveImageInfo =\n- | {\n- type: 'photo',\n- uri: string,\n- ...\n- }\n- | {\n- type: 'video',\n- uri: string,\n- ...\n- };\n-\n-async function intentionalSaveImage(mediaInfo: SaveImageInfo) {\n+async function intentionalSaveImage(uri: string) {\nlet errorMessage;\nif (Platform.OS === 'android') {\n- errorMessage = await saveImageAndroid(mediaInfo, 'request');\n+ errorMessage = await saveImageAndroid(uri, 'request');\n} else if (Platform.OS === 'ios') {\n- errorMessage = await saveImageIOS(mediaInfo);\n+ errorMessage = await saveImageIOS(uri);\n} else {\nerrorMessage = `saving images is unsupported on ${Platform.OS}`;\n}\n@@ -44,18 +32,18 @@ async function intentionalSaveImage(mediaInfo: SaveImageInfo) {\ndisplayActionResultModal(message);\n}\n-async function saveImage(mediaInfo: SaveImageInfo) {\n+async function saveImage(uri: string) {\nif (Platform.OS === 'android') {\n- await saveImageAndroid(mediaInfo, 'check');\n+ await saveImageAndroid(uri, 'check');\n} else if (Platform.OS === 'ios') {\n- await saveImageIOS(mediaInfo);\n+ await saveImageIOS(uri);\n}\n}\n// On Android, we save the image to our own SquadCal folder in the\n// Pictures directory, and then trigger the media scanner to pick it up\nasync function saveImageAndroid(\n- mediaInfo: SaveImageInfo,\n+ inputURI: string,\npermissions: 'check' | 'request',\n) {\nlet hasPermission;\n@@ -80,7 +68,7 @@ async function saveImageAndroid(\nconst saveFolder = `${filesystem.PicturesDirectoryPath}/SquadCal/`;\npromises.push(filesystem.mkdir(saveFolder));\n- let { uri } = mediaInfo;\n+ let uri = inputURI;\nlet tempFile, mime, error;\nif (uri.startsWith('http')) {\npromises.push(\n@@ -118,8 +106,8 @@ async function saveImageAndroid(\n}\n// On iOS, we save the image to the camera roll\n-async function saveImageIOS(mediaInfo: SaveImageInfo) {\n- let { uri } = mediaInfo;\n+async function saveImageIOS(inputURI: string) {\n+ let uri = inputURI;\nlet tempFile;\nif (uri.startsWith('http')) {\nconst saveResult = await saveRemoteMediaToDisk(\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] saveImage only needs URI |
129,187 | 27.04.2020 14:53:37 | 14,400 | d296c48ffddbb49b4480235229185eb45bb5d67d | [native] saveImage -> saveMedia | [
{
"change_type": "MODIFY",
"old_path": "native/chat/multimedia-tooltip-modal.react.js",
"new_path": "native/chat/multimedia-tooltip-modal.react.js",
"diff": "@@ -5,7 +5,7 @@ import type { ChatMultimediaMessageInfoItem } from './multimedia-message.react';\nimport { createTooltip, tooltipHeight } from '../navigation/tooltip.react';\nimport MultimediaTooltipButton from './multimedia-tooltip-button.react';\n-import { intentionalSaveImage } from '../media/save-image';\n+import { intentionalSaveMedia } from '../media/save-media';\ntype CustomProps = {\nitem: ChatMultimediaMessageInfoItem,\n@@ -14,7 +14,7 @@ type CustomProps = {\n};\nfunction onPressSave(props: CustomProps) {\n- return intentionalSaveImage(props.mediaInfo.uri);\n+ return intentionalSaveMedia(props.mediaInfo.uri);\n}\nconst spec = {\n"
},
{
"change_type": "MODIFY",
"old_path": "native/media/camera-modal.react.js",
"new_path": "native/media/camera-modal.react.js",
"diff": "@@ -61,7 +61,7 @@ import ConnectedStatusBar from '../connected-status-bar.react';\nimport { clamp, gestureJustEnded } from '../utils/animation-utils';\nimport ContentLoading from '../components/content-loading.react';\nimport { colors } from '../themes/colors';\n-import { saveImage } from './save-image';\n+import { saveMedia } from './save-media';\nimport SendMediaButton from './send-media-button.react';\n/* eslint-disable import/no-named-as-default-member */\n@@ -967,7 +967,7 @@ class CameraModal extends React.PureComponent<Props, State> {\n[capture],\n);\n- saveImage(pendingPhotoCapture.uri);\n+ saveMedia(pendingPhotoCapture.uri);\n};\nclearPendingImage = () => {\n"
},
{
"change_type": "MODIFY",
"old_path": "native/media/multimedia-modal.react.js",
"new_path": "native/media/multimedia-modal.react.js",
"diff": "@@ -54,7 +54,7 @@ import {\ngestureJustStarted,\ngestureJustEnded,\n} from '../utils/animation-utils';\n-import { intentionalSaveImage } from './save-image';\n+import { intentionalSaveMedia } from './save-media';\n/* eslint-disable import/no-named-as-default-member */\nconst {\n@@ -1178,7 +1178,7 @@ class MultimediaModal extends React.PureComponent<Props, State> {\nsave = async () => {\nconst { mediaInfo } = this.props.navigation.state.params;\n- await intentionalSaveImage(mediaInfo.uri);\n+ await intentionalSaveMedia(mediaInfo.uri);\n};\nsetCloseButtonEnabled = ([enabledNum]: [number]) => {\n"
},
{
"change_type": "RENAME",
"old_path": "native/media/save-image.js",
"new_path": "native/media/save-media.js",
"diff": "@@ -18,31 +18,31 @@ import { fetchFileInfo } from './file-utils';\nimport { displayActionResultModal } from '../navigation/action-result-modal';\nimport { getAndroidPermission } from '../utils/android-permissions';\n-async function intentionalSaveImage(uri: string) {\n+async function intentionalSaveMedia(uri: string) {\nlet errorMessage;\nif (Platform.OS === 'android') {\n- errorMessage = await saveImageAndroid(uri, 'request');\n+ errorMessage = await saveMediaAndroid(uri, 'request');\n} else if (Platform.OS === 'ios') {\n- errorMessage = await saveImageIOS(uri);\n+ errorMessage = await saveMediaIOS(uri);\n} else {\n- errorMessage = `saving images is unsupported on ${Platform.OS}`;\n+ errorMessage = `saving media is unsupported on ${Platform.OS}`;\n}\nconst message = errorMessage ? errorMessage : 'saved!';\ndisplayActionResultModal(message);\n}\n-async function saveImage(uri: string) {\n+async function saveMedia(uri: string) {\nif (Platform.OS === 'android') {\n- await saveImageAndroid(uri, 'check');\n+ await saveMediaAndroid(uri, 'check');\n} else if (Platform.OS === 'ios') {\n- await saveImageIOS(uri);\n+ await saveMediaIOS(uri);\n}\n}\n-// On Android, we save the image to our own SquadCal folder in the\n+// On Android, we save the media to our own SquadCal folder in the\n// Pictures directory, and then trigger the media scanner to pick it up\n-async function saveImageAndroid(\n+async function saveMediaAndroid(\ninputURI: string,\npermissions: 'check' | 'request',\n) {\n@@ -105,8 +105,8 @@ async function saveImageAndroid(\nreturn null;\n}\n-// On iOS, we save the image to the camera roll\n-async function saveImageIOS(inputURI: string) {\n+// On iOS, we save the media to the camera roll\n+async function saveMediaIOS(inputURI: string) {\nlet uri = inputURI;\nlet tempFile;\nif (uri.startsWith('http')) {\n@@ -240,4 +240,4 @@ async function copyToSortedDirectory(\nreturn { success: true, path: newPath, mime };\n}\n-export { intentionalSaveImage, saveImage };\n+export { intentionalSaveMedia, saveMedia };\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] saveImage -> saveMedia |
129,187 | 27.04.2020 15:03:25 | 14,400 | cd0fc2425564d2a8fea2ab35047a95287159d1c9 | [native] Move saveMedia for captures to processMedia | [
{
"change_type": "MODIFY",
"old_path": "native/media/camera-modal.react.js",
"new_path": "native/media/camera-modal.react.js",
"diff": "@@ -61,7 +61,6 @@ import ConnectedStatusBar from '../connected-status-bar.react';\nimport { clamp, gestureJustEnded } from '../utils/animation-utils';\nimport ContentLoading from '../components/content-loading.react';\nimport { colors } from '../themes/colors';\n-import { saveMedia } from './save-media';\nimport SendMediaButton from './send-media-button.react';\n/* eslint-disable import/no-named-as-default-member */\n@@ -966,8 +965,6 @@ class CameraModal extends React.PureComponent<Props, State> {\nthis.props.navigation.state.params.threadID,\n[capture],\n);\n-\n- saveMedia(pendingPhotoCapture.uri);\n};\nclearPendingImage = () => {\n"
},
{
"change_type": "MODIFY",
"old_path": "native/media/media-utils.js",
"new_path": "native/media/media-utils.js",
"diff": "@@ -16,8 +16,10 @@ import { pathFromURI, readableFilename } from 'lib/utils/file-utils';\nimport { fetchFileInfo } from './file-utils';\nimport { processVideo } from './video-utils';\nimport { processImage } from './image-utils';\n+import { saveMedia } from './save-media';\ntype MediaProcessConfig = $Shape<{|\n+ // Blocks return until we can confirm result has the correct MIME\nfinalFileHeaderCheck: boolean,\n|}>;\ntype MediaResult = {|\n@@ -57,24 +59,26 @@ async function processMediaMission(\nconfig: MediaProcessConfig,\nsendResult: (MediaMissionFailure | MediaResult) => void,\n): Promise<$ReadOnlyArray<MediaMissionStep>> {\n- const steps = [];\nlet initialURI = null,\nuploadURI = null,\ndimensions = selection.dimensions,\n+ mediaType = null,\nmime = null,\nloop = false,\n- finished = false;\n- let mediaType;\n- const finish = (failure?: MediaMissionFailure) => {\n- invariant(!finished, 'finish called twice in processMediaMission');\n- finished = true;\n+ resultReturned = false;\n+ const returnResult = (failure?: MediaMissionFailure) => {\n+ invariant(\n+ !resultReturned,\n+ 'returnResult called twice in processMediaMission',\n+ );\n+ resultReturned = true;\nif (failure) {\nsendResult(failure);\nreturn;\n}\ninvariant(\nuploadURI && mime && mediaType,\n- 'missing required fields to finish',\n+ 'missing required fields in returnResult',\n);\nconst shouldDisposePath =\ninitialURI !== uploadURI ? pathFromURI(uploadURI) : null;\n@@ -92,6 +96,25 @@ async function processMediaMission(\n});\n};\n+ const steps = [],\n+ completeBeforeFinish = [];\n+ const finish = async (failure?: MediaMissionFailure) => {\n+ if (!resultReturned) {\n+ returnResult(failure);\n+ }\n+ await Promise.all(completeBeforeFinish);\n+ return steps;\n+ };\n+\n+ if (selection.captureTime) {\n+ const { uri } = selection;\n+ invariant(\n+ pathFromURI(uri),\n+ `captured URI ${uri} should use file:// scheme`,\n+ );\n+ completeBeforeFinish.push(saveMedia(uri));\n+ }\n+\nconst possiblyPhoto = selection.step.startsWith('photo_');\nconst mediaNativeID = selection.mediaNativeID\n? selection.mediaNativeID\n@@ -107,18 +130,16 @@ async function processMediaMission(\n);\nsteps.push(...fileInfoSteps);\nif (!fileInfoResult.success) {\n- finish(fileInfoResult);\n- return steps;\n+ return await finish(fileInfoResult);\n}\nconst { orientation, fileSize } = fileInfoResult;\n({ uri: initialURI, mime, mediaType } = fileInfoResult);\nif (!mime || !mediaType) {\n- finish({\n+ return await finish({\nsuccess: false,\nreason: 'media_type_fetch_failed',\ndetectedMIME: mime,\n});\n- return steps;\n}\nif (mediaType === 'video') {\n@@ -131,8 +152,7 @@ async function processMediaMission(\n});\nsteps.push(...videoSteps);\nif (!videoResult.success) {\n- finish(videoResult);\n- return steps;\n+ return await finish(videoResult);\n}\n({ uri: uploadURI, mime, dimensions, loop } = videoResult);\n} else if (mediaType === 'photo') {\n@@ -145,8 +165,7 @@ async function processMediaMission(\n});\nsteps.push(...imageSteps);\nif (!imageResult.success) {\n- finish(imageResult);\n- return steps;\n+ return await finish(imageResult);\n}\n({ uri: uploadURI, mime, dimensions } = imageResult);\n} else {\n@@ -154,12 +173,11 @@ async function processMediaMission(\n}\nif (uploadURI === initialURI) {\n- finish();\n- return steps;\n+ return await finish();\n}\nif (!config.finalFileHeaderCheck) {\n- finish();\n+ returnResult();\n}\nconst {\n@@ -168,15 +186,11 @@ async function processMediaMission(\n} = await fetchFileInfo(uploadURI, undefined, { mime: true });\nsteps.push(...finalFileInfoSteps);\nif (!finalFileInfoResult.success) {\n- if (config.finalFileHeaderCheck) {\n- finish(finalFileInfoResult);\n- }\n- return steps;\n+ return await finish(finalFileInfoResult);\n}\nif (finalFileInfoResult.mime && finalFileInfoResult.mime !== mime) {\n- if (config.finalFileHeaderCheck) {\n- finish({\n+ return await finish({\nsuccess: false,\nreason: 'mime_type_mismatch',\nreportedMediaType: mediaType,\n@@ -184,14 +198,8 @@ async function processMediaMission(\ndetectedMIME: finalFileInfoResult.mime,\n});\n}\n- return steps;\n- }\n- if (config.finalFileHeaderCheck) {\n- finish();\n- }\n-\n- return steps;\n+ return await finish();\n}\nfunction getDimensions(uri: string): Promise<Dimensions> {\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Move saveMedia for captures to processMedia |
129,187 | 27.04.2020 17:38:06 | 14,400 | 819ab2606855a4ef8fe9b327bc45e50e758a2c41 | [native] disposeTempFile | [
{
"change_type": "MODIFY",
"old_path": "lib/types/media-types.js",
"new_path": "lib/types/media-types.js",
"diff": "@@ -130,6 +130,14 @@ export type FrameCountMediaMissionStep = {|\nhasMultipleFrames: ?boolean,\n|};\n+export type DisposeTemporaryFileMediaMissionStep = {|\n+ step: 'dispose_temporary_file',\n+ success: boolean,\n+ exceptionMessage: ?string,\n+ time: number, // ms\n+ path: string,\n+|};\n+\nexport type MediaLibrarySelection =\n| {|\nstep: 'photo_library',\n@@ -234,13 +242,7 @@ export type MediaMissionStep =\nreturnCode: ?number,\nnewPath: ?string,\n|}\n- | {|\n- step: 'dispose_uploaded_local_file',\n- success: boolean,\n- exceptionMessage: ?string,\n- time: number, // ms\n- path: string,\n- |}\n+ | DisposeTemporaryFileMediaMissionStep\n| {|\nstep: 'upload',\nsuccess: boolean,\n@@ -396,7 +398,7 @@ export const mediaMissionPropType = PropTypes.shape({\nnewPath: PropTypes.string,\n}),\nPropTypes.shape({\n- step: PropTypes.oneOf(['dispose_uploaded_local_file']).isRequired,\n+ step: PropTypes.oneOf(['dispose_temporary_file']).isRequired,\nsuccess: PropTypes.bool.isRequired,\nexceptionMessage: PropTypes.string,\ntime: PropTypes.number.isRequired,\n"
},
{
"change_type": "MODIFY",
"old_path": "native/input/input-state-container.react.js",
"new_path": "native/input/input-state-container.react.js",
"diff": "@@ -35,7 +35,6 @@ import * as React from 'react';\nimport PropTypes from 'prop-types';\nimport invariant from 'invariant';\nimport { createSelector } from 'reselect';\n-import filesystem from 'react-native-fs';\nimport * as Upload from 'react-native-background-upload';\nimport { Platform } from 'react-native';\n@@ -70,6 +69,7 @@ import {\n} from './input-state';\nimport { processMedia } from '../media/media-utils';\nimport { displayActionResultModal } from '../navigation/action-result-modal';\n+import { disposeTempFile } from '../media/file-utils';\nlet nextLocalUploadID = 0;\nfunction getNewLocalID() {\n@@ -583,35 +583,11 @@ class InputStateContainer extends React.PureComponent<Props, State> {\ntime: Date.now() - uploadStart,\n});\n- if (!shouldDisposePath) {\n- return await finish(mediaMissionResult);\n+ if (shouldDisposePath) {\n+ const disposeStep = await disposeTempFile(shouldDisposePath);\n+ steps.push(disposeStep);\n}\n- let disposeSuccess = false,\n- disposeExceptionMessage;\n- const disposeStart = Date.now();\n- try {\n- await filesystem.unlink(shouldDisposePath);\n- disposeSuccess = true;\n- } catch (e) {\n- if (\n- e &&\n- typeof e === 'object' &&\n- e.message &&\n- typeof e.message === 'string'\n- ) {\n- disposeExceptionMessage = e.message;\n- }\n- }\n-\n- steps.push({\n- step: 'dispose_uploaded_local_file',\n- success: disposeSuccess,\n- exceptionMessage: disposeExceptionMessage,\n- time: Date.now() - disposeStart,\n- path: shouldDisposePath,\n- });\n-\nreturn await finish(mediaMissionResult);\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "native/media/file-utils.js",
"new_path": "native/media/file-utils.js",
"diff": "@@ -5,6 +5,7 @@ import type {\nMediaMissionFailure,\nMediaType,\nReadFileHeaderMediaMissionStep,\n+ DisposeTemporaryFileMediaMissionStep,\n} from 'lib/types/media-types';\nimport { Platform } from 'react-native';\n@@ -335,4 +336,32 @@ async function getMediaTypeInfo(\nreturn { steps, result };\n}\n-export { fetchFileInfo };\n+async function disposeTempFile(\n+ path: string,\n+): Promise<DisposeTemporaryFileMediaMissionStep> {\n+ let success = false,\n+ exceptionMessage;\n+ const start = Date.now();\n+ try {\n+ await filesystem.unlink(path);\n+ success = true;\n+ } catch (e) {\n+ if (\n+ e &&\n+ typeof e === 'object' &&\n+ e.message &&\n+ typeof e.message === 'string'\n+ ) {\n+ exceptionMessage = e.message;\n+ }\n+ }\n+ return {\n+ step: 'dispose_temporary_file',\n+ success,\n+ exceptionMessage,\n+ time: Date.now() - start,\n+ path,\n+ };\n+}\n+\n+export { fetchFileInfo, disposeTempFile };\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] disposeTempFile |
129,187 | 27.04.2020 20:59:40 | 14,400 | 1f914f8f25d52f891d1e2dbe26d43ab9392dcbf5 | [server] Update squadbot's message for MediaMission reports | [
{
"change_type": "MODIFY",
"old_path": "server/src/creators/report-creator.js",
"new_path": "server/src/creators/report-creator.js",
"diff": "@@ -163,8 +163,8 @@ function getSquadbotMessage(\n} else if (request.type === reportTypes.MEDIA_MISSION) {\nconst mediaMissionJSON = JSON.stringify(request.mediaMission);\nconst success = request.mediaMission.result.success\n- ? 'uploaded media successfully'\n- : 'failed to upload media :(';\n+ ? 'media mission success!'\n+ : 'media mission failed :(';\nreturn `${name} ${success}\\n` + mediaMissionJSON;\n} else {\nreturn null;\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [server] Update squadbot's message for MediaMission reports |
129,187 | 27.04.2020 23:08:12 | 14,400 | ec888bc67bcb305fb4dc1cd65a982cd22077c9ad | Send MediaMission from intentionalSaveImage | [
{
"change_type": "MODIFY",
"old_path": "lib/types/report-types.js",
"new_path": "lib/types/report-types.js",
"diff": "@@ -89,9 +89,11 @@ export type MediaMissionReportCreationRequest = {|\nplatformDetails: PlatformDetails,\ntime: number, // ms\nmediaMission: MediaMission,\n- uploadServerID: ?string,\n- uploadLocalID: string,\n- mediaLocalID: string,\n+ uploadServerID?: ?string,\n+ uploadLocalID?: ?string,\n+ mediaLocalID?: ?string, // deprecated\n+ messageServerID?: ?string,\n+ messageLocalID?: ?string,\n|};\nexport type ReportCreationRequest =\n| ErrorReportCreationRequest\n@@ -175,8 +177,10 @@ export const queuedClientReportCreationRequestPropType = PropTypes.oneOfType([\ntime: PropTypes.number.isRequired,\nmediaMission: mediaMissionPropType.isRequired,\nuploadServerID: PropTypes.string,\n- uploadLocalID: PropTypes.string.isRequired,\n- mediaLocalID: PropTypes.string.isRequired,\n+ uploadLocalID: PropTypes.string,\n+ mediaLocalID: PropTypes.string,\n+ messageServerID: PropTypes.string,\n+ messageLocalID: PropTypes.string,\n}),\n]);\n"
},
{
"change_type": "MODIFY",
"old_path": "native/chat/multimedia-message-multimedia.react.js",
"new_path": "native/chat/multimedia-message-multimedia.react.js",
"diff": "@@ -205,7 +205,7 @@ class MultimediaMessageMultimedia extends React.PureComponent<Props> {\n}\nthis.clickable = false;\n- const { scrollViewModalState, mediaInfo } = this.props;\n+ const { scrollViewModalState, mediaInfo, item } = this.props;\nif (scrollViewModalState) {\nscrollViewModalState.setModalState('open');\n}\n@@ -217,6 +217,7 @@ class MultimediaMessageMultimedia extends React.PureComponent<Props> {\nparams: {\npresentedFrom: this.props.navigation.state.key,\nmediaInfo,\n+ item,\ninitialCoordinates: coordinates,\nverticalBounds,\n},\n"
},
{
"change_type": "MODIFY",
"old_path": "native/chat/multimedia-tooltip-modal.react.js",
"new_path": "native/chat/multimedia-tooltip-modal.react.js",
"diff": "@@ -14,7 +14,11 @@ type CustomProps = {\n};\nfunction onPressSave(props: CustomProps) {\n- return intentionalSaveMedia(props.mediaInfo.uri);\n+ const { mediaInfo, item } = props;\n+ const { id: uploadID, uri } = mediaInfo;\n+ const { id: messageServerID, localID: messageLocalID } = item.messageInfo;\n+ const ids = { uploadID, messageServerID, messageLocalID };\n+ return intentionalSaveMedia(uri, ids);\n}\nconst spec = {\n"
},
{
"change_type": "MODIFY",
"old_path": "native/input/input-state-container.react.js",
"new_path": "native/input/input-state-container.react.js",
"diff": "@@ -747,7 +747,7 @@ class InputStateContainer extends React.PureComponent<Props, State> {\nmediaMission,\nuploadServerID: ids.serverID,\nuploadLocalID: ids.localID,\n- mediaLocalID: ids.localMessageID,\n+ messageLocalID: ids.localMessageID,\n};\nthis.props.dispatchActionPayload(queueReportsActionType, {\nreports: [report],\n"
},
{
"change_type": "MODIFY",
"old_path": "native/media/multimedia-modal.react.js",
"new_path": "native/media/multimedia-modal.react.js",
"diff": "@@ -20,6 +20,8 @@ import {\nlayoutCoordinatesPropType,\n} from '../types/layout-types';\nimport type { NativeMethodsMixinType } from '../types/react-native';\n+import type { ChatMultimediaMessageInfoItem } from '../chat/multimedia-message.react';\n+import { chatMessageItemPropType } from 'lib/selectors/chat-selectors';\nimport * as React from 'react';\nimport {\n@@ -184,6 +186,7 @@ type NavProp = NavigationStackProp<{|\nmediaInfo: MediaInfo,\ninitialCoordinates: LayoutCoordinates,\nverticalBounds: VerticalBounds,\n+ item: ChatMultimediaMessageInfoItem,\n|},\n|}>;\n@@ -213,6 +216,7 @@ class MultimediaModal extends React.PureComponent<Props, State> {\nmediaInfo: mediaInfoPropType.isRequired,\ninitialCoordinates: layoutCoordinatesPropType.isRequired,\nverticalBounds: verticalBoundsPropType.isRequired,\n+ item: chatMessageItemPropType.isRequired,\n}).isRequired,\n}).isRequired,\ngoBack: PropTypes.func.isRequired,\n@@ -1176,9 +1180,12 @@ class MultimediaModal extends React.PureComponent<Props, State> {\nthis.props.navigation.goBack();\n};\n- save = async () => {\n- const { mediaInfo } = this.props.navigation.state.params;\n- await intentionalSaveMedia(mediaInfo.uri);\n+ save = () => {\n+ const { mediaInfo, item } = this.props.navigation.state.params;\n+ const { id: uploadID, uri } = mediaInfo;\n+ const { id: messageServerID, localID: messageLocalID } = item.messageInfo;\n+ const ids = { uploadID, messageServerID, messageLocalID };\n+ return intentionalSaveMedia(uri, ids);\n};\nsetCloseButtonEnabled = ([enabledNum]: [number]) => {\n"
},
{
"change_type": "MODIFY",
"old_path": "native/media/save-media.js",
"new_path": "native/media/save-media.js",
"diff": "import type {\nMediaMissionStep,\nMediaMissionResult,\n- MediaMission,\nMediaMissionFailure,\n} from 'lib/types/media-types';\n+import {\n+ reportTypes,\n+ type MediaMissionReportCreationRequest,\n+} from 'lib/types/report-types';\nimport { Platform, PermissionsAndroid } from 'react-native';\nimport filesystem from 'react-native-fs';\n@@ -14,6 +17,8 @@ import * as MediaLibrary from 'expo-media-library';\nimport { readableFilename, pathFromURI } from 'lib/utils/file-utils';\nimport { promiseAll } from 'lib/utils/promises';\nimport { getMessageForException } from 'lib/utils/errors';\n+import { getConfig } from 'lib/utils/config';\n+import { queueReportsActionType } from 'lib/actions/report-actions';\nimport { fetchBlob } from './blob-utils';\nimport { getMediaLibraryIdentifier } from './identifier-utils';\n@@ -28,8 +33,16 @@ import {\n} from './file-utils';\nimport { displayActionResultModal } from '../navigation/action-result-modal';\nimport { getAndroidPermission } from '../utils/android-permissions';\n+import { dispatch } from '../redux/redux-setup';\n-async function intentionalSaveMedia(uri: string): Promise<MediaMission> {\n+async function intentionalSaveMedia(\n+ uri: string,\n+ ids: {|\n+ uploadID: string,\n+ messageServerID: ?string,\n+ messageLocalID: ?string,\n+ |},\n+): Promise<void> {\nconst start = Date.now();\nconst { resultPromise, reportPromise } = saveMedia(uri, 'request');\nconst result = await resultPromise;\n@@ -61,7 +74,24 @@ async function intentionalSaveMedia(uri: string): Promise<MediaMission> {\nconst steps = await reportPromise;\nconst totalTime = Date.now() - start;\n- return { steps, result, userTime, totalTime };\n+ const mediaMission = { steps, result, userTime, totalTime };\n+\n+ const { uploadID, messageServerID, messageLocalID } = ids;\n+ const uploadIDIsLocal = uploadID.startsWith('localUpload');\n+ const report: MediaMissionReportCreationRequest = {\n+ type: reportTypes.MEDIA_MISSION,\n+ time: Date.now(),\n+ platformDetails: getConfig().platformDetails,\n+ mediaMission,\n+ uploadServerID: uploadIDIsLocal ? undefined : uploadID,\n+ uploadLocalID: uploadIDIsLocal ? uploadID : undefined,\n+ messageServerID,\n+ messageLocalID,\n+ };\n+ dispatch({\n+ type: queueReportsActionType,\n+ payload: { reports: [report] },\n+ });\n}\ntype Permissions = 'check' | 'request';\n"
},
{
"change_type": "MODIFY",
"old_path": "server/src/responders/report-responders.js",
"new_path": "server/src/responders/report-responders.js",
"diff": "@@ -79,8 +79,10 @@ const mediaMissionReportCreationRequest = tShape({\ntime: t.Number,\nmediaMission: t.Object,\nuploadServerID: t.maybe(t.String),\n- uploadLocalID: t.String,\n- mediaLocalID: t.String,\n+ uploadLocalID: t.maybe(t.String),\n+ mediaLocalID: t.maybe(t.String),\n+ messageServerID: t.maybe(t.String),\n+ messageLocalID: t.maybe(t.String),\n});\nconst reportCreationRequestInputValidator = t.union([\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | Send MediaMission from intentionalSaveImage |
129,187 | 27.04.2020 23:28:56 | 14,400 | 91e9625fd3b934cd5243e4028b268e7e061e3bfe | [native] Only check header of blob for fileType | [
{
"change_type": "MODIFY",
"old_path": "lib/utils/file-utils.js",
"new_path": "lib/utils/file-utils.js",
"diff": "@@ -30,6 +30,8 @@ const mimeTypesToExtensions = Object.freeze({\n'video/quicktime': 'mp4',\n});\n+const bytesNeededForFileTypeCheck = 64;\n+\nexport type FileDataInfo = {|\nmime: ?string,\nmediaType: ?MediaType,\n@@ -98,6 +100,7 @@ function filenameFromPathOrURI(pathOrURI: string): ?string {\n}\nexport {\n+ bytesNeededForFileTypeCheck,\nfileInfoFromData,\nreplaceExtension,\nreadableFilename,\n"
},
{
"change_type": "MODIFY",
"old_path": "native/media/blob-utils.js",
"new_path": "native/media/blob-utils.js",
"diff": "@@ -8,7 +8,10 @@ import type {\nimport base64 from 'base-64';\nimport invariant from 'invariant';\n-import { fileInfoFromData } from 'lib/utils/file-utils';\n+import {\n+ fileInfoFromData,\n+ bytesNeededForFileTypeCheck,\n+} from 'lib/utils/file-utils';\nimport { getMessageForException } from 'lib/utils/errors';\nimport { getFetchableURI } from './identifier-utils';\n@@ -31,6 +34,8 @@ function blobToDataURI(blob: Blob): Promise<string> {\n});\n}\n+const base64CharsNeeded = 4 * Math.ceil(bytesNeededForFileTypeCheck / 3);\n+\nfunction dataURIToIntArray(dataURI: string): Uint8Array {\nconst uri = dataURI.replace(/\\r?\\n/g, '');\n@@ -42,7 +47,7 @@ function dataURIToIntArray(dataURI: string): Uint8Array {\nconst meta = uri.substring(5, firstComma).split(';');\nconst base64Encoded = meta.some(metum => metum === 'base64');\n- let data = unescape(uri.substring(firstComma + 1));\n+ let data = unescape(uri.substr(firstComma + 1, base64CharsNeeded));\nif (base64Encoded) {\ndata = base64.decode(data);\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "native/media/file-utils.js",
"new_path": "native/media/file-utils.js",
"diff": "@@ -18,7 +18,11 @@ import filesystem from 'react-native-fs';\nimport base64 from 'base-64';\nimport invariant from 'invariant';\n-import { pathFromURI, fileInfoFromData } from 'lib/utils/file-utils';\n+import {\n+ pathFromURI,\n+ fileInfoFromData,\n+ bytesNeededForFileTypeCheck,\n+} from 'lib/utils/file-utils';\nimport { getMessageForException } from 'lib/utils/errors';\nimport { stringToIntArray } from './blob-utils';\n@@ -246,7 +250,7 @@ async function readFileHeader(\nlocalURI: string,\nfileSize: number,\n): Promise<ReadFileHeaderMediaMissionStep> {\n- const fetchBytes = Math.min(fileSize, 64);\n+ const fetchBytes = Math.min(fileSize, bytesNeededForFileTypeCheck);\nconst start = Date.now();\nlet fileData,\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Only check header of blob for fileType |
129,187 | 28.04.2020 00:36:08 | 14,400 | e8f4af16e1d5e67e896cebc6e0d1c279ac5a9890 | [native] Initial save_media step for intentionalSaveMedia | [
{
"change_type": "MODIFY",
"old_path": "lib/types/media-types.js",
"new_path": "lib/types/media-types.js",
"diff": "@@ -279,6 +279,11 @@ export type MediaMissionStep =\nnewPath: ?string,\n|}\n| DisposeTemporaryFileMediaMissionStep\n+ | {|\n+ step: 'save_media',\n+ uri: string,\n+ time: number, // ms timestamp\n+ |}\n| {|\nstep: 'permissions_check',\nsuccess: boolean,\n@@ -538,6 +543,11 @@ export const mediaMissionPropType = PropTypes.shape({\ntime: PropTypes.number.isRequired,\npath: PropTypes.string.isRequired,\n}),\n+ PropTypes.shape({\n+ step: PropTypes.oneOf(['save_media']).isRequired,\n+ uri: PropTypes.string.isRequired,\n+ time: PropTypes.number.isRequired,\n+ }),\nPropTypes.shape({\nstep: PropTypes.oneOf(['permissions_check']).isRequired,\nsuccess: PropTypes.bool.isRequired,\n"
},
{
"change_type": "MODIFY",
"old_path": "native/media/save-media.js",
"new_path": "native/media/save-media.js",
"diff": "@@ -44,6 +44,8 @@ async function intentionalSaveMedia(\n|},\n): Promise<void> {\nconst start = Date.now();\n+ const steps = [{ step: 'save_media', uri, time: start }];\n+\nconst { resultPromise, reportPromise } = saveMedia(uri, 'request');\nconst result = await resultPromise;\nconst userTime = Date.now() - start;\n@@ -72,7 +74,8 @@ async function intentionalSaveMedia(\n}\ndisplayActionResultModal(message);\n- const steps = await reportPromise;\n+ const reportSteps = await reportPromise;\n+ steps.push(...reportSteps);\nconst totalTime = Date.now() - start;\nconst mediaMission = { steps, result, userTime, totalTime };\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Initial save_media step for intentionalSaveMedia |
129,187 | 29.04.2020 01:03:02 | 14,400 | 9e171489252630bba9b510a234f9cb0cc714417d | [native] Use MediaLibrary.requestPermissionsAsync in Android MediaGalleryKeyboard | [
{
"change_type": "MODIFY",
"old_path": "native/media/media-gallery-keyboard.react.js",
"new_path": "native/media/media-gallery-keyboard.react.js",
"diff": "@@ -10,14 +10,7 @@ import type { ViewToken, LayoutEvent } from '../types/react-native';\nimport type { ViewStyle } from '../types/styles';\nimport * as React from 'react';\n-import {\n- View,\n- Text,\n- Platform,\n- PermissionsAndroid,\n- FlatList,\n- ActivityIndicator,\n-} from 'react-native';\n+import { View, Text, FlatList, ActivityIndicator } from 'react-native';\nimport { KeyboardRegistry } from 'react-native-keyboard-input';\nimport invariant from 'invariant';\nimport { Provider } from 'react-redux';\n@@ -40,7 +33,6 @@ import {\ncolorsSelector,\nstyleSelector,\n} from '../themes/colors';\n-import { getAndroidPermission } from '../utils/android-permissions';\nimport SendMediaButton from './send-media-button.react';\nimport { getCompatibleMediaURI } from './identifier-utils';\n@@ -303,18 +295,7 @@ class MediaGalleryKeyboard extends React.PureComponent<Props, State> {\n}\nasync getPermissions(): Promise<boolean> {\n- let granted;\n- if (Platform.OS === 'android') {\n- granted = await getAndroidPermission(\n- PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,\n- {\n- title: 'Access Your Photos',\n- message: 'Requesting access to your external storage',\n- },\n- );\n- } else {\n- ({ granted } = await MediaLibrary.requestPermissionsAsync());\n- }\n+ const { granted } = await MediaLibrary.requestPermissionsAsync();\nif (!granted) {\nthis.guardedSetState({ error: \"don't have permission :(\" });\n}\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Use MediaLibrary.requestPermissionsAsync in Android MediaGalleryKeyboard |
129,187 | 29.04.2020 01:04:31 | 14,400 | 60da4c583a84db6f08c483e366ff9b6294988160 | [native] Rework android-permissions.js | [
{
"change_type": "MODIFY",
"old_path": "native/media/save-media.js",
"new_path": "native/media/save-media.js",
"diff": "@@ -32,7 +32,7 @@ import {\ncopyFile,\n} from './file-utils';\nimport { displayActionResultModal } from '../navigation/action-result-modal';\n-import { getAndroidPermission } from '../utils/android-permissions';\n+import { requestAndroidPermission } from '../utils/android-permissions';\nimport { dispatch } from '../redux/redux-setup';\nasync function intentionalSaveMedia(\n@@ -152,14 +152,10 @@ async function saveMediaAndroid(\npermissionCheckExceptionMessage;\nconst permissionCheckStart = Date.now();\ntry {\n- if (permissions === 'check') {\n- hasPermission = await PermissionsAndroid.check(androidSavePermission);\n- } else {\n- hasPermission = await getAndroidPermission(androidSavePermission, {\n- title: 'Save Photo',\n- message: 'Requesting access to your external storage',\n- });\n- }\n+ hasPermission = await requestAndroidPermission(\n+ androidSavePermission,\n+ 'throw',\n+ );\n} catch (e) {\npermissionCheckExceptionMessage = getMessageForException(e);\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "native/types/react-native.js",
"new_path": "native/types/react-native.js",
"diff": "@@ -12,6 +12,4 @@ export type {\nKeyPressEvent,\n} from 'react-native/Libraries/Components/TextInput/TextInput';\n-export type { Rationale } from 'react-native/Libraries/PermissionsAndroid/PermissionsAndroid';\n-\nexport type { NativeMethodsMixinType } from 'react-native/Libraries/Renderer/shims/ReactNativeTypes';\n"
},
{
"change_type": "MODIFY",
"old_path": "native/utils/android-permissions.js",
"new_path": "native/utils/android-permissions.js",
"diff": "// @flow\nimport { PermissionsAndroid } from 'react-native';\n-import type { Rationale } from '../types/react-native';\n+\n+import { getMessageForException } from 'lib/utils/errors';\n+import { promiseAll } from 'lib/utils/promises';\nconst granted = new Set();\n-async function getAndroidPermission(permission: string, rationale?: Rationale) {\n+type CheckOrRequest = 'check' | 'request';\n+type ThrowExceptions = 'throw' | typeof undefined;\n+\n+async function getAndroidPermissions(\n+ permissions: $ReadOnlyArray<string>,\n+ checkOrRequest: CheckOrRequest,\n+ throwExceptions?: ThrowExceptions,\n+) {\n+ const result = {},\n+ missing = [];\n+\n+ for (let permission of permissions) {\nif (granted.has(permission)) {\n- return true;\n+ result[permission] = true;\n+ } else {\n+ missing.push(permission);\n+ }\n}\n+ if (missing.length === 0) {\n+ return result;\n+ }\n+\n+ if (checkOrRequest === 'check') {\n+ for (let permission of missing) {\n+ result[permission] = (async () => {\ntry {\n- const result = await PermissionsAndroid.request(permission, rationale);\n- const gotPermission = result === PermissionsAndroid.RESULTS.GRANTED;\n- if (gotPermission) {\n- granted.add(permission);\n+ return await PermissionsAndroid.check(permission);\n+ } catch (e) {\n+ printException(e, 'PermissionsAndroid.check');\n+ if (throwExceptions === 'throw') {\n+ throw e;\n}\n- return gotPermission;\n- } catch (err) {\nreturn false;\n}\n+ })();\n+ }\n+ return await promiseAll(result);\n+ }\n+\n+ let requestResult = {};\n+ try {\n+ requestResult = await PermissionsAndroid.requestMultiple(missing);\n+ } catch (e) {\n+ printException(e, 'PermissionsAndroid.requestMultiple');\n+ if (throwExceptions === 'throw') {\n+ throw e;\n+ }\n+ }\n+ for (let permission of missing) {\n+ result[permission] =\n+ requestResult[permission] === PermissionsAndroid.RESULTS.GRANTED;\n+ }\n+ return result;\n+}\n+\n+function printException(e: mixed, caller: string) {\n+ const exceptionMessage = getMessageForException(e);\n+ const suffix = exceptionMessage ? `: ${exceptionMessage}` : '';\n+ console.log(`${caller} returned exception${suffix}`);\n+}\n+\n+function requestAndroidPermissions(\n+ permissions: $ReadOnlyArray<string>,\n+ throwExceptions?: ThrowExceptions,\n+) {\n+ return getAndroidPermissions(permissions, 'request', throwExceptions);\n+}\n+\n+function checkAndroidPermissions(\n+ permissions: $ReadOnlyArray<string>,\n+ throwExceptions?: ThrowExceptions,\n+) {\n+ return getAndroidPermissions(permissions, 'check', throwExceptions);\n+}\n+\n+async function getAndroidPermission(\n+ permission: string,\n+ checkOrRequest: CheckOrRequest,\n+ throwExceptions?: ThrowExceptions,\n+) {\n+ const result = await getAndroidPermissions(\n+ [permission],\n+ checkOrRequest,\n+ throwExceptions,\n+ );\n+ return result[permission];\n+}\n+\n+function requestAndroidPermission(\n+ permission: string,\n+ throwExceptions?: ThrowExceptions,\n+) {\n+ return getAndroidPermission(permission, 'request', throwExceptions);\n+}\n+\n+function checkAndroidPermission(\n+ permission: string,\n+ throwExceptions?: ThrowExceptions,\n+) {\n+ return getAndroidPermission(permission, 'check', throwExceptions);\n}\n-export { getAndroidPermission };\n+export {\n+ getAndroidPermissions,\n+ requestAndroidPermissions,\n+ checkAndroidPermissions,\n+ getAndroidPermission,\n+ requestAndroidPermission,\n+ checkAndroidPermission,\n+};\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Rework android-permissions.js |
129,187 | 29.04.2020 19:25:39 | 14,400 | 24dd5bd2b9de7ffff06db6aa0d755ebfcc2730d4 | [native] Increase Java heap size for Android build | [
{
"change_type": "MODIFY",
"old_path": "native/android/gradle.properties",
"new_path": "native/android/gradle.properties",
"diff": "# Specifies the JVM arguments used for the daemon process.\n# The setting is particularly useful for tweaking memory settings.\n# Default value: -Xmx10248m -XX:MaxPermSize=256m\n-# org.gradle.jvmargs=-Xmx2048m -XX:MaxPermSize=512m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8\n+org.gradle.jvmargs=-Xmx4096m -XX:MaxPermSize=4096m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8\n# When configured, Gradle will run in incubating parallel mode.\n# This option should only be used with decoupled projects. More details, visit\n# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects\n-# org.gradle.parallel=true\n+org.gradle.parallel=true\nandroid.useAndroidX=true\nandroid.enableJetifier=true\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Increase Java heap size for Android build |
129,187 | 29.04.2020 14:47:38 | 14,400 | 6ca0d2523ecf19f48b07a0e9fd3dd4417d847000 | [native] Fix Hermes path in Android build.gradle
Enabling right now trashes performance, likely because of | [
{
"change_type": "MODIFY",
"old_path": "native/android/app/build.gradle",
"new_path": "native/android/app/build.gradle",
"diff": "@@ -78,6 +78,7 @@ import com.android.build.OutputFile\nproject.ext.react = [\nentryFile: \"index.js\",\nenableHermes: false, // clean and rebuild if changing\n+ hermesCommand: \"../../../node_modules/hermes-engine/%OS-BIN%/hermes\",\n]\napply from: \"../../../node_modules/react-native/react.gradle\"\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Fix Hermes path in Android build.gradle
Enabling right now trashes performance, likely because of https://github.com/facebook/hermes/issues/111
https://github.com/facebook/react-native/issues/25986 |
129,187 | 29.04.2020 01:05:15 | 14,400 | 683743be5e006f084c0435be7af34eb8e061e012 | [native] Ask for permissions before opening CameraModal | [
{
"change_type": "MODIFY",
"old_path": "native/chat/chat-input-bar.react.js",
"new_path": "native/chat/chat-input-bar.react.js",
"diff": "@@ -40,6 +40,7 @@ import {\nText,\nActivityIndicator,\nTouchableWithoutFeedback,\n+ PermissionsAndroid,\n} from 'react-native';\nimport Icon from 'react-native-vector-icons/Ionicons';\nimport FAIcon from 'react-native-vector-icons/FontAwesome';\n@@ -71,6 +72,8 @@ import {\ntype NavContextType,\n} from '../navigation/navigation-context';\nimport ClearableTextInput from '../components/clearable-text-input.react';\n+import { displayActionResultModal } from '../navigation/action-result-modal';\n+import { requestAndroidPermissions } from '../utils/android-permissions';\nconst draftKeyFromThreadID = (threadID: string) =>\n`${threadID}/message_composer`;\n@@ -523,8 +526,16 @@ class ChatInputBar extends React.PureComponent<Props, State> {\nthis.setState({ buttonsExpanded: false });\n}\n- openCamera = () => {\n+ openCamera = async () => {\nthis.dismissKeyboard();\n+ const permissionResult = await requestAndroidPermissions([\n+ PermissionsAndroid.PERMISSIONS.CAMERA,\n+ PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,\n+ ]);\n+ if (!permissionResult[PermissionsAndroid.PERMISSIONS.CAMERA]) {\n+ displayActionResultModal(\"don't have permission :(\");\n+ return;\n+ }\nthis.props.navigation.navigate({\nrouteName: CameraModalRouteName,\nparams: {\n"
},
{
"change_type": "MODIFY",
"old_path": "native/media/camera-modal.react.js",
"new_path": "native/media/camera-modal.react.js",
"diff": "@@ -108,11 +108,6 @@ const zoomUpdateFactor = (() => {\nreturn 0.03;\n})();\n-const permissionRationale = {\n- title: 'Access Your Camera',\n- message: 'Requesting access to your device camera',\n-};\n-\nconst stagingModeAnimationConfig = {\nduration: 150,\neasing: Easing.inOut(Easing.ease),\n@@ -796,7 +791,7 @@ class CameraModal extends React.PureComponent<Props, State> {\nflashMode={this.state.flashMode}\nautoFocusPointOfInterest={this.state.autoFocusPointOfInterest}\nstyle={styles.fill}\n- androidCameraPermissionOptions={permissionRationale}\n+ androidCameraPermissionOptions={null}\nref={this.cameraRef}\n>\n{this.renderCamera}\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Ask for permissions before opening CameraModal |
129,187 | 29.04.2020 22:27:54 | 14,400 | bd8bb7643e4f296ccbcc1e6a48891372c9b313e5 | [native] Prevent weirdo Android rendering bug that happens before camera permissions request | [
{
"change_type": "MODIFY",
"old_path": "native/chat/chat-input-bar.react.js",
"new_path": "native/chat/chat-input-bar.react.js",
"diff": "@@ -55,6 +55,7 @@ import { saveDraftActionType } from 'lib/actions/miscellaneous-action-types';\nimport { threadHasPermission, viewerIsMember } from 'lib/shared/thread-utils';\nimport { joinThreadActionTypes, joinThread } from 'lib/actions/thread-actions';\nimport { createLoadingStatusSelector } from 'lib/selectors/loading-selectors';\n+import sleep from 'lib/utils/sleep';\nimport Button from '../components/button.react';\nimport { nonThreadCalendarQuery } from '../navigation/nav-selectors';\n@@ -73,7 +74,7 @@ import {\n} from '../navigation/navigation-context';\nimport ClearableTextInput from '../components/clearable-text-input.react';\nimport { displayActionResultModal } from '../navigation/action-result-modal';\n-import { requestAndroidPermissions } from '../utils/android-permissions';\n+import { requestAndroidPermission } from '../utils/android-permissions';\nconst draftKeyFromThreadID = (threadID: string) =>\n`${threadID}/message_composer`;\n@@ -528,14 +529,23 @@ class ChatInputBar extends React.PureComponent<Props, State> {\nopenCamera = async () => {\nthis.dismissKeyboard();\n- const permissionResult = await requestAndroidPermissions([\n+\n+ // This prevents a very strange transient rendering bug where Android\n+ // incorrectly draws the ActionResultModal triggered below. Layout Inspector\n+ // errors when you try to see what's going on, but the ActionResultModal\n+ // variously appears either with no text or with no background.\n+ if (Platform.OS === 'android') {\n+ await sleep(5);\n+ }\n+\n+ const permissionResult = await requestAndroidPermission(\nPermissionsAndroid.PERMISSIONS.CAMERA,\n- PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,\n- ]);\n- if (!permissionResult[PermissionsAndroid.PERMISSIONS.CAMERA]) {\n+ );\n+ if (!permissionResult) {\ndisplayActionResultModal(\"don't have permission :(\");\nreturn;\n}\n+\nthis.props.navigation.navigate({\nrouteName: CameraModalRouteName,\nparams: {\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Prevent weirdo Android rendering bug that happens before camera permissions request |
129,187 | 30.04.2020 00:28:50 | 14,400 | cafb60016c0c9de9b27cf46b34495bc8f17a644a | [native] Don't show sessionInvalidationAlert unless we were logged in before | [
{
"change_type": "MODIFY",
"old_path": "native/redux/redux-setup.js",
"new_path": "native/redux/redux-setup.js",
"diff": "@@ -317,7 +317,12 @@ function reducer(state: AppState = defaultState, action: *) {\n}\nfunction sessionInvalidationAlert(payload: SetSessionPayload) {\n- if (!payload.sessionChange.cookieInvalidated) {\n+ if (\n+ !payload.sessionChange.cookieInvalidated ||\n+ !payload.preRequestUserState ||\n+ !payload.preRequestUserState.currentUserInfo ||\n+ payload.preRequestUserState.currentUserInfo.anonymous\n+ ) {\nreturn;\n}\nif (payload.error === 'client_version_unsupported') {\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Don't show sessionInvalidationAlert unless we were logged in before |
129,187 | 30.04.2020 12:46:02 | 14,400 | 74490a678c6e9076f6089109ca1ebfc3fad287d6 | [native] Don't hide keyboard events while app is in background
I initially added this behavior over 2 years ago in
I can't figure out why I did or if it's still needed. Maybe I added it to do with `Modal`s at the time? | [
{
"change_type": "MODIFY",
"old_path": "native/keyboard/keyboard-avoiding-view.react.js",
"new_path": "native/keyboard/keyboard-avoiding-view.react.js",
"diff": "@@ -11,7 +11,6 @@ import {\nPlatform,\nView,\nViewPropTypes,\n- AppState,\n} from 'react-native';\nimport PropTypes from 'prop-types';\nimport _isEqual from 'lodash/fp/isEqual';\n@@ -46,7 +45,6 @@ class KeyboardAvoidingView extends React.PureComponent<Props, State> {\n};\nkeyboardSubscription: ?EmitterSubscription = null;\nframe: ?Layout = null;\n- currentState = AppState.currentState;\nrelativeKeyboardHeight(keyboardFrame: ScreenRect): number {\nconst { frame } = this;\n@@ -59,10 +57,6 @@ class KeyboardAvoidingView extends React.PureComponent<Props, State> {\n}\nonKeyboardChange = (event: ?KeyboardChangeEvent) => {\n- if (this.currentState !== 'active') {\n- return;\n- }\n-\nif (!event) {\nthis.setState({ bottom: 0 });\nreturn;\n@@ -95,10 +89,6 @@ class KeyboardAvoidingView extends React.PureComponent<Props, State> {\nthis.frame = event.nativeEvent.layout;\n};\n- handleAppStateChange = (nextAppState: ?string) => {\n- this.currentState = nextAppState;\n- };\n-\ncomponentDidMount() {\nif (Platform.OS !== 'ios') {\nreturn;\n@@ -107,7 +97,6 @@ class KeyboardAvoidingView extends React.PureComponent<Props, State> {\n'keyboardWillChangeFrame',\nthis.onKeyboardChange,\n);\n- AppState.addEventListener('change', this.handleAppStateChange);\n}\ncomponentWillUnmount() {\n@@ -117,7 +106,6 @@ class KeyboardAvoidingView extends React.PureComponent<Props, State> {\nif (this.keyboardSubscription) {\nthis.keyboardSubscription.remove();\n}\n- AppState.removeEventListener('change', this.handleAppStateChange);\n}\nrender() {\n"
},
{
"change_type": "MODIFY",
"old_path": "native/keyboard/keyboard.js",
"new_path": "native/keyboard/keyboard.js",
"diff": "// @flow\n-import { AppState, Keyboard, Platform, DeviceInfo } from 'react-native';\n+import { Keyboard, Platform, DeviceInfo } from 'react-native';\ntype ScreenRect = $ReadOnly<{|\nscreenX: number,\n@@ -17,29 +17,13 @@ export type KeyboardEvent = $ReadOnly<{|\ntype ShowKeyboardCallback = (event: KeyboardEvent) => void;\ntype HideKeyboardCallback = (event: ?KeyboardEvent) => void;\n-type IgnoredKeyboardEvent =\n- | {|\n- type: 'show',\n- callback: ShowKeyboardCallback,\n- event: KeyboardEvent,\n- time: number,\n- |}\n- | {|\n- type: 'hide',\n- callback: HideKeyboardCallback,\n- event: ?KeyboardEvent,\n- time: number,\n- |};\nexport type EmitterSubscription = {\n+remove: () => void,\n};\n-// If the app becomes active within 500ms after a keyboard event is triggered,\n-// we will call the relevant keyboard callbacks.\n-const appStateChangeDelay = 500;\n-\n-const isIPhoneX = Platform.OS === 'ios' && DeviceInfo.getConstants().isIPhoneX_deprecated;\n+const isIPhoneX =\n+ Platform.OS === 'ios' && DeviceInfo.getConstants().isIPhoneX_deprecated;\nconst defaultKeyboardHeight = Platform.select({\nios: isIPhoneX ? 335 : 216,\nandroid: 282.28,\n@@ -52,50 +36,7 @@ function getKeyboardHeight(): ?number {\nreturn defaultKeyboardHeight;\n}\n-let currentState = AppState.currentState;\n-let recentIgnoredKeyboardEvents: IgnoredKeyboardEvent[] = [];\n-function handleAppStateChange(nextAppState: ?string) {\n- currentState = nextAppState;\n-\n- const time = Date.now();\n- const ignoredEvents = recentIgnoredKeyboardEvents;\n- recentIgnoredKeyboardEvents = [];\n-\n- if (currentState !== 'active') {\n- return;\n- }\n- for (let ignoredEvent of ignoredEvents) {\n- if (ignoredEvent.time + appStateChangeDelay <= time) {\n- continue;\n- }\n- // Conditional necessary for Flow :(\n- if (ignoredEvent.type === 'show') {\n- ignoredEvent.callback(ignoredEvent.event);\n- } else {\n- ignoredEvent.callback(ignoredEvent.event);\n- }\n- }\n-}\n-\n-let listenersEnabled = 0;\n-let appStateListener = null;\n-function incrementAppStateListeners() {\n- if (!listenersEnabled++) {\n- currentState = AppState.currentState;\n- appStateListener = AppState.addEventListener(\n- 'change',\n- handleAppStateChange,\n- );\n- }\n-}\n-function decrementAppStateListeners() {\n- if (!--listenersEnabled && appStateListener) {\n- AppState.removeEventListener('change', appStateListener);\n- appStateListener = null;\n- }\n-}\n-\n-function callShowCallbackIfAppActive(\n+function callShowCallback(\ncallback: ShowKeyboardCallback,\n): ShowKeyboardCallback {\nreturn (event: KeyboardEvent) => {\n@@ -107,27 +48,17 @@ function callShowCallbackIfAppActive(\nkeyboardHeight = height;\n}\n}\n- if (currentState === 'active') {\ncallback(event);\n- } else {\n- recentIgnoredKeyboardEvents.push({\n- type: 'show',\n- callback,\n- event,\n- time: Date.now(),\n- });\n- }\n};\n}\nfunction addKeyboardShowListener(callback: ShowKeyboardCallback) {\n- incrementAppStateListeners();\nreturn Keyboard.addListener(\nPlatform.OS === 'ios' ? 'keyboardWillShow' : 'keyboardDidShow',\n- callShowCallbackIfAppActive(callback),\n+ callShowCallback(callback),\n);\n}\n-function callHideCallbackIfAppActive(\n+function callHideCallback(\ncallback: HideKeyboardCallback,\n): HideKeyboardCallback {\nreturn (event: ?KeyboardEvent) => {\n@@ -137,35 +68,20 @@ function callHideCallbackIfAppActive(\nkeyboardHeight = height;\n}\n}\n- if (currentState === 'active') {\ncallback(event);\n- } else {\n- recentIgnoredKeyboardEvents.push({\n- type: 'hide',\n- callback,\n- event,\n- time: Date.now(),\n- });\n- }\n};\n}\nfunction addKeyboardDismissListener(callback: HideKeyboardCallback) {\n- incrementAppStateListeners();\nreturn Keyboard.addListener(\nPlatform.OS === 'ios' ? 'keyboardWillHide' : 'keyboardDidHide',\n- callHideCallbackIfAppActive(callback),\n+ callHideCallback(callback),\n);\n}\nfunction addKeyboardDidDismissListener(callback: HideKeyboardCallback) {\n- incrementAppStateListeners();\n- return Keyboard.addListener(\n- 'keyboardDidHide',\n- callHideCallbackIfAppActive(callback),\n- );\n+ return Keyboard.addListener('keyboardDidHide', callHideCallback(callback));\n}\nfunction removeKeyboardListener(listener: EmitterSubscription) {\n- decrementAppStateListeners();\nlistener.remove();\n}\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Don't hide keyboard events while app is in background
I initially added this behavior over 2 years ago in bcab1b6fc51f90215aca599dee4b098a21fe06c6
I can't figure out why I did or if it's still needed. Maybe I added it to do with `Modal`s at the time? |
129,187 | 30.04.2020 21:44:10 | 14,400 | 30b319ea41215db1ab8aef3e93647e7cc65d7914 | [native] AndroidLifecycleModule | [
{
"change_type": "MODIFY",
"old_path": "native/android/app/build.gradle",
"new_path": "native/android/app/build.gradle",
"diff": "@@ -195,6 +195,9 @@ dependencies {\nimplementation \"com.facebook.react:react-native:+\" // From node_modules\nimplementation \"androidx.multidex:multidex:2.0.1\"\n+ implementation \"androidx.lifecycle:lifecycle-runtime:2.2.0\"\n+ implementation \"androidx.lifecycle:lifecycle-process:2.2.0\"\n+\nimplementation 'com.facebook.fresco:fresco:2.2.0'\nimplementation 'com.facebook.fresco:animated-gif:2.2.0'\nimplementation 'com.facebook.fresco:animated-webp:2.2.0'\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "native/android/app/src/main/java/org/squadcal/AndroidLifecycleModule.java",
"diff": "+package org.squadcal;\n+\n+import com.facebook.react.bridge.ReactApplicationContext;\n+import com.facebook.react.bridge.ReactContextBaseJavaModule;\n+import com.facebook.react.bridge.ReactMethod;\n+import com.facebook.react.module.annotations.ReactModule;\n+import com.facebook.react.modules.core.DeviceEventManagerModule;\n+import com.facebook.react.bridge.Arguments;\n+import com.facebook.react.bridge.WritableMap;\n+import com.facebook.react.bridge.Callback;\n+\n+import androidx.lifecycle.Lifecycle;\n+import androidx.lifecycle.LifecycleEventObserver;\n+import androidx.lifecycle.ProcessLifecycleOwner;\n+\n+import java.util.HashMap;\n+import java.util.Map;\n+\n+@ReactModule(name = AndroidLifecycleModule.NAME)\n+public class AndroidLifecycleModule extends ReactContextBaseJavaModule {\n+\n+ public static final String NAME = \"AndroidLifecycle\";\n+\n+ public static final String ANDROID_LIFECYCLE_ACTIVE = \"active\";\n+ public static final String ANDROID_LIFECYCLE_BACKGROUND = \"background\";\n+\n+ private static final String INITIAL_STATUS_KEY = \"initialStatus\";\n+ private static final String STATUS_KEY = \"status\";\n+\n+ private boolean isInitialized = false;\n+\n+ private String currentState;\n+\n+ public AndroidLifecycleModule(ReactApplicationContext reactContext) {\n+ super(reactContext);\n+\n+ final Lifecycle lifecycle = ProcessLifecycleOwner.get().getLifecycle();\n+ this.currentState = lifecycle.getCurrentState() == Lifecycle.State.RESUMED\n+ ? ANDROID_LIFECYCLE_ACTIVE\n+ : ANDROID_LIFECYCLE_BACKGROUND;\n+\n+ lifecycle.addObserver(\n+ (LifecycleEventObserver) (source, event) -> {\n+ final String name = event.toString();\n+ if (name != \"ON_START\" && name != \"ON_STOP\") {\n+ return;\n+ }\n+ if (!this.isInitialized) {\n+ return;\n+ }\n+ this.currentState = name == \"ON_START\"\n+ ? ANDROID_LIFECYCLE_ACTIVE\n+ : ANDROID_LIFECYCLE_BACKGROUND;\n+ reactContext\n+ .getJSModule(DeviceEventManagerModule.RCTDeviceEventEmitter.class)\n+ .emit(\"LIFECYCLE_CHANGE\", this.createEventMap());\n+ }\n+ );\n+ }\n+\n+ @Override\n+ public String getName() {\n+ return NAME;\n+ }\n+\n+ @Override\n+ public void initialize() {\n+ super.initialize();\n+ this.isInitialized = true;\n+ }\n+\n+ @Override\n+ public Map<String, Object> getConstants() {\n+ final Map<String, Object> constants = new HashMap<>();\n+ constants.put(INITIAL_STATUS_KEY, this.currentState);\n+ return constants;\n+ }\n+\n+ private WritableMap createEventMap() {\n+ WritableMap appState = Arguments.createMap();\n+ appState.putString(STATUS_KEY, this.currentState);\n+ return appState;\n+ }\n+\n+ @ReactMethod\n+ public void getCurrentLifecycleStatus(Callback success, Callback error) {\n+ success.invoke(createEventMap());\n+ }\n+\n+}\n\\ No newline at end of file\n"
},
{
"change_type": "MODIFY",
"old_path": "native/android/app/src/main/java/org/squadcal/MainApplication.java",
"new_path": "native/android/app/src/main/java/org/squadcal/MainApplication.java",
"diff": "@@ -40,6 +40,7 @@ public class MainApplication extends MultiDexApplication implements ReactApplica\npackages.add(new RNFirebaseMessagingPackage());\npackages.add(new RNFirebaseNotificationsPackage());\npackages.add(new KeyboardInputPackage(this.getApplication()));\n+ packages.add(new SquadCalPackage());\n// Add unimodules\nList<ReactPackage> unimodules = Arrays.<ReactPackage>asList(\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "native/android/app/src/main/java/org/squadcal/SquadCalPackage.java",
"diff": "+package org.squadcal;\n+\n+\n+import com.facebook.react.ReactPackage;\n+import com.facebook.react.bridge.NativeModule;\n+import com.facebook.react.bridge.ReactApplicationContext;\n+import com.facebook.react.uimanager.ViewManager;\n+\n+import java.util.ArrayList;\n+import java.util.Collections;\n+import java.util.List;\n+\n+public class SquadCalPackage implements ReactPackage {\n+\n+ @Override\n+ public List<ViewManager> createViewManagers(ReactApplicationContext reactContext) {\n+ return Collections.emptyList();\n+ }\n+\n+ @Override\n+ public List<NativeModule> createNativeModules(ReactApplicationContext reactContext) {\n+ List<NativeModule> modules = new ArrayList<>();\n+ modules.add(new AndroidLifecycleModule(reactContext));\n+ return modules;\n+ }\n+\n+}\n\\ No newline at end of file\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] AndroidLifecycleModule |
129,187 | 30.04.2020 22:07:53 | 14,400 | 7c7acc93b55b5f4852963bd8c544de4878dd8632 | [native] LifecycleHandler | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "native/lifecycle/lifecycle-handler.react.js",
"diff": "+// @flow\n+\n+import * as React from 'react';\n+import { useDispatch } from 'react-redux';\n+import { AppState as NativeAppState } from 'react-native';\n+\n+import {\n+ backgroundActionType,\n+ foregroundActionType,\n+} from 'lib/reducers/foreground-reducer';\n+\n+import { appBecameInactive } from '../redux/redux-setup';\n+\n+const LifecycleHandler = React.memo<{||}>(() => {\n+ const dispatch = useDispatch();\n+\n+ const lastStateRef = React.useRef();\n+ const onLifecycleChange = React.useCallback(\n+ (nextState: ?string) => {\n+ if (!nextState || nextState === 'unknown') {\n+ return;\n+ }\n+ const lastState = lastStateRef.current;\n+ lastStateRef.current = nextState;\n+ if (lastState === 'background' && nextState === 'active') {\n+ dispatch({ type: foregroundActionType, payload: null });\n+ } else if (lastState !== 'background' && nextState === 'background') {\n+ dispatch({ type: backgroundActionType, payload: null });\n+ appBecameInactive();\n+ }\n+ },\n+ [lastStateRef, dispatch],\n+ );\n+\n+ React.useEffect(() => {\n+ NativeAppState.addEventListener('change', onLifecycleChange);\n+ return () => {\n+ NativeAppState.removeEventListener('change', onLifecycleChange);\n+ };\n+ }, [onLifecycleChange]);\n+\n+ return null;\n+});\n+LifecycleHandler.displayName = 'LifecycleHandler';\n+\n+export default LifecycleHandler;\n"
},
{
"change_type": "MODIFY",
"old_path": "native/redux/dev-tools.react.js",
"new_path": "native/redux/dev-tools.react.js",
"diff": "@@ -123,5 +123,6 @@ const DevTools = React.memo<{||}>(() => {\nreturn null;\n});\n+DevTools.displayName = 'DevTools';\nexport default DevTools;\n"
},
{
"change_type": "MODIFY",
"old_path": "native/root.react.js",
"new_path": "native/root.react.js",
"diff": "import { type GlobalTheme, globalThemePropType } from './types/themes';\nimport type { AppState } from './redux/redux-setup';\n-import type { DispatchActionPayload } from 'lib/utils/action-utils';\nimport type { NavAction } from './navigation/navigation-context';\nimport * as React from 'react';\nimport { Provider } from 'react-redux';\n-import {\n- Platform,\n- UIManager,\n- AppState as NativeAppState,\n- View,\n- StyleSheet,\n-} from 'react-native';\n-import PropTypes from 'prop-types';\n+import { Platform, UIManager, View, StyleSheet } from 'react-native';\nimport Orientation from 'react-native-orientation-locker';\nimport { PersistGate } from 'redux-persist/integration/react';\nimport {\n@@ -26,14 +18,10 @@ import {\nimport AsyncStorage from '@react-native-community/async-storage';\nimport { connect } from 'lib/utils/redux-utils';\n-import {\n- backgroundActionType,\n- foregroundActionType,\n-} from 'lib/reducers/foreground-reducer';\nimport { actionLogger } from 'lib/utils/action-logger';\nimport RootNavigator from './navigation/root-navigator.react';\n-import { store, appBecameInactive } from './redux/redux-setup';\n+import { store } from './redux/redux-setup';\nimport ConnectedStatusBar from './connected-status-bar.react';\nimport ErrorBoundary from './error-boundary.react';\nimport DisconnectedBarVisibilityHandler from './navigation/disconnected-bar-visibility-handler.react';\n@@ -53,6 +41,7 @@ import NavigationHandler from './navigation/navigation-handler.react';\nimport { defaultNavigationState } from './navigation/default-state';\nimport InputStateContainer from './input/input-state-container.react';\nimport './themes/fonts';\n+import LifecycleHandler from './lifecycle/lifecycle-handler.react';\nif (Platform.OS === 'android') {\nUIManager.setLayoutAnimationEnabledExperimental &&\n@@ -81,8 +70,6 @@ const navStateAsyncStorageKey = 'navState';\ntype Props = {\n// Redux state\nactiveTheme: ?GlobalTheme,\n- // Redux dispatch functions\n- dispatchActionPayload: DispatchActionPayload,\n};\ntype State = {|\nnavContext: ?NavContextType,\n@@ -91,11 +78,8 @@ type State = {|\nclass Root extends React.PureComponent<Props, State> {\nstatic propTypes = {\nactiveTheme: globalThemePropType,\n- dispatchActionPayload: PropTypes.func.isRequired,\n};\n- currentAppState: ?string = NativeAppState.currentState;\n-\nnavDispatch: ?(action: NavAction) => boolean;\nnavState: ?NavigationState;\nnavStateInitialized = false;\n@@ -109,28 +93,9 @@ class Root extends React.PureComponent<Props, State> {\n}\ncomponentDidMount() {\n- NativeAppState.addEventListener('change', this.handleAppStateChange);\nOrientation.lockToPortrait();\n}\n- componentWillUnmount() {\n- NativeAppState.removeEventListener('change', this.handleAppStateChange);\n- }\n-\n- handleAppStateChange = (nextState: ?string) => {\n- if (!nextState || nextState === 'unknown') {\n- return;\n- }\n- const lastState = this.currentAppState;\n- this.currentAppState = nextState;\n- if (lastState === 'background' && nextState === 'active') {\n- this.props.dispatchActionPayload(foregroundActionType, null);\n- } else if (lastState !== 'background' && nextState === 'background') {\n- this.props.dispatchActionPayload(backgroundActionType, null);\n- appBecameInactive();\n- }\n- };\n-\nrender() {\nconst { detectUnsupervisedBackgroundRef } = this;\nconst reactNavigationTheme = this.props.activeTheme\n@@ -138,6 +103,7 @@ class Root extends React.PureComponent<Props, State> {\n: 'no-preference';\nconst gated: React.Node = (\n<>\n+ <LifecycleHandler />\n<Socket\ndetectUnsupervisedBackgroundRef={detectUnsupervisedBackgroundRef}\n/>\n@@ -265,13 +231,9 @@ const styles = StyleSheet.create({\n},\n});\n-const ConnectedRoot = connect(\n- (state: AppState) => ({\n+const ConnectedRoot = connect((state: AppState) => ({\nactiveTheme: state.globalThemeInfo.activeTheme,\n- }),\n- null,\n- true,\n-)(Root);\n+}))(Root);\nconst AppRoot = () => (\n<Provider store={store}>\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] LifecycleHandler |
129,187 | 30.04.2020 22:16:30 | 14,400 | 3231310a0af2a9714a7517411244d7b18e6045d9 | [native] addLifecycleListener | [
{
"change_type": "MODIFY",
"old_path": "native/lifecycle/lifecycle-handler.react.js",
"new_path": "native/lifecycle/lifecycle-handler.react.js",
"diff": "import * as React from 'react';\nimport { useDispatch } from 'react-redux';\n-import { AppState as NativeAppState } from 'react-native';\nimport {\nbackgroundActionType,\n@@ -10,6 +9,7 @@ import {\n} from 'lib/reducers/foreground-reducer';\nimport { appBecameInactive } from '../redux/redux-setup';\n+import { addLifecycleListener } from './lifecycle';\nconst LifecycleHandler = React.memo<{||}>(() => {\nconst dispatch = useDispatch();\n@@ -33,10 +33,8 @@ const LifecycleHandler = React.memo<{||}>(() => {\n);\nReact.useEffect(() => {\n- NativeAppState.addEventListener('change', onLifecycleChange);\n- return () => {\n- NativeAppState.removeEventListener('change', onLifecycleChange);\n- };\n+ const { remove } = addLifecycleListener(onLifecycleChange);\n+ return remove;\n}, [onLifecycleChange]);\nreturn null;\n"
},
{
"change_type": "ADD",
"old_path": null,
"new_path": "native/lifecycle/lifecycle.js",
"diff": "+// @flow\n+\n+import { AppState as NativeAppState } from 'react-native';\n+\n+function addLifecycleListener(listener: (state: ?string) => mixed) {\n+ NativeAppState.addEventListener('change', listener);\n+ return {\n+ remove: () => {\n+ NativeAppState.removeEventListener('change', listener);\n+ },\n+ };\n+}\n+\n+export { addLifecycleListener };\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] addLifecycleListener |
129,187 | 30.04.2020 22:20:44 | 14,400 | 7a5f479ac9ab297494664a38e02093ce60ecc965 | [native] Move PushHandler to addLifecycleListener | [
{
"change_type": "MODIFY",
"old_path": "native/lifecycle/lifecycle.js",
"new_path": "native/lifecycle/lifecycle.js",
"diff": "@@ -11,4 +11,8 @@ function addLifecycleListener(listener: (state: ?string) => mixed) {\n};\n}\n-export { addLifecycleListener };\n+function getCurrentLifecycleState() {\n+ return NativeAppState.currentState;\n+}\n+\n+export { addLifecycleListener, getCurrentLifecycleState };\n"
},
{
"change_type": "MODIFY",
"old_path": "native/push/push-handler.react.js",
"new_path": "native/push/push-handler.react.js",
"diff": "@@ -29,7 +29,6 @@ import PropTypes from 'prop-types';\nimport {\nAppRegistry,\nPlatform,\n- AppState as NativeAppState,\nAlert,\nVibration,\nYellowBox,\n@@ -80,6 +79,10 @@ import {\n} from '../root-context';\nimport { ChatRouteName, MessageListRouteName } from '../navigation/route-names';\nimport { replaceWithThreadActionType } from '../navigation/action-types';\n+import {\n+ addLifecycleListener,\n+ getCurrentLifecycleState,\n+} from '../lifecycle/lifecycle';\nYellowBox.ignoreWarnings([\n'Require cycle: ../node_modules/react-native-firebase',\n@@ -143,17 +146,20 @@ class PushHandler extends React.PureComponent<Props, State> {\nstate = {\ninAppNotifProps: null,\n};\n- currentState: ?string = NativeAppState.currentState;\n+ currentState: ?string = getCurrentLifecycleState();\nappStarted = 0;\nandroidTokenListener: ?() => void = null;\nandroidMessageListener: ?() => void = null;\nandroidNotifOpenListener: ?() => void = null;\ninitialAndroidNotifHandled = false;\nopenThreadOnceReceived: Set<string> = new Set();\n+ lifecycleSubscription: ?{ +remove: () => void };\ncomponentDidMount() {\nthis.appStarted = Date.now();\n- NativeAppState.addEventListener('change', this.handleAppStateChange);\n+ this.lifecycleSubscription = addLifecycleListener(\n+ this.handleAppStateChange,\n+ );\nthis.onForeground();\nif (Platform.OS === 'ios') {\nNotificationsIOS.addEventListener(\n@@ -193,7 +199,9 @@ class PushHandler extends React.PureComponent<Props, State> {\n}\ncomponentWillUnmount() {\n- NativeAppState.removeEventListener('change', this.handleAppStateChange);\n+ if (this.lifecycleSubscription) {\n+ this.lifecycleSubscription.remove();\n+ }\nif (Platform.OS === 'ios') {\nNotificationsIOS.removeEventListener(\n'remoteNotificationsRegistered',\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Move PushHandler to addLifecycleListener |
129,187 | 30.04.2020 22:23:31 | 14,400 | 8802c176ab16a5020b3d21274bf9ef7fc9ef4a1d | [native] Use AndroidLifecycleModule in lifecycle.js | [
{
"change_type": "MODIFY",
"old_path": "native/lifecycle/lifecycle.js",
"new_path": "native/lifecycle/lifecycle.js",
"diff": "// @flow\n-import { AppState as NativeAppState } from 'react-native';\n+import {\n+ Platform,\n+ AppState as NativeAppState,\n+ DeviceEventEmitter,\n+ NativeModules,\n+} from 'react-native';\nfunction addLifecycleListener(listener: (state: ?string) => mixed) {\n+ if (Platform.OS === 'android') {\n+ return DeviceEventEmitter.addListener('LIFECYCLE_CHANGE', event => {\n+ listener(event.status);\n+ });\n+ }\n+\nNativeAppState.addEventListener('change', listener);\nreturn {\nremove: () => {\n@@ -11,8 +22,19 @@ function addLifecycleListener(listener: (state: ?string) => mixed) {\n};\n}\n+let currentAndroidLifecycle;\n+if (Platform.OS === 'android') {\n+ currentAndroidLifecycle = NativeModules.AndroidLifecycle.getConstants()\n+ .initialStatus;\n+ addLifecycleListener(state => {\n+ currentAndroidLifecycle = state;\n+ });\n+}\n+\nfunction getCurrentLifecycleState() {\n- return NativeAppState.currentState;\n+ return Platform.OS === 'android'\n+ ? currentAndroidLifecycle\n+ : NativeAppState.currentState;\n}\nexport { addLifecycleListener, getCurrentLifecycleState };\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Use AndroidLifecycleModule in lifecycle.js |
129,187 | 01.05.2020 00:05:26 | 14,400 | df3bed4b67cdcead8d9b692bd6131c6389bca061 | [native] LifecycleEventEmitter | [
{
"change_type": "ADD",
"old_path": null,
"new_path": "native/lifecycle/lifecycle-event-emitter.js",
"diff": "+// @flow\n+\n+import invariant from 'invariant';\n+import { Platform } from 'react-native';\n+\n+import type { TurboModule } from 'react-native/Libraries/TurboModule/RCTExport';\n+import * as TurboModuleRegistry from 'react-native/Libraries/TurboModule/TurboModuleRegistry';\n+// eslint-disable-next-line import/default\n+import NativeEventEmitter from 'react-native/Libraries/EventEmitter/NativeEventEmitter';\n+\n+interface Spec extends TurboModule {\n+ +getConstants: () => {|\n+ initialStatus: string,\n+ |};\n+ +addListener: (eventName: string) => void;\n+ +removeListeners: (count: number) => void;\n+}\n+const AndroidLifecycle = (TurboModuleRegistry.getEnforcing<Spec>(\n+ 'AndroidLifecycle',\n+): Spec);\n+\n+class LifecycleEventEmitter extends NativeEventEmitter {\n+ currentLifecycleStatus: ?string;\n+\n+ constructor() {\n+ super(AndroidLifecycle);\n+ this.currentLifecycleStatus = AndroidLifecycle.getConstants().initialStatus;\n+ this.addLifecycleListener(state => {\n+ this.currentAndroidLifecycle = state;\n+ });\n+ }\n+\n+ addLifecycleListener = (listener: (state: ?string) => mixed) => {\n+ return this.addListener('LIFECYCLE_CHANGE', event => {\n+ listener(event.status);\n+ });\n+ };\n+}\n+\n+let lifecycleEventEmitter;\n+function getLifecycleEventEmitter() {\n+ if (lifecycleEventEmitter) {\n+ return lifecycleEventEmitter;\n+ }\n+ invariant(\n+ Platform.OS === 'android',\n+ 'LifecycleEventEmitter only works on Android',\n+ );\n+ lifecycleEventEmitter = new LifecycleEventEmitter();\n+ return lifecycleEventEmitter;\n+}\n+\n+export { getLifecycleEventEmitter };\n"
},
{
"change_type": "MODIFY",
"old_path": "native/lifecycle/lifecycle.js",
"new_path": "native/lifecycle/lifecycle.js",
"diff": "// @flow\n-import {\n- Platform,\n- AppState as NativeAppState,\n- DeviceEventEmitter,\n- NativeModules,\n-} from 'react-native';\n+import { Platform, AppState as NativeAppState } from 'react-native';\n+\n+import { getLifecycleEventEmitter } from './lifecycle-event-emitter';\nfunction addLifecycleListener(listener: (state: ?string) => mixed) {\nif (Platform.OS === 'android') {\n- return DeviceEventEmitter.addListener('LIFECYCLE_CHANGE', event => {\n- listener(event.status);\n- });\n+ return getLifecycleEventEmitter().addLifecycleListener(listener);\n}\nNativeAppState.addEventListener('change', listener);\n@@ -22,18 +17,9 @@ function addLifecycleListener(listener: (state: ?string) => mixed) {\n};\n}\n-let currentAndroidLifecycle;\n-if (Platform.OS === 'android') {\n- currentAndroidLifecycle = NativeModules.AndroidLifecycle.getConstants()\n- .initialStatus;\n- addLifecycleListener(state => {\n- currentAndroidLifecycle = state;\n- });\n-}\n-\nfunction getCurrentLifecycleState() {\nreturn Platform.OS === 'android'\n- ? currentAndroidLifecycle\n+ ? getLifecycleEventEmitter().currentLifecycleStatus\n: NativeAppState.currentState;\n}\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] LifecycleEventEmitter |
129,187 | 01.05.2020 00:08:32 | 14,400 | 75eba8fd512b448bb9b39005750ee78d655bb01b | [native] Fix bug where Lifecycle listener subscription wasn't being torn down properly | [
{
"change_type": "MODIFY",
"old_path": "native/lifecycle/lifecycle-handler.react.js",
"new_path": "native/lifecycle/lifecycle-handler.react.js",
"diff": "@@ -33,8 +33,8 @@ const LifecycleHandler = React.memo<{||}>(() => {\n);\nReact.useEffect(() => {\n- const { remove } = addLifecycleListener(onLifecycleChange);\n- return remove;\n+ const subscription = addLifecycleListener(onLifecycleChange);\n+ return () => subscription.remove();\n}, [onLifecycleChange]);\nreturn null;\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Fix bug where Lifecycle listener subscription wasn't being torn down properly |
129,187 | 01.05.2020 16:14:39 | 14,400 | f4a18b1dfcde9b94bf2a7b7cea68b8d03ba5b435 | [native] Prevent ActionResultModal from capturing presses | [
{
"change_type": "MODIFY",
"old_path": "native/navigation/action-result-modal.js",
"new_path": "native/navigation/action-result-modal.js",
"diff": "@@ -12,7 +12,7 @@ function displayActionResultModal(message: string) {\nnavContext.dispatch(\nNavigationActions.navigate({\nrouteName: ActionResultModalRouteName,\n- params: { message },\n+ params: { message, preventPresses: true },\n}),\n);\n}\n"
},
{
"change_type": "MODIFY",
"old_path": "native/navigation/action-result-modal.react.js",
"new_path": "native/navigation/action-result-modal.react.js",
"diff": "@@ -26,6 +26,7 @@ type NavProp = NavigationStackProp<{|\n...NavigationLeafRoute,\nparams: {|\nmessage: string,\n+ preventPresses: true,\n|},\n|}>;\n"
},
{
"change_type": "MODIFY",
"old_path": "native/navigation/overlay-navigator.react.js",
"new_path": "native/navigation/overlay-navigator.react.js",
"diff": "@@ -77,6 +77,7 @@ class OverlayNavigator extends React.PureComponent<Props> {\nconstructor(props: Props) {\nsuper(props);\n+ // eslint-disable-next-line import/no-named-as-default-member\nthis.position = new Animated.Value(props.navigation.state.index);\n}\n@@ -105,6 +106,7 @@ class OverlayNavigator extends React.PureComponent<Props> {\nonTransitionStart = (transitionProps: NavigationStackTransitionProps) => {\nconst { index } = transitionProps.navigation.state;\n+ // eslint-disable-next-line import/no-named-as-default-member\nAnimated.timing(this.position, {\nduration: 250,\neasing: Easing.inOut(Easing.ease),\n@@ -129,12 +131,36 @@ class OverlayNavigator extends React.PureComponent<Props> {\n};\nrenderScenes = (transitionProps: NavigationStackTransitionProps) => {\n- const { scenes } = transitionProps;\n- const renderScene = (scene: NavigationStackScene) =>\n- this.renderScene(scene, transitionProps);\n+ const views = [];\n+ let pressableSceneAssigned = false,\n+ activeSceneFound = false;\n+ for (let i = transitionProps.scenes.length - 1; i >= 0; i--) {\n+ const scene = transitionProps.scenes[i];\n+ const {\n+ isActive,\n+ route: { params },\n+ } = scene;\n+\n+ if (isActive) {\n+ activeSceneFound = true;\n+ }\n+\n+ let pressable = false;\n+ if (\n+ !pressableSceneAssigned &&\n+ activeSceneFound &&\n+ (!params || !params.preventPresses)\n+ ) {\n+ pressable = true;\n+ pressableSceneAssigned = true;\n+ }\n+\n+ views.unshift(this.renderScene(scene, transitionProps, pressable));\n+ }\n+\nreturn (\n<OverlayPositionContext.Provider value={this.position}>\n- {scenes.map(renderScene)}\n+ {views}\n</OverlayPositionContext.Provider>\n);\n};\n@@ -142,13 +168,14 @@ class OverlayNavigator extends React.PureComponent<Props> {\nrenderScene(\nscene: NavigationStackScene,\ntransitionProps: NavigationStackTransitionProps,\n+ pressable: boolean,\n) {\nif (!scene.descriptor) {\nreturn null;\n}\nconst { navigation, getComponent } = scene.descriptor;\nconst SceneComponent = getComponent();\n- const pointerEvents = scene.isActive ? 'auto' : 'none';\n+ const pointerEvents = pressable ? 'auto' : 'none';\nreturn (\n<View style={styles.scene} key={scene.key} pointerEvents={pointerEvents}>\n<SceneComponent\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Prevent ActionResultModal from capturing presses |
129,187 | 01.05.2020 16:29:26 | 14,400 | 0b4b8147d29e48eb942163583cc3391d5b84359b | [native] Extend ActionResultModal lifespan if its text changes | [
{
"change_type": "MODIFY",
"old_path": "native/navigation/action-result-modal.react.js",
"new_path": "native/navigation/action-result-modal.react.js",
"diff": "@@ -9,7 +9,6 @@ import type { AppState } from '../redux/redux-setup';\nimport * as React from 'react';\nimport { View, Text } from 'react-native';\n-import PropTypes from 'prop-types';\nimport Animated from 'react-native-reanimated';\nimport { connect } from 'lib/utils/redux-utils';\n@@ -37,61 +36,40 @@ type Props = {|\n// Redux state\nstyles: StyleSheetOf<typeof styles>,\n|};\n-class ActionResultModal extends React.PureComponent<Props> {\n- static propTypes = {\n- navigation: PropTypes.shape({\n- state: PropTypes.shape({\n- params: PropTypes.shape({\n- message: PropTypes.string.isRequired,\n- }).isRequired,\n- }).isRequired,\n- goBack: PropTypes.func.isRequired,\n- }).isRequired,\n- scene: PropTypes.object.isRequired,\n- position: PropTypes.instanceOf(Value).isRequired,\n- styles: PropTypes.objectOf(PropTypes.object).isRequired,\n- };\n- progress: Value;\n-\n- constructor(props: Props) {\n- super(props);\n-\n- const { position } = props;\n- const { index } = props.scene;\n- this.progress = interpolate(position, {\n+function ActionResultModal(props: Props) {\n+ const { position, scene } = props;\n+ const { index } = scene;\n+ const progress = React.useMemo(\n+ () =>\n+ interpolate(position, {\ninputRange: [index - 1, index],\noutputRange: [0, 1],\nextrapolate: Extrapolate.CLAMP,\n- });\n- }\n-\n- componentDidMount() {\n- setTimeout(this.goBack, 2000);\n- }\n+ }),\n+ [position, index],\n+ );\n- goBack = () => {\n- this.props.navigation.goBack();\n- };\n+ // Timer resets whenever message updates\n+ const { state, goBack } = props.navigation;\n+ const { message } = state.params;\n+ React.useEffect(() => {\n+ const timeoutID = setTimeout(goBack, 2000);\n+ return () => clearTimeout(timeoutID);\n+ }, [message, goBack]);\n- get containerStyle() {\n- return {\n- ...this.props.styles.container,\n- opacity: this.progress,\n+ const containerStyle = {\n+ ...props.styles.container,\n+ opacity: progress,\n};\n- }\n-\n- render() {\n- const { message } = this.props.navigation.state.params;\nreturn (\n- <Animated.View style={this.containerStyle}>\n- <View style={this.props.styles.message}>\n- <View style={this.props.styles.backdrop} />\n- <Text style={this.props.styles.text}>{message}</Text>\n+ <Animated.View style={containerStyle}>\n+ <View style={props.styles.message}>\n+ <View style={props.styles.backdrop} />\n+ <Text style={props.styles.text}>{message}</Text>\n</View>\n</Animated.View>\n);\n}\n-}\nconst styles = {\nbackdrop: {\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Extend ActionResultModal lifespan if its text changes |
129,187 | 01.05.2020 17:06:24 | 14,400 | 57bf35266e68204147194029dee7d1a87a7a16e6 | [native] Prevent phantom SendMediaButton on Android MediaGalleryKeyboard
See code comment | [
{
"change_type": "MODIFY",
"old_path": "native/media/media-gallery-keyboard.react.js",
"new_path": "native/media/media-gallery-keyboard.react.js",
"diff": "@@ -10,7 +10,13 @@ import type { ViewToken, LayoutEvent } from '../types/react-native';\nimport type { ViewStyle } from '../types/styles';\nimport * as React from 'react';\n-import { View, Text, FlatList, ActivityIndicator } from 'react-native';\n+import {\n+ View,\n+ Text,\n+ FlatList,\n+ ActivityIndicator,\n+ Platform,\n+} from 'react-native';\nimport { KeyboardRegistry } from 'react-native-keyboard-input';\nimport invariant from 'invariant';\nimport { Provider } from 'react-redux';\n@@ -19,6 +25,7 @@ import * as MediaLibrary from 'expo-media-library';\nimport { connect } from 'lib/utils/redux-utils';\nimport { extensionFromFilename } from 'lib/utils/file-utils';\n+import sleep from 'lib/utils/sleep';\nimport { store } from '../redux/redux-setup';\nimport {\n@@ -295,6 +302,14 @@ class MediaGalleryKeyboard extends React.PureComponent<Props, State> {\n}\nasync getPermissions(): Promise<boolean> {\n+ // For some reason, react-native-reanimated@1.8.0 on Android renders the\n+ // very first frame of SendMediaButton incorrectly. opacity is set to new\n+ // Value(0), but on the first frame it appears as 1. On Android requesting\n+ // permissions freezes your current activity, so we want to make sure that\n+ // we're rendering correctly before the freeze occurs.\n+ if (Platform.OS === 'android') {\n+ await sleep(5);\n+ }\nconst { granted } = await MediaLibrary.requestPermissionsAsync();\nif (!granted) {\nthis.guardedSetState({ error: \"don't have permission :(\" });\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Prevent phantom SendMediaButton on Android MediaGalleryKeyboard
See code comment |
129,187 | 01.05.2020 17:43:38 | 14,400 | 7728db3ef961c1cc59ad28b59ba8fc6eaa7bae0d | [native] Fix Android BackHandler behavior | [
{
"change_type": "MODIFY",
"old_path": "native/android/app/src/main/java/org/squadcal/MainActivity.java",
"new_path": "native/android/app/src/main/java/org/squadcal/MainActivity.java",
"diff": "@@ -52,7 +52,7 @@ public class MainActivity extends ReactFragmentActivity {\n}\n@Override\n- public void onBackPressed() {\n+ public void invokeDefaultOnBackPressed() {\nmoveTaskToBack(true);\n}\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Fix Android BackHandler behavior |
129,187 | 02.05.2020 18:56:32 | 14,400 | cf95ad61ec82de9bb62d30afc805b68177372e1d | [native] Let CameraModal ask for Android permissions instead of ChatInputBar
Continuing to see really strange render issues having to do with the permissions activity. After several full days of debugging I'm giving up lol | [
{
"change_type": "MODIFY",
"old_path": "native/chat/chat-input-bar.react.js",
"new_path": "native/chat/chat-input-bar.react.js",
"diff": "@@ -40,7 +40,6 @@ import {\nText,\nActivityIndicator,\nTouchableWithoutFeedback,\n- PermissionsAndroid,\n} from 'react-native';\nimport Icon from 'react-native-vector-icons/Ionicons';\nimport FAIcon from 'react-native-vector-icons/FontAwesome';\n@@ -55,7 +54,6 @@ import { saveDraftActionType } from 'lib/actions/miscellaneous-action-types';\nimport { threadHasPermission, viewerIsMember } from 'lib/shared/thread-utils';\nimport { joinThreadActionTypes, joinThread } from 'lib/actions/thread-actions';\nimport { createLoadingStatusSelector } from 'lib/selectors/loading-selectors';\n-import sleep from 'lib/utils/sleep';\nimport Button from '../components/button.react';\nimport { nonThreadCalendarQuery } from '../navigation/nav-selectors';\n@@ -73,8 +71,6 @@ import {\ntype NavContextType,\n} from '../navigation/navigation-context';\nimport ClearableTextInput from '../components/clearable-text-input.react';\n-import { displayActionResultModal } from '../navigation/action-result-modal';\n-import { requestAndroidPermission } from '../utils/android-permissions';\nconst draftKeyFromThreadID = (threadID: string) =>\n`${threadID}/message_composer`;\n@@ -529,23 +525,6 @@ class ChatInputBar extends React.PureComponent<Props, State> {\nopenCamera = async () => {\nthis.dismissKeyboard();\n-\n- // This prevents a very strange transient rendering bug where Android\n- // incorrectly draws the ActionResultModal triggered below. Layout Inspector\n- // errors when you try to see what's going on, but the ActionResultModal\n- // variously appears either with no text or with no background.\n- if (Platform.OS === 'android') {\n- await sleep(5);\n- }\n-\n- const permissionResult = await requestAndroidPermission(\n- PermissionsAndroid.PERMISSIONS.CAMERA,\n- );\n- if (!permissionResult) {\n- displayActionResultModal(\"don't have permission :(\");\n- return;\n- }\n-\nthis.props.navigation.navigate({\nrouteName: CameraModalRouteName,\nparams: {\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Let CameraModal ask for Android permissions instead of ChatInputBar
Continuing to see really strange render issues having to do with the permissions activity. After several full days of debugging I'm giving up lol |
129,187 | 03.05.2020 16:50:25 | 14,400 | 680eb625cd4669996fd4ecb2319cc6ab64a68ac2 | [native] Move capture disposal to InputStateContainer | [
{
"change_type": "MODIFY",
"old_path": "native/input/input-state-container.react.js",
"new_path": "native/input/input-state-container.react.js",
"diff": "@@ -130,6 +130,7 @@ class InputStateContainer extends React.PureComponent<Props, State> {\npendingUploads: {},\n};\nsendCallbacks: Array<() => void> = [];\n+ activeURIs = new Map();\nstatic getCompletedUploads(props: Props, state: State): CompletedUploads {\nconst completedUploads = {};\n@@ -302,6 +303,7 @@ class InputStateContainer extends React.PureComponent<Props, State> {\nregisterSendCallback: this.registerSendCallback,\nunregisterSendCallback: this.unregisterSendCallback,\nuploadInProgress: this.uploadInProgress,\n+ reportURIDisplayed: this.reportURIDisplayed,\n}),\n);\n@@ -569,11 +571,32 @@ class InputStateContainer extends React.PureComponent<Props, State> {\ntime: Date.now() - uploadStart,\n});\n+ const promises = [];\n+\nif (shouldDisposePath) {\n+ promises.push(\n+ (async () => {\nconst disposeStep = await disposeTempFile(shouldDisposePath);\nsteps.push(disposeStep);\n+ })(),\n+ );\n}\n+ if (selection.captureTime) {\n+ const captureURI = selection.uri;\n+ promises.push(\n+ (async () => {\n+ await this.onClearURI(captureURI);\n+ const capturePath = pathFromURI(captureURI);\n+ const removePath = capturePath ? capturePath : captureURI;\n+ const disposeStep = await disposeTempFile(removePath);\n+ steps.push(disposeStep);\n+ })(),\n+ );\n+ }\n+\n+ await Promise.all(promises);\n+\nreturn await finish(mediaMissionResult);\n}\n@@ -918,6 +941,39 @@ class InputStateContainer extends React.PureComponent<Props, State> {\n);\n};\n+ reportURIDisplayed = (uri: string, loaded: boolean) => {\n+ const prevActiveURI = this.activeURIs.get(uri);\n+ const curCount = prevActiveURI && prevActiveURI.count;\n+ const prevCount = curCount ? curCount : 0;\n+ const count = loaded ? prevCount + 1 : prevCount - 1;\n+ const prevOnClear = prevActiveURI && prevActiveURI.onClear;\n+ const onClear = prevOnClear ? prevOnClear : [];\n+ const activeURI = { count, onClear };\n+ if (count) {\n+ this.activeURIs.set(uri, activeURI);\n+ return;\n+ }\n+ this.activeURIs.delete(uri);\n+ for (let callback of onClear) {\n+ callback();\n+ }\n+ };\n+\n+ onClearURI(uri: string) {\n+ const activeURI = this.activeURIs.get(uri);\n+ return new Promise(resolve => {\n+ if (!activeURI) {\n+ resolve();\n+ return;\n+ }\n+ const newActiveURI = {\n+ ...activeURI,\n+ onClear: [...activeURI.onClear, resolve],\n+ };\n+ this.activeURIs.set(uri, newActiveURI);\n+ });\n+ }\n+\nrender() {\nconst inputState = this.inputStateSelector(this.state);\nreturn (\n"
},
{
"change_type": "MODIFY",
"old_path": "native/input/input-state.js",
"new_path": "native/input/input-state.js",
"diff": "@@ -44,6 +44,7 @@ export type InputState = {|\nregisterSendCallback: (() => void) => void,\nunregisterSendCallback: (() => void) => void,\nuploadInProgress: () => boolean,\n+ reportURIDisplayed: (uri: string, loaded: boolean) => void,\n|};\nconst inputStatePropType = PropTypes.shape({\n@@ -53,6 +54,7 @@ const inputStatePropType = PropTypes.shape({\nmessageHasUploadFailure: PropTypes.func.isRequired,\nretryMultimediaMessage: PropTypes.func.isRequired,\nuploadInProgress: PropTypes.func.isRequired,\n+ reportURIDisplayed: PropTypes.func.isRequired,\n});\nconst InputStateContext = React.createContext<?InputState>(null);\n"
},
{
"change_type": "MODIFY",
"old_path": "native/media/multimedia.react.js",
"new_path": "native/media/multimedia.react.js",
"diff": "@@ -5,26 +5,30 @@ import { type MediaInfo, mediaInfoPropType } from 'lib/types/media-types';\nimport * as React from 'react';\nimport PropTypes from 'prop-types';\nimport { View, Image, StyleSheet } from 'react-native';\n-import filesystem from 'react-native-fs';\nimport invariant from 'invariant';\n-import { pathFromURI } from 'lib/utils/file-utils';\n-\nimport RemoteImage from './remote-image.react';\n+import {\n+ type InputState,\n+ inputStatePropType,\n+ withInputState,\n+} from '../input/input-state';\ntype Props = {|\nmediaInfo: MediaInfo,\nspinnerColor: string,\n+ // withInputState\n+ inputState: ?InputState,\n|};\ntype State = {|\ncurrentURI: string,\ndepartingURI: ?string,\n- unlinkDepartingURI: boolean,\n|};\nclass Multimedia extends React.PureComponent<Props, State> {\nstatic propTypes = {\nmediaInfo: mediaInfoPropType.isRequired,\nspinnerColor: PropTypes.string.isRequired,\n+ inputState: inputStatePropType,\n};\nstatic defaultProps = {\nspinnerColor: 'black',\n@@ -35,47 +39,52 @@ class Multimedia extends React.PureComponent<Props, State> {\nthis.state = {\ncurrentURI: props.mediaInfo.uri,\ndepartingURI: null,\n- unlinkDepartingURI: false,\n};\n}\n- static shouldUnlinkDepartingURI(props: Props): boolean {\n- const { localMediaSelection } = props.mediaInfo;\n- if (!localMediaSelection) {\n- return false;\n+ get inputState() {\n+ const { inputState } = this.props;\n+ invariant(inputState, 'inputState should be set in Multimedia');\n+ return inputState;\n}\n- if (\n- localMediaSelection.step === 'photo_library' ||\n- localMediaSelection.step === 'video_library'\n- ) {\n- return false;\n+\n+ componentDidMount() {\n+ this.inputState.reportURIDisplayed(this.state.currentURI, true);\n+ }\n+\n+ componentWillUnmount() {\n+ const { inputState } = this;\n+ const { currentURI, departingURI } = this.state;\n+ inputState.reportURIDisplayed(currentURI, false);\n+ if (departingURI) {\n+ inputState.reportURIDisplayed(departingURI, false);\n}\n- invariant(\n- localMediaSelection.step === 'photo_capture',\n- 'selection should be photo_capture if not from library',\n- );\n- return true;\n}\n- componentDidUpdate(prevProps: Props) {\n+ componentDidUpdate(prevProps: Props, prevState: State) {\n+ const { inputState } = this;\n+\nconst newURI = this.props.mediaInfo.uri;\n- const oldURI = prevProps.mediaInfo.uri;\n- if (newURI !== oldURI && !this.state.departingURI) {\n- const unlinkDepartingURI = Multimedia.shouldUnlinkDepartingURI(prevProps);\n- this.setState({\n- currentURI: newURI,\n- departingURI: oldURI,\n- unlinkDepartingURI,\n- });\n- } else if (newURI !== oldURI) {\n+ const oldURI = this.state.currentURI;\n+ if (newURI !== oldURI) {\n+ inputState.reportURIDisplayed(newURI, true);\n+\n+ const { departingURI } = this.state;\n+ if (departingURI && oldURI !== departingURI) {\n+ // If there's currently an existing departingURI, that means that oldURI\n+ // hasn't loaded yet. Since it's being replaced anyways we don't need to\n+ // display it anymore, so we can unlink it now\n+ inputState.reportURIDisplayed(oldURI, false);\nthis.setState({ currentURI: newURI });\n+ } else {\n+ this.setState({ currentURI: newURI, departingURI: oldURI });\n}\n}\n- componentWillUnmount() {\n- const { departingURI, unlinkDepartingURI } = this.state;\n- if (departingURI && unlinkDepartingURI) {\n- Multimedia.unlinkURI(departingURI);\n+ const newDepartingURI = this.state.departingURI;\n+ const oldDepartingURI = prevState.departingURI;\n+ if (oldDepartingURI && oldDepartingURI !== newDepartingURI) {\n+ inputState.reportURIDisplayed(oldDepartingURI, false);\n}\n}\n@@ -117,28 +126,8 @@ class Multimedia extends React.PureComponent<Props, State> {\n}\nonLoad = () => {\n- const { departingURI, unlinkDepartingURI } = this.state;\n- if (!departingURI && !unlinkDepartingURI) {\n- return;\n- }\n- this.setState({ departingURI: null, unlinkDepartingURI: false });\n-\n- if (!departingURI || !unlinkDepartingURI) {\n- return;\n- }\n-\n- Multimedia.unlinkURI(departingURI);\n+ this.setState({ departingURI: null });\n};\n-\n- static unlinkURI(uri: string) {\n- const path = pathFromURI(uri);\n- if (!path) {\n- return;\n- }\n- try {\n- filesystem.unlink(path);\n- } catch (e) {}\n- }\n}\nconst styles = StyleSheet.create({\n@@ -154,4 +143,4 @@ const styles = StyleSheet.create({\n},\n});\n-export default Multimedia;\n+export default withInputState(Multimedia);\n"
}
] | JavaScript | BSD 3-Clause New or Revised License | comme2e/comm | [native] Move capture disposal to InputStateContainer |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.