Download speed doesn't work in react native - javascript

Good day all, Please I have this code below for testing download speed, and has been working for some time now. But recently always bring this error and doesn't work any more. Please help look into it.
Thanks
Tried with this url: 'https://drive.google.com/open?id=1MBHJXeRxMLLwHFpqbgTdEPsFArMM0cz7'
[Error: Unable to resolve host "drive.google.com": No address associated with hostname]
Tried with this url: 'https://upload.wikimedia.org/wikipedia/commons/b/b9/Pizigani_1367_Chart_1MB.jpg'
[Error: Unable to resolve host "upload.wikimedia.org": No address associated with hostname]
const downloadSizeInBits = 12000000;
const metric = 'MBps';
export const measureConnectionSpeed = (imageURIParam: string): any => {
const imageURI = imageURIParam
? imageURIParam
: 'https://drive.google.com/open?id=1MBHJXeRxMLLwHFpqbgTdEPsFArMM0cz7';
return new Promise((resolve, reject) => {
const startTime = new Date().getTime();
RNFetchBlob.config({
fileCache: false,
})
.fetch('GET', imageURI, {})
.then((res) => {
const endTime = new Date().getTime();
const duration = (endTime - startTime) / 1000;
const speed = downloadSizeInBits / (1024 * 1024 * duration);
resolve({metric, speed});
})
.catch(reject);
});
};
//Called from here in another component
getDownloadSpeed = async () => {
try {
const networkSpeed = await measureConnectionSpeed();
this.setState({value: networkSpeed.speed});
return networkSpeed.speed;
} catch (error) {
//handle error
ToastAndroid.show(
'Network Issues, unable to get download speed',
ToastAndroid.LONG,
);
console.log(error);
}
};
Thanks
Tim

Related

ERR Error: End of data reached (data length = 0, asked index = 4). Corrupted zip?

im making a whatsapp bot, im saving the chats in a excel file (im using exceljs) to read and handle some responses, i prefer to use promises and resolve them, i have a function to read chats:
const readChat = (number, message, step = null) =>
new Promise((resolve, reject) => {
setTimeout(() => {
number = number.replace("#c.us", "");
number = `${number}#c.us`;
const pathExcel = `./chats/${number}.xlsx`;
const workbook = new ExcelJS.Workbook();
const today = moment().format("DD-MM-YYYY hh:mm");
if (fs.existsSync(pathExcel)) {
const workbook = new ExcelJS.Workbook();
workbook.xlsx
.readFile(pathExcel)
.then(() => {
const worksheet = workbook.getWorksheet(1);
const lastRow = worksheet.lastRow;
let getRowInsert = worksheet.getRow(++lastRow.number);
getRowInsert.getCell("A").value = today;
getRowInsert.getCell("B").value = message;
if (step) {
getRowInsert.getCell("C").value = step;
}
getRowInsert.commit();
workbook.xlsx
.writeFile(pathExcel)
.then(() => {
const getRowPrevStep = worksheet.getRow(lastRow.number);
const lastStep = getRowPrevStep.getCell("C").value;
resolve(lastStep);
})
.catch((err) => {
console.log("ERR", err);
reject("error");
});
})
.catch((err) => {
console.log("ERR", err);
reject("error");
});
} else {
const worksheet = workbook.addWorksheet("Chats");
worksheet.columns = [
{ header: "Fecha", key: "number_customer" },
{ header: "Mensajes", key: "message" },
{ header: "Paso", key: "step" },
];
step = step || "";
worksheet.addRow([today, message, step]);
workbook.xlsx
.writeFile(pathExcel)
.then(() => {
resolve("STEP_1");
})
.catch((err) => {
console.log("Error", err);
reject("error");
});
}
}, 1000);
});
but the code after that else, its giving me the error: ERR Error: End of data reached (data length = 0, asked index = 4). Corrupted zip ?, the else, is supposed to be executed when there is no excel saved with that chat. I searched in many questions and pages, but i have not found any solution
I believe you would get this error after you stop your execution in between, i.e when the file is getting updated and this would corrupt the excel file.
You could try adding a "try catch" around read file in your if condition and create a new copy of workbook whenever you get these particular errors ('End of data reached (data length = 0, asked index = 4). Corrupted zip ?' or 'File not found:')
I've faced the same issue on frontend, in my case the file was corrupted. Try open it in excel.

Ethereum calculate slippage PancakeSwap EstimateGas always throw TransferHelper: TRANSFER_FROM_FAILED

I have been getting this error for a couple of days. I am trying to calculate the necessary Slippage in PancakeSweap automatically.
For this I am trying different percentages and I call estimateGas to see if the transaction fails. But I only get the error
TransferHelper: TRANSFER_FROM_FAILED
I have tried a lot of methods and none of them work for me.
I'm sure the contract is approved and that it should work in the blockchain side. In pancakeswap it works for me, same wallet, same tokens and same amounts. I do not understand that it can fail.
const Web3 = require("web3");
const abi = require("./abi.json");
const web3 = new Web3("https://bsc-dataseed.binance.org/");
const contract = new web3.eth.Contract(abi, "0x10ed43c718714eb63d5aa57b78b54704e256024e");
function isValid(res) {
return new Promise((resolve, reject) => {
contract.methods.swapExactTokensForTokens(res[0], res[1], ["TOKEN_A", "TOKEN_B" ], "MI_WALLET", 1639969436 ).estimateGas(function(error, result) {
console.log(error.message)
if(error.message.includes("INSUFFICIENT_OUTPUT_AMOUNT")) {
console.log("Bad slippage")
reject()
}
else if(error) {
reject()
}
else {
resolve()
}
});
})
}
(async () => {
contract.methods.getAmountsOut("20000000000", ["TOKEN_A", "TOKEN_B" ]).call().then(async res => {
const data = res;
let slippage = 0;
while (true) {
try {
await isValid(data);
break;
}
catch(e) {
slippage++;
console.log(slippage / 100 * data[1])
let newS = data[1] - (slippage / 100 * data[1])
console.log(slippage, newS);
if(slippage == 20) {
break;
}
}
}
console.log(slippage)
})
})();

How do I call 2 or more asynchronous methods in Actions on Google intent fulfilment V2

I had managed to call these 2 methods (geocoder.reverse, timezone.data) one after the other successfully in V1 DialogflowApp, but I am now upgrading to V2, and can't seem to get both asynchronous method calls right. Please help. I use these packages respectively
node-geocoder: ^3.22.0
node-google-timezone: ^0.1.1
const options = { provider: 'google', httpAdapter: 'https', apiKey: googleApi, formatter: 'json'};
const geocoder = NodeGeocoder(options);
const timezone = require('node-google-timezone');
app.intent('saving_prompt', (conv) => {
if (conv.data.area) {
const deviceCoordinatesStart = conv.device.location.coordinates;
const latitudeValueStart = deviceCoordinatesStart.latitude;
const longitudeValueStart = deviceCoordinatesStart.longitude;
let start = moment(); //Start time in UTC, you could also use dateTime()
let startTz = momentTz(); //used because of getting the Timezone
const timestamp = 1402629305; // Just a dud placeholder to fulfil timezone function
//GEOLOCATION REVERSAL (METHOD 1)
geocoder.reverse({lat:latitudeValueStart, lon:longitudeValueStart}, (err, res) => {
if (err) {
console.log(err);
}
let startLocation = res[0].administrativeLevels.level1long;
conv.data.startLocation = startLocation;
//GETTING LOCAL TIMEZONE FROM LAT/LONG AND TIMESTAMP (METHOD 2)
timezone.data(latitudeValueStart, longitudeValueStart, timestamp, (err, tz) => {
if (err) {
console.log(err);
}
var zoneHolder = tz.raw_response.timeZoneId;
const localTime = startTz.tz(zoneHolder).format('LLL');
conv.data.localTime = localTime;
app.ask('Your race starts by ' + localTime + 'at' + startLocation);
conv.ask(new Suggestions('End Race'));
});
});
} else { //Returned if permission not granted
conv.ask('You do not have your location on. Say "Locate me", to retrieve your location');
conv.ask(new Suggestions(['Locate me', 'Exit']));
}
});
//FUNCTION CREATED TO GET TIMEZONE WITHOUT 'node-google-timezone' PACKAGE
function callTimezoneApi(lat, lon) {
return new Promise((resolve, reject) => {
let path = '/maps/api/timezone/json?location=' + lat +
',' + lon + '&timestamp=' + ts + '&key=' + googleApi;
console.log('API Request: ' + host + path);
// Make the HTTP request to get the weather
http.get({
host: host,
path: path
}, (res) => {
let body = ''; // var to store the response chunks
res.on('data', (d) => {
body += d;
}); // store each response chunk
res.on('end', () => {
let response = JSON.parse(body);
let zoneHolder = response.timeZoneId;
let startTz = momentTz(); //used in fulfilling the Timezone
const localTime = startTz.tz(zoneHolder).format('LLL');
console.log(localTime);
return resolve(localTime);
});
res.on('error', (error) => {reject(error);});
});
});
}
If you use Node 8 you can use async/await to untangle the nested callback structure. It will ensure that your asynchronous calls are completed before proceeding with the next call, that has dependency on another async value.
app.intent('saving_prompt', async (conv) => {
if (conv.data.area) {
const deviceCoordinatesStart = conv.device.location.coordinates;
const latitudeValueStart = deviceCoordinatesStart.latitude;
const longitudeValueStart = deviceCoordinatesStart.longitude;
let start = moment(); //Start time in UTC, you could also use dateTime()
let startTz = momentTz(); //used because of getting the Timezone
const timestamp = 1402629305; // Just a dud placeholder to fulfil timezone function
const startLocation = await new Promise((resolve, reject) => {
geocoder.reverse({ lat: latitudeValueStart, lon: longitudeValueStart }, (err, res) => {
if (err) {
console.log(err);
reject(err);
} else {
resolve(res[0].administrativeLevels.level1long);
}
});
});
const localTime = await new Promise((resolve, reject) => {
timezone.data(latitudeValueStart, longitudeValueStart, timestamp, (err, tz) => {
if (err) {
console.log(err);
reject(err);
} else {
var zoneHolder = tz.raw_response.timeZoneId;
resolve(startTz.tz(zoneHolder).format('LLL'));
}
});
});
app.ask('Your race starts by ' + localTime + 'at' + startLocation);
conv.ask(new Suggestions('End Race'));
} else { //Returned if permission not granted
conv.ask('You do not have your location on. Say "Locate me", to retrieve your location');
conv.ask(new Suggestions(['Locate me', 'Exit']));
}
});

BINANCE API - How to get Account info with User Data Stream

I'm using Node and the ws npm package to work with WebSockets. Got the listenKey as stated in the docs (below), but I'm unable to get my account info using User Data Stream. I'd prefer to use a stream to read my most current account info (balances, etc) since using the Rest API to do it incurs a penalty (WEIGHT: 5) each time.
I've tried doing ws.send('outboundAccountInfo') but no joy.
DOCS: https://github.com/binance-exchange/binance-official-api-docs/blob/master/user-data-stream.md
Full code example - does not return any data:
import request from 'request'
import WebSocket from 'ws'
import { API_KEY } from '../../assets/secrets'
const DATA_STREAM_ENDPOINT = 'wss://stream.binance.com:9443/ws'
const BINANCE_API_ROOT = 'https://api.binance.com'
const LISTEN_KEY_ENDPOINT = `${BINANCE_API_ROOT}/api/v1/userDataStream`
const fetchAccountWebsocketData = async() => {
const listenKey = await fetchListenKey()
console.log('-> ', listenKey) // valid key is returned
let ws
try {
ws = await openWebSocket(`${DATA_STREAM_ENDPOINT}/${listenKey}`)
} catch (err) {
throw(`ERROR - fetchAccountWebsocketData: ${err}`)
}
// Nothing returns from either
ws.on('message', data => console.log(data))
ws.on('outboundAccountInfo', accountData => console.log(accountData))
}
const openWebSocket = endpoint => {
const p = new Promise((resolve, reject) => {
const ws = new WebSocket(endpoint)
console.log('\n-->> New Account Websocket')
ws.on('open', () => {
console.log('\n-->> Websocket Account open...')
resolve(ws)
}, err => {
console.log('fetchAccountWebsocketData error:', err)
reject(err)
})
})
p.catch(err => console.log(`ERROR - fetchAccountWebsocketData: ${err}`))
return p
}
const fetchListenKey = () => {
const p = new Promise((resolve, reject) => {
const options = {
url: LISTEN_KEY_ENDPOINT,
headers: {'X-MBX-APIKEY': API_KEY}
}
request.post(options, (err, httpResponse, body) => {
if (err)
return reject(err)
resolve(JSON.parse(body).listenKey)
})
})
p.catch(err => console.log(`ERROR - fetchListenKey: ${err}`))
return p
}
export default fetchAccountWebsocketData
Was stuggling too .... for hours !!!
https://www.reddit.com/r/BinanceExchange/comments/a902cq/user_data_streams_has_anyone_used_it_successfully/
The binance user data stream doesn't return anything when you connect
to it, only when something changes in your account. Try running your
code, then go to binance and place an order in the book, you should
see some data show up*

Convert image path to blob react native

Problem
I am trying to create an app with react native and firebase. One of the features I would like for this app is the ability to upload images. I am having some trouble uploading the images to firebase storage though. I am using expo's image picker to find the path of the image that the user wants to upload, but once I have the path I don't know how to convert that to something I can upload to firebase.
Can somebody help me convert the path of an image to something I can upload to firebase storage with react native?
What I've tried
I tried using:
_pickImage = async () => {
let result = await ImagePicker.launchImageLibraryAsync({
MediaTypeOptions: 'Images',
quality: 0.4,
_uploadAsByteArray = async (pickerResultAsByteArray, progressCallback) => {
try {
var metadata = {
contentType: 'image/jpeg',
};
var storageRef = firebase.storage().ref();
var ref = storageRef.child('images/'+expoID+'/'+this.state.time)
let uploadTask = ref.put(pickerResultAsByteArray, metadata)
uploadTask.on('state_changed', function (snapshot) {
progressCallback && progressCallback(snapshot.bytesTransferred / snapshot.totalBytes)
var progress = (snapshot.bytesTransferred / snapshot.totalBytes) * 100;
console.log('Upload is ' + progress + '% done');
}, function (error) {
console.log("in _uploadAsByteArray ", error)
}, function () {
var downloadURL = uploadTask.snapshot.downloadURL;
console.log("_uploadAsByteArray ", uploadTask.snapshot.downloadURL)
this.setState({imageUploaded:true})
});
} catch (ee) {
console.log("when trying to load _uploadAsByteArray ", ee)
}
}
convertToByteArray = (input) => {
var binary_string = this.atob(input);
var len = binary_string.length;
var bytes = new Uint8Array(len);
for (var i = 0; i < len; i++) {
bytes[i] = binary_string.charCodeAt(i);
}
return bytes
}
atob = (input) => {
const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
let str = input.replace(/=+$/, '');
let output = '';
if (str.length % 4 == 1) {
throw new Error("'atob' failed: The string to be decoded is not correctly encoded.");
}
for (let bc = 0, bs = 0, buffer, i = 0;
buffer = str.charAt(i++);
~buffer && (bs = bc % 4 ? bs * 64 + buffer : buffer,
bc++ % 4) ? output += String.fromCharCode(255 & bs >> (-2 * bc & 6)) : 0
) {
buffer = chars.indexOf(buffer);
}
return output;
}
uploadImage(bsfdata){
this.setState({imageUploaded:false})
this._uploadAsByteArray(this.convertToByteArray(bsfdata), (progress) => {
this.setState({ progress:progress })
})
}
base64:true,
});
/* if (!result.cancelled) {
this.setState({ image: result.uri });
let formData = new FormData();
formData.append('photo', {
uri,
name: `photo.${fileType}`,
type: `image/${fileType}`,
});}*/
this.uploadImage(result.base64);
};
}
I've tried it with the commented code added, which doesn't upload anything, and I've tried it with how the code is now, which gives me the error Can currently only create a Blob from other Blobs, and the uploading progress never gets above 0%.
If you are using expo (>=26), then you can do it easily with the following lines of code.
uploadImage = async(imageUri) => {
const response = await fetch(imageUri);
const blob = await response.blob();
var ref = firebase.storage().ref().child("image.jpg");
return ref.put(blob);
}
Reference: https://youtu.be/KkZckepfm2Q
Refer this link - https://github.com/dailydrip/react-native-firebase-storage/blob/master/src/App.js#L43-L69
Following block of code is working fine.
uploadImage(uri, mime = 'application/octet-stream') {
return new Promise((resolve, reject) => {
const uploadUri = Platform.OS === 'ios' ? uri.replace('file://', '') : uri
let uploadBlob = null
const imageRef = FirebaseClient.storage().ref('images').child('image_001')
fs.readFile(uploadUri, 'base64')
.then((data) => {
return Blob.build(data, { type: `${mime};BASE64` })
})
.then((blob) => {
uploadBlob = blob
return imageRef.put(blob, { contentType: mime })
})
.then(() => {
uploadBlob.close()
return imageRef.getDownloadURL()
})
.then((url) => {
resolve(url)
})
.catch((error) => {
reject(error)
})
})
}
You need to install rn-fetch-blob module:
npm install --save rn-fetch-blob
Then, do the following:
import RNFetchBlob from 'rn-fetch-blob';
const Blob = RNFetchBlob.polyfill.Blob;
const fs = RNFetchBlob.fs;
window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest;
window.Blob = Blob;
function uploadImage(path) {
const imageFile = RNFetchBlob.wrap(path);
// 'path/to/image' is where you wish to put your image in
// the database, if you would like to put it in the folder
// 'subfolder' inside 'mainFolder' and name it 'myImage', just
// replace it with 'mainFolder/subfolder/myImage'
const ref = firebase.storage().ref('path/to/image');
var uploadBlob = null;
Blob.build(imageFile, { type: 'image/jpg;' })
.then((imageBlob) => {
uploadBlob = imageBlob;
return ref.put(imageBlob, { contentType: 'image/jpg' });
})
.then(() => {
uploadBlob.close();
return ref.getDownloadURL();
})
.((url) => {
// do something with the url if you wish to
})
.catch(() => {
dispatch({
type: UPDATE_PROFILE_INFO_FAIL,
payload: 'Unable to upload profile picture, please try again'
});
});
}
Please do ask if there's any part of the code that you don't understand. To upload multiple images, simply wrap this code with a for loop. Or if you want to make sure that every image is uploaded without any error, use Promise
Not sure whom this might help, but if you're using MediaLibrary to load images from the gallery, then the uri comes in the format of uri = file:///storage/emulated/0/DCIM/Camera/filename.jpg
In this case, using fetch(uri) didn't help me get the blob.
But if you use fetch(uri.replace("file:///","file:/")) and then follow #sriteja Sugoor's answer, you'll be able to upload the file blob.
const Blob = RNFetchBlob.polyfill.Blob;
const fs = RNFetchBlob.fs;
let uploadBlob;
await fs
.readFile(params?.file.path, 'base64')
.then((data) => {
return Blob.build(data, {type: `BASE64`});
})
.then((blob) => {
uploadBlob = blob;
console.log(uploadBlob, 'uploadBlob');
});

Categories

Resources