Skip to content

compose: Don't send immediately on adding image #5474

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Merged
merged 5 commits into from
Jan 12, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions src/compose/ComposeBox.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ import React, {
forwardRef,
} from 'react';
import { Platform, View } from 'react-native';
import type { DocumentPickerResponse } from 'react-native-document-picker';
import type { LayoutEvent } from 'react-native/Libraries/Types/CoreEventTypes';
import { SafeAreaView } from 'react-native-safe-area-context';
import invariant from 'invariant';
Expand Down Expand Up @@ -73,6 +72,7 @@ import useUncontrolledInput from '../useUncontrolledInput';
import { tryFetch } from '../message/fetchActions';
import { getMessageUrl } from '../utils/internalLinks';
import * as logging from '../utils/logging';
import type { Attachment } from './ComposeMenu';

/* eslint-disable no-shadow */

Expand Down Expand Up @@ -319,8 +319,8 @@ const ComposeBox: React$AbstractComponent<Props, ImperativeHandle> = forwardRef(
);

const [numUploading, setNumUploading] = useState<number>(0);
const insertAttachment = useCallback(
async (attachments: $ReadOnlyArray<DocumentPickerResponse>) => {
const insertAttachments = useCallback(
async (attachments: $ReadOnlyArray<Attachment>) => {
setNumUploading(n => n + 1);
try {
const fileNames: string[] = [];
Expand All @@ -338,7 +338,7 @@ const ComposeBox: React$AbstractComponent<Props, ImperativeHandle> = forwardRef(
const placeholder = placeholders[i];
let response = null;
try {
response = await api.uploadFile(auth, attachments[i].uri, fileName);
response = await api.uploadFile(auth, attachments[i].url, fileName);
} catch {
showToast(_('Failed to upload file: {fileName}', { fileName }));
setMessageInputValue(state =>
Expand Down Expand Up @@ -744,7 +744,7 @@ const ComposeBox: React$AbstractComponent<Props, ImperativeHandle> = forwardRef(
/>
<ComposeMenu
destinationNarrow={destinationNarrow}
insertAttachment={insertAttachment}
insertAttachments={insertAttachments}
insertVideoCallLink={
videoChatProvider !== null ? () => insertVideoCallLink(videoChatProvider) : null
}
Expand Down
51 changes: 33 additions & 18 deletions src/compose/ComposeMenu.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,21 +8,24 @@ import DocumentPicker from 'react-native-document-picker';
import type { DocumentPickerResponse } from 'react-native-document-picker';
import { launchCamera, launchImageLibrary } from 'react-native-image-picker';

import { useDispatch } from '../react-redux';
import * as logging from '../utils/logging';
import { TranslationContext } from '../boot/TranslationProvider';
import type { Narrow } from '../types';
import { showErrorAlert } from '../utils/info';
import { createStyleSheet } from '../styles';
import { IconImage, IconCamera, IconAttach, IconVideo } from '../common/Icons';
import { uploadFile } from '../actions';
import { androidEnsureStoragePermission } from '../lightbox/download';
import { ThemeContext } from '../styles/theme';
import type { SpecificIconType } from '../common/Icons';

export type Attachment = {|
+name: string | null,
+url: string,
|};

type Props = $ReadOnly<{|
destinationNarrow: Narrow,
insertAttachment: ($ReadOnlyArray<DocumentPickerResponse>) => Promise<void>,
insertAttachments: ($ReadOnlyArray<Attachment>) => Promise<void>,
insertVideoCallLink: (() => void) | null,
|}>;

Expand Down Expand Up @@ -95,9 +98,8 @@ function MenuButton(props: MenuButtonProps) {
}

export default function ComposeMenu(props: Props): Node {
const { destinationNarrow, insertAttachment, insertVideoCallLink } = props;
const { insertAttachments, insertVideoCallLink } = props;

const dispatch = useDispatch();
const _ = useContext(TranslationContext);

const handleImagePickerResponse = useCallback(
Expand Down Expand Up @@ -140,28 +142,41 @@ export default function ComposeMenu(props: Props): Node {
return;
}

const { assets } = response;

// TODO: support sending multiple files; see library's docs for how to
// let `assets` have more than one item in `response`.
const firstAsset = response.assets && response.assets[0];
const firstAsset = assets && assets[0];

const { uri, fileName } = firstAsset ?? {};

if (!firstAsset || uri == null || fileName == null) {
if (!firstAsset) {
// TODO: See if we these unexpected situations actually happen. …Ah,
// yep, reportedly (and we've seen in Sentry):
// https://github.com/react-native-image-picker/react-native-image-picker/issues/1945
showErrorAlert(_('Error'), _('Something went wrong, and your message was not sent.'));
logging.error('Unexpected response from image picker', {
'!firstAsset': !firstAsset,
'uri == null': uri == null,
'fileName == null': fileName == null,
showErrorAlert(_('Error'), _('Failed to attach your file.'));
logging.error('Image picker response gave falsy `assets` or falsy `assets[0]`', {
'!assets': !assets,
});
return;
}

dispatch(uploadFile(destinationNarrow, uri, chooseUploadImageFilename(uri, fileName)));
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looks like this was the only call site of that uploadFile function — so let's cut that out too.

const { uri, fileName } = firstAsset;

if (uri == null || fileName == null) {
// TODO: See if these unexpected situations actually happen.
showErrorAlert(_('Error'), _('Failed to attach your file.'));
logging.error(
'First (should be only) asset returned from image picker had nullish `url` and/or `fileName`',
{
'uri == null': uri == null,
'fileName == null': fileName == null,
},
);
return;
}

insertAttachments([{ name: chooseUploadImageFilename(uri, fileName), url: uri }]);
},
[_, destinationNarrow, dispatch],
[_, insertAttachments],
);

const handleImagePicker = useCallback(() => {
Expand Down Expand Up @@ -221,8 +236,8 @@ export default function ComposeMenu(props: Props): Node {
return;
}

insertAttachment(response);
}, [_, insertAttachment]);
insertAttachments(response.map(a => ({ name: a.name, url: a.uri })));
}, [_, insertAttachments]);

const styles = useMemo(
() =>
Expand Down
11 changes: 0 additions & 11 deletions src/message/fetchActions.js
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@ import {
import { FIRST_UNREAD_ANCHOR, LAST_MESSAGE_ANCHOR } from '../anchor';
import { ALL_PRIVATE_NARROW, apiNarrowOfNarrow, caseNarrow, topicNarrow } from '../utils/narrow';
import { BackoffMachine, promiseTimeout, TimeoutError } from '../utils/async';
import { addToOutbox } from '../outbox/outboxActions';
import { getAllUsersById, getOwnUserId } from '../users/userSelectors';
import type { ServerSettings } from '../api/settings/getServerSettings';

Expand Down Expand Up @@ -390,16 +389,6 @@ export async function tryFetch<T>(
}
}

export const uploadFile =
(destinationNarrow: Narrow, uri: string, name: string): ThunkAction<Promise<void>> =>
async (dispatch, getState) => {
const auth = getAuth(getState());
const response = await api.uploadFile(auth, uri, name);
const messageToSend = `[${name}](${response.uri})`;

dispatch(addToOutbox(destinationNarrow, messageToSend));
};

export async function fetchServerSettings(realm: URL): Promise<
| {| +type: 'success', +value: ServerSettings |}
| {|
Expand Down
2 changes: 1 addition & 1 deletion static/translations/messages_en.json
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
"Updates may be delayed.": "Updates may be delayed.",
"No one has read this message yet.": "No one has read this message yet.",
"Confirm": "Confirm",
"Failed to attach your file.": "Failed to attach your file.",
"Configure permissions": "Configure permissions",
"You": "You",
"Discard changes": "Discard changes",
Expand Down Expand Up @@ -72,7 +73,6 @@
"The server sent a malformed response.": "The server sent a malformed response.",
"Storage permission needed": "Storage permission needed",
"Zulip will save a copy of your photo on your device. To do so, Zulip will need permission to store files on your device.": "Zulip will save a copy of your photo on your device. To do so, Zulip will need permission to store files on your device.",
"Something went wrong, and your message was not sent.": "Something went wrong, and your message was not sent.",
"Message not sent": "Message not sent",
"Please specify a topic.": "Please specify a topic.",
"Please specify a stream.": "Please specify a stream.",
Expand Down