react-native-firebase icon indicating copy to clipboard operation
react-native-firebase copied to clipboard

[🐛] Android push notifications in background with images containing exif metadata sometimes rotated incorrectly

Open markoboras0712 opened this issue 1 year ago • 9 comments

I have rn mobile app developed using https://expo.dev/ and for push notifications I'm using @react-native-firebase/messaging (background and terminated states). Push notifications are sent through FCM via our backend.

Everything works as intended but I have issue on android devices. Our push notifications contain images that are stored on amazon s3 buckets (example https://s3.us-east-1......./files/public/..../w700/1....jpg)

If you inspect exif metadata for this image you can see that it has orientation rotate 90 CW https://jimpl.com/results/Lz1h8ohTfFbK7o1QzvWHcrXQ?target=exif

Image

For background and terminated states I have in my app registered listeners setBackgroundMessageHandler and getInitialNotification where my push notifications are auto displayed correctly.

My issue is following:

  • If image stored on amazon s3 bucket has inside of it EXIF metadata, image in background and terminated states on android is rotated by 90 degrees.

NOTE:

  • I've recreated issue locally where I've created node js server to test this and if I strip from image exif metadata, reupload it, get image url and pass it in send of push notification, image is displayed correctly. Issue is that our system hundreds and hundreds of assets and they're coming from different sources.
  • If I send data-only push notifications auto display is ignored and I can display push notifications using https://notifee.app/ for background, foreground and terminated states, but I don't want to do that because I'm losing auto display feature and I need to handle a lot of more things inside of my mobile app.

Question

  • Can I somehow control to ignore EXIF metadata when image is auto displayed?

markoboras0712 avatar Mar 25 '25 11:03 markoboras0712

Can you please add a description?

MichaelVerdon avatar Mar 25 '25 11:03 MichaelVerdon

@MichaelVerdon sorry, I've updated now description.

markoboras0712 avatar Mar 25 '25 11:03 markoboras0712

This problem is even more fun I bet - I am willing to wager that the problem is device-specific and probably happens most on Samsung / Sony / maybe LG devices. Maybe doesn't happen on Pixel? Or does this really happen on every device?

In my experience the internet is littered with this problem and you can see it if you search for it

https://duckduckgo.com/?q=Android+image+rotated+incorrectly+90+degrees+EXIF

I'm not aware of a general solution on-device (other than notifee, which you mention). You may be able to wrap the storage fetch from s3 into a firebase function that sits between your app and the s3 storage and manipulates the EXIF data such that android devices consume it correctly. (so you would send FCM that reference an image URL that was your cloud function, not the s3 image directly, and the function gets a chance to "fix" the image as needed )

mikehardy avatar Mar 25 '25 12:03 mikehardy

@mikehardy

I am testing on xiaomi and samsung and on both of them this issue happens. On some android devices (don't know right now which one), it renders good.

Yeah there is a lot of issues with exif metadata for android.

Your solution that you're recommending for firebase function between my app and s3 storage seems legit, but IMHO if I am going to strip exif metadata I can do it directly in backend function where I'm sending push notification to device.

Issue with this approach is that I need to process image, strip exif metadata, reupload image somewhere to get image url and pass that imageUrl to my push notification.

Do you have any other recommendation or is it possible to fix this inside of @react-native-firebase/messaging lib?

markoboras0712 avatar Mar 25 '25 12:03 markoboras0712

There are supposedly third party plugins that can remove exif metadata for javascript, that could be the simplest solution. I don't believe the native sdks after some research even support letting you deal with Exif Metadata through messaging itself and if that is the case, we certainly won't be able to support it here unless the native sdks support it there. I would recommend reporting it here

MichaelVerdon avatar Mar 25 '25 13:03 MichaelVerdon

On some android devices (don't know right now which one), it renders good.

As I suspected - yep - you've just hit on one of the little pains that mobile developers have to deal with. I wish there were better options for you but I'm unaware of them.

but IMHO if I am going to strip exif metadata I can do it directly in backend function where I'm sending push notification to device.

I suppose so - I had not thought of that, do you mean send the image as base64 data inside the notification, already "fixed"? I think that's what you mean, and I think that works technically. You mention reprocess and store and everything, but I think you can include the image as base64. Worth a try. Otherwise, no need to process/store, make new function like I mention that is a proxy for the s3 storage bucket image URL. The URL to that new function is the desired processed image, when accessed the URL runs the function (with parameters to specify the image...) and it dynamically fetches it, processes it, and serves it to client. No storage needed.

Do you have any other recommendation or is it possible to fix this inside of @react-native-firebase/messaging lib?

No, we don't even get execution control when you use notification blocks in FCM. It happens at a much lower level. There will be no fix possible here

@MichaelVerdon -

There are supposedly third party plugins that can remove exif metadata for javascript

Javascript is not executing in this scenario, this is FCM-containing-notification-block-and-image, handled low-level by device notification display after firebase-android-sdk posts it raw, we never get control so react-native is not running so no javascript execution ability

mikehardy avatar Mar 25 '25 13:03 mikehardy

For what it's worth, I have had to deal with this before in another pure-native Android app, it's the only reason I know about it. Sort of blew my mind when I ran into it, I was a new developer then. I couldn't believe it was happening. And then I couldn't believe it was device-specific so it was even harder to workaround. Now nothing surprises me, but that's a sad statement 😆 . It is just hard to be a mobile developer, there are so many little things like this.

mikehardy avatar Mar 25 '25 13:03 mikehardy

@mikehardy

Thank you very much man, you've saved my life with this suggestion and everything works smoothly.

Mobile app

No changes at all:

  • foreground I use notifee to display push notification like I was and everything is okay
  • background and terminated messaging().setBackgroundMessageHandler.... to use auto display from react native firebase messaging

Backend

I've created firebase onRequest function that serves as proxy

export const processImageProxy = region('europe-west2').https.onRequest(
  async (req, res) => {
    const imageUrl = req.query.url as string;

    if (!imageUrl) {
      res.status(400).send('Missing image URL');
      return;
    }

    try {
      console.log(`⏳ Downloading image from URL: ${imageUrl}`);
      const response = await axios({
        url: imageUrl,
        responseType: 'arraybuffer',
      });
      const buffer = Buffer.from(response.data);
      // Process image: Remove EXIF metadata & auto-rotate
      const processedBuffer = await sharp(buffer)
        .rotate() // Auto-rotate based on EXIF
        .jpeg()
        .toBuffer();
      console.log('✅ Image processed successfully (EXIF stripped)');

      res.setHeader('Content-Type', 'image/jpeg');
      res.setHeader('Cache-Control', 'public, max-age=2592000');

      // Send the processed image
      res.send(processedBuffer);
      return;
    } catch (error) {
      console.error('❌ Error processing image:', error);
      res.status(500).send('Failed to process image');
      return;
    }
  },
);

And then inside of my testing function (I'll pas url of this proxy to my real backend) I use it like:

export const exifMetadataTesting = region('europe-west2').https.onRequest(
  (req, res) =>
    cors({ origin: true })(req, res, async () => {
      try {
        const originalImageUrl =
          'https://s3.us-east-1.amazonaws.com/s3........jpg';
        const functionBaseUrl =
          'https://europe-west2-...../processImageProxy';
        const proxyUrl = `${functionBaseUrl}?url=${encodeURIComponent(
          originalImageUrl,
        )}`;

        await messaging().send({
          token: fcmToken,
          data: {
            webViewUrl:
              '.....,
          },
          notification: {
            body: 'Notification body',
            title: 'Notification title',
            imageUrl: proxyUrl,
          },
        });

        console.log('✅ Push notification sent successfully with proxy image!');
        return res.status(200).send({
          success: true,
          proxyUrl: proxyUrl,
        });
      } catch (e) {
        ErrorHandlerService.handleError(e, 'sendPushNotificationTest');
        return res.status(500).send();
      }
    }),
);

markoboras0712 avatar Mar 25 '25 13:03 markoboras0712

That looks just about right, developer-to-developer it is a shame it's necessary, but it is - and since it is, this looks like what I'd do. Nice

I took a moment for a quick search and it appears that notifee supports base64 images from FCM contents but that's a custom feature in notifee to decode it and show it, I don't believe it's possible directly in android notifications like you want to do, so I think this is the best solution

Given that, I'm going to close this - glad you have a way a forward that works. Cheers

mikehardy avatar Mar 25 '25 14:03 mikehardy