No Description

Home_page.js 8.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. import React, {useState, useEffect, useRef} from 'react'
  2. import { Button, Text, View, StyleSheet, SafeAreaView} 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 [appointments, setAppointments] = useState([]);
  26. const [roomName, setRoomName] = useState('');
  27. const [expoPushToken, setExpoPushToken] = useState('');
  28. const [notification, setNotification] = useState(false);
  29. const notificationListener = useRef();
  30. const responseListener = useRef();
  31. useEffect(() => {
  32. registerForPushNotificationsAsync().then(token => setExpoPushToken(token));
  33. notificationListener.current = Notifications.addNotificationReceivedListener(notification => {
  34. setNotification(notification);
  35. });
  36. responseListener.current = Notifications.addNotificationResponseReceivedListener(response => {
  37. console.log(response);
  38. });
  39. const fire = firebase.firestore()
  40. .collection('THREADS')
  41. .where("members", "array-contains", firebase.auth().currentUser.uid)
  42. .onSnapshot(querySnapshot => {
  43. const threads = querySnapshot.docs.map(documentSnapshot => {
  44. return{
  45. _id:documentSnapshot.id,
  46. name:'',
  47. ...documentSnapshot.data()
  48. };
  49. });
  50. setThreads(threads);
  51. console.log(threads);
  52. if(loading){
  53. setLoading(false);
  54. }
  55. });
  56. const cita = firebase.firestore().collection('APPOINTMENTS').where('Day', '==', 8).onSnapshot(snapShot => {
  57. const appointments = snapShot.docs.map(docSnap => {
  58. return{
  59. _id:docSnap.id,
  60. Day:'',
  61. Month:'',
  62. Time:'',
  63. ...docSnap.data()
  64. };
  65. });
  66. setAppointments(appointments);
  67. console.log(appointments);
  68. });
  69. //return () => fire();
  70. return () => {
  71. Notifications.removeNotificationSubscription(notificationListener.current);
  72. Notifications.removeNotificationSubscription(responseListener.current);
  73. fire();
  74. cita();
  75. }
  76. }, []);
  77. if (loading) {
  78. return <Loading />;
  79. }
  80. const sendMessage = (token) => {
  81. fetch('https://exp.host/--/api/v2/push/send', {
  82. method: 'POST',
  83. headers: {
  84. Accept: 'application/json',
  85. 'Accept-encoding': 'gzip, deflate',
  86. 'Content-type': 'application/json',
  87. },
  88. body: JSON.stringify({
  89. to: token,
  90. title: 'Ernesto',
  91. body: 'Freehand message',
  92. data: { data: 'goes here' },
  93. _displayInForeground: true,
  94. }),
  95. });
  96. }
  97. function handleButtonPress() {
  98. firebase.firestore()
  99. .collection('THREADS')
  100. .add({
  101. name: 'PedroFecha',
  102. members: [
  103. firebase.auth().currentUser.uid,
  104. '02yOZHxFcGUX4MNwjeEbAlCShdu1'
  105. ]
  106. })
  107. //.then(() => {
  108. //navigation.navigate('allChats');
  109. //});
  110. }
  111. return (
  112. <ImageBackground style={styles.stdcontainer} source={require('../../assets/yellow-white.jpg')}>
  113. <FlatList
  114. data={threads}
  115. keyExtractor = {item => item._id}
  116. ItemSeparatorComponent={() => <Divider />}
  117. renderItem = {({item}) => (
  118. <TouchableOpacity
  119. onPress={() => navigation.navigate('Room', {thread: item})}
  120. >
  121. <List.Item
  122. title={item.name}
  123. titleNumberOfLines={1}
  124. titleStyle={styles.listTitle}
  125. descriptionStyle={styles.listDescription}
  126. descriptionNumberOfLines={1}
  127. />
  128. </TouchableOpacity>
  129. )}
  130. />
  131. <FlatList
  132. data={appointments}
  133. keyExtractor = {item => item._id}
  134. ItemSeparatorComponent={() => <Divider />}
  135. renderItem = {({item}) => (
  136. <TouchableOpacity
  137. onPress={async () => {
  138. await sendPushNotification(expoPushToken);
  139. }}
  140. >
  141. <List.Item
  142. title={item.Month}
  143. titleNumberOfLines={1}
  144. titleStyle={styles.listTitle}
  145. descriptionStyle={styles.listDescription}
  146. descriptionNumberOfLines={1}
  147. />
  148. <List.Item
  149. title={item.Day}
  150. titleNumberOfLines={1}
  151. titleStyle={styles.listTitle}
  152. descriptionStyle={styles.listDescription}
  153. descriptionNumberOfLines={1}
  154. />
  155. <List.Item
  156. title={item.Time}
  157. titleNumberOfLines={1}
  158. titleStyle={styles.listTitle}
  159. descriptionStyle={styles.listDescription}
  160. descriptionNumberOfLines={1}
  161. />
  162. </TouchableOpacity>
  163. )}
  164. />
  165. <Text>Your expo push token: {expoPushToken}</Text>
  166. <View style={{ alignItems: 'center', justifyContent: 'center' }}>
  167. <Text>Title: {notification && notification.request.content.title} </Text>
  168. <Text>Body: {notification && notification.request.content.body}</Text>
  169. <Text>Data: {notification && JSON.stringify(notification.request.content.data)}</Text>
  170. </View>
  171. <Button
  172. title="Press to Send Notification"
  173. onPress={async () => {
  174. await sendPushNotification(expoPushToken);
  175. }}
  176. />
  177. <Button
  178. title='CrearChat'
  179. onPress={() => handleButtonPress()}
  180. />
  181. <Button
  182. title ='Hacer Busqueda'
  183. onPress= {() => navigation.navigate('Search')}
  184. />
  185. <Button
  186. title ='Logout'
  187. onPress= {() => firebase.auth().signOut()}
  188. />
  189. </ImageBackground>
  190. );
  191. }
  192. // Can use this function below, OR use Expo's Push Notification Tool-> https://expo.dev/notifications
  193. async function sendPushNotification(expoPushToken) {
  194. const message = {
  195. to: expoPushToken,
  196. sound: 'default',
  197. title: 'Original Title',
  198. body: 'And here is the body!',
  199. data: { someData: 'goes here' },
  200. };
  201. await fetch('https://exp.host/--/api/v2/push/send', {
  202. method: 'POST',
  203. headers: {
  204. Accept: 'application/json',
  205. 'Accept-encoding': 'gzip, deflate',
  206. 'Content-Type': 'application/json',
  207. },
  208. body: JSON.stringify(message),
  209. });
  210. }
  211. async function registerForPushNotificationsAsync() {
  212. let token;
  213. if (Constants.isDevice) {
  214. const { status: existingStatus } = await Notifications.getPermissionsAsync();
  215. let finalStatus = existingStatus;
  216. if (existingStatus !== 'granted') {
  217. const { status } = await Notifications.requestPermissionsAsync();
  218. finalStatus = status;
  219. }
  220. if (finalStatus !== 'granted') {
  221. alert('Failed to get push token for push notification!');
  222. return;
  223. }
  224. token = (await Notifications.getExpoPushTokenAsync()).data;
  225. console.log(token);
  226. } else {
  227. alert('Must use physical device for Push Notifications');
  228. }
  229. if (Platform.OS === 'android') {
  230. Notifications.setNotificationChannelAsync('default', {
  231. name: 'default',
  232. importance: Notifications.AndroidImportance.MAX,
  233. vibrationPattern: [0, 250, 250, 250],
  234. lightColor: '#FF231F7C',
  235. });
  236. }
  237. firebase.firestore().collection('Users').doc(firebase.auth().currentUser.uid).update({'push_token': token})
  238. return token;
  239. }
  240. const mapStateToProps = (store) => ({
  241. currentUser: store.userState.currentUser
  242. })
  243. const mapDispatchProps = (dispatch) => bindActionCreators({fetchUser}, dispatch);
  244. export default connect(mapStateToProps, mapDispatchProps)(Home_page);