utils.ts 5.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  1. import moment from 'moment';
  2. import * as Notifications from 'expo-notifications';
  3. import { Alert, Platform } from 'react-native';
  4. import { NAVIGATION_PAGES } from 'src/types';
  5. import { storage, StoreType } from 'src/storage';
  6. import { Image as ImageCompressor, Video as VideoCompressor } from 'react-native-compressor';
  7. import { FileSystem } from 'src/utils';
  8. import Share from 'react-native-share';
  9. import { APP_VERSION } from 'src/constants';
  10. export const formatDate = (dateString: Date): string => {
  11. const inputDate = moment.utc(dateString).local();
  12. const today = moment().local();
  13. const yesterday = moment().local().subtract(1, 'days');
  14. if (inputDate.isSame(today, 'day')) {
  15. return inputDate.format('HH:mm');
  16. }
  17. if (inputDate.isSame(yesterday, 'day')) {
  18. return 'yesterday';
  19. }
  20. if (!inputDate.isSame(today, 'year')) {
  21. return inputDate.format('DD.MM.YYYY');
  22. }
  23. return inputDate.format('DD.MM');
  24. };
  25. export const dismissChatNotifications = async (
  26. chatWithUserId: number | string,
  27. isSubscribed: boolean,
  28. setModalInfo: (data: any) => void,
  29. navigation: any
  30. ) => {
  31. const { status } = await Notifications.getPermissionsAsync();
  32. const askedOnce = storage.get('askedNotificationPermission', StoreType.BOOLEAN) ?? false;
  33. if ((status !== 'granted' || !isSubscribed) && !askedOnce) {
  34. setModalInfo({
  35. visible: true,
  36. type: 'success',
  37. message:
  38. 'To use this feature we need your permission to access your notifications. You will be redirected to the notification settings screen where you need to enable them.',
  39. action: () => {
  40. navigation.navigate(NAVIGATION_PAGES.NOTIFICATIONS);
  41. setModalInfo({ visible: false });
  42. }
  43. });
  44. storage.set('askedNotificationPermission', true);
  45. return;
  46. }
  47. const getNotificationData = (notification: Notifications.Notification) => {
  48. if (Platform.OS === 'android') {
  49. const data = notification.request.content.data;
  50. if (data?.params) {
  51. try {
  52. return JSON.parse(data?.params) ?? {};
  53. } catch (error) {
  54. console.error('Error parsing params:', error);
  55. return {};
  56. }
  57. } else {
  58. Notifications.dismissNotificationAsync(notification.request.identifier);
  59. return {};
  60. }
  61. } else {
  62. const data = (notification.request.trigger as Notifications.PushNotificationTrigger)?.payload;
  63. if (data?.params) {
  64. try {
  65. return JSON.parse(data.params as string) ?? {};
  66. } catch (error) {
  67. console.error('Error parsing params:', error);
  68. return {};
  69. }
  70. }
  71. }
  72. };
  73. const clearNotificationsFromUser = async (userId: number | string) => {
  74. const presentedNotifications = await Notifications.getPresentedNotificationsAsync();
  75. presentedNotifications.forEach((notification) => {
  76. const parsedParams = getNotificationData(notification);
  77. const conversation_with_user = parsedParams?.id ?? parsedParams?.group_token;
  78. if (conversation_with_user === userId) {
  79. Notifications.dismissNotificationAsync(notification.request.identifier);
  80. }
  81. });
  82. };
  83. await clearNotificationsFromUser(chatWithUserId);
  84. Notifications.setNotificationHandler({
  85. handleNotification: async (notification) => {
  86. let conversation_with_user = 0;
  87. const parsedParams = getNotificationData(notification);
  88. conversation_with_user = parsedParams?.id ?? parsedParams?.group_token;
  89. if (conversation_with_user === chatWithUserId) {
  90. return {
  91. shouldShowAlert: false,
  92. shouldShowBanner: false,
  93. shouldShowList: false,
  94. shouldPlaySound: false,
  95. shouldSetBadge: false
  96. };
  97. }
  98. return {
  99. shouldShowAlert: true,
  100. shouldShowBanner: true,
  101. shouldShowList: true,
  102. shouldPlaySound: false,
  103. shouldSetBadge: false
  104. };
  105. }
  106. });
  107. return () => {
  108. Notifications.setNotificationHandler({
  109. handleNotification: async () => ({
  110. shouldShowAlert: true,
  111. shouldShowBanner: true,
  112. shouldShowList: true,
  113. shouldPlaySound: false,
  114. shouldSetBadge: false
  115. })
  116. });
  117. };
  118. };
  119. export const isMessageEdited = (edits: string) => {
  120. try {
  121. const parsedEdits = JSON.parse(edits);
  122. return Array.isArray(parsedEdits) && parsedEdits.length > 0;
  123. } catch (error) {
  124. return false;
  125. }
  126. };
  127. export const compressImageWithProgress = (
  128. uri: string,
  129. onProgress: (p: number) => void
  130. ): Promise<string> => {
  131. return ImageCompressor.compress(uri, {
  132. compressionMethod: 'auto',
  133. progressDivider: 10,
  134. downloadProgress: (progress) => {
  135. onProgress(progress);
  136. }
  137. });
  138. };
  139. export const compressVideoWithProgress = (
  140. uri: string,
  141. onProgress: (p: number) => void
  142. ): Promise<string> => {
  143. return VideoCompressor.compress(uri, {}, (progress) => {
  144. onProgress(progress);
  145. });
  146. };
  147. export async function downloadImageFromViewer(uri: string, token: string) {
  148. if (!uri) return;
  149. try {
  150. if (uri.startsWith('file://')) {
  151. await Share.open({
  152. url: uri,
  153. failOnCancel: false
  154. });
  155. return;
  156. }
  157. const fileExt = 'jpg';
  158. const fileName = `image_${Date.now()}.${fileExt}`;
  159. const fileUri = `${FileSystem.cacheDirectory}${fileName}`;
  160. const { uri: localUri } = await FileSystem.downloadAsync(uri, fileUri, {
  161. headers: {
  162. Nmtoken: token,
  163. 'App-Version': APP_VERSION,
  164. Platform: Platform.OS
  165. }
  166. });
  167. await Share.open({
  168. url: localUri,
  169. type: 'image/jpeg',
  170. failOnCancel: false
  171. });
  172. } catch (e) {
  173. Alert.alert('Error', 'Failed to save image');
  174. }
  175. }