暫無描述

Home_page.js 8.4KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  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 [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. const dimensions = Dimensions.get('window');
  112. const screenWidth = dimensions.width;
  113. return (
  114. <ImageBackground style={styles.stdcontainer} source={require('../../assets/yellow-white.jpg')}>
  115. <FlatList style={{
  116. flex: 1,
  117. width: screenWidth,
  118. }}
  119. data={threads}
  120. keyExtractor = {item => item._id}
  121. ItemSeparatorComponent={() => <Divider />}
  122. renderItem = {({item}) => (
  123. <TouchableOpacity
  124. onPress={() => navigation.navigate('Room', {thread: item})}
  125. >
  126. <List.Item
  127. title={item.name}
  128. titleNumberOfLines={1}
  129. titleStyle={styles.listTitle}
  130. descriptionStyle={styles.listDescription}
  131. descriptionNumberOfLines={1}
  132. />
  133. </TouchableOpacity>
  134. )}
  135. />
  136. <FlatList style={{
  137. flex: 1,
  138. width: screenWidth,
  139. }}
  140. data={appointments}
  141. keyExtractor = {item => item._id}
  142. ItemSeparatorComponent={() => <Divider />}
  143. renderItem = {({item}) => (
  144. <TouchableOpacity
  145. onPress={async () => {
  146. await sendPushNotification(expoPushToken);
  147. }}
  148. >
  149. <List.Item
  150. title={item.Month}
  151. titleNumberOfLines={1}
  152. titleStyle={styles.listTitle}
  153. descriptionStyle={styles.listDescription}
  154. descriptionNumberOfLines={1}
  155. />
  156. <List.Item
  157. title={item.Day}
  158. titleNumberOfLines={1}
  159. titleStyle={styles.listTitle}
  160. descriptionStyle={styles.listDescription}
  161. descriptionNumberOfLines={1}
  162. />
  163. <List.Item
  164. title={item.Time}
  165. titleNumberOfLines={1}
  166. titleStyle={styles.listTitle}
  167. descriptionStyle={styles.listDescription}
  168. descriptionNumberOfLines={1}
  169. />
  170. </TouchableOpacity>
  171. )}
  172. />
  173. <Text>Your expo push token: {expoPushToken}</Text>
  174. <View style={{ alignItems: 'center', justifyContent: 'center' }}>
  175. <Text>Title: {notification && notification.request.content.title} </Text>
  176. <Text>Body: {notification && notification.request.content.body}</Text>
  177. <Text>Data: {notification && JSON.stringify(notification.request.content.data)}</Text>
  178. </View>
  179. <Button
  180. title="Press to Send Notification"
  181. onPress={async () => {
  182. await sendPushNotification(expoPushToken);
  183. }}
  184. />
  185. <Button
  186. title='CrearChat'
  187. onPress={() => handleButtonPress()}
  188. />
  189. <Button
  190. title ='Hacer Busqueda'
  191. onPress= {() => navigation.navigate('Search')}
  192. />
  193. <Button
  194. title ='Logout'
  195. onPress= {() => firebase.auth().signOut()}
  196. />
  197. </ImageBackground>
  198. );
  199. }
  200. // Can use this function below, OR use Expo's Push Notification Tool-> https://expo.dev/notifications
  201. async function sendPushNotification(expoPushToken) {
  202. const message = {
  203. to: expoPushToken,
  204. sound: 'default',
  205. title: 'Original Title',
  206. body: 'And here is the body!',
  207. data: { someData: 'goes here' },
  208. };
  209. await fetch('https://exp.host/--/api/v2/push/send', {
  210. method: 'POST',
  211. headers: {
  212. Accept: 'application/json',
  213. 'Accept-encoding': 'gzip, deflate',
  214. 'Content-Type': 'application/json',
  215. },
  216. body: JSON.stringify(message),
  217. });
  218. }
  219. async function registerForPushNotificationsAsync() {
  220. let token;
  221. if (Constants.isDevice) {
  222. const { status: existingStatus } = await Notifications.getPermissionsAsync();
  223. let finalStatus = existingStatus;
  224. if (existingStatus !== 'granted') {
  225. const { status } = await Notifications.requestPermissionsAsync();
  226. finalStatus = status;
  227. }
  228. if (finalStatus !== 'granted') {
  229. alert('Failed to get push token for push notification!');
  230. return;
  231. }
  232. token = (await Notifications.getExpoPushTokenAsync()).data;
  233. console.log(token);
  234. } else {
  235. alert('Must use physical device for Push Notifications');
  236. }
  237. if (Platform.OS === 'android') {
  238. Notifications.setNotificationChannelAsync('default', {
  239. name: 'default',
  240. importance: Notifications.AndroidImportance.MAX,
  241. vibrationPattern: [0, 250, 250, 250],
  242. lightColor: '#FF231F7C',
  243. });
  244. }
  245. firebase.firestore().collection('Users').doc(firebase.auth().currentUser.uid).update({'push_token': token})
  246. return token;
  247. }
  248. const mapStateToProps = (store) => ({
  249. currentUser: store.userState.currentUser
  250. })
  251. const mapDispatchProps = (dispatch) => bindActionCreators({fetchUser}, dispatch);
  252. export default connect(mapStateToProps, mapDispatchProps)(Home_page);