ChatGPT fixed my upload by adding batches and feedback
This commit is contained in:
173
Views/NewPost.js
173
Views/NewPost.js
@@ -7,125 +7,178 @@ import { useNavigation } from '@react-navigation/native';
|
|||||||
import * as ImagePicker from 'expo-image-picker';
|
import * as ImagePicker from 'expo-image-picker';
|
||||||
import i18n from "../i18nMessages";
|
import i18n from "../i18nMessages";
|
||||||
import Media from '../components/Media';
|
import Media from '../components/Media';
|
||||||
|
import { Platform } from 'react-native';
|
||||||
|
|
||||||
|
const BATCH_SIZE = 1; // Constant for batch size
|
||||||
|
|
||||||
let NewPostView = (props) => {
|
let NewPostView = (props) => {
|
||||||
let [postContent, setPostContent] = useState('');
|
let [postContent, setPostContent] = useState('');
|
||||||
let initialContent = props.route.params.intialContent;
|
let initialContent = props.route.params.intialContent;
|
||||||
let [extraContent, setExtraContent] = useState([initialContent]);
|
let [extraContent, setExtraContent] = useState([initialContent]);
|
||||||
let [toProfile, setToProfile] = useState([]);
|
let [toProfile, setToProfile] = useState([]);
|
||||||
const [photo, setPhoto] = React.useState(null);
|
const [photo, setPhoto] = useState(null);
|
||||||
|
const [uploadProgress, setUploadProgress] = useState(0);
|
||||||
|
const [isUploading, setIsUploading] = useState(false); // Variable to prevent posting during upload
|
||||||
|
const [cancelUpload, setCancelUpload] = useState(false); // Variable to handle upload cancellation
|
||||||
const navigation = useNavigation();
|
const navigation = useNavigation();
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
//console.log(props)
|
|
||||||
let subscribed = true;
|
let subscribed = true;
|
||||||
const getProfileData = async () => {
|
const getProfileData = async () => {
|
||||||
if (!props.route.params?.toProfile) return 0;
|
if (!props.route.params?.toProfile) return;
|
||||||
await API.getUserProfile(props.route.params.toProfile).then((profileObj) => {
|
try {
|
||||||
if (!subscribed) return 0;
|
// Fetch profile data and update state if component is still subscribed
|
||||||
setToProfile(profileObj);
|
const profileObj = await API.getUserProfile(props.route.params.toProfile);
|
||||||
});
|
if (subscribed) setToProfile(profileObj);
|
||||||
|
// If sendNow flag is present, trigger post creation
|
||||||
if (props.route.params?.sendNow) {
|
if (props.route.params?.sendNow) {
|
||||||
console.log("sending from tab bar button")
|
console.log("sending from tab bar button");
|
||||||
await handleNewPostButton()
|
await handleNewPostButton();
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error fetching profile data", error);
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
getProfileData();
|
getProfileData();
|
||||||
return () => {
|
return () => {
|
||||||
|
// Cleanup subscription flag
|
||||||
subscribed = false;
|
subscribed = false;
|
||||||
}
|
}
|
||||||
}, [props.route.params?.sendNow]);
|
}, [props.route.params?.sendNow]);
|
||||||
|
|
||||||
const pickImage = async () => {
|
const pickImage = async () => {
|
||||||
// No permissions request is necessary for launching the image library
|
try {
|
||||||
let result = await ImagePicker.launchImageLibraryAsync({
|
// Launch image picker to select images from gallery
|
||||||
|
const result = await ImagePicker.launchImageLibraryAsync({
|
||||||
mediaTypes: ImagePicker.MediaTypeOptions.Images,
|
mediaTypes: ImagePicker.MediaTypeOptions.Images,
|
||||||
//allowsEditing: true,
|
quality: 0.2, // Set image quality
|
||||||
//aspect: [4, 3],
|
allowsMultipleSelection: true, // Allow multiple images to be selected
|
||||||
quality: 0.2,
|
|
||||||
allowsMultipleSelection: true,
|
|
||||||
});
|
});
|
||||||
if (!result.canceled) {
|
if (!result.canceled) {
|
||||||
setPhoto(result);
|
setIsUploading(true); // Set uploading state to true
|
||||||
let newPhotoURLs = await handleUploadPhoto(result);
|
setCancelUpload(false); // Reset cancel flag
|
||||||
let newExtraContent = [extraContent]
|
await handleUploadPhoto(result); // Upload selected photos
|
||||||
newPhotoURLs.forEach((newPhotoURL) => {
|
setPhoto(null); // Clear selected photo after upload
|
||||||
newExtraContent = ["@image:" + newPhotoURL].concat(newExtraContent);
|
setIsUploading(false); // Set uploading state to false
|
||||||
});
|
}
|
||||||
setExtraContent(newExtraContent);
|
} catch (error) {
|
||||||
setPhoto(null);
|
console.error("Error picking image", error);
|
||||||
|
setIsUploading(false); // Set uploading state to false in case of error
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleUploadPhoto = async (results) => {
|
const handleUploadPhoto = async (results) => {
|
||||||
if (!results) return;
|
if (!results) return;
|
||||||
let allUploads = [];
|
try {
|
||||||
results.assets.forEach(photo => {
|
setIsUploading(true); // Set uploading state to true
|
||||||
|
let uploadedFiles = [];
|
||||||
|
let totalPhotos = results.assets.length;
|
||||||
|
let currentIndex = 0;
|
||||||
|
|
||||||
|
// Upload photos in batches of BATCH_SIZE
|
||||||
|
while (currentIndex < totalPhotos) {
|
||||||
|
if (cancelUpload) {
|
||||||
|
setIsUploading(false);
|
||||||
|
setUploadProgress(0);
|
||||||
|
alert("Upload cancelled.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const batch = results.assets.slice(currentIndex, currentIndex + BATCH_SIZE);
|
||||||
|
setPhoto(batch[0]); // Set the first photo in the batch to preview it
|
||||||
|
const batchUploads = batch.map((photo) => {
|
||||||
|
// Prepare photo for upload
|
||||||
const uri =
|
const uri =
|
||||||
Platform.OS === "android"
|
Platform.OS === "android"
|
||||||
? photo.uri
|
? photo.uri // Use photo URI directly on Android
|
||||||
: photo.uri.replace("file://", "");
|
: photo.uri.replace("file://", ""); // Remove file:// prefix on other platforms
|
||||||
const filename = photo.uri.split("/").pop();
|
const filename = photo.uri.split("/").pop(); // Extract filename from URI
|
||||||
const match = /\.(\w+)$/.exec(filename);
|
const match = /\.(\w+)$/.exec(filename); // Extract file extension
|
||||||
const ext = match?.[1];
|
const ext = match?.[1];
|
||||||
const type = match ? `image/${match[1]}` : `image`;
|
const type = match ? `image/${match[1]}` : `image`; // Set MIME type based on file extension
|
||||||
const formData = new FormData();
|
const formData = new FormData();
|
||||||
formData.append("banner", {
|
formData.append("banner", {
|
||||||
uri,
|
uri,
|
||||||
name: `image.${ext}`,
|
name: `image.${ext}`, // Set the file name for upload
|
||||||
type,
|
type,
|
||||||
});
|
});
|
||||||
try {
|
// Upload photo to server using .then statements
|
||||||
allUploads.push(fetch("https://social.emmint.com/upload.php", {
|
return fetch("https://social.emmint.com/upload.php", {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
body: formData,
|
body: formData,
|
||||||
headers: { "Content-Type": "multipart/form-data" }
|
headers: { "Content-Type": "multipart/form-data" }
|
||||||
})
|
})
|
||||||
.then((res) => res.json())
|
.then((response) => {
|
||||||
.then((data) => {
|
if (!response.ok) {
|
||||||
return data.fileName;
|
throw new Error('Failed to upload image');
|
||||||
})
|
|
||||||
.catch((err) => console.error(err)));
|
|
||||||
|
|
||||||
} catch (err) {
|
|
||||||
console.log(err);
|
|
||||||
alert("Something went wrong uploading the photo.");
|
|
||||||
}
|
}
|
||||||
|
return response.json();
|
||||||
|
})
|
||||||
|
.then((data) => {
|
||||||
|
return data.fileName; // Return the filename from the server response
|
||||||
});
|
});
|
||||||
uploadedFiles = Promise.all(allUploads);
|
});
|
||||||
return uploadedFiles;
|
const batchResults = await Promise.all(batchUploads); // Wait for all uploads in the batch to complete
|
||||||
|
uploadedFiles = uploadedFiles.concat(batchResults); // Add uploaded files to the list
|
||||||
|
currentIndex += BATCH_SIZE; // Move to the next batch
|
||||||
|
setUploadProgress((currentIndex / totalPhotos) * 100); // Update upload progress
|
||||||
|
|
||||||
|
// Update extra content after each batch completes
|
||||||
|
setExtraContent(prevExtraContent => {
|
||||||
|
return prevExtraContent.concat(batchResults.map(url => "@image:" + url));
|
||||||
|
});
|
||||||
|
}
|
||||||
|
setIsUploading(false); // Set uploading state to false after completion
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error uploading photo", error);
|
||||||
|
alert("Something went wrong uploading the photo.");
|
||||||
|
setIsUploading(false); // Set uploading state to false in case of error
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const handleNewPostButton = async () => {
|
const handleNewPostButton = async () => {
|
||||||
//setPostContent('');
|
if (isUploading) {
|
||||||
API.newPost(postContent + " " + extraContent.join(" "), props.route.params?.toProfile).then((newPost) => {
|
alert("Please wait for the upload to finish before posting.");
|
||||||
setPostContent('');
|
return;
|
||||||
setExtraContent([]);
|
|
||||||
navigation.navigate('Feed', { reRender: Math.random() });
|
|
||||||
//if (newPostCB) newPostCB(newPost);
|
|
||||||
});
|
|
||||||
}
|
}
|
||||||
|
try {
|
||||||
|
// Create a new post with the combined content
|
||||||
|
await API.newPost(postContent + " " + extraContent.join(" "), props.route.params?.toProfile);
|
||||||
|
setPostContent(''); // Clear post content after submission
|
||||||
|
setExtraContent([]); // Clear extra content after submission
|
||||||
|
navigation.navigate('Feed', { reRender: Math.random() }); // Navigate back to the Feed and trigger re-render
|
||||||
|
} catch (error) {
|
||||||
|
console.error("Error creating new post", error);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const handleCancelUpload = () => {
|
||||||
|
setCancelUpload(true); // Set cancel flag to true
|
||||||
|
};
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ScrollView>
|
<ScrollView>
|
||||||
<View style={{ padding: 10, paddingTop: 20, flex: 1, justifyContent: "center" }}>
|
<View style={{ padding: 10, paddingTop: 20, flex: 1, justifyContent: "center" }}>
|
||||||
|
{/* Header section with status update text and post button */}
|
||||||
<View style={{ flexDirection: "row", marginBottom: 10, justifyContent: "space-around" }}>
|
<View style={{ flexDirection: "row", marginBottom: 10, justifyContent: "space-around" }}>
|
||||||
<Text style={{ fontSize: 25 }}>{i18n.t("message.statusUpdate")}:</Text>
|
<Text style={{ fontSize: 25 }}>{i18n.t("message.statusUpdate")}:</Text>
|
||||||
<Button icon="send" mode="outlined" onPress={handleNewPostButton}>
|
<Button icon="send" mode="outlined" onPress={handleNewPostButton}>
|
||||||
{i18n.t("message.post")}
|
{i18n.t("message.post")}
|
||||||
</Button>
|
</Button>
|
||||||
</View>
|
</View>
|
||||||
|
{/* Display the profile being posted on if available */}
|
||||||
{
|
{
|
||||||
toProfile._id ?
|
toProfile._id ?
|
||||||
<Text style={{ paddingLeft: 10, paddingBottom: 5 }}>
|
<Text style={{ paddingLeft: 10, paddingBottom: 5 }}>
|
||||||
Posting on: {toProfile._id ? toProfile.profile.firstName + " " + toProfile.profile.lastName : ''}
|
Posting on: {toProfile.profile?.firstName} {toProfile.profile?.lastName}
|
||||||
</Text> : <></>
|
</Text> : null
|
||||||
}
|
}
|
||||||
<Divider bold={true} />
|
<Divider bold={true} />
|
||||||
|
{/* Text input for post content */}
|
||||||
<TextInput
|
<TextInput
|
||||||
value={postContent}
|
value={postContent}
|
||||||
onChangeText={setPostContent}
|
onChangeText={setPostContent}
|
||||||
|
placeholder="What is on your mind today?"
|
||||||
multiline={true}
|
multiline={true}
|
||||||
numberOfLines={8}
|
numberOfLines={8}
|
||||||
style={{
|
style={{
|
||||||
@@ -138,11 +191,18 @@ let NewPostView = (props) => {
|
|||||||
autoFocus={true}
|
autoFocus={true}
|
||||||
/>
|
/>
|
||||||
<Divider bold={true} />
|
<Divider bold={true} />
|
||||||
|
{/* Button to pick images from the gallery */}
|
||||||
<View style={{ flexDirection: "row", marginTop: 10, justifyContent: "space-around" }}>
|
<View style={{ flexDirection: "row", marginTop: 10, justifyContent: "space-around" }}>
|
||||||
<Button icon="add-a-photo" mode="outlined" onPress={pickImage}>
|
<Button icon="add-a-photo" mode="outlined" onPress={pickImage}>
|
||||||
Add Photos
|
Add Photos
|
||||||
</Button>
|
</Button>
|
||||||
|
{isUploading && (
|
||||||
|
<Button icon="cancel" mode="outlined" onPress={handleCancelUpload}>
|
||||||
|
Cancel Upload
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
</View>
|
</View>
|
||||||
|
{/* Display uploading state and selected image preview */}
|
||||||
{photo && (
|
{photo && (
|
||||||
<View>
|
<View>
|
||||||
<Text>Uploading...</Text>
|
<Text>Uploading...</Text>
|
||||||
@@ -152,6 +212,13 @@ let NewPostView = (props) => {
|
|||||||
/>
|
/>
|
||||||
</View>
|
</View>
|
||||||
)}
|
)}
|
||||||
|
{/* Display upload progress if in progress */}
|
||||||
|
{
|
||||||
|
uploadProgress > 0 && uploadProgress < 100 && (
|
||||||
|
<Text>Upload Progress: {uploadProgress.toFixed(2)}%</Text>
|
||||||
|
)
|
||||||
|
}
|
||||||
|
{/* Display media content if extra content is available */}
|
||||||
{
|
{
|
||||||
extraContent.length > 0 && (
|
extraContent.length > 0 && (
|
||||||
<Media content={extraContent.join(" ")} />
|
<Media content={extraContent.join(" ")} />
|
||||||
|
|||||||
Reference in New Issue
Block a user