Skip to content

Commit

Permalink
Merge pull request #4258 from tloncorp/lb/contact-suggest-fix-2
Browse files Browse the repository at this point in the history
contact suggestions: fix trigger
  • Loading branch information
latter-bolden authored Dec 5, 2024
2 parents 7cb5f52 + dcd26a0 commit a036694
Show file tree
Hide file tree
Showing 8 changed files with 51 additions and 7 deletions.
2 changes: 2 additions & 0 deletions apps/tlon-mobile/src/components/AuthenticatedApp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { useShip } from '@tloncorp/app/contexts/ship';
import { useAppStatusChange } from '@tloncorp/app/hooks/useAppStatusChange';
import { useConfigureUrbitClient } from '@tloncorp/app/hooks/useConfigureUrbitClient';
import { useCurrentUserId } from '@tloncorp/app/hooks/useCurrentUser';
import { useFindSuggestedContacts } from '@tloncorp/app/hooks/useFindSuggestedContacts';
import { useNavigationLogging } from '@tloncorp/app/hooks/useNavigationLogger';
import { useNetworkLogger } from '@tloncorp/app/hooks/useNetworkLogger';
import { useTelemetry } from '@tloncorp/app/hooks/useTelemetry';
Expand Down Expand Up @@ -29,6 +30,7 @@ function AuthenticatedApp() {
useNavigationLogging();
useNetworkLogger();
useCheckAppUpdated();
useFindSuggestedContacts();

useEffect(() => {
configureClient();
Expand Down
2 changes: 2 additions & 0 deletions apps/tlon-web-new/src/app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
} from '@react-navigation/native';
import { useConfigureUrbitClient } from '@tloncorp/app/hooks/useConfigureUrbitClient';
import { useCurrentUserId } from '@tloncorp/app/hooks/useCurrentUser';
import { useFindSuggestedContacts } from '@tloncorp/app/hooks/useFindSuggestedContacts';
import { useIsDarkMode } from '@tloncorp/app/hooks/useIsDarkMode';
import { checkDb, useMigrations } from '@tloncorp/app/lib/webDb';
import { BasePathNavigator } from '@tloncorp/app/navigation/BasePathNavigator';
Expand Down Expand Up @@ -135,6 +136,7 @@ const App = React.memo(function AppComponent() {
const [dbIsLoaded, setDbIsLoaded] = useState(false);
const [startedSync, setStartedSync] = useState(false);
const configureClient = useConfigureUrbitClient();
useFindSuggestedContacts();

useEffect(() => {
handleError(() => {
Expand Down
10 changes: 10 additions & 0 deletions packages/app/hooks/useFindSuggestedContacts.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import * as store from '@tloncorp/shared/store';
import { useEffect } from 'react';

export function useFindSuggestedContacts() {
const { data: joinedGroupCount } = store.useJoinedGroupsCount();

useEffect(() => {
store.findContactSuggestions();
}, [joinedGroupCount]);
}
5 changes: 5 additions & 0 deletions packages/shared/src/db/keyValue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -290,6 +290,11 @@ export const groupsUsedForSuggestions = createStorageItem<string[]>({
defaultValue: [],
});

export const lastAddedSuggestionsAt = createStorageItem<number>({
key: 'lastAddedSuggestionsAt',
defaultValue: 0,
});

export const postDraft = (opts: {
key: string;
type: 'caption' | 'text' | undefined; // matches GalleryDraftType
Expand Down
13 changes: 13 additions & 0 deletions packages/shared/src/db/queries.ts
Original file line number Diff line number Diff line change
Expand Up @@ -153,6 +153,19 @@ export const getGroupPreviews = createReadQuery(
['groups']
);

export const getJoinedGroupsCount = createReadQuery(
'getJoinedGroupCount',
async (ctx: QueryCtx) => {
const result = await ctx.db
.select({ count: count() })
.from($groups)
.where(eq($groups.currentUserIsMember, true));

return result[0]?.count ?? 0;
},
['groups']
);

// TODO: inefficient, should optimize
export const getGroupsWithMemberThreshold = createReadQuery(
'getGroupsWithMemberThreshold',
Expand Down
13 changes: 11 additions & 2 deletions packages/shared/src/store/contactActions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,14 @@ export async function findContactSuggestions() {
const MAX_SUGGESTIONS = 6; // arbitrary

try {
// if we've already added suggestions recently, don't do it again
const lastAddedSuggestionsAt = await db.lastAddedSuggestionsAt.getValue();
const oneDayAgo = Date.now() - 24 * 60 * 60 * 1000;
if (lastAddedSuggestionsAt > oneDayAgo) {
logger.log('Suggestions added recently, skipping');
return;
}

// first see if we have any joined groups and seem to be a somewhat
// new user
const groups = await db.getGroups({ includeUnjoined: false });
Expand Down Expand Up @@ -182,10 +190,11 @@ export async function findContactSuggestions() {
runContext.suggestions = suggestions.length;

logger.crumb(`Found ${suggestions.length} suggestions`);
db.groupsUsedForSuggestions.setValue(groupchats.map((g) => g.id));

if (suggestions.length > 0) {
await addContactSuggestions(suggestions);
addContactSuggestions(suggestions);
db.groupsUsedForSuggestions.setValue(groupchats.map((g) => g.id));
db.lastAddedSuggestionsAt.setValue(Date.now());
logger.trackEvent('Client Contact Suggestions', {
...runContext,
suggestionsFound: true,
Expand Down
8 changes: 8 additions & 0 deletions packages/shared/src/store/dbHooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -325,6 +325,14 @@ export const useGroup = ({ id }: { id?: string }) => {
});
};

export const useJoinedGroupsCount = () => {
const deps = useKeyFromQueryDeps(db.getJoinedGroupsCount);
return useQuery({
queryKey: ['joinedGroupsCount', deps],
queryFn: () => db.getJoinedGroupsCount(),
});
};

export const useGroupByChannel = (channelId: string) => {
return useQuery({
queryKey: [['group', channelId]],
Expand Down
5 changes: 0 additions & 5 deletions packages/shared/src/store/sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import {
INFINITE_ACTIVITY_QUERY_KEY,
resetActivityFetchers,
} from '../store/useActivityFetchers';
import { findContactSuggestions } from './contactActions';
import { useLureState } from './lure';
import { getSyncing, updateIsSyncing, updateSession } from './session';
import { SyncCtx, SyncPriority, syncQueue } from './syncQueue';
Expand Down Expand Up @@ -1175,10 +1174,6 @@ export const syncStart = async (alreadySubscribed?: boolean) => {
});

updateIsSyncing(false);

// finding contacts is a bit of an outlier here, but it's work we need to do
// that can roughly be batched whenever we sync
findContactSuggestions();
};

export const setupHighPrioritySubscriptions = async (ctx?: SyncCtx) => {
Expand Down

0 comments on commit a036694

Please sign in to comment.