React native FS copyFile() never resolves - react-native

I have to copy a file picked with react-native-document-picker to the temporary path of my app and then read this file, but when it reaches the await ReactNativeFS.copyFile(realPath, tempPath); line, it never resolves. Here's the code
searchAndReadFiles = async () => {
try {
const fileSelected = await DocumentPicker.pick ({
type: DocumentPicker.types.plainText,
});
const decodedURI = decodeURIComponent(fileSelected.uri);
const split = decodedURI.split('/');
const name = split.pop();
const inbox = split.pop();
const realPath = `${ReactNativeFS.TemporaryDirectoryPath}/${name}`;
const tempPath = `${ReactNativeFS.ExternalStorageDirectoryPath}/${fileSelected.name}`;
await ReactNativeFS.copyFile(realPath, tempPath);
const fileRead = await ReactNativeFS.readFile(tempPath);
} catch (err) {
console.warn(err);
}
}

So I discovered that the copyFile() method by itself decodes the path, and I just passed the coded uri (the same way as I was receiving from document-picker pick() method) as argument and it worked fine, thank you.
searchAndReadFiles = async () => {
try {
const fileSelected = await DocumentPicker.pick ({
type: DocumentPicker.types.allFiles,
});
const destPath = `${ReactNativeFS.CachesDirectoryPath}/${fileSelected.name}`;
await ReactNativeFS.copyFile(fileSelected.uri, destPath);
...

Related

Where is module './get-username'?

I am attempting to write a script using the puppeteer library for node and I'm running it on the microtask platform rapidworkers.com
I have run into a challenge when writing part of the script that solves the captcha on the rapidworkers login page, when I try to run my script with node index.js I get the error: Cannot find module './get-username'
here is my code: (copied from https://jsoverson.medium.com/bypassing-captchas-with-headless-chrome-93f294518337)
const puppeteer = require('puppeteer');
const request = require('request-promise-native');
const poll = require('promise-poller').default;
const siteDetails = {
sitekey: '6LeEP20UAAAAAPYQsP7kIhE7XUT_LsDYjzO46uG3',
pageurl: 'https://rapidworkers.com/Login'
}
const getUsername = require('./get-username');
const getPassword = require('./get-password');
const apiKey = require('./api-key');
const chromeOptions = {
executablePath:'/Applications/Google Chrome.app/Contents/MacOS/Google
Chrome',
headless:false,
slowMo:10,
defaultViewport: null
};
(async function main() {
const browser = await puppeteer.launch(chromeOptions);
const page = await browser.newPage();
await page.goto('https://rapidworkers.com/Login');
const requestId = await initiateCaptchaRequest(apiKey);
await page.type('#username', getUsername());
const password = getPassword();
await page.type('#password', password);
const response = await pollForRequestResults(apiKey, requestId);
await page.evaluate(`document.getElementById("g-recaptcha-
response").innerHTML="${response}";`);
page.click('#register-form button[type=submit]');
})()
async function initiateCaptchaRequest(apiKey) {
const formData = {
method: 'userrecaptcha',
googlekey: siteDetails.sitekey,
key: apiKey,
pageurl: siteDetails.pageurl,
json: 1
};
const response = await request.post('http://2captcha.com/in.php', {form:
formData});
return JSON.parse(response).request;
}
async function pollForRequestResults(key, id, retries = 30, interval = 1500,
delay = 15000) {
await timeout(delay);
return poll({
taskFn: requestCaptchaResults(key, id),
interval,
retries
});
}
function requestCaptchaResults(apiKey, requestId) {
const url = `http://2captcha.com/res.php?
key=${apiKey}&action=get&id=${requestId}&json=1`;
return async function() {
return new Promise(async function(resolve, reject){
const rawResponse = await request.get(url);
const resp = JSON.parse(rawResponse);
if (resp.status === 0) return reject(resp.request);
resolve(resp.request);
});
}
}
const timeout = millis => new Promise(resolve => setTimeout(resolve,
millis))

Setting state using hooks resulting in null value in subsequent function call

First I call this where result is an object
const _onSaveEvent = async (result) => {
console.log(result);
setSignature(result);
followUp();
};
Then I invoke,
const handleActualSubmission = async () => {
console.log(signature);
const { encoded, pathName } = signature;
const extension = pathName.split('.').pop();
const path = `${RNFS.DocumentDirectoryPath}/${uuidv4()}.${extension}`;
await RNFS.writeFile(path, encoded, 'base64');
stops.forEach(async (stopForPhotoConf) => {
await saveDeliveryProof(driverRoute, stopForPhotoConf, path, extension, 'signature');
});
close();
};
The resulting error is signature being null on line 1 of handleActualSubmission where const [signature, setSignature] = useState(null);
I have verifeid that the _onSaveEvent function always returns a truthy value. This issue does not appear every time this sequence of functions runs.
This code should work:
useEffect(() => {
if (signature) {
processSavedSignature();
}
}, [signature]);

getdownloadurl from Firebase storage expo cli

I am trying to display the image from firebase storage. Below is the file location copied from firebase storage. It is a jpeg file
profile/2186uPKjgo4pMOQNm0Cm/profilepic
My following code returned error.
useEffect(() => {
function geturl(){
const filename = "profile/"+userid+"/profilepic.jpeg";
var ref = firebase.storage().ref(filename);
console.log(filename);
// This returns the exact file name
ref.getDownloadURL().then((url)=> {
console.log(url);
});
}
geturl();
}, []);
I got this error [object Object]. After that, I tried the following code async await
useEffect(() => {
async function geturl(){
const filename = "profile/"+userid+"/profilepic.jpeg";
var ref = firebase.storage().ref(filename);
console.log("inside geturl");
const downloadurl = await ref.getDownloadURL();
console.log(downloadurl);
}
geturl();
}, []);
Now Im getting the following error.
Possible Unhandled Promise Rejection (id: 29):
"code_": "storage/object-not-found",
"message_": "Firebase Storage: Object 'profile/2186uPKjgo4pMOQNm0Cm/profilepic.jpeg' does not exist.",
"name_": "FirebaseError",
"serverResponse_": "{
\"error\": {
\"code\": 404,
\"message\": \"Not Found. Could not get object\",
\"status\": \"GET_OBJECT\"
}
}",
}
Please let me know how I can get the url?
here you go you can use this function it uploads image to firebase storage and get the image uri at the same time
const uploadImage = async () => {
const response = await fetch(image);
const blob = await response.blob();
let filename = image.substring(image.lastIndexOf('/')+1);
const ext = filename.split('.').pop();
const name = filename.split('.').slice(0, -1).join('.');
filename = name + Date.now() + '.' + ext;
try {
var ref = firebase.storage().ref().child('post-images/'+filename);
await ref.put(blob)
.then(snapshot => {
return snapshot.ref.getDownloadURL();
})
.then(downloadURL => {
console.log(`Successfully uploaded file and got download link');
return downloadURL;
});
return null;
} catch (error) {
return null;
}
}

Not able to wait for download file in react

I tried searching a lot for this issue but did not get anything that helps me.
I am trying to download a bunch of pdf files from Strapi using URL and after downloading every pdf I am pushing it into a folder to create a zip.
My issue is while downloading, few of the files are not able to push in zip folder because of large file size. Basically, zip creation is not waiting to complete the download.
Here is my code, I am using map() to get URLs and using blob() to download it and then used zip to save it in the zip folder.
const downloadPdf = async (newData: any) => {
return new Promise(async (resolve) => {
let PolicyDocData: any;
[...some operation...]
if (newData.laws) {
if (newData.laws.description[0]) {
[...some operation to create an array for URL...]
let lawDoc = Array.from(new Set(lawDocArray));
lawDoc.map(async (val: any, index: any) => {
const lawUrl = val.url.slice(1);
const DocUrl = serverUrl + lawUrl;
let download = await fetch(DocUrl, {
method: "GET",
}).then((response) => response.blob()).then((response) => {
let fileType = ".pdf";
const timeStamp = Math.floor(Date.now() / 1000);
const fileName = val.name;
let docFileName = fileName + "_" + timeStamp;
zip.folder("Compliance/Laws").file(docFileName + fileType, response);
})
if (lawDoc.length - 1 === index) {
resolve(Contents);
}
})
}
}
}).then((Contents: any) => {
if (Contents) {
Packer.toBlob(PolicyDocumentCreator(Contents)).then((blob) => {
zip.generateAsync({ type: "blob" }).then(function (content: any) {
saveAs(content, folderName ? folderName : complianceName + ".zip");
setLoading(false);
})
});
}
});
};
I tried to solve it using setTimeout() but this is not a feasible solution.
Finally, I got the solution and I am posting here if anyone looking for it.
I break my whole function into two different functions and used Async/await and Promise.all()
Like this:
const downloadPdf = async (newData: any) => {
if (newData.laws) {
if (newData.laws.description[0]) {
[...Few operation to create an array of URLs...]
let lawDoc = Array.from(new Set(lawDocArray));
const val: any = await downloadAllLawPdf(lawDoc);
}
}
if (Contents) {
const blob = await Packer.toBlob(PolicyDocumentCreator(Contents));
const content: any = await zip.generateAsync({ type: "blob" });
saveAs(content, folderName ? folderName : complianceName + ".zip");
setLoading(false);
}
};
and then use a function downloadAllLawPdf() to download and wait till download gets completed and return the response.
const downloadAllLawPdf = async (lawDoc: any) => {
return Promise.all(lawDoc.map(async (val: any, index: any) => {
const lawUrl = val.url.slice(1);
const DocUrl = serverUrl + lawUrl;
let docFileName = ''
let fileType = ".pdf";
const res = await fetch(DocUrl, {
method: "GET",
});
const response = await res.blob();
const timeStamp = Math.floor(Date.now() / 1000);
const fileName = val.name;
docFileName = fileName + "_" + timeStamp;
zip.folder("Compliance/Laws").file(docFileName + fileType, response);
}));
}

GCloud Function & GStorage: sending downloaded file error: 'write after end'

My goal is to retrieve a file from Google Storage and then send it back via response. The problem is that, when I launch this function for the first time it crashes with Error [ERR_STREAM_WRITE_AFTER_END]: write after end. The next executions work fine.
exports = module.exports = region(defaultRegion).https.onRequest(async (req, res): Promise<void> => {
const [authError] = await to(handleAuth(req, res));
if (authError) {
res.status(500).send(authError.message);
return;
}
const { assetId, contentType, path } = req.query;
const file = bloqifyStorage.bucket().file(`assets/${assetId}/${path}`);
const fileExists = (await file.exists())[0];
if (!fileExists) {
res.status(404).send(`${path} was not found`);
return;
}
const fileStream = file.createReadStream();
fileStream.pipe(res).on('end', (): void => {
res.setHeader('content-type', contentType);
});
});
What am I missing here?
Edit: removing the set header doesn't solve it. Ex:
const fileStream = file.createReadStream();
// res.setHeader('content-type', contentType);
fileStream.pipe(res).on('error', (e): void => {
console.log(e);
});
It will print the same error.