Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Disable the Firebase functionality while still using firebase. #36

Closed
Johann13 opened this issue Nov 11, 2020 · 11 comments
Closed

Disable the Firebase functionality while still using firebase. #36

Johann13 opened this issue Nov 11, 2020 · 11 comments
Labels
enhancement New feature or request

Comments

@Johann13
Copy link

This might sound weird.
I'm using a lot of Firebase services including FCM.
And I love your Plugin and would like to use it.
But I have my own payload structure and would like to keep it.
Is there a way to use this plugin and firebase but not the firebase functionality of the plugin?
Currently I forked this plugin and disabled it on the android site by commenting out the FCMService from the Manifest. How would I disable it on iOS?

@rafaelsetragni
Copy link
Owner

rafaelsetragni commented Nov 12, 2020

Yes! I saw your fork.
And don't worry. Each project has its own needs, I'm glad you bring your own.

Have you encountered a problem using notifications with FCM and other Firebase services?

@Johann13
Copy link
Author

No, it all works.

Previously I had my own native Android implementation to handle Notifications.
Now with firebase_messaging 8 you can handle background notification with Flutter as well.

So I migrate to using that and you plugin but disabled your fcm part.
I tried doing the same for iOS but it didn't work/ I'm not sure what code I have to remove for your plugin to not handle fcm notifications. I can receive Notification on iOS send from the firebase console but not ones that I send from my server, these include a data payload.

@rafaelsetragni
Copy link
Owner

This is very interesting! I want to see how they do with iOS dart background executions.

I do not design this plugin to be disabled like this. I will study how this can be done.

@Johann13
Copy link
Author

Thanks,

the only reason I need this is because I have my own data structure for the notification payload and your plugin requires to use yours.
But again your plugin is great, I love the notification customizations!

@rafaelsetragni
Copy link
Owner

Can you send me an example of your payload content?
I had believed that a Map<String, String> was enough for the applications.

@Johann13
Copy link
Author

{
        "messageType": "newYoutubeVideo",
        "id": "xmw2C02Oyb4",
        "channelId": "UCH-_hzb2ILSCo9ftVSnrCIQ",
        "channelName": "Yogscast Lewis & Simon",
        "duration": "14:43",
        "videoId": "xmw2C02Oyb4",
        "videoTitle": "NEW ROLE: DETRAITOR | Gmod TTT",
        "date": "1604862527499",
        "publishedMills": "1604862527499",
        "creatorNames": "[Lewis,Ben,Duncan,Rythian,Daltos,Pedguin,Zylus,Zoey",
        "creatorKeys": "[-LO4RXOIYbfmHBxRQsb3,-LV7p9gJgRCO5ubEAZ9M,-LO4RgjL5OZNOMyZl3PT,-LO4tVwQPgtV5jYenvzr,-LOFjRQqUxcLcDGtZrRQ,-LOFfpUuNnXTb2rMmbYr,-LOFATAWo-IgqWFpGVxM,-LO4RmRnLAcMCTUfnGqR]",
        "creator": "["
                   "{\"name\":\"Lewis\",\"key\":\"-LO4RXOIYbfmHBxRQsb3\"},"
                   "{\"name\":\"Ben\",\"key\":\"-LV7p9gJgRCO5ubEAZ9M\"},"
                   "{\"name\":\"Duncan\",\"key\":\"-LO4RgjL5OZNOMyZl3PT\"},"
                   "{\"name\":\"Rythian\",\"key\":\"-LO4tVwQPgtV5jYenvzr\"},"
                   "{\"name\":\"Daltos\",\"key\":\"-LOFjRQqUxcLcDGtZrRQ\"},"
                   "{\"name\":\"Pedguin\",\"key\":\"-LOFfpUuNnXTb2rMmbYr\"},"
                   "{\"name\":\"Zylus\",\"key\":\"-LOFATAWo-IgqWFpGVxM\"},"
                   "{\"name\":\"Zoey\",\"key\":\"-LO4RmRnLAcMCTUfnGqR\"}"
                   "]"
    }

Some fields are a bit redundant but this is one of the notification types I'm sending.

@Johann13
Copy link
Author

I have done one more experiment.
I removed your plugin completly and tried sending notifications with success.

After reading it it stopped working.
If it helps here is part of my main.dart and handle_notifications.dart
(I did a lot of prints sry)

Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  print("Handling a background message ${message.messageId}");
  print("Handling a background message ${message.data}");
  handleNotifications(message);
}

void main(List<String> args) async {
  YRouter.init(f.FluroRouter());
  WidgetsFlutterBinding.ensureInitialized();
  try {
    await Firebase.initializeApp();
    print('initializeApp');
  } catch (e) {
    print('initializeApp: $e');
  }

  try {
    FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);
    FirebaseMessaging.onMessage.listen(firebaseMessagingBackgroundHandler);
    print('init fcm listener');
  } catch (e) {
    print('init fcm listener: $e');
  }

  /// Update the iOS foreground notification presentation options to allow
  /// heads up notifications.
  try {
    await FirebaseMessaging.instance
        .setForegroundNotificationPresentationOptions(
      alert: true,
      badge: true,
      sound: true,
    );
    print('setForegroundNotificationPresentationOptions');
  } catch (e) {
    print('setForegroundNotificationPresentationOptions: $e');
  }

  // Pass all uncaught errors to Crashlytics.
  // FlutterError.onError = Crashlytics.instance.recordFlutterError;

  runApp(
    NotificationHandler(
      child: NewRoot(
        child: App(),
      ),
    ),
  );
}

handle_notification.dart

Future<void> handleNotifications(RemoteMessage remoteMessage) async {
  Map<String, String> data = remoteMessage.data;
  print('data: $data');
  String messageType = data['messageType'];
  print('handleNotifications');
  print('messageType: $messageType');
  print(remoteMessage.data);
  if (messageType == null) {
    return null;
  }
  switch (messageType.toLowerCase()) {
    case "newyoutubevideo":
      return showFirebaseNewYoutubeVideoNotification(remoteMessage);
    case 'twitchchannellive':
      return showFirebaseTwitchChannelLiveNotification(remoteMessage);
    case 'other':
      print('other');
      showFirebaseNotification(remoteMessage);
      break;
  }
}
class NotificationHandler extends StatefulWidget {
  final Widget child;

  const NotificationHandler({Key key, @required this.child}) : super(key: key);

  @override
  _NotificationHandlerState createState() => _NotificationHandlerState();
}

class _NotificationHandlerState extends State<NotificationHandler> {
  StreamSubscription _onMessage;
  StreamSubscription _createdStream;
  StreamSubscription _displayedStream;
  StreamSubscription _actionStream;
  StreamSubscription _dismissedStream;

  StreamSubscription _ANfcmToken;
  StreamSubscription _fcmToken;

  @override
  void initState() {
    _init();
    super.initState();
  }

  @override
  void dispose() {
    _onMessage?.cancel();
    _createdStream?.cancel();
    _displayedStream?.cancel();
    _actionStream?.cancel();
    _dismissedStream?.cancel();
    _fcmToken?.cancel();
    _ANfcmToken?.cancel();
    super.dispose();
  }

  void _init() async {
    print('NotificationHandler _init');

    await _initChannel();

    try {
      _createdStream = AwesomeNotifications().createdStream.listen(_created);
      print('NotificationHandler _init 1');

      _displayedStream =
          AwesomeNotifications().displayedStream.listen(_displayed);

      print('NotificationHandler _init 2');

      _actionStream = AwesomeNotifications().actionStream.listen(_action);

      _dismissedStream =
          AwesomeNotifications().dismissedStream.listen(_dismissed);

      print('NotificationHandler _init 3');
      _ANfcmToken =
          AwesomeNotifications().fcmTokenStream.listen((String newFcmToken) {
        print("AwesomeNotifications FCM token: $newFcmToken");
      });
    } catch (e) {
      print('NotificationHandler _init: $e');
    }

    try {
      _fcmToken = FirebaseMessaging.instance.onTokenRefresh.listen((event) {
        print('token: $event');
      }, onError: (e) {
        print('token error: $e');
      });

      print('NotificationHandler _init 4');
    } catch (e) {
      print('_fcmTokenStreamError $e');
    }

    try {
      String apns = await FirebaseMessaging.instance.getAPNSToken();
      print('apns $apns');
    } catch (e) {
      print('apns error $e');
    }
    print('NotificationHandler _init done');
  }

  Future<void> _initChannel() async {
    print('_initChannel');
    try {
      await AwesomeNotifications().initialize(
        'resource://drawable/ic_notification_y_white',
        [
          NotificationChannel(
            channelKey: YNotificationChannel.jjNotification,
            channelName: 'Jingle Jam Related Notifications',
            defaultColor: YColors.jingleJam,
            ledColor: YColors.jingleJam,
          ),
          NotificationChannel(
            channelKey: YNotificationChannel.pollNotification,
            channelName: 'Poll Notifications',
            defaultColor: YColors.primaryColor,
            ledColor: YColors.primaryColor,
          ),
          NotificationChannel(
            channelKey: YNotificationChannel.otherNotification,
            channelName: 'Other Notifications',
            defaultColor: YColors.primaryColor,
            ledColor: YColors.primaryColor,
          ),
          NotificationChannel(
            channelKey: YNotificationChannel.twitchNotification,
            channelName: 'Twitch Notifications',
            defaultColor: YColors.twitchPallet,
            ledColor: YColors.twitchPallet,
          ),
          NotificationChannel(
            channelKey: YNotificationChannel.youtubeNotification,
            channelName: 'Youtube Notifications',
            defaultColor: YColors.youtubeRed,
            ledColor: YColors.youtubeRed,
          ),
          NotificationChannel(
            channelKey: YNotificationChannel.otherTwitchNotification,
            channelName: 'Other Twitch Notifications',
            defaultColor: YColors.twitchPallet,
            ledColor: YColors.twitchPallet,
          ),
          NotificationChannel(
            channelKey: YNotificationChannel.otherYoutubeNotification,
            channelName: 'Other Youtube Notifications',
            defaultColor: YColors.youtubeRed,
            ledColor: YColors.youtubeRed,
          ),
          NotificationChannel(
            channelKey: YNotificationChannel.twitterNotification,
            channelName: 'Twitter Related Notifications',
            defaultColor: YColors.primaryColor,
            ledColor: YColors.primaryColor,
          ),
          NotificationChannel(
            channelKey: YNotificationChannel.merchNotification,
            channelName: 'Merch Related Notifications',
            defaultColor: YColors.primaryColor,
            ledColor: YColors.primaryColor,
          ),
        ],
      );
      print('init channel');
    } catch (e) {
      print('init channel: $e');
    }
  }

  void _created(ReceivedNotification notification) {
    print('notification created ${notification.id}');
  }

  void _displayed(ReceivedNotification notification) {
    print('notification displayed ${notification.id}');
  }

  void _action(ReceivedAction action) async {
    print(
        'notification action pressed ${action.buttonKeyPressed}, ${action.id}');

    if (action.channelKey == YNotificationChannel.youtubeNotification) {
      YoutubeNotification youtubeNotification = YoutubeNotification.fromMap(
        {
          for (String key in action.payload.keys) key: action.payload[key],
        },
      );
      if (action.buttonKeyPressed == null) {
        if (await canLaunch(
            'https://www.youtube.com/watch?v=${youtubeNotification.videoId}')) {
          launch(
              'https://www.youtube.com/watch?v=${youtubeNotification.videoId}');
        } else {
          print('can not launch');
        }
      } else if (action.buttonKeyPressed == 'open_youtube') {
        if (await canLaunch(
            'https://www.youtube.com/watch?v=${youtubeNotification.videoId}')) {
          launch(
              'https://www.youtube.com/watch?v=${youtubeNotification.videoId}');
        } else {
          print('can not launch');
        }
      } else if (action.buttonKeyPressed == 'later') {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        int min = prefs.getInt('youtubeNotificationLater') ?? 60;
        showYoutubeNotification(
          youtubeNotification,
          schedule: DateTime.now().add(Duration(minutes: min)),
        );
      }
    }
  }

  void _dismissed(ReceivedAction action) {
    print('notification dismissed ${action.id}');
  }

  @override
  Widget build(BuildContext context) {
    return widget.child;
  }
}

@rafaelsetragni
Copy link
Owner

rafaelsetragni commented Nov 13, 2020

Firebase cloud message scripts fires the notifications globally across the app. To "disable" my plugin you just need to make the fcmservice.java do nothing.

I gonna implement a switch to make my plugin ignore it by default until you activate it intentionally. What do you think?

@Johann13
Copy link
Author

Yeah something like
AwesomeNotifications().enableFCM(bool enable);
sounds good.

I have disabled it on android do I have to do something on iOS? Since it is currently not working with your plugin added to the pubsec.yaml. If I remove it and all references to it, then I receive Notifications.

@rafaelsetragni
Copy link
Owner

Just write your own Service Extension Target and the plugin will not process the notification.

@rafaelsetragni rafaelsetragni added the enhancement New feature or request label Nov 16, 2020
@Johann13
Copy link
Author

Sry that I'm only able to answer now. I removed the AwesomeNotificationService and ContentExtension but without success. The notification is still not received. Only when I remove the plugin completely, is it received again.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

No branches or pull requests

2 participants