2021-12-15 00:45:13 +00:00
|
|
|
import {
|
|
|
|
getFirestore,
|
|
|
|
doc,
|
|
|
|
setDoc,
|
|
|
|
getDoc,
|
2021-12-16 01:34:36 +00:00
|
|
|
collection,
|
|
|
|
query,
|
|
|
|
where,
|
|
|
|
limit,
|
|
|
|
getDocs,
|
2022-01-18 03:20:25 +00:00
|
|
|
orderBy,
|
2022-02-18 01:16:58 +00:00
|
|
|
updateDoc,
|
2022-06-03 04:52:14 +00:00
|
|
|
deleteDoc,
|
2022-06-08 03:24:18 +00:00
|
|
|
collectionGroup,
|
|
|
|
onSnapshot,
|
2021-12-15 00:45:13 +00:00
|
|
|
} from 'firebase/firestore'
|
2021-12-08 16:42:50 +00:00
|
|
|
import { getAuth } from 'firebase/auth'
|
|
|
|
import { ref, getStorage, uploadBytes, getDownloadURL } from 'firebase/storage'
|
|
|
|
import {
|
|
|
|
onAuthStateChanged,
|
|
|
|
GoogleAuthProvider,
|
|
|
|
signInWithPopup,
|
|
|
|
} from 'firebase/auth'
|
2022-06-26 21:42:42 +00:00
|
|
|
import { throttle, zip } from 'lodash'
|
2021-12-08 16:42:50 +00:00
|
|
|
|
2022-01-18 07:18:38 +00:00
|
|
|
import { app } from './init'
|
2022-06-24 17:14:20 +00:00
|
|
|
import { PortfolioMetrics, PrivateUser, User } from 'common/user'
|
2022-05-19 22:04:34 +00:00
|
|
|
import { createUser } from './fn-call'
|
2022-05-01 16:36:54 +00:00
|
|
|
import { getValue, getValues, listenForValue, listenForValues } from './utils'
|
2022-05-12 15:07:10 +00:00
|
|
|
import { feed } from 'common/feed'
|
|
|
|
import { CATEGORY_LIST } from 'common/categories'
|
2022-05-26 05:30:03 +00:00
|
|
|
import { safeLocalStorage } from '../util/local'
|
2022-06-08 03:24:18 +00:00
|
|
|
import { filterDefined } from 'common/util/array'
|
2022-02-18 01:16:58 +00:00
|
|
|
|
2022-01-10 21:07:57 +00:00
|
|
|
export type { User }
|
2021-12-14 17:36:23 +00:00
|
|
|
|
2022-06-24 17:14:20 +00:00
|
|
|
export type Period = 'daily' | 'weekly' | 'monthly' | 'allTime'
|
2022-06-22 20:29:40 +00:00
|
|
|
|
2021-12-08 16:42:50 +00:00
|
|
|
const db = getFirestore(app)
|
|
|
|
export const auth = getAuth(app)
|
|
|
|
|
2022-06-08 03:24:18 +00:00
|
|
|
export const userDocRef = (userId: string) => doc(db, 'users', userId)
|
|
|
|
|
2021-12-08 16:42:50 +00:00
|
|
|
export async function getUser(userId: string) {
|
2022-06-08 03:24:18 +00:00
|
|
|
const docSnap = await getDoc(userDocRef(userId))
|
2021-12-08 16:42:50 +00:00
|
|
|
return docSnap.data() as User
|
|
|
|
}
|
|
|
|
|
2021-12-16 01:34:36 +00:00
|
|
|
export async function getUserByUsername(username: string) {
|
|
|
|
// Find a user whose username matches the given username, or null if no such user exists.
|
|
|
|
const userCollection = collection(db, 'users')
|
|
|
|
const q = query(userCollection, where('username', '==', username), limit(1))
|
|
|
|
const docs = await getDocs(q)
|
|
|
|
const users = docs.docs.map((doc) => doc.data() as User)
|
|
|
|
return users[0] || null
|
|
|
|
}
|
|
|
|
|
2021-12-08 16:42:50 +00:00
|
|
|
export async function setUser(userId: string, user: User) {
|
|
|
|
await setDoc(doc(db, 'users', userId), user)
|
|
|
|
}
|
|
|
|
|
2022-02-18 01:16:58 +00:00
|
|
|
export async function updateUser(userId: string, update: Partial<User>) {
|
|
|
|
await updateDoc(doc(db, 'users', userId), { ...update })
|
|
|
|
}
|
|
|
|
|
2022-05-16 03:41:07 +00:00
|
|
|
export async function updatePrivateUser(
|
|
|
|
userId: string,
|
|
|
|
update: Partial<PrivateUser>
|
|
|
|
) {
|
|
|
|
await updateDoc(doc(db, 'private-users', userId), { ...update })
|
|
|
|
}
|
|
|
|
|
2022-02-04 00:13:04 +00:00
|
|
|
export function listenForUser(
|
|
|
|
userId: string,
|
|
|
|
setUser: (user: User | null) => void
|
|
|
|
) {
|
2021-12-15 00:45:13 +00:00
|
|
|
const userRef = doc(db, 'users', userId)
|
2022-02-04 00:13:04 +00:00
|
|
|
return listenForValue<User>(userRef, setUser)
|
2021-12-15 00:45:13 +00:00
|
|
|
}
|
|
|
|
|
2022-02-04 03:04:56 +00:00
|
|
|
export function listenForPrivateUser(
|
|
|
|
userId: string,
|
2022-02-04 03:11:59 +00:00
|
|
|
setPrivateUser: (privateUser: PrivateUser | null) => void
|
2022-02-04 03:04:56 +00:00
|
|
|
) {
|
|
|
|
const userRef = doc(db, 'private-users', userId)
|
2022-02-04 03:11:59 +00:00
|
|
|
return listenForValue<PrivateUser>(userRef, setPrivateUser)
|
2022-02-04 03:04:56 +00:00
|
|
|
}
|
|
|
|
|
2021-12-08 16:42:50 +00:00
|
|
|
const CACHED_USER_KEY = 'CACHED_USER_KEY'
|
2022-01-18 07:18:38 +00:00
|
|
|
|
|
|
|
// used to avoid weird race condition
|
|
|
|
let createUserPromise: Promise<User | null> | undefined = undefined
|
|
|
|
|
2022-05-22 08:36:05 +00:00
|
|
|
const warmUpCreateUser = throttle(createUser, 5000 /* ms */)
|
2022-05-05 16:51:09 +00:00
|
|
|
|
2021-12-17 04:09:38 +00:00
|
|
|
export function listenForLogin(onUser: (user: User | null) => void) {
|
2022-05-26 05:30:03 +00:00
|
|
|
const local = safeLocalStorage()
|
|
|
|
const cachedUser = local?.getItem(CACHED_USER_KEY)
|
|
|
|
onUser(cachedUser && JSON.parse(cachedUser))
|
2021-12-17 04:09:38 +00:00
|
|
|
|
2022-05-05 16:51:09 +00:00
|
|
|
if (!cachedUser) warmUpCreateUser()
|
2022-01-18 07:18:38 +00:00
|
|
|
|
2021-12-17 04:09:38 +00:00
|
|
|
return onAuthStateChanged(auth, async (fbUser) => {
|
|
|
|
if (fbUser) {
|
2022-01-18 07:18:38 +00:00
|
|
|
let user: User | null = await getUser(fbUser.uid)
|
|
|
|
|
2021-12-17 04:09:38 +00:00
|
|
|
if (!user) {
|
2022-01-18 07:18:38 +00:00
|
|
|
if (!createUserPromise) {
|
|
|
|
createUserPromise = createUser()
|
2021-12-08 16:42:50 +00:00
|
|
|
}
|
2022-01-18 07:18:38 +00:00
|
|
|
user = (await createUserPromise) || null
|
2021-12-08 16:42:50 +00:00
|
|
|
}
|
2022-01-18 07:18:38 +00:00
|
|
|
|
2021-12-17 04:09:38 +00:00
|
|
|
onUser(user)
|
2021-12-08 16:42:50 +00:00
|
|
|
|
|
|
|
// Persist to local storage, to reduce login blink next time.
|
|
|
|
// Note: Cap on localStorage size is ~5mb
|
2022-05-26 05:30:03 +00:00
|
|
|
local?.setItem(CACHED_USER_KEY, JSON.stringify(user))
|
2021-12-08 16:42:50 +00:00
|
|
|
} else {
|
2021-12-09 23:37:26 +00:00
|
|
|
// User logged out; reset to null
|
|
|
|
onUser(null)
|
2022-05-26 05:30:03 +00:00
|
|
|
local?.removeItem(CACHED_USER_KEY)
|
2022-01-18 07:18:38 +00:00
|
|
|
createUserPromise = undefined
|
2021-12-08 16:42:50 +00:00
|
|
|
}
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function firebaseLogin() {
|
|
|
|
const provider = new GoogleAuthProvider()
|
2022-06-23 08:07:52 +00:00
|
|
|
return signInWithPopup(auth, provider)
|
2021-12-08 16:42:50 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
export async function firebaseLogout() {
|
|
|
|
auth.signOut()
|
|
|
|
}
|
|
|
|
|
|
|
|
const storage = getStorage(app)
|
|
|
|
// Example: uploadData('avatars/ajfi8iejsf.png', data)
|
|
|
|
export async function uploadData(
|
|
|
|
path: string,
|
|
|
|
data: ArrayBuffer | Blob | Uint8Array
|
|
|
|
) {
|
|
|
|
const uploadRef = ref(storage, path)
|
|
|
|
// Uploaded files should be cached for 1 day, then revalidated
|
|
|
|
// See https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Cache-Control
|
|
|
|
const metadata = { cacheControl: 'public, max-age=86400, must-revalidate' }
|
|
|
|
await uploadBytes(uploadRef, data, metadata)
|
|
|
|
return await getDownloadURL(uploadRef)
|
|
|
|
}
|
2022-01-16 03:09:15 +00:00
|
|
|
|
2022-03-21 01:07:45 +00:00
|
|
|
export async function listUsers(userIds: string[]) {
|
|
|
|
if (userIds.length > 10) {
|
|
|
|
throw new Error('Too many users requested at once; Firestore limits to 10')
|
|
|
|
}
|
|
|
|
const userCollection = collection(db, 'users')
|
|
|
|
const q = query(userCollection, where('id', 'in', userIds))
|
|
|
|
const docs = await getDocs(q)
|
|
|
|
return docs.docs.map((doc) => doc.data() as User)
|
|
|
|
}
|
|
|
|
|
2022-01-16 03:09:15 +00:00
|
|
|
export async function listAllUsers() {
|
|
|
|
const userCollection = collection(db, 'users')
|
|
|
|
const q = query(userCollection)
|
|
|
|
const docs = await getDocs(q)
|
|
|
|
return docs.docs.map((doc) => doc.data() as User)
|
|
|
|
}
|
|
|
|
|
|
|
|
export function listenForAllUsers(setUsers: (users: User[]) => void) {
|
|
|
|
const userCollection = collection(db, 'users')
|
|
|
|
const q = query(userCollection)
|
|
|
|
listenForValues(q, setUsers)
|
|
|
|
}
|
2022-01-18 03:20:25 +00:00
|
|
|
|
2022-01-24 06:48:06 +00:00
|
|
|
export function listenForPrivateUsers(
|
|
|
|
setUsers: (users: PrivateUser[]) => void
|
|
|
|
) {
|
|
|
|
const userCollection = collection(db, 'private-users')
|
|
|
|
const q = query(userCollection)
|
|
|
|
listenForValues(q, setUsers)
|
|
|
|
}
|
|
|
|
|
2022-06-24 17:14:20 +00:00
|
|
|
export function getTopTraders(period: Period) {
|
2022-06-22 20:29:40 +00:00
|
|
|
const topTraders = query(
|
|
|
|
collection(db, 'users'),
|
|
|
|
orderBy('profitCached.' + period, 'desc'),
|
|
|
|
limit(20)
|
|
|
|
)
|
2022-01-18 03:20:25 +00:00
|
|
|
|
2022-06-22 20:29:40 +00:00
|
|
|
return getValues(topTraders)
|
2022-01-18 03:20:25 +00:00
|
|
|
}
|
|
|
|
|
2022-06-24 17:14:20 +00:00
|
|
|
export function getTopCreators(period: Period) {
|
2022-06-22 20:29:40 +00:00
|
|
|
const topCreators = query(
|
|
|
|
collection(db, 'users'),
|
|
|
|
orderBy('creatorVolumeCached.' + period, 'desc'),
|
|
|
|
limit(20)
|
|
|
|
)
|
|
|
|
return getValues(topCreators)
|
|
|
|
}
|
2022-01-18 03:20:25 +00:00
|
|
|
|
2022-06-22 16:05:54 +00:00
|
|
|
export async function getTopFollowed() {
|
|
|
|
const users = await getValues<User>(topFollowedQuery)
|
|
|
|
return users.slice(0, 20)
|
|
|
|
}
|
|
|
|
|
|
|
|
const topFollowedQuery = query(
|
|
|
|
collection(db, 'users'),
|
|
|
|
orderBy('followerCountCached', 'desc'),
|
|
|
|
limit(20)
|
|
|
|
)
|
|
|
|
|
2022-04-19 06:47:58 +00:00
|
|
|
export function getUsers() {
|
|
|
|
return getValues<User>(collection(db, 'users'))
|
|
|
|
}
|
|
|
|
|
2022-05-01 16:36:54 +00:00
|
|
|
export async function getUserFeed(userId: string) {
|
|
|
|
const feedDoc = doc(db, 'private-users', userId, 'cache', 'feed')
|
|
|
|
const userFeed = await getValue<{
|
2022-05-12 15:07:10 +00:00
|
|
|
feed: feed
|
2022-05-01 16:36:54 +00:00
|
|
|
}>(feedDoc)
|
|
|
|
return userFeed?.feed ?? []
|
|
|
|
}
|
2022-05-12 15:07:10 +00:00
|
|
|
|
|
|
|
export async function getCategoryFeeds(userId: string) {
|
|
|
|
const cacheCollection = collection(db, 'private-users', userId, 'cache')
|
|
|
|
const feedData = await Promise.all(
|
|
|
|
CATEGORY_LIST.map((category) =>
|
|
|
|
getValue<{ feed: feed }>(doc(cacheCollection, `feed-${category}`))
|
|
|
|
)
|
|
|
|
)
|
|
|
|
const feeds = feedData.map((data) => data?.feed ?? [])
|
2022-05-22 08:36:05 +00:00
|
|
|
return Object.fromEntries(zip(CATEGORY_LIST, feeds) as [string, feed][])
|
2022-05-12 15:07:10 +00:00
|
|
|
}
|
2022-06-03 04:52:14 +00:00
|
|
|
|
|
|
|
export async function follow(userId: string, followedUserId: string) {
|
|
|
|
const followDoc = doc(db, 'users', userId, 'follows', followedUserId)
|
|
|
|
await setDoc(followDoc, {
|
|
|
|
userId: followedUserId,
|
|
|
|
timestamp: Date.now(),
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
export async function unfollow(userId: string, unfollowedUserId: string) {
|
|
|
|
const followDoc = doc(db, 'users', userId, 'follows', unfollowedUserId)
|
|
|
|
await deleteDoc(followDoc)
|
|
|
|
}
|
|
|
|
|
2022-06-24 17:14:20 +00:00
|
|
|
export async function getPortfolioHistory(userId: string) {
|
|
|
|
return getValues<PortfolioMetrics>(
|
|
|
|
query(
|
|
|
|
collectionGroup(db, 'portfolioHistory'),
|
|
|
|
where('userId', '==', userId),
|
|
|
|
orderBy('timestamp', 'asc')
|
|
|
|
)
|
|
|
|
)
|
|
|
|
}
|
|
|
|
|
2022-06-03 04:52:14 +00:00
|
|
|
export function listenForFollows(
|
|
|
|
userId: string,
|
|
|
|
setFollowIds: (followIds: string[]) => void
|
|
|
|
) {
|
|
|
|
const follows = collection(db, 'users', userId, 'follows')
|
|
|
|
return listenForValues<{ userId: string }>(follows, (docs) =>
|
|
|
|
setFollowIds(docs.map(({ userId }) => userId))
|
|
|
|
)
|
|
|
|
}
|
2022-06-08 03:24:18 +00:00
|
|
|
|
|
|
|
export function listenForFollowers(
|
|
|
|
userId: string,
|
|
|
|
setFollowerIds: (followerIds: string[]) => void
|
|
|
|
) {
|
|
|
|
const followersQuery = query(
|
|
|
|
collectionGroup(db, 'follows'),
|
|
|
|
where('userId', '==', userId)
|
|
|
|
)
|
|
|
|
return onSnapshot(
|
|
|
|
followersQuery,
|
|
|
|
{ includeMetadataChanges: true },
|
|
|
|
(snapshot) => {
|
|
|
|
if (snapshot.metadata.fromCache) return
|
|
|
|
|
|
|
|
const values = snapshot.docs.map((doc) => doc.ref.parent.parent?.id)
|
|
|
|
setFollowerIds(filterDefined(values))
|
|
|
|
}
|
|
|
|
)
|
|
|
|
}
|