Merge pull request #5682 from urbit/po/fix-silent-s3-failures

groups: fix silent s3 failures
This commit is contained in:
Hunter Miller 2022-03-31 11:26:40 -05:00 committed by GitHub
commit 1949174f63
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
6 changed files with 380 additions and 207 deletions

View File

@ -10,7 +10,7 @@ export interface IuseStorage {
upload: (file: File, bucket: string) => Promise<string>;
uploadDefault: (file: File) => Promise<string>;
uploading: boolean;
promptUpload: () => Promise<string>;
promptUpload: (onError?: (err: Error) => void) => Promise<string>;
}
const useStorage = ({ accept = '*' } = { accept: '*' }): IuseStorage => {
@ -85,7 +85,7 @@ const useStorage = ({ accept = '*' } = { accept: '*' }): IuseStorage => {
}, [s3, upload]);
const promptUpload = useCallback(
(): Promise<string> => {
(onError?: (err: Error) => void): Promise<string> => {
return new Promise((resolve, reject) => {
const fileSelector = document.createElement('input');
fileSelector.setAttribute('type', 'file');
@ -95,6 +95,9 @@ const useStorage = ({ accept = '*' } = { accept: '*' }): IuseStorage => {
const files = fileSelector.files;
if (!files || files.length <= 0) {
reject();
} else if (onError) {
uploadDefault(files[0]).then(resolve).catch(err => onError(err));
document.body.removeChild(fileSelector);
} else {
uploadDefault(files[0]).then(resolve);
document.body.removeChild(fileSelector);

View File

@ -1,6 +1,13 @@
import { Box, Icon, LoadingSpinner, Row } from '@tlon/indigo-react';
import { Box, Col, Icon, LoadingSpinner, Row, Text } from '@tlon/indigo-react';
import { Contact, Content, evalCord } from '@urbit/api';
import React, { FC, PropsWithChildren, useRef, useState } from 'react';
import VisibilitySensor from 'react-visibility-sensor';
import React, {
FC,
PropsWithChildren,
useEffect,
useRef,
useState
} from 'react';
import tokenizeMessage from '~/logic/lib/tokenizeMessage';
import { IuseStorage } from '~/logic/lib/useStorage';
import { MOBILE_BROWSER_REGEX } from '~/logic/lib/util';
@ -11,41 +18,57 @@ import { ChatAvatar } from './ChatAvatar';
import { useChatStore } from './ChatPane';
import { useImperativeHandle } from 'react';
import { FileUploadSource, useFileUpload } from '~/logic/lib/useFileUpload';
import { Portal } from '~/views/components/Portal';
import styled from 'styled-components';
import { useOutsideClick } from '~/logic/lib/useOutsideClick';
type ChatInputProps = PropsWithChildren<IuseStorage & {
hideAvatars: boolean;
ourContact?: Contact;
placeholder: string;
onSubmit: (contents: Content[]) => void;
}>;
const FixedOverlay = styled(Col)`
position: fixed;
-webkit-transition: all 0.1s ease-out;
-moz-transition: all 0.1s ease-out;
-o-transition: all 0.1s ease-out;
transition: all 0.1s ease-out;
`;
type ChatInputProps = PropsWithChildren<
IuseStorage & {
hideAvatars: boolean;
ourContact?: Contact;
placeholder: string;
onSubmit: (contents: Content[]) => void;
uploadError: string;
setUploadError: (val: string) => void;
handleUploadError: (err: Error) => void;
}
>;
const InputBox: FC = ({ children }) => (
<Row
alignItems='center'
position='relative'
alignItems="center"
position="relative"
flexGrow={1}
flexShrink={0}
borderTop={1}
borderTopColor='lightGray'
backgroundColor='white'
className='cf'
borderTopColor="lightGray"
backgroundColor="white"
className="cf"
zIndex={0}
>
{ children }
{children}
</Row>
);
const IconBox = ({ children, ...props }) => (
<Box
ml='12px'
ml="12px"
mr={3}
flexShrink={0}
height='16px'
width='16px'
flexBasis='16px'
height="16px"
width="16px"
flexBasis="16px"
{...props}
>
{ children }
{children}
</Box>
);
@ -68,99 +91,158 @@ const MobileSubmitButton = ({ enabled, onSubmit }) => (
</Box>
);
export const ChatInput = React.forwardRef(({ ourContact, hideAvatars, placeholder, onSubmit }: ChatInputProps, ref) => {
const chatEditor = useRef<CodeMirrorShim>(null);
useImperativeHandle(ref, () => chatEditor.current);
const [inCodeMode, setInCodeMode] = useState(false);
export const ChatInput = React.forwardRef(
(
{
ourContact,
hideAvatars,
placeholder,
onSubmit,
uploadError,
setUploadError,
handleUploadError
}: ChatInputProps,
ref
) => {
const chatEditor = useRef<CodeMirrorShim>(null);
useImperativeHandle(ref, () => chatEditor.current);
const [inCodeMode, setInCodeMode] = useState(false);
const [showPortal, setShowPortal] = useState(false);
const [visible, setVisible] = useState(false);
const innerRef = useRef<HTMLDivElement>(null);
const outerRef = useRef<HTMLDivElement>(null);
const {
message,
setMessage
} = useChatStore();
const { canUpload, uploading, promptUpload, onPaste } = useFileUpload({
onSuccess: uploadSuccess
});
useEffect(() => {
if (!visible) {
setShowPortal(false);
}
}, [visible]);
function uploadSuccess(url: string, source: FileUploadSource) {
if (source === 'paste') {
setMessage(url);
} else {
onSubmit([{ url }]);
}
}
useOutsideClick(innerRef, () => setShowPortal(false));
function toggleCode() {
setInCodeMode(!inCodeMode);
}
const { message, setMessage } = useChatStore();
const { canUpload, uploading, promptUpload, onPaste } = useFileUpload({
onSuccess: uploadSuccess,
onError: handleUploadError
});
async function submit() {
const text = chatEditor.current?.getValue() || '';
if (text === '') {
return;
function uploadSuccess(url: string, source: FileUploadSource) {
if (source === 'paste') {
setMessage(url);
} else {
onSubmit([{ url }]);
}
setUploadError('');
}
if (inCodeMode) {
const output = await airlock.thread<string[]>(evalCord(text));
onSubmit([{ code: { output, expression: text } }]);
} else {
onSubmit(tokenizeMessage(text));
function toggleCode() {
setInCodeMode(!inCodeMode);
}
setInCodeMode(false);
setMessage('');
chatEditor.current.focus();
}
async function submit() {
const text = chatEditor.current?.getValue() || '';
return (
<InputBox>
<Row p='12px 4px 12px 12px' flexShrink={0} alignItems='center'>
<ChatAvatar contact={ourContact} hideAvatars={hideAvatars} />
</Row>
<ChatEditor
ref={chatEditor}
inCodeMode={inCodeMode}
submit={submit}
onPaste={(cm, e) => onPaste(e)}
placeholder={placeholder}
/>
<IconBox mr={canUpload ? '12px' : 3}>
<Icon
icon='Dojo'
cursor='pointer'
onClick={toggleCode}
color={inCodeMode ? 'blue' : 'black'}
/>
</IconBox>
{canUpload && (
<IconBox>
{uploading ? (
<LoadingSpinner />
) : (
<Icon
icon='Attachment'
cursor='pointer'
width='16'
height='16'
onClick={() =>
promptUpload().then(url => uploadSuccess(url, 'direct'))
}
if (text === '') {
return;
}
if (inCodeMode) {
const output = await airlock.thread<string[]>(evalCord(text));
onSubmit([{ code: { output, expression: text } }]);
} else {
onSubmit(tokenizeMessage(text));
}
setInCodeMode(false);
setMessage('');
chatEditor.current.focus();
}
return (
<Box ref={outerRef}>
<VisibilitySensor active={showPortal} onChange={setVisible}>
<InputBox>
{showPortal && (
<Portal>
<FixedOverlay
ref={innerRef}
backgroundColor="white"
color="washedGray"
border={1}
right={25}
bottom={75}
borderRadius={2}
borderColor="lightGray"
boxShadow="0px 0px 0px 3px"
zIndex={3}
fontSize={0}
width="250px"
padding={3}
justifyContent="center"
alignItems="center"
>
<Text>{uploadError}</Text>
<Text>Please check S3 settings.</Text>
</FixedOverlay>
</Portal>
)}
<Row p="12px 4px 12px 12px" flexShrink={0} alignItems="center">
<ChatAvatar contact={ourContact} hideAvatars={hideAvatars} />
</Row>
<ChatEditor
ref={chatEditor}
inCodeMode={inCodeMode}
submit={submit}
onPaste={(cm, e) => onPaste(e)}
placeholder={placeholder}
/>
)}
</IconBox>
)}
{MOBILE_BROWSER_REGEX.test(navigator.userAgent) && (
<MobileSubmitButton
enabled={message !== ''}
onSubmit={submit}
/>
)}
</InputBox>
);
});
<IconBox mr={canUpload ? '12px' : 3}>
<Icon
icon="Dojo"
cursor="pointer"
onClick={toggleCode}
color={inCodeMode ? 'blue' : 'black'}
/>
</IconBox>
{console.log({ uploadError })}
{canUpload && (
<IconBox>
{uploadError == '' && uploading && <LoadingSpinner />}
{uploadError !== '' && (
<Icon
icon="ExclaimationMark"
cursor="pointer"
onClick={() => setShowPortal(true)}
/>
)}
{uploadError == '' && !uploading && (
<Icon
icon="Attachment"
cursor="pointer"
width="16"
height="16"
onClick={() =>
promptUpload(handleUploadError).then(url =>
uploadSuccess(url, 'direct')
)
}
/>
)}
</IconBox>
)}
{MOBILE_BROWSER_REGEX.test(navigator.userAgent) && (
<MobileSubmitButton enabled={message !== ''} onSubmit={submit} />
)}
</InputBox>
</VisibilitySensor>
</Box>
);
}
);
// @ts-ignore withLocalState prop passing weirdness
export default withLocalState<Omit<ChatInputProps, keyof IuseStorage>, 'hideAvatars', ChatInput>(
ChatInput,
['hideAvatars']
);
export default withLocalState<
Omit<ChatInputProps, keyof IuseStorage>,
'hideAvatars',
typeof ChatInput
>(ChatInput, ['hideAvatars']);

View File

@ -114,8 +114,18 @@ export function ChatPane(props: ChatPaneProps): ReactElement {
const graphTimesentMap = useGraphTimesent(id);
const ourContact = useOurContact();
const { restore, setMessage } = useChatStore(s => ({ setMessage: s.setMessage, restore: s.restore }));
const [uploadError, setUploadError] = useState<string>('');
const handleUploadError = useCallback((err: Error) => {
setUploadError(err.message);
}, []);
const { canUpload, drag } = useFileUpload({
onSuccess: url => onSubmit([{ url }])
onSuccess: (url) => {
onSubmit([{ url }]);
setUploadError('');
},
onError: handleUploadError
});
useEffect(() => {
@ -171,6 +181,9 @@ export function ChatPane(props: ChatPaneProps): ReactElement {
onSubmit={onSubmit}
ourContact={(promptShare.length === 0 && ourContact) || undefined}
placeholder="Message..."
uploadError={uploadError}
setUploadError={setUploadError}
handleUploadError={handleUploadError}
/>
)}
</Col>

View File

@ -1,5 +1,5 @@
import React, { useCallback, useState } from 'react';
import { Box, LoadingSpinner, Action, Row } from '@tlon/indigo-react';
import { Box, LoadingSpinner, Action, Row, Icon, Text } from '@tlon/indigo-react';
import { StatelessUrlInput } from '~/views/components/StatelessUrlInput';
import SubmitDragger from '~/views/components/SubmitDragger';
@ -21,6 +21,7 @@ export function LinkBlockInput(props: LinkBlockInputProps) {
const [url, setUrl] = useState(props.url || '');
const [valid, setValid] = useState(false);
const [focussed, setFocussed] = useState(false);
const [error, setError] = useState<string>('');
const addPost = useGraphState(selGraph);
@ -39,10 +40,16 @@ export function LinkBlockInput(props: LinkBlockInputProps) {
const handleChange = useCallback((val: string) => {
setUrl(val);
setValid(URLparser.test(val) || Boolean(parsePermalink(val)));
setError('');
}, []);
const handleError = useCallback((err: Error) => {
setError(err.message);
}, []);
const { uploading, canUpload, promptUpload, drag } = useFileUpload({
onSuccess: handleChange
onSuccess: handleChange,
onError: handleError
});
const doPost = () => {
@ -64,7 +71,7 @@ export function LinkBlockInput(props: LinkBlockInputProps) {
};
const onKeyPress = useCallback(
(e) => {
(e: any) => {
if (e.key === 'Enter') {
e.preventDefault();
doPost();
@ -89,22 +96,43 @@ export function LinkBlockInput(props: LinkBlockInputProps) {
backgroundColor="washedGray"
{...drag.bind}
>
{drag.dragging && <SubmitDragger />}
{drag.dragging && canUpload && <SubmitDragger />}
{uploading ? (
<Box
display="flex"
width="100%"
height="100%"
position="absolute"
left={0}
right={0}
bg="white"
zIndex={9}
alignItems="center"
justifyContent="center"
>
<LoadingSpinner />
</Box>
error != '' ? (
<Box
display="flex"
flexDirection="column"
width="100%"
height="100%"
padding={3}
position="absolute"
left={0}
right={0}
bg="white"
zIndex={9}
alignItems="center"
justifyContent="center"
>
<Icon icon="ExclaimationMarkBold" size={32} />
<Text bold>{error}</Text>
<Text>Please check your S3 settings.</Text>
</Box>
) : (
<Box
display="flex"
width="100%"
height="100%"
position="absolute"
left={0}
right={0}
bg="white"
zIndex={9}
alignItems="center"
justifyContent="center"
>
<LoadingSpinner />
</Box>
)
) : (
<StatelessUrlInput
value={url}
@ -114,6 +142,7 @@ export function LinkBlockInput(props: LinkBlockInputProps) {
focussed={focussed}
onBlur={onBlur}
promptUpload={promptUpload}
handleError={handleError}
onKeyPress={onKeyPress}
center
/>
@ -125,7 +154,11 @@ export function LinkBlockInput(props: LinkBlockInputProps) {
p="2"
justifyContent="row-end"
>
<Action onClick={doPost} disabled={!valid} backgroundColor="transparent">
<Action
onClick={doPost}
disabled={!valid}
backgroundColor="transparent"
>
Post
</Action>
</Row>

View File

@ -1,6 +1,13 @@
import { BaseInput, Box, Button, LoadingSpinner } from '@tlon/indigo-react';
import {
BaseInput,
Box,
Button,
Icon,
LoadingSpinner,
Text
} from '@tlon/indigo-react';
import { hasProvider } from 'oembed-parser';
import React, { useState, useEffect } from 'react';
import React, { useState, useEffect, useCallback } from 'react';
import { parsePermalink, permalinkToReference } from '~/logic/lib/permalinks';
import { StatelessUrlInput } from '~/views/components/StatelessUrlInput';
import SubmitDragger from '~/views/components/SubmitDragger';
@ -22,15 +29,18 @@ const LinkSubmit = (props: LinkSubmitProps) => {
const [linkTitle, setLinkTitle] = useState('');
const [disabled, setDisabled] = useState(false);
const [linkValid, setLinkValid] = useState(false);
const [error, setError] = useState<string>('');
const {
canUpload,
uploading,
promptUpload,
drag,
onPaste
} = useFileUpload({
onSuccess: setLinkValue,
const handleError = useCallback((err: Error) => {
setError(err.message);
}, []);
const { canUpload, uploading, promptUpload, drag, onPaste } = useFileUpload({
onSuccess: (url) => {
setLinkValue(url);
setError('');
},
onError: handleError,
multiple: false
});
@ -38,25 +48,21 @@ const LinkSubmit = (props: LinkSubmitProps) => {
const url = linkValue;
const text = linkTitle ? linkTitle : linkValue;
const contents = url.startsWith('web+urbitgraph:/')
? [{ text }, permalinkToReference(parsePermalink(url)!)]
: [{ text }, { url }];
? [{ text }, permalinkToReference(parsePermalink(url)!)]
: [{ text }, { url }];
setDisabled(true);
const parentIndex = props.parentIndex || '';
const post = createPost(window.ship, contents, parentIndex);
addPost(
`~${props.ship}`,
props.name,
post
);
addPost(`~${props.ship}`, props.name, post);
setDisabled(false);
setLinkValue('');
setLinkTitle('');
setLinkValid(false);
};
const validateLink = (link) => {
const validateLink = (link: any) => {
const URLparser = new RegExp(
/((?:([\w\d\.-]+)\:\/\/?){1}(?:(www)\.?){0,1}(((?:[\w\d-]+\.)*)([\w\d-]+\.[\w\d]+))){1}(?:\:(\d+)){0,1}((\/(?:(?:[^\/\s\?]+\/)*))(?:([^\?\/\s#]+?(?:.[^\?\s]+){0,1}){0,1}(?:\?([^\s#]+)){0,1})){0,1}(?:#([^#\s]+)){0,1}/
);
@ -70,9 +76,9 @@ const LinkSubmit = (props: LinkSubmitProps) => {
setLinkValue(link);
}
}
if(link.startsWith('web+urbitgraph://')) {
if (link.startsWith('web+urbitgraph://')) {
const permalink = parsePermalink(link);
if(!permalink) {
if (!permalink) {
setLinkValid(false);
return;
}
@ -86,17 +92,23 @@ const LinkSubmit = (props: LinkSubmitProps) => {
if (result.title && !linkTitle) {
setLinkTitle(result.title);
}
}).catch((error) => { /* noop*/ });
})
.catch((error) => {
/* noop*/
});
} else if (!linkTitle) {
setLinkTitle(decodeURIComponent(link
.split('/')
.pop()
.split('.')
.slice(0, -1)
.join('.')
.replace('_', ' ')
.replace(/\d{4}\.\d{1,2}\.\d{2}\.\.\d{2}\.\d{2}\.\d{2}-/, '')
));
setLinkTitle(
decodeURIComponent(
link
.split('/')
.pop()
.split('.')
.slice(0, -1)
.join('.')
.replace('_', ' ')
.replace(/\d{4}\.\d{1,2}\.\d{2}\.\.\d{2}\.\d{2}\.\d{2}-/, '')
)
);
}
}
return link;
@ -113,7 +125,7 @@ const LinkSubmit = (props: LinkSubmitProps) => {
useEffect(onLinkChange, [linkValue]);
const onKeyPress = (e) => {
const onKeyPress = (e: any) => {
if (e.key === 'Enter') {
e.preventDefault();
doPost();
@ -122,60 +134,86 @@ const LinkSubmit = (props: LinkSubmitProps) => {
return (
<>
{/* @ts-ignore archaic event type mismatch */}
{/* @ts-ignore archaic event type mismatch */}
<Box
flexShrink={0}
position='relative'
border='1px solid'
position="relative"
border="1px solid"
borderColor={submitFocused ? 'black' : 'lightGray'}
width='100%'
width="100%"
borderRadius={2}
{...drag.bind}
>
{uploading && <Box
display="flex"
width="100%"
height="100%"
position="absolute"
left={0}
right={0}
bg="white"
zIndex={9}
alignItems="center"
justifyContent="center"
>
<LoadingSpinner />
</Box>}
{drag.dragging && <SubmitDragger />}
<StatelessUrlInput
value={linkValue}
promptUpload={promptUpload}
canUpload={canUpload}
onSubmit={doPost}
onChange={setLinkValue}
error={linkValid ? 'Invalid URL' : undefined}
onKeyPress={onKeyPress}
onPaste={onPaste}
/>
<BaseInput
type="text"
pl={2}
backgroundColor="transparent"
width="100%"
color="black"
fontSize={1}
style={{
resize: 'none',
height: 40
}}
placeholder="Provide a title"
onChange={e => setLinkTitle(e.target.value)}
onBlur={() => setSubmitFocused(false)}
onFocus={() => setSubmitFocused(true)}
spellCheck="false"
onKeyPress={onKeyPress}
value={linkTitle}
/>
{uploading ? (
error !== '' ? (
<Box
display="flex"
flexDirection="column"
width="100%"
height="100%"
left={0}
right={0}
bg="white"
zIndex={9}
alignItems="center"
justifyContent="center"
py={2}
>
<Icon icon="ExclaimationMarkBold" size={32} />
<Text bold>{error}</Text>
<Text>Please check your S3 settings.</Text>
</Box>
) : (
<Box
display="flex"
width="100%"
height="100%"
left={0}
right={0}
bg="white"
zIndex={9}
alignItems="center"
justifyContent="center"
py={2}
>
<LoadingSpinner />
</Box>
)
) : (
<>
<StatelessUrlInput
value={linkValue}
promptUpload={promptUpload}
canUpload={canUpload}
onSubmit={doPost}
onChange={setLinkValue}
error={linkValid ? 'Invalid URL' : undefined}
onKeyPress={onKeyPress}
onPaste={onPaste}
handleError={handleError}
/>
<BaseInput
type="text"
pl={2}
backgroundColor="transparent"
width="100%"
color="black"
fontSize={1}
style={{
resize: 'none',
height: 40
}}
placeholder="Provide a title"
onChange={e => setLinkTitle(e.target.value)}
onBlur={() => setSubmitFocused(false)}
onFocus={() => setSubmitFocused(true)}
spellCheck="false"
onKeyPress={onKeyPress}
value={linkTitle}
/>
</>
)}
{drag.dragging && <SubmitDragger />}
</Box>
<Box mt={2} mb={4}>
<Button
@ -183,7 +221,9 @@ const LinkSubmit = (props: LinkSubmitProps) => {
flexShrink={0}
disabled={!linkValid || disabled}
onClick={doPost}
>Post link</Button>
>
Post link
</Button>
</Box>
</>
);

View File

@ -9,8 +9,9 @@ type StatelessUrlInputProps = PropFunc<typeof BaseInput> & {
focussed?: boolean;
disabled?: boolean;
onChange?: (value: string) => void;
promptUpload: () => Promise<string>;
promptUpload: (onError: (err: Error) => void) => Promise<string>;
canUpload: boolean;
handleError: (err: Error) => void;
center?: boolean;
};
@ -22,6 +23,7 @@ export function StatelessUrlInput(props: StatelessUrlInputProps) {
onChange = () => {},
promptUpload,
canUpload,
handleError,
center = false,
...rest
} = props;
@ -53,7 +55,7 @@ export function StatelessUrlInput(props: StatelessUrlInputProps) {
cursor="pointer"
color="blue"
style={{ pointerEvents: 'all' }}
onClick={() => promptUpload().then(onChange)}
onClick={() => promptUpload(handleError).then(onChange)}
>
upload
</Text>{' '}