import AsyncStorage from '@react-native-community/async-storage'; import moment from 'moment'; import {Alert} from 'react-native'; import { EDIT_PROFILE_ENDPOINT, GET_FB_POSTS_ENDPOINT, GET_IG_POSTS_ENDPOINT, GET_TWITTER_POSTS_ENDPOINT, HEADER_PHOTO_ENDPOINT, PASSWORD_RESET_ENDPOINT, PROFILE_INFO_ENDPOINT, PROFILE_PHOTO_ENDPOINT, REGISTER_ENDPOINT, SEND_OTP_ENDPOINT, TAGG_CUSTOMER_SUPPORT, USER_PROFILE_ENDPOINT, USER_PROFILE_VISITED_ENDPOINT, VERIFY_OTP_ENDPOINT, } from '../constants'; import { ERROR_DOUBLE_CHECK_CONNECTION, ERROR_DUP_OLD_PWD, ERROR_INVALID_PWD_CODE, ERROR_PROFILE_UPDATE_SHORT, ERROR_PWD_ACCOUNT, ERROR_SOMETHING_WENT_WRONG, ERROR_SOMETHING_WENT_WRONG_REFRESH, ERROR_VERIFICATION_FAILED_SHORT, SUCCESS_PWD_RESET, SUCCESS_VERIFICATION_CODE_SENT, } from '../constants/strings'; import {loadUserData} from '../store/actions'; import { ProfileInfoType, ProfileType, SocialAccountType, UserType, } from '../types'; export const loadProfileInfo = async (token: string, userId: string) => { try { const response = await fetch(PROFILE_INFO_ENDPOINT + `${userId}/`, { method: 'GET', headers: { Authorization: 'Token ' + token, }, }); const status = response.status; if (status === 200) { const data: ProfileInfoType = await response.json(); const birthday = data.birthday; return { ...data, birthday: birthday && moment(birthday).format('YYYY-MM-DD'), }; } else { throw 'Unable to load profile data'; } } catch (error) { Alert.alert(ERROR_SOMETHING_WENT_WRONG_REFRESH); } }; export const getProfilePic = async ( token: string, userId: string, type: 'profile' | 'header', ) => { try { const url = type === 'profile' ? PROFILE_PHOTO_ENDPOINT : HEADER_PHOTO_ENDPOINT; const response = await fetch(url + `${userId}/`, { method: 'GET', headers: { Authorization: 'Token ' + token, }, }); if (response.status === 200) { return (await response.json()).url; } } catch (error) { console.log(error); } }; export const updateProfileVisibility = async ( token: string, user: UserType, isPrivateAccount: Boolean, dispatch: Function, ) => { try { const url = EDIT_PROFILE_ENDPOINT + `${user.userId}/`; const request = new FormData(); request.append('is_private', isPrivateAccount ? 'True' : 'False'); let response = await fetch(url, { method: 'PATCH', headers: { 'Content-Type': 'multipart/form-data', Authorization: 'Token ' + token, }, body: request, }); const {status} = response; let data = await response.json(); if (status === 200) { await dispatch(loadUserData(user)); } else if (status >= 400) { Alert.alert( ERROR_PROFILE_UPDATE_SHORT, data.error || 'Something went wrong! 😭', ); } } catch (error) { Alert.alert(ERROR_PROFILE_UPDATE_SHORT, ERROR_DOUBLE_CHECK_CONNECTION); return { name: 'Profile update error', description: error, }; } }; const integratedSocialPostsEndpoints: {[social: string]: string} = { Facebook: GET_FB_POSTS_ENDPOINT, Instagram: GET_IG_POSTS_ENDPOINT, Twitter: GET_TWITTER_POSTS_ENDPOINT, }; export const loadSocialPosts: ( userId: string, socialType: string, token?: string, ) => Promise = async (userId, socialType, token) => { if (!token) { token = (await AsyncStorage.getItem('token')) ?? ''; } const endpoint = integratedSocialPostsEndpoints[socialType]; const accountData: SocialAccountType = {}; accountData.posts = []; try { const response = await fetch(endpoint + `${userId}/`, { method: 'GET', headers: { Authorization: 'Token ' + token, }, }); if (response.status === 200) { const body = await response.json(); accountData.handle = body.handle; accountData.posts = body.posts; accountData.profile_pic = body.profile_pic; } } catch (error) { console.log(error); } return accountData; }; export const loadRecentlySearchedUsers = async () => { try { const asyncCache = await AsyncStorage.getItem('@recently_searched_users'); return asyncCache != null ? JSON.parse(asyncCache) : null; } catch (e) { console.log(e); } }; export const handlePasswordResetRequest = async (value: string) => { try { const response = await fetch(PASSWORD_RESET_ENDPOINT + 'request/', { method: 'POST', body: JSON.stringify({ value, }), }); const status = response.status; if (status === 200) { Alert.alert( 'A code was sent to your registered phone number, please use the same to reset your password', ); return true; } else { if (status === 404) { Alert.alert( `Please make sure that the email / username entered is registered with us. You may contact our customer support at ${TAGG_CUSTOMER_SUPPORT}`, ); } else { Alert.alert(ERROR_SOMETHING_WENT_WRONG_REFRESH); } console.log(response); return false; } } catch (error) { console.log(error); Alert.alert(ERROR_SOMETHING_WENT_WRONG); return false; } }; export const handlePasswordCodeVerification = async ( value: string, otp: string, ) => { try { const response = await fetch(PASSWORD_RESET_ENDPOINT + 'verify/', { method: 'POST', body: JSON.stringify({ value, otp, }), }); const status = response.status; if (status === 200) { return true; } else { if (status === 404) { Alert.alert(ERROR_PWD_ACCOUNT(TAGG_CUSTOMER_SUPPORT)); } else if (status === 401) { Alert.alert(ERROR_INVALID_PWD_CODE); } else { Alert.alert(ERROR_SOMETHING_WENT_WRONG); } console.log(response); return false; } } catch (error) { console.log(error); Alert.alert(ERROR_SOMETHING_WENT_WRONG); return false; } }; export const handlePasswordReset = async (value: string, password: string) => { try { const response = await fetch(PASSWORD_RESET_ENDPOINT + 'reset/', { method: 'POST', body: JSON.stringify({ value, password, }), }); const status = response.status; if (status === 200) { Alert.alert(SUCCESS_PWD_RESET); return true; } else { if (status === 404) { Alert.alert(ERROR_PWD_ACCOUNT(TAGG_CUSTOMER_SUPPORT)); } else if (status === 406) { Alert.alert(ERROR_DUP_OLD_PWD); } else { Alert.alert(ERROR_SOMETHING_WENT_WRONG_REFRESH); } console.log(response); return false; } } catch (error) { console.log(error); Alert.alert(ERROR_SOMETHING_WENT_WRONG); return false; } }; export const verifyOtp = async (phone: string, otp: string) => { try { let response = await fetch(VERIFY_OTP_ENDPOINT, { method: 'POST', body: JSON.stringify({ phone_number: '+1' + phone, otp, }), }); let statusCode = response.status; if (statusCode === 200) { return true; } else { if (statusCode === 401) { Alert.alert( 'Invalid verification code 🤔', 'Try again. Tap the resend code button if you need a new code.', ); } else { Alert.alert(ERROR_SOMETHING_WENT_WRONG_REFRESH); } } } catch (error) { Alert.alert(ERROR_VERIFICATION_FAILED_SHORT, ERROR_DOUBLE_CHECK_CONNECTION); return { name: 'Verification error', description: error, }; } }; export const sendOtp = async (phone: string) => { try { let response = await fetch(SEND_OTP_ENDPOINT, { method: 'POST', body: JSON.stringify({ phone_number: '+1' + phone, }), }); let status = response.status; if (status === 200) { Alert.alert(SUCCESS_VERIFICATION_CODE_SENT); return true; } else { Alert.alert(ERROR_SOMETHING_WENT_WRONG); return false; } } catch (error) { console.log(error); return false; } }; export const sendOtpStatusCode = async (phone: string) => { try { let response = await fetch(SEND_OTP_ENDPOINT, { method: 'POST', body: JSON.stringify({ phone_number: '+1' + phone, }), }); return response.status; } catch (error) { console.log(error); return undefined; } }; export const sendRegister = async ( firstName: string, lastName: string, phone: string, email: string, username: string, password: string, ) => { try { const form = new FormData(); form.append('first_name', firstName); form.append('last_name', lastName); form.append('email', email); form.append('phone_number', phone); form.append('username', username); form.append('password', password); const response = await fetch(REGISTER_ENDPOINT, { method: 'POST', headers: { 'Content-Type': 'multipart/form-data', }, body: form, }); return response; } catch (error) { console.log(error); return undefined; } }; export const fetchUserProfile = async (userId: string, token?: string) => { try { if (!token) { token = (await AsyncStorage.getItem('token')) ?? ''; } const response = await fetch(USER_PROFILE_ENDPOINT + userId + '/', { method: 'GET', headers: { Authorization: 'Token ' + token, }, }); if (response.status === 200) { const data: ProfileType = await response.json(); return data; } } catch (error) { console.log(error); return undefined; } }; export const patchEditProfile = async (form: FormData, userId: string) => { const endpoint = EDIT_PROFILE_ENDPOINT + `${userId}/`; try { const token = await AsyncStorage.getItem('token'); let response = await fetch(endpoint, { method: 'PATCH', headers: { 'Content-Type': 'multipart/form-data', Authorization: 'Token ' + token, }, body: form, }); let statusCode = response.status; if (statusCode === 200) { return true; } else if (statusCode === 400) { let data = await response.json(); throw ( 'Profile update failed. 😔' + data.error || 'Something went wrong! 😭' ); } else { throw ERROR_SOMETHING_WENT_WRONG_REFRESH; } } catch (error) { throw ERROR_DOUBLE_CHECK_CONNECTION; } }; export const visitedUserProfile = async (userId: string) => { try { const token = await AsyncStorage.getItem('token'); const form = new FormData(); form.append('user_id', userId); const response = await fetch(USER_PROFILE_VISITED_ENDPOINT, { method: 'POST', headers: { 'Content-Type': 'multipart/form-data', Authorization: 'Token ' + token, }, body: form, }); if (response.status !== 200) { console.error('Failed to submit a profile visit'); } } catch (error) { return undefined; } };