π¨ The ultimate agentic social media scheduling tool π€
TypeScript nextjsopen-sourceopen-source-social-media-scheduling-toolosspostiz-cloudpostiz-hostedredisscheduling-toolsocial-media-scheduling-tooltypescript
feat: whop
Nevo Davidb3681d2ac1b0
diff --git a/apps/frontend/public/icons/platforms/whop.png b/apps/frontend/public/icons/platforms/whop.pngnew file mode 100644index 000000000..2944dd501Binary files /dev/null and b/apps/frontend/public/icons/platforms/whop.png differdiff --git a/apps/frontend/src/components/new-launch/providers/show.all.providers.tsx b/apps/frontend/src/components/new-launch/providers/show.all.providers.tsxindex b9a3ec8f2..3ade88705 100644--- a/apps/frontend/src/components/new-launch/providers/show.all.providers.tsx+++ b/apps/frontend/src/components/new-launch/providers/show.all.providers.tsx@@ -37,6 +37,7 @@ import ListmonkProvider from '@gitroom/frontend/components/new-launch/providers/import GmbProvider from '@gitroom/frontend/components/new-launch/providers/gmb/gmb.provider';import MoltbookProvider from '@gitroom/frontend/components/new-launch/providers/moltbook/moltbook.provider';import SkoolProvider from '@gitroom/frontend/components/new-launch/providers/skool/skool.provider';+import WhopProvider from '@gitroom/frontend/components/new-launch/providers/whop/whop.provider';export const Providers = [{@@ -162,6 +163,10 @@ export const Providers = [{identifier: 'skool',component: SkoolProvider,+ },+ {+ identifier: 'whop',+ component: WhopProvider,}];export const ShowAllProviders = forwardRef((props, ref) => {diff --git a/apps/frontend/src/components/new-launch/providers/whop/whop.company.select.tsx b/apps/frontend/src/components/new-launch/providers/whop/whop.company.select.tsxnew file mode 100644index 000000000..3dc88a3f6--- /dev/null+++ b/apps/frontend/src/components/new-launch/providers/whop/whop.company.select.tsx@@ -0,0 +1,58 @@+'use client';++import { FC, useEffect, useState } from 'react';+import { useCustomProviderFunction } from '@gitroom/frontend/components/launches/helpers/use.custom.provider.function';+import { Select } from '@gitroom/react/form/select';+import { useSettings } from '@gitroom/frontend/components/launches/helpers/use.values';+import { useT } from '@gitroom/react/translation/get.transation.service.client';++export const WhopCompanySelect: FC<{+ name: string;+ onChange: (event: {+ target: {+ value: string;+ name: string;+ };+ }) => void;+}> = (props) => {+ const { onChange, name } = props;+ const t = useT();+ const customFunc = useCustomProviderFunction();+ const [companies, setCompanies] = useState([]);+ const { getValues } = useSettings();+ const [currentCompany, setCurrentCompany] = useState<string | undefined>();+ const onChangeInner = (event: {+ target: {+ value: string;+ name: string;+ };+ }) => {+ setCurrentCompany(event.target.value);+ onChange(event);+ };+ useEffect(() => {+ customFunc.get('companies').then((data) => setCompanies(data));+ const settings = getValues()[props.name];+ if (settings) {+ setCurrentCompany(settings);+ }+ }, []);+ if (!companies.length) {+ return null;+ }+ return (+ <Select+ name={name}+ label="Select Company"+ onChange={onChangeInner}+ value={currentCompany}+ >+ <option value="">{t('select_1', '--Select--')}</option>+ {companies.map((company: any) => (+ <option key={company.id} value={company.id}>+ {company.name}+ </option>+ ))}+ </Select>+ );+};diff --git a/apps/frontend/src/components/new-launch/providers/whop/whop.experience.select.tsx b/apps/frontend/src/components/new-launch/providers/whop/whop.experience.select.tsxnew file mode 100644index 000000000..93c0cb74b--- /dev/null+++ b/apps/frontend/src/components/new-launch/providers/whop/whop.experience.select.tsx@@ -0,0 +1,70 @@+'use client';++import { FC, useEffect, useState } from 'react';+import { useCustomProviderFunction } from '@gitroom/frontend/components/launches/helpers/use.custom.provider.function';+import { Select } from '@gitroom/react/form/select';+import { useSettings } from '@gitroom/frontend/components/launches/helpers/use.values';+import { useT } from '@gitroom/react/translation/get.transation.service.client';++export const WhopExperienceSelect: FC<{+ name: string;+ companyId: string | undefined;+ onChange: (event: {+ target: {+ value: string;+ name: string;+ };+ }) => void;+}> = (props) => {+ const { onChange, name, companyId } = props;+ const t = useT();+ const customFunc = useCustomProviderFunction();+ const [experiences, setExperiences] = useState([]);+ const { getValues } = useSettings();+ const [currentExperience, setCurrentExperience] = useState<+ string | undefined+ >();+ const onChangeInner = (event: {+ target: {+ value: string;+ name: string;+ };+ }) => {+ setCurrentExperience(event.target.value);+ onChange(event);+ };+ useEffect(() => {+ if (!companyId) {+ setExperiences([]);+ setCurrentExperience(undefined);+ return;+ }+ customFunc+ .get('experiences', { id: companyId })+ .then((data) => setExperiences(data));+ }, [companyId]);+ useEffect(() => {+ const settings = getValues()[name];+ if (settings) {+ setCurrentExperience(settings);+ }+ }, []);+ if (!companyId || !experiences.length) {+ return null;+ }+ return (+ <Select+ name={name}+ label="Select Forum"+ onChange={onChangeInner}+ value={currentExperience}+ >+ <option value="">{t('select_1', '--Select--')}</option>+ {experiences.map((experience: any) => (+ <option key={experience.id} value={experience.id}>+ {experience.name}+ </option>+ ))}+ </Select>+ );+};diff --git a/apps/frontend/src/components/new-launch/providers/whop/whop.provider.tsx b/apps/frontend/src/components/new-launch/providers/whop/whop.provider.tsxnew file mode 100644index 000000000..3c08938e6--- /dev/null+++ b/apps/frontend/src/components/new-launch/providers/whop/whop.provider.tsx@@ -0,0 +1,47 @@+'use client';++import {+ PostComment,+ withProvider,+} from '@gitroom/frontend/components/new-launch/providers/high.order.provider';+import { WhopDto } from '@gitroom/nestjs-libraries/dtos/posts/providers-settings/whop.dto';+import { Input } from '@gitroom/react/form/input';+import { useSettings } from '@gitroom/frontend/components/launches/helpers/use.values';+import { WhopCompanySelect } from '@gitroom/frontend/components/new-launch/providers/whop/whop.company.select';+import { WhopExperienceSelect } from '@gitroom/frontend/components/new-launch/providers/whop/whop.experience.select';+import { FC, useState } from 'react';++const WhopSettings: FC = () => {+ const form = useSettings();+ const [selectedCompany, setSelectedCompany] = useState<string | undefined>(+ form.getValues().company+ );+ const companyRegister = form.register('company');+ const onCompanyChange = (event: {+ target: { value: string; name: string };+ }) => {+ setSelectedCompany(event.target.value);+ companyRegister.onChange(event);+ };++ return (+ <div>+ <WhopCompanySelect {...companyRegister} onChange={onCompanyChange} />+ <WhopExperienceSelect+ {...form.register('experience')}+ companyId={selectedCompany}+ />+ <Input label="Title (optional)" {...form.register('title')} />+ </div>+ );+};++export default withProvider({+ postComment: PostComment.COMMENT,+ minimumCharacters: [],+ SettingsComponent: WhopSettings,+ CustomPreviewComponent: undefined,+ dto: WhopDto,+ checkValidity: undefined,+ maximumCharacters: 50000,+});diff --git a/libraries/nestjs-libraries/src/dtos/posts/providers-settings/all.providers.settings.ts b/libraries/nestjs-libraries/src/dtos/posts/providers-settings/all.providers.settings.tsindex 6bf171924..071be7826 100644--- a/libraries/nestjs-libraries/src/dtos/posts/providers-settings/all.providers.settings.ts+++ b/libraries/nestjs-libraries/src/dtos/posts/providers-settings/all.providers.settings.ts@@ -22,6 +22,7 @@ import { FarcasterDto } from '@gitroom/nestjs-libraries/dtos/posts/providers-setimport { FacebookDto } from '@gitroom/nestjs-libraries/dtos/posts/providers-settings/facebook.dto';import { MoltbookDto } from '@gitroom/nestjs-libraries/dtos/posts/providers-settings/moltbook.dto';import { SkoolDto } from '@gitroom/nestjs-libraries/dtos/posts/providers-settings/skool.dto';+import { WhopDto } from '@gitroom/nestjs-libraries/dtos/posts/providers-settings/whop.dto';export type ProviderExtension<T extends string, M> = { __type: T } & M;export type AllProvidersSettings =@@ -55,7 +56,8 @@ export type AllProvidersSettings =| ProviderExtension<'nostr', None>| ProviderExtension<'moltbook', MoltbookDto>| ProviderExtension<'vk', None>- | ProviderExtension<'skool', SkoolDto>;+ | ProviderExtension<'skool', SkoolDto>+ | ProviderExtension<'whop', WhopDto>;type None = NonNullable<unknown>;@@ -92,6 +94,7 @@ export const allProviders = (setEmpty?: any) => {{ value: setEmpty, name: 'vk' },{ value: MoltbookDto, name: 'moltbook' },{ value: SkoolDto, name: 'skool' },+ { value: WhopDto, name: 'whop' },].filter((f) => f.value);};diff --git a/libraries/nestjs-libraries/src/dtos/posts/providers-settings/whop.dto.ts b/libraries/nestjs-libraries/src/dtos/posts/providers-settings/whop.dto.tsnew file mode 100644index 000000000..c7d5ae5e4--- /dev/null+++ b/libraries/nestjs-libraries/src/dtos/posts/providers-settings/whop.dto.ts@@ -0,0 +1,24 @@+import { IsDefined, IsOptional, IsString, MinLength } from 'class-validator';+import { JSONSchema } from 'class-validator-jsonschema';++export class WhopDto {+ @MinLength(1)+ @IsDefined()+ @IsString()+ @JSONSchema({+ description: 'Company ID',+ })+ company: string;++ @MinLength(1)+ @IsDefined()+ @IsString()+ @JSONSchema({+ description: 'Experience ID for the Whop forum',+ })+ experience: string;++ @IsOptional()+ @IsString()+ title?: string;+}diff --git a/libraries/nestjs-libraries/src/integrations/integration.manager.ts b/libraries/nestjs-libraries/src/integrations/integration.manager.tsindex ba2ff6079..731bdbe51 100644--- a/libraries/nestjs-libraries/src/integrations/integration.manager.ts+++ b/libraries/nestjs-libraries/src/integrations/integration.manager.ts@@ -34,6 +34,7 @@ import { TwitchProvider } from '@gitroom/nestjs-libraries/integrations/social/twimport { SocialAbstract } from '@gitroom/nestjs-libraries/integrations/social.abstract';import { MoltbookProvider } from '@gitroom/nestjs-libraries/integrations/social/moltbook.provider';import { SkoolProvider } from '@gitroom/nestjs-libraries/integrations/social/skool.provider';+import { WhopProvider } from '@gitroom/nestjs-libraries/integrations/social/whop.provider';export const socialIntegrationList: Array<SocialAbstract & SocialProvider> = [new XProvider(),@@ -66,6 +67,7 @@ export const socialIntegrationList: Array<SocialAbstract & SocialProvider> = [new WordpressProvider(),new ListmonkProvider(),new MoltbookProvider(),+ new WhopProvider(),new SkoolProvider(),// new MastodonCustomProvider(),];diff --git a/libraries/nestjs-libraries/src/integrations/social/whop.provider.ts b/libraries/nestjs-libraries/src/integrations/social/whop.provider.tsnew file mode 100644index 000000000..604f9ecee--- /dev/null+++ b/libraries/nestjs-libraries/src/integrations/social/whop.provider.ts@@ -0,0 +1,375 @@+import { createHash, randomBytes } from 'crypto';+import {+ AuthTokenDetails,+ MediaContent,+ PostDetails,+ PostResponse,+ SocialProvider,+} from '@gitroom/nestjs-libraries/integrations/social/social.integrations.interface';+import { makeId } from '@gitroom/nestjs-libraries/services/make.is';+import { timer } from '@gitroom/helpers/utils/timer';+import { SocialAbstract } from '@gitroom/nestjs-libraries/integrations/social.abstract';+import { WhopDto } from '@gitroom/nestjs-libraries/dtos/posts/providers-settings/whop.dto';+import { Integration } from '@prisma/client';+import { Tool } from '@gitroom/nestjs-libraries/integrations/tool.decorator';++export class WhopProvider extends SocialAbstract implements SocialProvider {+ identifier = 'whop';+ name = 'Whop';+ isBetweenSteps = false;+ scopes = ['openid', 'profile', 'email', 'forum:post:create', 'forum:read', 'company:basic:read'];+ refreshCron = true;+ editor = 'markdown' as const;+ dto = WhopDto;+ toolTip = 'Schedule posts to forums';++ maxLength() {+ return 50000;+ }++ private generateCodeChallenge(codeVerifier: string): string {+ return createHash('sha256').update(codeVerifier).digest('base64url');+ }++ override handleErrors(+ body: string+ ):+ | { type: 'refresh-token' | 'bad-body'; value: string }+ | undefined {+ if (body.includes('invalid_grant')) {+ return {+ type: 'refresh-token' as const,+ value: 'Invalid token, please re-authenticate',+ };+ }++ if (body.includes('insufficient_scope')) {+ return {+ type: 'refresh-token' as const,+ value:+ 'Insufficient permissions, please re-authenticate with required scopes',+ };+ }++ if (body.includes('invalid_request')) {+ return {+ type: 'bad-body' as const,+ value: 'Invalid request parameters',+ };+ }++ if (body.includes('not_found')) {+ return {+ type: 'bad-body' as const,+ value: 'Forum or experience not found',+ };+ }++ return undefined;+ }++ async refreshToken(refreshToken: string): Promise<AuthTokenDetails> {+ const response = await (+ await fetch('https://api.whop.com/oauth/token', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ grant_type: 'refresh_token',+ refresh_token: refreshToken,+ client_id: process.env.WHOP_CLIENT_ID,+ }),+ })+ ).json();++ const userInfo = await (+ await fetch('https://api.whop.com/oauth/userinfo', {+ headers: { Authorization: `Bearer ${response.access_token}` },+ })+ ).json();++ return {+ id: userInfo.sub,+ name: userInfo.name || userInfo.preferred_username || '',+ accessToken: response.access_token,+ refreshToken: response.refresh_token,+ expiresIn: response.expires_in || 3600,+ picture: userInfo.picture || '',+ username: userInfo.preferred_username || '',+ };+ }++ async generateAuthUrl() {+ const state = makeId(6);+ const codeVerifier = randomBytes(32).toString('base64url');+ const codeChallenge = this.generateCodeChallenge(codeVerifier);+ const nonce = makeId(16);++ return {+ url:+ 'https://api.whop.com/oauth/authorize' ++ `?response_type=code` ++ `&client_id=${process.env.WHOP_CLIENT_ID}` ++ `&redirect_uri=${encodeURIComponent(+ `${process.env.FRONTEND_URL}/integrations/social/whop`+ )}` ++ `&scope=${encodeURIComponent(this.scopes.join(' '))}` ++ `&state=${state}` ++ `&nonce=${nonce}` ++ `&code_challenge=${codeChallenge}` ++ `&code_challenge_method=S256`,+ codeVerifier,+ state,+ };+ }++ async authenticate(params: {+ code: string;+ codeVerifier: string;+ refresh?: string;+ }) {+ const redirectUri = `${process.env.FRONTEND_URL}/integrations/social/whop${+ params.refresh ? `?refresh=${params.refresh}` : ''+ }`;++ const tokenResponse = await (+ await fetch('https://api.whop.com/oauth/token', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({+ grant_type: 'authorization_code',+ code: params.code,+ redirect_uri: redirectUri,+ client_id: process.env.WHOP_CLIENT_ID,+ code_verifier: params.codeVerifier,+ }),+ })+ ).json();++ if (tokenResponse.error) {+ return `Authentication failed: ${+ tokenResponse.error_description || tokenResponse.error+ }`;+ }++ const userInfo = await (+ await fetch('https://api.whop.com/oauth/userinfo', {+ headers: { Authorization: `Bearer ${tokenResponse.access_token}` },+ })+ ).json();++ return {+ id: userInfo.sub,+ name: userInfo.name || userInfo.preferred_username || '',+ accessToken: tokenResponse.access_token,+ refreshToken: tokenResponse.refresh_token,+ expiresIn: tokenResponse.expires_in || 3600,+ picture: userInfo.picture || '',+ username: userInfo.preferred_username || '',+ };+ }++ @Tool({ description: 'Companies', dataSchema: [] })+ async companies(accessToken: string, params: any, id: string) {+ try {+ const response = await fetch(+ 'https://api.whop.com/api/v1/companies?first=50',+ {+ headers: {+ Authorization: `Bearer ${accessToken}`,+ },+ }+ );++ const { data } = await response.json();++ return (data || []).map((company: any) => ({+ id: company.id,+ name: company.title,+ }));+ } catch {+ return [];+ }+ }++ @Tool({ description: 'Experiences', dataSchema: [] })+ async experiences(accessToken: string, params: any, id: string) {+ try {+ if (!params?.id) return [];++ const response = await fetch(+ `https://api.whop.com/api/v1/forums?company_id=${params.id}&first=50`,+ {+ headers: {+ Authorization: `Bearer ${accessToken}`,+ },+ }+ );++ const { data } = await response.json();++ return (data || []).map((forum: any) => ({+ id: forum.experience?.id || forum.id,+ name: forum.experience?.name || forum.id,+ }));+ } catch {+ return [];+ }+ }++ private async uploadMediaToWhop(+ media: MediaContent[],+ accessToken: string+ ): Promise<{ id: string }[]> {+ if (!media || media.length === 0) return [];++ const attachments: { id: string }[] = [];++ for (const item of media) {+ const fileResponse = await fetch(item.path);+ const fileBuffer = await fileResponse.arrayBuffer();+ const fileName = item.path.split('/').pop() || 'file';++ const createFileResponse = await (+ await this.fetch(+ 'https://api.whop.com/api/v1/files',+ {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${accessToken}`,+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify({+ filename: fileName,+ }),+ },+ 'create file record'+ )+ ).json();++ if (createFileResponse.upload_url) {+ await fetch(createFileResponse.upload_url, {+ method: 'PUT',+ headers: createFileResponse.upload_headers || {},+ body: fileBuffer,+ });++ let uploadStatus = 'pending';+ while (uploadStatus !== 'ready') {+ const fileStatus = await (+ await this.fetch(+ `https://api.whop.com/api/v1/files/${createFileResponse.id}`,+ {+ headers: {+ Authorization: `Bearer ${accessToken}`,+ },+ },+ 'check file status',+ 0,+ true+ )+ ).json();+ uploadStatus = fileStatus.upload_status;+ if (uploadStatus === 'failed') {+ throw new Error('File upload failed');+ }+ if (uploadStatus !== 'ready') {+ await timer(5000);+ }+ }+ }++ attachments.push({ id: createFileResponse.id });+ }++ return attachments;+ }++ async post(+ id: string,+ accessToken: string,+ postDetails: PostDetails<WhopDto>[],+ integration: Integration+ ): Promise<PostResponse[]> {+ const [post] = postDetails;++ const attachments = await this.uploadMediaToWhop(+ post.media || [],+ accessToken+ );++ const data = await (+ await this.fetch(+ 'https://api.whop.com/api/v1/forum_posts',+ {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${accessToken}`,+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify({+ experience_id: post.settings.experience,+ content: post.message,+ ...(post.settings.title ? { title: post.settings.title } : {}),+ ...(attachments.length ? { attachments } : {}),+ }),+ },+ 'create forum post'+ )+ ).json();++ return [+ {+ id: post.id,+ postId: data.id,+ releaseURL: `https://whop.com/experiences/${post.settings.experience}/${data.id}`,+ status: 'success',+ },+ ];+ }++ async comment(+ id: string,+ postId: string,+ lastCommentId: string | undefined,+ accessToken: string,+ postDetails: PostDetails<WhopDto>[],+ integration: Integration+ ): Promise<PostResponse[]> {+ const [post] = postDetails;+ const replyToId = lastCommentId || postId;++ const attachments = await this.uploadMediaToWhop(+ post.media || [],+ accessToken+ );++ const data = await (+ await this.fetch(+ 'https://api.whop.com/api/v1/forum_posts',+ {+ method: 'POST',+ headers: {+ Authorization: `Bearer ${accessToken}`,+ 'Content-Type': 'application/json',+ },+ body: JSON.stringify({+ experience_id: post.settings.experience,+ content: post.message,+ parent_id: replyToId,+ ...(attachments.length ? { attachments } : {}),+ }),+ },+ 'create comment'+ )+ ).json();++ return [+ {+ id: post.id,+ postId: data.id,+ releaseURL: `https://whop.com/experiences/${post.settings.experience}/${postId}`,+ status: 'success',+ },+ ];+ }+}