Skip to content

Commit

Permalink
feat: mastodon posts searching system. (#95)
Browse files Browse the repository at this point in the history
Adding a search function that utilizes Mastodon's API to explore content
in users' statuses.

![image](https://github.com/commune-os/weird/assets/61906684/e8c33ff0-f670-4bfe-9ad2-9932d92a079a)
  • Loading branch information
kimlimjustin committed Jul 3, 2024
1 parent 5c68e96 commit ab6c850
Show file tree
Hide file tree
Showing 10 changed files with 62 additions and 7 deletions.
19 changes: 19 additions & 0 deletions backend/weird/src/profile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,8 @@ pub struct Profile {
pub mastodon_server: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub mastodon_username: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub mastodon_access_token: Option<String>,
}

#[derive(Serialize, Deserialize, Debug, Default, Clone)]
Expand Down Expand Up @@ -251,6 +253,13 @@ impl Profile {
.ok()
.map(|x| x.to_owned());

let mastodon_access_token = profile
.get_key("mastodon_access_token")
.await?
.as_str()
.ok()
.map(|x| x.to_owned());

futures::pin_mut!(tags_stream);
let mut tags = Vec::new();
while let Some(tag) = tags_stream.next().await {
Expand Down Expand Up @@ -312,6 +321,7 @@ impl Profile {
lists,
mastodon_server,
mastodon_username,
mastodon_access_token,
})
}

Expand Down Expand Up @@ -404,6 +414,15 @@ impl Profile {
.unwrap_or(Value::Null),
)
.await?;
value
.set_key(
"mastodon_access_token",
self.mastodon_access_token
.clone()
.map(|x| x.into())
.unwrap_or(Value::Null),
)
.await?;

let tags = value.get_or_init_map("tags").await?;
// Clear existing tags
Expand Down
1 change: 1 addition & 0 deletions src/lib/rauthy/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ export interface UserInfo {
groups: string[];
mastodon_server: string;
mastodon_username: string;
mastodon_access_token: string;
}

export const setUserInfo = (info?: UserInfo) => setContext('userInfo', info);
Expand Down
1 change: 1 addition & 0 deletions src/routes/(app)/account/link-mastodon/+page.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ export interface Profile {
links?: { label?: string; url: string }[];
mastodon_username?: string;
mastodon_server?: string;
mastodon_access_token?: string;
}
export type WorkCapacity = 'full_time' | 'part_time';
export type WorkCompensation = 'paid' | 'volunteer';
Expand Down
5 changes: 3 additions & 2 deletions src/routes/(app)/account/link-mastodon/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -55,7 +55,7 @@
})
});
const data = await response.json();
console.log(data);
localStorage.setItem('access_token', data.access_token);
localStorage.setItem('mastodon_server', mastodon_server);
Expand All @@ -71,6 +71,7 @@
const form_data = new FormData();
form_data.append('mastodon_server', mastodon_server);
form_data.append('mastodon_username', user_data.username);
form_data.append('mastodon_access_token', data.access_token);
form_data.append('username', username);
form_data.append('display_name', display_name);
form_data.append('avatar_seed', avatar_seed);
Expand All @@ -84,7 +85,7 @@
form_data.append('link-label', link.label ?? '');
form_data.append('link-url', link.url ?? '');
});
console.log(JSON.stringify(Object.fromEntries(form_data.entries())));
await fetch('/account/update', {
method: 'POST',
body: form_data
Expand Down
7 changes: 6 additions & 1 deletion src/routes/(app)/account/update/+page.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,10 @@ export const actions = {
if (mastodon_username == '') {
mastodon_username = null;
}
let mastodon_access_token = data.get('mastodon_access_token');
if (mastodon_access_token == '') {
mastodon_access_token = null;
}

const json = JSON.stringify({
username,
Expand All @@ -81,7 +85,8 @@ export const actions = {
work_compensation,
bio,
mastodon_server,
mastodon_username
mastodon_username,
mastodon_access_token
});

try {
Expand Down
1 change: 1 addition & 0 deletions src/routes/(app)/auth/v1/account/+page.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@ export interface Profile {
links?: { label?: string; url: string }[];
mastodon_username?: string;
mastodon_server?: string;
mastodon_access_token?: string;
}
export type WorkCapacity = 'full_time' | 'part_time';
export type WorkCompensation = 'paid' | 'volunteer';
Expand Down
2 changes: 2 additions & 0 deletions src/routes/(app)/auth/v1/account/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
let nextLink = $state({ label: '', url: '' } as { label?: string; url: string });
let mastodon_server = $state(data.profile?.mastodon_server || '');
let mastodon_username = $state(data.profile?.mastodon_username || '');
let mastodon_access_token = $state(data.profile?.mastodon_access_token || '');
let tags = $state(data.profile?.tags || []);
let tagsString = $state((data.profile?.tags || []).join(', '));
Expand Down Expand Up @@ -370,6 +371,7 @@
</label>

<input type="hidden" name="mastodon_username" bind:value={mastodon_username} />
<input type="hidden" name="mastodon_access_token" bind:value={mastodon_access_token} />

<button class="variant-filled btn mt-4"> Save </button>
</form>
Expand Down
2 changes: 1 addition & 1 deletion src/routes/(app)/u/[username]/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -96,7 +96,7 @@
{printWorkCompensation(profile.work_compensation)}
</div>
{/if}
{#if profile.mastodon_server && profile.username}
{#if profile.mastodon_server && profile.mastodon_username && profile.username}
<a
class="variant-ghost btn"
href={`/u/${parseUsername(profile.username!).name}/mastodon`}
Expand Down
7 changes: 5 additions & 2 deletions src/routes/(app)/u/[username]/mastodon/+page.server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,13 @@ import type { MastodonProfile } from './mastodon';
export const load: PageServerLoad = async ({
fetch,
request,
params
params,
url
}): Promise<{
profile: Profile | { error: string };
params: typeof params;
mastodon_profile: MastodonProfile;
search?: string;
}> => {
let { userInfo } = await getSession(fetch, request);
const loggedIn = !!userInfo;
Expand All @@ -26,6 +28,7 @@ export const load: PageServerLoad = async ({

const mastodon_server = profile.mastodon_server;
const mastodon_username = profile.mastodon_username;
const mastodon_access_token = profile.mastodon_access_token;

const mastodon_data = await fetch(
`${mastodon_server}/api/v1/accounts/lookup?acct=${mastodon_username}`,
Expand All @@ -49,5 +52,5 @@ export const load: PageServerLoad = async ({
mastodon_server: mastodon_server ? mastodon_server.replace('https://', '') : ''
};

return { profile, params, mastodon_profile };
return { profile, params, mastodon_profile, search: url.searchParams.get('q') || undefined };
};
24 changes: 23 additions & 1 deletion src/routes/(app)/u/[username]/mastodon/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@
import Favorite from '$lib/icons/Favorite.svelte';
const { data }: { data: PageData } = $props();
const profile = data.profile;
let search = $state(data.search);
const mastodon_profile = data.mastodon_profile;
let statuses: any[] = $state([]);
let show_blogs = $state('blogs');
Expand Down Expand Up @@ -45,7 +46,22 @@
reblog_flag = '&exclude_reblogs=true';
break;
}
fetchStatuses(reblog_flag);
if (search && profile.mastodon_access_token) {
fetch(
`https://${mastodon_profile.mastodon_server}/api/v2/search?q=${search}&resolve=true&type=statuses&limit=40&account_id=${mastodon_profile.id}`,
{
method: 'GET',
headers: {
Authorization: `Bearer ${profile.mastodon_access_token}`
}
}
)
.then((r) => r.json())
.then((stt) => {
console.log(stt);
statuses = stt.statuses;
});
} else fetchStatuses(reblog_flag);
});
const fetchMore = () => {
Expand Down Expand Up @@ -137,6 +153,12 @@
<option value="blogs">Blogs</option>
<option value="all">All</option>
</select>
<input
type="text"
class="form-input w-44 border border-gray-300 px-2 py-1 dark:bg-gray-800"
placeholder="Search"
bind:value={search}
/>
</div>
<div class="columns-1 md:columns-2 lg:columns-3 xl:columns-4">
{#each statuses as status}
Expand Down

0 comments on commit ab6c850

Please sign in to comment.