Advertisement
anhhtz

Untitled

Oct 11th, 2018
265
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import React from 'react';
  2. import {AsyncStorage, View, Text, TouchableHighlight, Alert, FlatList, DeviceEventEmitter, Platform} from 'react-native';
  3. import firebase from 'react-native-firebase';
  4. import { Notification, NotificationOpen } from 'react-native-firebase';
  5. import NotifyPayload from './NotifyPayload';
  6. import RowNotify from './RowNotify';
  7. import { RemoteMessage } from 'react-native-firebase';
  8.  
  9. import bsStyle from '../assets/BsStyle';
  10.  
  11. class HomeScreen extends React.Component {
  12.   constructor(props) {
  13.     super(props);
  14.     this.state = {
  15.       listNotify: false
  16.     }
  17.   }
  18.  
  19.   static navigationOptions = {
  20.     title: 'Home',
  21.   };
  22.  
  23.   async _handleNewNotify(tNotify) {
  24.     let listString = await AsyncStorage.getItem('list_notifications')
  25.     console.log('begin handle');
  26.     let listNotify = JSON.parse(listString);
  27.     let notify = new NotifyPayload(tNotify.data);
  28.     if (listNotify && listNotify.length > 0) {
  29.       if (!listNotify.find(notif => notif.key == notify.key)) {
  30.         listNotify.push(notify);
  31.       }
  32.     } else {
  33.       listNotify = [notify];
  34.     }
  35.     await AsyncStorage.setItem('list_notifications', JSON.stringify(listNotify));
  36.     DeviceEventEmitter.emit('notifyChange', {type: 'add', data: {
  37.       key: notify.key
  38.     }});
  39.     this.getNewestNotifications();
  40.     console.log('Done in handle');
  41.   }
  42.  
  43.   componentDidMount() {
  44.     console.log('didmounttt');
  45.     // Check permission
  46.     firebase.messaging().hasPermission()
  47.       .then(enabled => {
  48.         if (!enabled) {
  49.           firebase.messaging().requestPermission()
  50.           .then(() => {
  51.             console.log('subcribe after reqest permisssion');
  52.             firebase.messaging().subscribeToTopic('rain')
  53.           })
  54.           .catch(error => {
  55.             console.log(error);
  56.           });
  57.         } else {
  58.           firebase.messaging().subscribeToTopic('rain');
  59.           console.log('Subcribed!');
  60.         }
  61.       })
  62.       .catch(error => {
  63.         console.log(error);
  64.       });
  65.  
  66.     DeviceEventEmitter.addListener('notifyChange', () => {
  67.       if (this._isMounted) {
  68.         this.getNewestNotifications();
  69.       }
  70.     });
  71.     this._isMounted = true;
  72.     this.messageListener = firebase.messaging().onMessage((message: RemoteMessage) => {
  73.       // Process your message as required
  74.      this._handleNewNotify(message)
  75.         .then(console.log('Done handle message'));
  76.     });
  77.  
  78.     // Check if App was opened by a notification
  79.     this.backgroundNotifyListener = firebase.notifications().getInitialNotification()
  80.       .then((notificationOpen: NotificationOpen) => {
  81.         if (notificationOpen) {
  82.           console.log('App opened by notification');
  83.           // const action = notificationOpen.action;
  84.           const notification: Notification = notificationOpen.notification;
  85.           firebase.notifications().removeDeliveredNotification(notification.notificationId);
  86.           this._handleNewNotify(notification);
  87.         }
  88.       });
  89.     if (Platform.OS == 'android') {
  90.     const channel = new firebase.notifications.Android.Channel('rain', 'Weather Rain', firebase.notifications.Android.Importance.Max)
  91.       .setDescription('Get weather information info');
  92.     // Create the channel
  93.     firebase.notifications().android.createChannel(channel);
  94.   }
  95.  
  96.   this.notificationListener = firebase.notifications().onNotification((notification: Notification) => {
  97.     console.log('Process and display notification when app is opened');
  98.     // Process notification as required
  99.     notification
  100.       .android.setChannelId('rain')
  101.       .android.setSmallIcon('ic_launcher');
  102.     firebase.notifications()
  103.       .displayNotification(notification);
  104.   });
  105.   }
  106.   componentWillUnmount() {
  107.     DeviceEventEmitter.removeListener('notifyChange');
  108.     this.backgroundNotifyListener();
  109.     this.notificationListener();
  110.     this.messageListener();
  111.     DeviceEventEmitter.removeAllListeners();
  112.     this._isMounted = false;
  113.   }
  114.  
  115.   getNewestNotifications(limit = 5) {
  116.     AsyncStorage.getItem('list_notifications')
  117.       .then(res => {
  118.         if (res) {
  119.           let listNotify = JSON.parse(res);
  120.           if (listNotify.length > limit) {
  121.             listNotify = listNotify.slice(1).slice(0 - limit);
  122.           }
  123.           this.setState({listNotify: listNotify.reverse()})
  124.         } else {
  125.           this.setState({listNotify: []});
  126.         }
  127.       });
  128.   }
  129.  
  130.   _confirmResetNotify() {
  131.     Alert.alert(
  132.       'Confirm delete',
  133.       'Area you sure want to delete all notifications?',
  134.       [
  135.         {text: 'Cancel', onPress: () => {}, style: 'cancel'},
  136.         {text: 'OK', onPress: () => {this._resetNotify()}},
  137.       ],
  138.       { cancelable: false }
  139.     )
  140.   }
  141.  
  142.   _resetNotify() {
  143.     AsyncStorage.setItem('list_notifications', '').then(() => {
  144.       DeviceEventEmitter.emit('notifyChange');
  145.     })
  146.  }
  147.  
  148.   componentWillMount() {
  149.     this.getNewestNotifications();
  150.   }
  151.  
  152.   render() {
  153.     const { navigate } = this.props.navigation;
  154.     if (this.state.listNotify !== false) {
  155.       if (this.state.listNotify.length > 0) {
  156.         return (
  157.           <View>
  158.             <FlatList
  159.               data={this.state.listNotify}
  160.               renderItem={({item}) => <RowNotify notify={item} navigate={navigate}/>
  161.               }
  162.               keyExtractor={(item) => item.key}
  163.             />
  164.             <View style={{flex: 1, flexDirection: 'row', justifyContent: 'center'}}>
  165.               <TouchableHighlight underlayColor="white" style={[bsStyle.btn, homeStyle.btn, bsStyle.btnSuccess]} onPress={() => navigate('List')}>
  166.                 <View style={bsStyle.textCenter}>
  167.                   <Text style={bsStyle.cWhite}>See All</Text>
  168.                 </View>
  169.               </TouchableHighlight>
  170.               <TouchableHighlight underlayColor="white" style={[bsStyle.btn, homeStyle.btn, bsStyle.btnSuccess, homeStyle.btnReset]} onPress={() => this._confirmResetNotify()}>
  171.                 <View style={bsStyle.textCenter}>
  172.                   <Text style={bsStyle.cWhite}>Reset</Text>
  173.                 </View>
  174.               </TouchableHighlight>
  175.             </View>
  176.           </View>
  177.         )
  178.       } else {
  179.         return (<View style={bsStyle.emptyStatusCover}><Text>You have no notification!</Text></View>)
  180.       }
  181.     } else {
  182.       return (<View style={bsStyle.emptyStatusCover}><Text>Loading...</Text></View>)
  183.     }
  184.   }
  185. }
  186.  
  187. var homeStyle = {
  188.   btn: {
  189.     marginTop: 10,
  190.     width: 120,
  191.     height: 40,
  192.     justifyContent: 'center'
  193.   },
  194.   btnReset: {
  195.     marginLeft: 20,
  196.     backgroundColor: '#dc3545',
  197.   }
  198. }
  199.  
  200. export default HomeScreen;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement