1.0.3 • Published 11 months ago

@henritrip/subscribepushservice v1.0.3

Weekly downloads
-
License
ISC
Repository
github
Last release
11 months ago

subscribepushservice

Subscribe Expo/token and Reporting events

In order to use this library, you need to have an account on https://push.henritrip.fr/. After registering, you will need the application api-key for your app.

Supported platforms

This is a Expo/ReactNative SDK.

If you find any compatibility issues, please raise an issue in the repository or contact support at dev@henritrip.fr. We will happily investigate reported problems ❤️.

Installation

You need to be running at least REACT-NATIVE 0.71.3+ to use this library.

$ npm i @henritrip/subscribepushservice

Importing

It's possible to use subscribepushservice with javascript.

import {subscribepushservice,initpushservice } from '@henritrip/subscribepushservice'

Configuration

import { initpushservice } from '@henritrip/subscribepushservice'

initpushservice( "API_KEY" ,
"HOST" // required, usually https://push.henritrip.fr/api/token
 );

Subscribing the token in the registerForPushNotificationsAsync:

await subscribepushservice(token)

Reporting opening, open by notif, and over events:

 subscribepushservice(null,
     {name:"OPEN_BY_NOTIF",any_attribute:any_value},
    {...any_profile_data } //profile user
 ).then((response)=>{})
 subscribepushservice(null,
    {name:"ANY_EVENT",any_attribute:any_value},
    {...any_profile_data } //profile user
 ).then((response)=>{})

Usage

Example

Single screen app, with multiple reports

import { StatusBar } from 'expo-status-bar';

import { Linking } from 'react-native';
import { LatLng, LeafletView } from 'react-native-leaflet-view';
import { useState, useEffect, useRef } from 'react';
import { StyleSheet ,Text, View, Platform } from 'react-native';
import * as Device from 'expo-device';
import { NavigationContainer } from '@react-navigation/native';
import * as Notifications from 'expo-notifications';

import {subscribepushservice,initpushservice } from '@henritrip/subscribepushservice'

initpushservice( "API_KEY" ,"https://push.henritrip.fr/api/token"  );

Notifications.setNotificationHandler({
  handleNotification: async () => ({
    shouldShowAlert: true,
    shouldPlaySound: false,
    shouldSetBadge: false,
  }),
});


async function registerForPushNotificationsAsync() {
  let token;
  if (Device.isDevice) {
    const { status: existingStatus } = await Notifications.getPermissionsAsync();
    let finalStatus = existingStatus;
    if (existingStatus !== 'granted') {
      const { status } = await Notifications.requestPermissionsAsync();
      finalStatus = status;
    }
    if (finalStatus !== 'granted') {
      alert('Failed to get push token for push notification!');
      return;
    }
    token = (await Notifications.getExpoPushTokenAsync()).data;
    console.log(token);
  } else {
    alert('Must use physical device for Push Notifications');
  }

  if (Platform.OS === 'android') {
    Notifications.setNotificationChannelAsync('default', {
      name: 'default',
      importance: Notifications.AndroidImportance.MAX,
      vibrationPattern: [0, 250, 250, 250],
      lightColor: '#FF231F7C',
    });

  }

await subscribepushservice(token)

  return token;
}




export default function App() {

  const [expoPushToken, setExpoPushToken] = useState('');
  const [notification, setNotification] = useState(false);
  const notificationListener = useRef();
  const responseListener = useRef();


  useEffect(() => {
    registerForPushNotificationsAsync().then(token => {
      
    console.log('token', token);  
      setExpoPushToken(token);
    });

    notificationListener.current = Notifications.addNotificationReceivedListener(notification => {
      const data=  notification.request.content.data
   if("campaign_id" in data)
   {
    subscribepushservice(null,{name:"OPEN_BY_NOTIF",campaign_id:data.campaign_id}).then((response)=>{})
   }
console.log( "FOREGROUND  RECEIVED " ,notification.request.content )
    //  setNotification(notification);
    });

    responseListener.current = Notifications.addNotificationResponseReceivedListener(response => {
      const data=  response.notification.request.content.data
      if("campaign_id" in data)
      {
        subscribepushservice(null,{name:"OPEN_BY_NOTIF",campaign_id:data.campaign_id}).then((response)=>{})
      }
   console.log( "BACKGROUND RECEIVED " ,response.notification.request.content )
      console.log(response);
    });

    return () => {
      Notifications.removeNotificationSubscription(notificationListener.current);
      Notifications.removeNotificationSubscription(responseListener.current);
    };
  }, []);

  return (
    <NavigationContainer
      linking={{
        config: {
          // Configuration for linking
        },
        async getInitialURL() {
          // First, you may want to do the default deep link handling
          // Check if app was opened from a deep link
          const url = await Linking.getInitialURL();
          console.log( " Listening  " ,url)
          if (url != null) {
            return url;
          }

          // Handle URL from expo push notifications
          const response = await Notifications.getLastNotificationResponseAsync();
                         
          return response?.notification.request.content.data.url;
        },
        subscribe(listener) {
          const onReceiveURL = ({ url }) => listener(url);

          // Listen to incoming links from deep linking
          Linking.addEventListener('url', onReceiveURL);

          // Listen to expo push notifications
          const subscription = Notifications.addNotificationResponseReceivedListener(response => {
const data=  response.notification.request.content.data
   if("campaign_id" in data)
   {
    subscribepushservice(null,{name:"OPEN_BY_NOTIF",campaign_id:data.campaign_id}).then((response)=>{})
   }
console.log( " RECEIVED " ,response.notification.request.content )

            const url = response.notification.request.content.data.url;
            console.log( " OPEN  " ,url)
            // Any custom logic to see whether the URL needs to be handled
            //...

            // Let React Navigation handle the URL
            listener(url);
          });

          return () => {
            // Clean up the event listeners
           // Linking.removeEventListener('url', onReceiveURL);
           console.log(Linking);
           subscription.remove();
          };
        },
      }}><View style={styles.container}>
     <LeafletView
    // The rest of your props, see the list below
    mapCenterPosition={  {lat:43.5904407 ,lng: 1.4456872}  }
    zoom = {20}
    
/><View style={{ flex: 1, alignItems: 'center', justifyContent: 'space-around' }}>
      <Text>Your expo push token: {expoPushToken}</Text>
      <View style={{ alignItems: 'center', justifyContent: 'center' }}>
        <Text>Title: {notification && notification.request.content.title} </Text>
        <Text>Body: {notification && notification.request.content.body}</Text>
        <Text>Data: {notification && JSON.stringify(notification.request.content.data)}</Text>
      </View>

    </View><StatusBar style="auto" /></View></NavigationContainer>
  );
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

License

This code is free to use under the terms of the MIT license.

1.0.3

11 months ago

1.0.2

11 months ago

1.0.1

11 months ago

1.0.0

11 months ago