aboutsummaryrefslogtreecommitdiff
path: root/src/utils/users.ts
blob: 64ad10e9563ddd582267fab35fc40dfe79279c65 (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
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
import AsyncStorage from '@react-native-community/async-storage';
import {Alert} from 'react-native';
import ImagePicker from 'react-native-image-crop-picker';
import {INTEGRATED_SOCIAL_LIST} from '../constants';
import {isUserBlocked, loadSocialPosts, patchEditProfile} from '../services';
import {
  loadAllSocials,
  loadBlockedList,
  loadFriendsData,
  loadRecentlySearched,
  loadUserData,
  loadUserMoments,
  loadUserNotifications,
  logout,
} from '../store/actions';
import {NO_SOCIAL_ACCOUNTS} from '../store/initialStates';
import {loadUserMomentCategories} from './../store/actions/momentCategories';
import {loadUserX} from './../store/actions/userX';
import {AppDispatch} from './../store/configureStore';
import {RootState} from './../store/rootReducer';
import {
  ProfileInfoType,
  ProfilePreviewType,
  ScreenType,
  UserType,
} from './../types/types';

const loadData = async (dispatch: AppDispatch, user: UserType) => {
  await Promise.all([
    dispatch(loadUserData(user)),
    dispatch(loadFriendsData(user.userId)),
    dispatch(loadUserMomentCategories(user.userId)),
    dispatch(loadUserMoments(user.userId)),
    dispatch(loadUserNotifications()),
    dispatch(loadAllSocials(user.userId)),
    dispatch(loadBlockedList(user.userId)),
    dispatch(loadRecentlySearched()),
  ]);
};

/**
 * This tries to log the user in present with the AsyncStorage if user.userId is empty
 * Else it tries to login the user passed in
 * @param dispatch This is the dispatch object from the redux store
 * @param user The user if at all any
 */
export const userLogin = async (dispatch: AppDispatch, user: UserType) => {
  try {
    let localUser = {...user};
    if (!user.userId) {
      const [id, username, token] = await Promise.all([
        AsyncStorage.getItem('userId'),
        AsyncStorage.getItem('username'),
        AsyncStorage.getItem('token'),
      ]);
      if (id && username && token) {
        localUser = {...localUser, userId: id, username: username};
      } else {
        return;
      }
    } else {
      await Promise.all([
        AsyncStorage.setItem('userId', user.userId),
        AsyncStorage.setItem('username', user.username),
      ]);
    }
    await loadData(dispatch, localUser);
  } catch (error) {
    console.log(error);
  }
};

/**
 * This tries to load data userX passed in
 * @param dispatch This is the dispatch object from the redux store
 * @param user The user
 */
export const fetchUserX = async (
  dispatch: AppDispatch,
  user: UserType,
  screenType: ScreenType,
) => {
  try {
    await Promise.all([dispatch(loadUserX(user, screenType))]);
  } catch (error) {
    console.log(error);
  }
};

/**
 * This function checks if the userX slice of our store contains the given user for the provided Screen
 */
export const userXInStore = (
  state: RootState,
  screen: ScreenType,
  userId: string,
) => {
  const userX = state.userX[screen];
  return userX && userId in userX && userX[userId].user.userId;
};

/**
 * Abstracted the code to laod all socials out.
 * @param userId userId for whom socials should be fetched
 */
export const loadAllSocialsForUser = async (userId: string, token?: string) => {
  if (!token) {
    token = (await AsyncStorage.getItem('token')) ?? '';
  }
  let socials = NO_SOCIAL_ACCOUNTS;
  try {
    const fetchedSocials = await Promise.all(
      INTEGRATED_SOCIAL_LIST.map((socialType) =>
        loadSocialPosts(userId, socialType, token).then((data) => ({
          key: socialType,
          data,
        })),
      ),
    );
    for (const fetchedSocial of fetchedSocials) {
      socials = {...socials, [fetchedSocial.key]: fetchedSocial.data};
    }
    return socials;
  } catch (error) {
    console.log(error);
  }
};

/**
 * Push the user out of system if token is not present in async storage
 * @param dispatch
 */
export const getTokenOrLogout = async (dispatch: Function): Promise<string> => {
  const token = await AsyncStorage.getItem('token');
  if (!token) {
    dispatch(logout());
    return '';
  }
  return token;
};

/**
 * Creates ProfilePreviewType of a user using UserType && ProfileType
 * @param passedInUser This is the UserType of the user
 * @param passedInProfile This is the ProfileType of the user
 */
export const getUserAsProfilePreviewType = (
  passedInUser: UserType,
  passedInProfile: ProfileInfoType,
): ProfilePreviewType => {
  const fullName = passedInProfile.name.split(' ');
  return {
    id: passedInUser.userId,
    username: passedInUser.username,
    first_name: fullName[0],
    last_name: fullName[1],
  };
};

export const checkIfUserIsBlocked = async (
  userId: string,
  dispatch: Function,
  loggedInUser: UserType,
) => {
  const token = await AsyncStorage.getItem('token');
  if (!token) {
    dispatch(logout());
    return false;
  }
  return await isUserBlocked(userId, loggedInUser.userId, token);
};

/**
 * Used to determine whether the logged-in user is able to view userX's private
 * information or not.
 *
 * @param state redux store's root state
 * @param userXId target userX's id
 * @param screenType current screen type
 * @returns true if abel to view private info, false otherwise
 */
export const canViewProfile = (
  state: RootState,
  userXId: string | undefined,
  screenType: ScreenType,
) => {
  // own profile
  if (!userXId || state.user.user.userId === userXId) {
    return true;
  }
  // not private
  if (!(userXId && state.userX[screenType][userXId].profile.is_private)) {
    return true;
  }
  // is friend
  if (
    userXId &&
    state.userX[screenType][userXId].profile.friendship_status === 'friends'
  ) {
    return true;
  }
  return false;
};

export const navigateToProfile = async (
  state: RootState,
  dispatch: any,
  navigation: any,
  screenType: ScreenType,
  user: UserType,
) => {
  const loggedInUserId = state.user.user.userId;
  const {userId, username} = user;
  if (!userXInStore(state, screenType, userId)) {
    await fetchUserX(
      dispatch,
      {userId: userId, username: username},
      screenType,
    );
  }
  navigation.push('Profile', {
    userXId: userId === loggedInUserId ? undefined : userId,
    screenType,
  });
};

/* Function to open imagepicker and
 * select images, which are sent to
 * the database to update the profile
 */
export const patchProfile = async (
  title: 'profile' | 'header',
  userId: string,
) => {
  let imageSettings = {};
  let screenTitle: string;
  let requestTitle: string;
  let fileName: string;
  switch (title) {
    case 'header':
      screenTitle = 'Select Header Picture';
      requestTitle = 'largeProfilePicture';
      fileName = 'large_profile_pic.jpg';
      imageSettings = {
        smartAlbums: [
          'Favorites',
          'RecentlyAdded',
          'SelfPortraits',
          'Screenshots',
          'UserLibrary',
        ],
        width: 580,
        height: 580,
        cropping: true,
        cropperToolbarTitle: screenTitle,
        mediaType: 'photo',
      };
      break;
    case 'profile':
      screenTitle = 'Select Profile Picture';
      requestTitle = 'smallProfilePicture';
      fileName = 'small_profile_pic.jpg';
      imageSettings = {
        smartAlbums: [
          'Favorites',
          'RecentlyAdded',
          'SelfPortraits',
          'Screenshots',
          'UserLibrary',
        ],
        width: 580,
        height: 580,
        cropping: true,
        cropperToolbarTitle: screenTitle,
        mediaType: 'photo',
        cropperCircleOverlay: true,
      };
      break;
    default:
      screenTitle = '';
      requestTitle = '';
      fileName = '';
  }

  return await ImagePicker.openPicker(imageSettings)
    .then((picture) => {
      if ('path' in picture) {
        const request = new FormData();
        request.append(requestTitle, {
          uri: picture.path,
          name: fileName,
          type: 'image/jpg',
        });

        return patchEditProfile(request, userId)
          .then((_) => {
            return true;
          })
          .catch((error) => {
            Alert.alert(error);
            return false;
          });
      }
    })
    .catch((_) => {
      return false;
    });
};