aboutsummaryrefslogtreecommitdiff
path: root/src/utils/messages.ts
blob: dd29f31777999a18a1fa37e52e1b4c3ba3959655 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
import AsyncStorage from '@react-native-community/async-storage';
import moment from 'moment';
import {loadChatTokenService} from '../services/ChatService';
import {RootState} from '../store/rootReducer';
import {ChannelGroupedType} from '../types';
import {StreamChat} from 'stream-chat';

/**
 * Finds the difference in time in minutes
 * @param lastActive given time e.g. "2021-04-08T19:07:09.361300983Z"
 * @returns diff in minutes
 */
const _diffInMinutes = (lastActive: string | undefined) => {
  if (!lastActive) {
    return undefined;
  }
  return moment().diff(moment(lastActive), 'minutes');
};

/**
 * Formats the last activity status.
 *  - "Active now"          (≤ 5 minutes)
 *  - "Seen X minutes ago"  (5 > x ≥ 59 minutes)
 *  - "Seen X hours ago"    (x = [1, 2])
 *  - "Offline"
 * @param lastActive given time e.g. "2021-04-08T19:07:09.361300983Z"
 * @returns
 */
export const formatLastSeenText = (lastActive: string | undefined) => {
  const diff = _diffInMinutes(lastActive);
  if (!diff) {
    return 'Offline';
  }
  if (diff <= 5) {
    return 'Active now';
  }
  if (diff <= 59) {
    return `Seen ${diff} minutes ago`;
  }
  if (diff <= 180) {
    const hours = Math.floor(diff / 60);
    return `Seen ${hours} hours ago`;
  }
  return 'Offline';
};

/**
 * Checks if a lastActive timestamp is considered Online or not.
 *
 * A user is online if last active is ≤ 15 minutes.
 *
 * @param lastActive given time e.g. "2021-04-08T19:07:09.361300983Z"
 * @returns True if active
 */
export const isOnline = (lastActive: string | undefined) => {
  if (!lastActive) {
    return false;
  }
  const diff = _diffInMinutes(lastActive);
  if (!diff) {
    return false;
  }
  return diff <= 15;
};

/**
 * Gets the other member in the channel.
 * @param channel the current chat channel
 * @param state the current redux state
 * @returns other member or undefined
 */
export const getMember = (
  channel: ChannelGroupedType | undefined,
  state: RootState,
) => {
  if (!channel) {
    return undefined;
  }
  const loggedInUserId = state.user.user.userId;
  const otherMembers = channel
    ? Object.values(channel.state.members).filter(
        (member) => member.user?.id !== loggedInUserId,
      )
    : [];
  return otherMembers.length === 1 ? otherMembers[0] : undefined;
};

export const connectChatAccount = async (
  loggedInUserId: string,
  chatClient: StreamChat,
) => {
  try {
    await getChatToken();
    const chatToken = await AsyncStorage.getItem('chatToken');
    if (!chatClient.user && chatToken) {
      await chatClient.connectUser(
        {
          id: loggedInUserId,
        },
        chatToken,
      );
      return true;
    } else if (chatClient.user) {
      return true;
    } else {
      console.log('Unable to connect to stream. Empty chat token');
      return false;
    }
  } catch (err) {
    console.log('Error while connecting user to Stream: ', err);
    return false;
  }
};

export const getChatToken = async () => {
  try {
    const currentChatToken = await AsyncStorage.getItem('chatToken');
    if (currentChatToken === null) {
      const chatToken = await loadChatTokenService();
      await AsyncStorage.setItem('chatToken', chatToken);
    }
  } catch (err) {
    console.log(err);
  }
};

export const createChannel = async (
  loggedInUser: string,
  id: string,
  chatClient: any,
) => {
  try {
    const channel = chatClient.channel('messaging', {
      members: [loggedInUser, id],
    });
    await channel.watch();
    return channel;
  } catch (error) {
    console.log(error);
    throw error;
  }
};