Flutter web index.html not same as examples for fcm what to do now - flutter

I am building a flutter web app. Using flutter 3.0.7. I need to send push notifications and it looks like the only real way is with fcm. So I created a project and with the cli I created a firebase_options.dart file. Then I created a firebase-messaging-sw.js file.
If I send a message from the console I recieve the message but as soon as I try to send the message from y app to a topic or registration key I get no message.
I red in the examples the few out there to change my index.html file.
To theThis code is not in my index.html, dont know if it is because I am working with flutter 3.0.7
<script>
if ("serviceWorker" in navigator) {
window.addEventListener("load", function () {
mine looks like this
<script>
// The value below is injected by flutter build, do not touch.
var serviceWorkerVersion = null;
So could that be the problem that I can not send with legacy fcm api to my app users?
The send method I use is as follows
sendPushMessageToWeb(String? fcm_token) async {
if (fcm_token == null) {
print('Unable to send FCM message, no token exists.');
return;
}
try {
await http
.post(
Uri.parse('https://fcm.googleapis.com/fcm/send'),
headers: <String, String>{
'Content-Type': 'application/json',
'Authorization':
'key=my server key'
},
body: json.encode({
'to': "${fcm_token}",
'message': {
'token': "${fcm_token}",
},
"notification": {
"title": "Push Notification",
"body": "Firebase push notification"
}
}),
)
.then((value) => print(value.body));
print('FCM request for web sent!');
} catch (e) {
print(e);
}
}
When I send the message the method it tells me the message was send but no message is recieved. But when using console with the registration key it sends the message. Could it be because I did not change my index.html?
Thank you

Related

The generated token with vdomah JWT plugin in october cms is not accepted by the route with flutter

Hello i'm using flutter and i built an api with october cms.
I used the plugin by vdomah for the JWT Authentication, i think i followed the README.md but when i try to send the token to the api, i think is not accepted, the code:
the route:
Route::post('storephoto', function (Work $Work, Request $request) {
...
$Work->save();
})->middleware('Tymon\JWTAuth\Middleware\GetUserFromToken');
the flutter side:
upload(String fileName) {
http.post(AppUrl.baseURL + "/storephoto",
headers: {
'Authorization': 'Bearer $token'
},
body: {
"name": workNameController.text,
"images": fileName,
"description": descriptionController.text
}).then((result) {
setStatus(result.statusCode == 200 ? result.body : errMessage);
if(result.statusCode == 200) {
Navigator.push(context,
MaterialPageRoute(
builder: (context) => MainScreen()));
};
}).catchError((error) {
setStatus(error);
});
}
I printed the token in this function, and it exists, but i can't see the error in console.
I tried to make a GET route and the api seems to work in the browser, the message:
{
"error": "token_not_provided"
}
Now i think the token generated is not signed, or not recognized, how i can do?
Thanks in advance.
Once I faced the same issue, not sure there is some issue in the plugin, and doing the below change solved it.
plugins/vdomah/jwtauth/Plugin.php in this file do below change.
if you have any doubts please comment.
and can you use middleware like this
Route::group(['middleware' =>
['\Tymon\JWTAuth\Middleware\GetUserFromToken']], function() {
Route::post('storephoto', function (Request $request) {
//..code
});
});
as if I do like this its working

Service workers "sync" operation is working while its offline?

I have a PWA project where I send the data to server. During this process, if the user is offline then the data is stored in indexedDb and a sync tag is registered. So, then when the user comes online that data can sent to the server.
But In my case the sync event gets executed immediately when the we register a sync event tag, which means the data is tried to be sent to server while its offline, which is not going to work.
I think the sync event supposed to fire while its online only, what could be issue here ?
The service worker's sync event works accordingly when I tried to enable and disable the offline option of chrome devtools, and also works correctly in my android phone.
This is how I register my sync tag
function onFailure() {
var form = document.querySelector("form");
//Register the sync on post form error
if ('serviceWorker' in navigator && 'SyncManager' in window) {
navigator.serviceWorker.ready
.then(function (sw) {
var post = {
datetime1: form.datetime1.value,
datetime: form.datetime.value,
name: form.name.value,
image: form.url.value,
message: form.comment.value
};
writeData('sync-comments', post)
.then(function () {
return sw.sync.register('sync-new-comment');
})
.then(function () {
console.log("[Sync tag registered]");
})
.catch(function (err) {
console.log(err);
});
});
}
}
And this is how the sync event is called
self.addEventListener('sync', function (event) {
console.log("[Service worker] Sync new comment", event);
if (event.tag === 'sync-new-comment') {
event.waitUntil(
readAllData('sync-comments')
.then(function (data) {
setTimeout(() => {
data.forEach(async (dt) => {
const url = "/api/post_data/post_new_comment";
const parameters = {
method: 'POST',
headers: {
'Content-Type': "application/json",
'Accept': 'application/json'
},
body: JSON.stringify({
datetime: dt.datetime,
name: dt.name,
url: dt.image,
comment: dt.message,
datetime1: dt.datetime1,
})
};
fetch(url, parameters)
.then((res) => {
return res.json();
})
.then(response => {
if (response && response.datetimeid) deleteItemFromData('sync-comments', response.datetimeid);
}).catch((error) => {
console.log('[error post message]', error.message);
})
})
}, 5000);
})
);
}
});
you mention
The service worker's sync event works accordingly when I tried to enable and disable the offline option of chrome devtools, and also works correctly in my android phone.
So I'm not sure which case is the one failing.
You are right that the sync will be triggered when the browser thinks the user is online, if the browser detects that the user is online at the time of the sync registration it will trigger the sync:
In true extensible web style, this is a low level feature that gives you the freedom to do what you need. You ask for an event to be fired when the user has connectivity, which is immediate if the user already has connectivity. Then, you listen for that event and do whatever you need to do.
Also, from the workbox documentation
Browsers that support the BackgroundSync API will automatically replay failed requests on your behalf at an interval managed by the browser, likely using exponential backoff between replay attempts.

How to send a message in the Slack channel using Flutter?

I am creating an attendance app in which if an employee got the approval on leave request, then the app should send a message in the Slack channel.
I have seen this flutter package on the pub but it is not very helpful:-
https://pub.dev/packages/flutter_slack_oauth
Any idea on how I can send a message in the Slack channel using Flutter?
Finally got the answer, and wants to share :)
Here is the slack API URL to create a new app:-
https://api.slack.com/apps
After creating a new app, activate the Incoming Webhooks feature:-
Grab the webhook URL for your workspace, and make a request via this Flutter function:-
import 'dart:convert';
import 'package:http/http.dart' as http;
sendSlackMessage(String messageText) {
//Slack's Webhook URL
var url = 'https://hooks.slack.com/services/TA******JS/B0**********SZ/Kk*******************1D';
//Makes request headers
Map<String, String> requestHeader = {
'Content-type': 'application/json',
};
var request = {
'text': messageText,
};
var result = http
.post(url, body: json.encode(request), headers: requestHeader)
.then((response) {
print(response.body);
});
print(result);
}
You can also use slack post api for posting message.
var url = "https://slack.com/api/chat.postMessage";
var headers: {
"Content-type": "application/json",
"Authorization": 'Bearer $oAuthToken'
};
var body = {"channel": "Your_Channel_Id", "text": ":tada: :tada: :tada:", "as_user": true};
Add scope chat:write in your app configuration.
And now you will be able to send message to you channel. Hopefully it helps.

Sending voip push notification from one signal triggered firebase cloud functions

I`m trying to send Voip push notification from one signal triggered by firebase cloud functions. So far it being able to send normal message push notifications from one signal to IOS devices using firebase cloud functions with below code.
var sendNotification = function(data) {
var headers = {
"Content-Type": "application/json; charset=utf-8"
};
var options = {
host: "onesignal.com",
port: 443,
path: "/api/v1/notifications",
method: "POST",
headers: headers
};
var https = require('https');
var req = https.request(options, function(res) {
res.on('data', function(data) {
console.log("Response:");
console.log(JSON.parse(data));
});
});
req.on('error', function(e) {
console.log("ERROR:");
console.log(e);
});
req.write(JSON.stringify(data));
req.end();
};
var message = {
app_id: "*********************",
contents: {"en": "English Message"},
include_player_ids: ["******************7b0bdc38"]
};
sendNotification(message);
Does anyone know how to send Voip push notifications from one signal using firebase cloud functions??
(If the above code is required to change some part of it, it would be very thankful telling me where it is.)
As per one signal documentation (https://documentation.onesignal.com/docs/voip-notifications) you are missing the DEVICE_VOIP_TOKEN that you should have received from the iOS application.
Please try adding that and let me know, think of adding the exact error message if any.

Keep track of installed pwa instances

We want to keep track of each pwa installation for a user. So we could track notifications, like did every instance of the app user installed (pc or phone, or ff, or chrome) have received the update. Can we know the pwa instance was uninstalled? Can we know web push was delivered to every instance?
In your service worker, fire a http post to your server in the "install" event. You'll need to get your userID from indexdb or similar. Use "fetch" not xmlhttp the service worker.
self.addEventListener('install', function(e) {
console.log('[ServiceWorker] Install');
e.waitUntil(
caches.open(cacheName).then(function(cache) {
console.log('[ServiceWorker] Caching app shell');
var rc = cache.addAll(filesToCache);
postServerStatus( "installcomplete" );
return rc;
})
);
});
function postServerStatus( strStatus ) {
var strUserID = "getfromindexdb";
fetch('./datasvc.aspx', {
method: 'post',
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify({
service: strStatus,
userid: strUserID
}),
});
}