No Description

Home_page.js 6.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. import React, {useState, useEffect, useRef} from 'react'
  2. import { Button, Text, View, StyleSheet} from 'react-native'
  3. import {FlatList, ListViewBase } from 'react-native'
  4. import {TouchableOpacity} from 'react-native-gesture-handler'
  5. import {List, Divider} from 'react-native-paper'
  6. import Loading from './Loading'
  7. import firebase from 'firebase';
  8. import { styles } from "../../config/styles";
  9. import { TextInput, TouchableWithoutFeedback, Keyboard, ImageBackground} from "react-native";
  10. import { connect } from 'react-redux'
  11. import { bindActionCreators } from 'redux'
  12. import { fetchUser } from '../../redux/actions/index'
  13. import Constants from 'expo-constants';
  14. import * as Notifications from 'expo-notifications';
  15. Notifications.setNotificationHandler({
  16. handleNotification: async () => ({
  17. shouldShowAlert: true,
  18. shouldPlaySound: true,
  19. shouldSetBadge: false,
  20. }),
  21. });
  22. export function Home_page({navigation}) {
  23. const [threads, setThreads] = useState([]);
  24. const [loading, setLoading] = useState(true);
  25. const [roomName, setRoomName] = useState('');
  26. const [expoPushToken, setExpoPushToken] = useState('');
  27. const [notification, setNotification] = useState(false);
  28. const notificationListener = useRef();
  29. const responseListener = useRef();
  30. useEffect(() => {
  31. registerForPushNotificationsAsync().then(token => setExpoPushToken(token));
  32. notificationListener.current = Notifications.addNotificationReceivedListener(notification => {
  33. setNotification(notification);
  34. });
  35. responseListener.current = Notifications.addNotificationResponseReceivedListener(response => {
  36. console.log(response);
  37. });
  38. const fire = firebase.firestore()
  39. .collection('THREADS')
  40. .where("members", "array-contains", firebase.auth().currentUser.uid)
  41. .onSnapshot(querySnapshot => {
  42. const threads = querySnapshot.docs.map(documentSnapshot => {
  43. return{
  44. _id:documentSnapshot.id,
  45. name:'',
  46. ...documentSnapshot.data()
  47. };
  48. });
  49. setThreads(threads);
  50. if(loading){
  51. setLoading(false);
  52. }
  53. });
  54. //return () => fire();
  55. return () => {
  56. Notifications.removeNotificationSubscription(notificationListener.current);
  57. Notifications.removeNotificationSubscription(responseListener.current);
  58. fire();
  59. }
  60. }, []);
  61. if (loading) {
  62. return <Loading />;
  63. }
  64. const sendMessage = (token) => {
  65. fetch('https://exp.host/--/api/v2/push/send', {
  66. method: 'POST',
  67. headers: {
  68. Accept: 'application/json',
  69. 'Accept-encoding': 'gzip, deflate',
  70. 'Content-type': 'application/json',
  71. },
  72. body: JSON.stringify({
  73. to: token,
  74. title: 'Ernesto',
  75. body: 'Freehand message',
  76. data: { data: 'goes here' },
  77. _displayInForeground: true,
  78. }),
  79. });
  80. }
  81. function handleButtonPress() {
  82. firebase.firestore()
  83. .collection('THREADS')
  84. .add({
  85. name: 'PedroFecha',
  86. members: [
  87. firebase.auth().currentUser.uid,
  88. '02yOZHxFcGUX4MNwjeEbAlCShdu1'
  89. ]
  90. })
  91. //.then(() => {
  92. //navigation.navigate('allChats');
  93. //});
  94. }
  95. return (
  96. <ImageBackground style={styles.stdcontainer} source={require('../../assets/yellow-white.jpg')}>
  97. <FlatList
  98. data={threads}
  99. keyExtractor = {item => item._id}
  100. ItemSeparatorComponent={() => <Divider />}
  101. renderItem = {({item}) => (
  102. <TouchableOpacity
  103. onPress={() => navigation.navigate('Room', {thread: item})}
  104. >
  105. <List.Item
  106. title={item.name}
  107. titleNumberOfLines={1}
  108. titleStyle={styles.listTitle}
  109. descriptionStyle={styles.listDescription}
  110. descriptionNumberOfLines={1}
  111. />
  112. </TouchableOpacity>
  113. )}
  114. />
  115. <Text>Your expo push token: {expoPushToken}</Text>
  116. <View style={{ alignItems: 'center', justifyContent: 'center' }}>
  117. <Text>Title: {notification && notification.request.content.title} </Text>
  118. <Text>Body: {notification && notification.request.content.body}</Text>
  119. <Text>Data: {notification && JSON.stringify(notification.request.content.data)}</Text>
  120. </View>
  121. <Button
  122. title="Press to Send Notification"
  123. onPress={async () => {
  124. await sendPushNotification(expoPushToken);
  125. }}
  126. />
  127. <Button
  128. title='CrearChat'
  129. onPress={() => handleButtonPress()}
  130. />
  131. <Button
  132. title ='Hacer Busqueda'
  133. onPress= {() => navigation.navigate('Search')}
  134. />
  135. <Button
  136. title ='Logout'
  137. onPress= {() => firebase.auth().signOut()}
  138. />
  139. <Button
  140. title ='SendMessage'
  141. onPress= {() => sendMessage(expoPushToken)}
  142. />
  143. </ImageBackground>
  144. );
  145. }
  146. // Can use this function below, OR use Expo's Push Notification Tool-> https://expo.dev/notifications
  147. async function sendPushNotification(expoPushToken) {
  148. const message = {
  149. to: expoPushToken,
  150. sound: 'default',
  151. title: 'Original Title',
  152. body: 'And here is the body!',
  153. data: { someData: 'goes here' },
  154. };
  155. await fetch('https://exp.host/--/api/v2/push/send', {
  156. method: 'POST',
  157. headers: {
  158. Accept: 'application/json',
  159. 'Accept-encoding': 'gzip, deflate',
  160. 'Content-Type': 'application/json',
  161. },
  162. body: JSON.stringify(message),
  163. });
  164. }
  165. async function registerForPushNotificationsAsync() {
  166. let token;
  167. if (Constants.isDevice) {
  168. const { status: existingStatus } = await Notifications.getPermissionsAsync();
  169. let finalStatus = existingStatus;
  170. if (existingStatus !== 'granted') {
  171. const { status } = await Notifications.requestPermissionsAsync();
  172. finalStatus = status;
  173. }
  174. if (finalStatus !== 'granted') {
  175. alert('Failed to get push token for push notification!');
  176. return;
  177. }
  178. token = (await Notifications.getExpoPushTokenAsync()).data;
  179. console.log(token);
  180. } else {
  181. alert('Must use physical device for Push Notifications');
  182. }
  183. if (Platform.OS === 'android') {
  184. Notifications.setNotificationChannelAsync('default', {
  185. name: 'default',
  186. importance: Notifications.AndroidImportance.MAX,
  187. vibrationPattern: [0, 250, 250, 250],
  188. lightColor: '#FF231F7C',
  189. });
  190. }
  191. firebase.firestore().collection('Users').doc(firebase.auth().currentUser.uid).update({'push_token': token})
  192. return token;
  193. }
  194. const mapStateToProps = (store) => ({
  195. currentUser: store.userState.currentUser
  196. })
  197. const mapDispatchProps = (dispatch) => bindActionCreators({fetchUser}, dispatch);
  198. export default connect(mapStateToProps, mapDispatchProps)(Home_page);