No Description

Home_page.js 7.8KB

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