Skip to content

Commit

Permalink
Merge pull request #4 from Tharki-God/works
Browse files Browse the repository at this point in the history
Works
  • Loading branch information
Wolfkid200444 authored Dec 8, 2023
2 parents 85a7608 + 9b1fd5f commit e09af7f
Show file tree
Hide file tree
Showing 8 changed files with 264 additions and 245 deletions.
17 changes: 12 additions & 5 deletions manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,18 @@
"id": "dev.wolfplugs.decor",
"name": "Decor plugin",
"description": "Adds Custom Decoration to your profile",
"author": {
"name": "Wolfkid200444",
"discordID": "347096063569559553",
"github": "WolfPlugs"
},
"author": [
{
"name": "Wolfkid200444",
"discordID": "347096063569559553",
"github": "WolfPlugs"
},
{
"name": "Ahlawat",
"discordID": "1025214794766221384",
"github": "TharkiDev"
}
],
"version": "1.0.0",
"updater": {
"type": "github",
Expand Down
8 changes: 4 additions & 4 deletions src/lib/api.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import { API_URL } from "./constants";
import { useAuthorizationStore } from "./stores/AuthorizationStore";

import { authorizationStore } from "./stores/AuthorizationStore";

export interface Preset {
id: string;
Expand Down Expand Up @@ -31,7 +30,7 @@ export async function fetchApi(url: RequestInfo, options?: RequestInit) {
...options,
headers: {
...options?.headers,
Authorization: `Bearer ${useAuthorizationStore.getState().token}`,
Authorization: `Bearer ${authorizationStore.token}`,
},
});

Expand All @@ -53,4 +52,5 @@ export const getUserDecorations = async (id: string = "@me"): Promise<Decoration
export const getUserDecoration = async (id: string = "@me"): Promise<Decoration | null> =>
fetchApi(API_URL + `/users/${id}/decoration`).then((c) => c.json());

export const getPresets = async (): Promise<Preset[]> => fetch(API_URL + "/decorations/presets").then(c => c.json());
export const getPresets = async (): Promise<Preset[]> =>
fetch(API_URL + "/decorations/presets").then((c) => c.json());
61 changes: 24 additions & 37 deletions src/lib/stores/AuthorizationStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,44 +16,31 @@ interface AuthorizationState {
isAuthorized: () => boolean;
}

const indexedDBStorage: StateStorage = {
async getItem(name: string): Promise<string | null> {
return (await authorizationToken).get(name).then((v) => v ?? null);
export const authorizationStore = {
get token() {
return authorizationToken.get("token", null);
},
async setItem(name: string, value: string): Promise<void> {
(await authorizationToken).set(name, value);
get tokens() {
return authorizationToken.get("tokens", {
[users.getCurrentUser().id]: authorizationToken.get("token", null),
});
},
async removeItem(name: string): Promise<void> {
(await authorizationToken).set(name, null);
init: () => {},
setToken: (token: string) => {
authorizationToken.set("token", token);
authorizationToken.set("tokens", {
...authorizationToken.get("tokens", {}),
[users.getCurrentUser().id]: token,
});
},
};

export const useAuthorizationStore = create<AuthorizationState>(
persist(
(set, get) => ({
token: null,
tokens: {},
init: () => {
set({ token: get().tokens[users.getCurrentUser().id] ?? null });
},
setToken: (token: string) =>
set({ token, tokens: { ...get().tokens, [users.getCurrentUser().id]: token } }),
remove: (id: string) => {
const { tokens, init } = get();
const newTokens = { ...tokens };
delete newTokens[id];
set({ tokens: newTokens });
remove: (id: string) => {
const tokens = authorizationToken.get("tokens", {});

init();
},
authorize: () => void showAuthorizationModal(),
isAuthorized: () => !!get().token,
}),
{
name: "decor-auth",
getStorage: () => indexedDBStorage,
partialize: (state) => ({ tokens: state.tokens }),
onRehydrateStorage: () => (state) => state?.init(),
},
),
);
delete tokens[id];
authorizationToken.set("tokens", tokens);
},
authorize: () => void showAuthorizationModal(),
get isAuthorized() {
return () => Boolean(authorizationToken.get("token", null));
},
};
7 changes: 3 additions & 4 deletions src/lib/stores/UserDecorationsStore.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { DECORATION_FETCH_COOLDOWN, SKU_ID } from "../constants";
import { AvatarDecoration } from "../..";
import subscribeToFluxDispatcher from "../utils/subscribeToFluxDispatcher";
import { useCurrentUserDecorationsStore } from "./CurrentUserDecorationsStore";
import { useAuthorizationStore } from "./AuthorizationStore";
import { authorizationStore } from "./AuthorizationStore";

const { lodash, users, fluxDispatcher, React, channels } = common;

Expand All @@ -31,7 +31,7 @@ export const useUsersDecorationsStore = create<UsersDecorationsState>((set, get)
fetchQueue: new Set(),
bulkFetch: lodash.debounce(async () => {
const { fetchQueue, usersDecorations } = get();
set({ fetchQueue: new Set() });
set({ fetchQueue: new Set() });

const fetchIds = Array.from(fetchQueue);
if (fetchIds.length === 0) return;
Expand Down Expand Up @@ -112,7 +112,6 @@ export const subscriptions = [
}),

subscribeToFluxDispatcher("CONNECTION_OPEN", () => {
useAuthorizationStore.getState().init();
useCurrentUserDecorationsStore.getState().clear();
useUsersDecorationsStore.getState().fetch(users.getCurrentUser().id, true);
}),
Expand Down Expand Up @@ -145,7 +144,7 @@ export function useUserDecorAvatarDecoration(user): AvatarDecoration | null | un
fetchUserDecorAvatarDecoration(user.id);
}, []);

console.log("Effects", decorAvatarDecoration)
console.log("Effects", decorAvatarDecoration);

return decorAvatarDecoration ? { asset: decorAvatarDecoration, skuId: SKU_ID } : null;
}
6 changes: 3 additions & 3 deletions src/lib/utils/settings.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { settings } from "replugged"
import { settings } from "replugged";

export const defaultSettings = {}
export const authorizationToken = settings.init("decor.auth", defaultSettings)
export const defaultSettings = {};
export const authorizationToken = await settings.init("decor.auth", defaultSettings);
49 changes: 26 additions & 23 deletions src/lib/utils/showAuthorizationModal.tsx
Original file line number Diff line number Diff line change
@@ -1,13 +1,17 @@
import { webpack, common } from "replugged"
import { useAuthorizationStore } from "../stores/AuthorizationStore";
import { webpack, common } from "replugged";
import { authorizationStore } from "../stores/AuthorizationStore";
import { AUTHORIZE_URL, CLIENT_ID } from "../constants";
import { logger } from "../..";

const { modal: { openModal } } = common
const OAuth = webpack.getByProps("OAuth2AuthorizeModal")
const {
modal: { openModal },
} = common;
const OAuth = webpack.getByProps("OAuth2AuthorizeModal");

export default async () => new Promise(r => openModal(props =>
<OAuth.OAuth2AuthorizeModal
export default async () =>
new Promise((r) =>
openModal((props) => (
<OAuth.OAuth2AuthorizeModal
{...props}
scopes={["identify"]}
responseType="code"
Expand All @@ -16,24 +20,23 @@ export default async () => new Promise(r => openModal(props =>
clientId={CLIENT_ID}
cancelCompletesFlow={false}
callback={async (response: any) => {
try {
const url = new URL(response.location);
url.searchParams.append("client", "replugged");
try {
const url = new URL(response.location);
url.searchParams.append("client", "replugged");

const req = await fetch(url);
const req = await fetch(url);

if (req?.ok) {
const token = await req.text();
useAuthorizationStore.getState().setToken(token);
} else {
throw new Error("Request not OK");
}
r(void 0);
} catch (e) {
logger.error("Decor: Failed to authorize", e);
if (req?.ok) {
const token = await req.text();
authorizationStore.setToken(token);
} else {
throw new Error("Request not OK");
}
r(void 0);
} catch (e) {
logger.error("Decor: Failed to authorize", e);
}
}}
/>
))


/>
)),
);
85 changes: 46 additions & 39 deletions src/ui/components/DecorSection.tsx
Original file line number Diff line number Diff line change
@@ -1,56 +1,63 @@
import { webpack, common, components } from "replugged";
import { useAuthorizationStore } from "../../lib/stores/AuthorizationStore";
import { authorizationStore } from "../../lib/stores/AuthorizationStore";
import { useCurrentUserDecorationsStore } from "../../lib/stores/CurrentUserDecorationsStore";
import { cl } from "..";
import { openChangeDecorationModal } from "../modals/ChangeDecorationModal";

const { React } = common
const { Flex, Button } = components
const { React } = common;
const { Flex, Button } = components;
let CustomizationSection;


interface DecorSectionProps {
hideTitle?: boolean;
hideDivider?: boolean;
noMargin?: boolean;
}


export default function DecorSection({ hideTitle = false, hideDivider = false, noMargin = false }: DecorSectionProps) {
export default function DecorSection({
hideTitle = false,
hideDivider = false,
noMargin = false,
}: DecorSectionProps) {
CustomizationSection ??= webpack.getBySource(".customizationSectionBackground");
const authorization = useAuthorizationStore();
const { selectedDecoration, select: selectDecoration, fetch: fetchDecorations } = useCurrentUserDecorationsStore();

const {
selectedDecoration,
select: selectDecoration,
fetch: fetchDecorations,
} = useCurrentUserDecorationsStore();

React.useEffect(() => {
if (authorization.isAuthorized()) fetchDecorations();
}, [authorization.token]);
if (authorizationStore.isAuthorized()) fetchDecorations();
}, [authorizationStore.token]);

return <CustomizationSection
title={!hideTitle && "Decor"}
hasBackground={true}
hideDivider={hideDivider}
className={noMargin && cl("section-remove-margin")}
>
<Flex>
<Button
onClick={() => {
if (!authorization.isAuthorized()) {
authorization.authorize().then(openChangeDecorationModal).catch(() => { });
} else openChangeDecorationModal();
// openChangeDecorationModal();
}}
size={Button.Sizes.SMALL}
>
Change Decoration
</Button>
{selectedDecoration && authorization.isAuthorized() && <Button
onClick={() => selectDecoration(null)}
color={Button.Colors.PRIMARY}
size={Button.Sizes.SMALL}
look={Button.Looks.LINK}
>
Remove Decoration
</Button>}
</Flex>
</CustomizationSection>
return (
<CustomizationSection
title={!hideTitle && "Decor"}
hasBackground={true}
hideDivider={hideDivider}
className={noMargin && cl("section-remove-margin")}>
<Flex>
<Button
onClick={() => {
if (!authorizationStore.isAuthorized()) {
authorizationStore.authorize();
openChangeDecorationModal();
} else openChangeDecorationModal();
// openChangeDecorationModal();
}}
size={Button.Sizes.SMALL}>
Change Decoration
</Button>
{selectedDecoration && authorizationStore.isAuthorized() && (
<Button
onClick={() => selectDecoration(null)}
color={Button.Colors.PRIMARY}
size={Button.Sizes.SMALL}
look={Button.Looks.LINK}>
Remove Decoration
</Button>
)}
</Flex>
</CustomizationSection>
);
}
Loading

0 comments on commit e09af7f

Please sign in to comment.