React-Native: read timestamp saved on Firebase, after updating it - android

I update a timestamp in a Firebase server every time I click a button on my react-native app (android).
The problem is that, after updating it, I want to read it and set my state with this timestamp.
Here is some code I found on the Internet, it updates the date on Firebase, reach the first 'then' block but then never go on, so never reach the second 'then' block and never show the alert(onlyDate);
I have no error about rules on Firebase, read and write are both available.
getDateServerFirebase = () => {
let fb_currentTime = firebase.database().ref('currentTime/');
fb_currentTime.update({ time: firebase.database.ServerValue.TIMESTAMP })
.then(() => {
fb_currentTime.once('value').then(function (data) {
//console.log(data);
let timestamp = data._value.time;
let fullDate = new Date(timestamp);
let onlyDate = fullDate.getDate() + '/' + (fullDate.getMonth()+1) + '/' + fullDate.getFullYear();
alert(onlyDate);
}, function serverTimeErr(err) {
console.log('Could not reach to the server time !');
});
}, function (err) {
console.log ('set time error:', err)
});
}
I tried this and still the same problem: writing works, reading not.
setData = () =>{
firebase.database().ref('prova/').set({
name:'luis',
surname:'rew'
}, function(error) {
if (error) {
// The write failed...
} else {
// Data saved successfully!
}
});
}
readData = () =>{
firebase.database().ref('prova/')
.once('value')
.then((data)=>{
alert(data);
})
}
Can someone help me??

The way you access response from firebase function is through running the val(); function on the result.
change this line
let timestamp = data._value.time;
into this:
let timestamp = data.val().time;

Related

Pasre server on AWS EC2 giving 141 error on cloud code

I am now using the below cloud code to only update "downloads" column on my parse server running on AWS EC2 instance. But I am getting the error code 141(invalid function)
Parse.Cloud.define("updateDownloads", async (request) => {
const query = new Parse.Query(request.params.className);
query.get(request.params.objectId)
.then((watchFace) => {
downloads = watchFace.get("downloads")
watchFace.set("downloads", downloads + 1);
await watchFace.save(null, { useMasterKey: true });
return "download updated";
}, (error) => {
return "something went wrong";
});
});
I have place my code in /opt/bitnami/cloud/main.js.
I even tried adding “cloud”: “/opt/bitnami/cloud/main.js” in config.json file but then the parse server gives 503 Service Unavailable error. So I removed it.
If you don't add the cloud code main.js file to your parse server configuration, parse server will never find your function, and that's why you get the invalid function error.
If you get error when adding the file, you are either adding it in a wrong way (you need to check your parse server initialization code) or the config.json is in wrong format or the cloud code has a problem.
The best way to figure it out is by checking your logs.
At a first glance, a problem that I see (may have others) is the usage of await in a function that is not async. You are also using a combination of async and then, which is little strange.
I'd recommend you to change the code to something like:
Parse.Cloud.define("updateDownloads", async (request) => {
const query = new Parse.Query(request.params.className);
const watchFace = await query.get(request.params.objectId);
const downloads = watchFace.get("downloads");
watchFace.set("downloads", downloads + 1); // You can use inc function to avoid concurrency problem
await watchFace.save(null, { useMasterKey: true });
return "download updated";
});

How to get Instagram Following List using Instagram graph api

How to get the following list from the Instagram account using the access token
I tried everything but not work.
here some API link which I tried before but none of them work.
I tried this one https://www.instagram.com/urvish_._/?__a=1
also this one
I tried but nothing can help me.
You can get the following (or also follower) list using the code below. Steps:
Make sure you're logged in on instagram.com
Open the API link: https://www.instagram.com/urvish_._/?__a=1 (your target username here is urvish_._)
Open the browser console: normally Ctrl+Shift+J on Windows/Linux or ⌘+Option+J on Mac
Paste this code and press Enter:
const GRAPHQL_MAX_PER_PAGE = 50;
async function getList() {
let pageLimit = 200; // from my testing
let baseInfo = JSON.parse(document.getElementsByTagName('body')[0].innerText);
let userId = baseInfo.graphql.user.id;
let config = { user_edge: 'edge_follow', query_hash: 'd04b0a864b4b54837c0d870b0e77e076', total_count: baseInfo.graphql.user.edge_follow.count };
// for followers instead of followings:
// { user_edge: 'edge_followed_by', query_hash: 'c76146de99bb02f6415203be841dd25a', total_count: baseInfo.graphql.user.edge_followed_by.count }
let after = null, hasNext = true, thisList = [];
for (pageCount = 1; hasNext && (pageCount <= pageLimit); ++pageCount) {
try {
let response = await fetch(`https://www.instagram.com/graphql/query/?query_hash=${config.query_hash}&variables=` + encodeURIComponent(JSON.stringify({
id: userId, include_reel: true, fetch_mutual: true, first: GRAPHQL_MAX_PER_PAGE, after: after
})));
if (!response.ok) {
console.warn(`Failed at page number ${pageCount.toLocaleString()}. HTTP status ${response.status}: ${response.statusText}.`);
break;
}
try {
response = await response.json();
} catch (error) {
console.error(`You may need to verify your account. Stopping. Failed at page number ${pageCount.toLocaleString()}.`, error);
break;
}
hasNext = response.data.user[config.user_edge].page_info.has_next_page
after = response.data.user[config.user_edge].page_info.end_cursor
thisList = thisList.concat(response.data.user[config.user_edge].edges.map(({ node }) => {
return {
id: node.id,
username: node.username,
full_name: node.full_name,
profile_pic_url: node.profile_pic_url,
};
}));
} catch (error) {
console.warn(`Error at page number ${pageCount.toLocaleString()}:`, error);
}
console.log(`${thisList.length.toLocaleString()} of ${config.total_count.toLocaleString()} fetched so far`);
}
console.info(`${thisList.length.toLocaleString()} fetched.`);
console.log(thisList);
}
getList()
Browser console showing a fetched list after code execution
In the code I've set the page limit to 200 so you can get up to 10,000 of your followings.
PS: For a way to visualise your lists and get more details, you can try Instagram Lists, a tool I made.

Uploading chunked file using Ionic4 and Angular HttpClient fails after some successful uploads with net::ERR_FILE_NOT_FOUND

i'm trying to upload a large file (500+Mb, but could be even bigger) to our php server, using an app written in Ionic4+Angular+Cordova, on an emulator with Android 10.
I set up a system to upload the file in chunks.
It reads the file choosen by the user using THIS PLUGIN, chunk by chunk (5Mb per chunk).
Then it proceeds to send it to our server performing a POST request with Content-type multipart/form-data.
The file goes to server, server saves it, says "OK", then the app proceeds to send the following chunk.
Everything works fine, for the first 25/29 chunks.
Then, the POST request fails with
POST http://192.168.1.2/work/path/to/webservices/uploadChunks.php net::ERR_FILE_NOT_FOUND
I tried:
starting at another point in the file instead of byte 0 - got the same error
reading the file chunk by chunk, without making any POST request- could cycle the whole 500Mb file
reading the file chunk by chunk and making the POST requests, but not sending the chunks with them - could execute every single call without any error, through the end of the file
reading the file chunk by chunk and sending them to ANOTHER webservice - got the same error
reading the file chunk by chunk and performing a POST request to another webservice, with content-type application/json and putting the formData object into the request body (not sure this is a valid test tho) - could execute every single call without any error, through the end of the file
Checking out memory snapshots taken in chrome inspector during different chunks upload did not show any sign of memory leak.
The case was tested on a rather old device, where the same procedure caused the app to exit, without signaling any error (not even in logcat apparently).
Here is the piece of code used to chunk and send the file:
const generatedName = 'some_name_for_file';
// Path obtained from fileChooser plugin
let path_to_file = 'content://com.android.externalstorage.documents/document/primary%3ADownload%2Ffilename.avi'
const min_chunk_size = (5 * 1024 * 1024);
// Converting path to file:// path
this.filePath.resolveNativePath(path_to_file).then((resolvedPath) => {
return this.fileAPI.resolveLocalFilesystemUrl(resolvedPath);
}, (error) => {
console.log('ERROR FILEPATH');
console.log(error);
return Promise.reject('Can not access file.<br>Code : F - ' + error);
}).then(
(entry) => {
path_to_file = entry.toURL();
console.log(path_to_file);
(entry as FileEntry).file((file) => {
//Getting back to the zone
this.ngZone.run(() => {
// Re-computing chunk size to be sure we do not get more than 10k chunks (very remote case)
let file_chunk_size = file.size / 10000;
if (file_chunk_size < min_chunk_size) {
file_chunk_size = min_chunk_size;
}
//Total number of chunks
const tot_chunk = Math.ceil(file.size / file_chunk_size);
const reader = new FileReader();
let retry_count = 0; //Counter to check on retries
const readFile = (nr_part: number, part_start: number, length: number) => {
// Computing end of chunk
const part_end = Math.min(part_start + length, file.size);
// Slicing file to get desired chunk
const blob = file.slice(part_start, part_end);
reader.onload = (event: any) => {
if (event.target.readyState === FileReader.DONE) {
let formData = new FormData();
//Creating blob
let fileBlob = new Blob([reader.result], {
type: file.type
});
formData.append('file', fileBlob, generatedName || file.name);
formData.append('tot_chunk', tot_chunk.toString());
formData.append('nr_chunk', nr_part.toString());
// UPLOAD
const sub = this.http.post('http://192.168.1.2/path/to/webservice/uploadChunk.php', formData).subscribe({
next: (response: any) => {
console.log('UPLOAD completed');
console.log(response);
retry_count = 0;
if (response && response.status === 'OK') {
//Emptying form and blob to be sure memory is clean
formData = null;
fileBlob = null;
// Checking if this was the last chunk
if (part_end >= file.size) {
// END
callback({
status: 'OK'
});
} else {
// Go to next chunk
readFile(nr_part + 1, part_end, length);
}
//Clearing post call subscription
sub.unsubscribe();
} else {
//There was an error server-side
callback(response);
}
},
error: (err) => {
console.log('POST CALL ERROR');
console.log(err);
if (retry_count < 5) {
setTimeout(() => {
retry_count++;
console.log('RETRY (' + (retry_count + 1) + ')');
readFile(nr_part, part_start, length);
}, 1000);
} else {
console.log('STOP RETRYING');
callback({status:'ERROR'});
}
}
});
}
};
//If for some reason the start point is after the end point, we exit with success...
if (part_start < part_end) {
reader.readAsArrayBuffer(blob);
} else {
callback({
status: 'OK'
});
}
};
//Start reading chunks
readFile(1, 0, file_chunk_size);
});
}, (error) => {
console.log('DEBUG - ERROR 3 ');
console.log(error);
callback({
status: 'ERROR',
code: error.code,
message: 'Can not read file<br>(Code: 3-' + error.code + ')'
});
});
}, (error) => {
console.log('ERROR 3');
console.log(error);
return Promise.reject('Can not access file.<br>Code : 3 - ' + error);
}
);
I can not figure out what is going wrong. Can someone help me debug this, or knows what could be going on?
Thank you very much.
I still do not know what caused this issue, but i resolved using a PUT request instead of a POST request, sending the raw chunk, and putting additional data in custom headers (something like "X-nr-chunk" or "X-tot-chunk"). Upload completed fine without the error message.
I also used the cordova-advanced-http plugin, but i do not think it made a difference here, since it did not work with the POST request, like the other method (httpClient).
This has been tested on android only for now, not on iOS. I'll report if there is any problem. For now i consider this solved, but if you know what may have caused this problem, please share your thoughts.
Thanks everyone.

How to wait for firebase data fetch finishes and get values not a promise in react-native?

I have data in firebase data that looks like the following:
The code for getting customers data:
getCustomersOnQeueu = async () => {
let customers = this.customersRef.orderByChild("ticket").once('value')
return customers
}
Code for rendering data:
renderCustomers = () => {
let customersViews = []
this.getCustomersOnQeueu().then((customers) => {
let customersTickets = customers.val()
console.log(customersTickets)
let sortedKeys = Object.keys(customersTickets).sort(function(a, b){
return customersTickets[b].ticket - customersTickets[a].ticket
})
console.log(sortedKeys)
for(i=0; i<sortedKeys.length; i++) {
let key = sortedKeys[i]
console.log(customersTickets[key]["customer"])
customersViews.push(<View>
<Text>{customersTickets[key["customer"]}</Text>
</View>)
}
})
return (<View>
<Text>Available Customers: </Text>
{customersViews}
</View>)
}
render() {
return (
<View>
{this.renderCustomers()}
</View>
)
}
Now after data being fetched and sorted I can see the following in console:
I have a problem that this line of code is never executed:
customersViews.push(<View>
<Text>{customersTickets[key["customer"]}</Text>
</View>)
I am guessing that it might be because customersViews array is initialized after rendering is done and not before, how can I wait for data fetching and sorting to finish then render the data?
When you are attempting to get your firebase response you're not actually waiting for it. The code below does not wait for it to be executed.
getCustomersOnQeueu = async () => {
let customers = this.customersRef.orderByChild("ticket").once('value')
return customers
}
To WAIT for it to be executed use AWAIT:
getCustomersOnQeueu = async () => {
let customers = await this.customersRef.orderByChild("ticket").once('value')
return customers
}
setting state via this.setState() always rerenders a component. If you want to rerender a vraible's latest value, put it in the state. Putting customerViews in state and updating it via this.setState() might solve your problem here.
Not sure what you are trying to render. a list of names?
It seems that your line you are talking about is not working because customersTickets.push cant push react element to the array.
You can even try it in your developer console
let array = []
arr.push(test)
and the result is "Uncaught SyntaxError"

Geolocation reporting in Ionic app Background

I intend to get users geolocation even when the app sits dormant in the background and store the same in the database.
I'm using katzer's Cordova Background Plug-in,
When I try to access navigator.geolocation.getCurrentPosition inside backgroundMode.onactivate function, nothing happens, Whereas when I try passing hard coded values api is called, data is stored in database.
following is my code
document.addEventListener('deviceready', function() {
// Android customization
cordova.plugins.backgroundMode.setDefaults({
text: 'Doing heavy tasks.'
});
// Enable background mode
cordova.plugins.backgroundMode.enable();
// Called when background mode has been activated
cordova.plugins.backgroundMode.onactivate = function() {
console.log('inside background')
a();
}
var a = function() {
console.log('a called')
navigator.geolocation.getCurrentPosition(function(pos) {
console.log('inside navigate');
var data = {
Lati: '123456',
Longi: '132456',
//LoginID: JSON.parse(window.localStorage.getItem('LoginId'))
EmpCode: localStorage.getItem('LoginId')
};
$http.post("https://app.sbismart.com/bo/ContactManagerApi/UpdateEmployeeLoc", data).success(function(rsdata, status) {
console.log('inside rsdata');
console.log(data.Lati + "," + data.Longi);
})
}, function(error) {
alert('Unable to get location: ' + error.message);
});
}
}, false);
cordova.plugins.backgroundMode.onfailure = function(errorCode) {
console.log(errorCode)
};`
and check as to why is it failing....then again u need to run the locationService function in a timeout function in the background to get updated about the location and check the location from previously got location.
Something like this...
cordova.plugins.backgroundMode.onactivate = function () {
setTimeout(function () {
a();
}, 5000);
}
Hope this helps.

Categories

Resources