Skip to content

πŸ“¨ The ultimate agentic social media scheduling tool πŸ€–

feat: plugs

Nevo David7ca7a14294e7
diff --cc apps/backend/src/api/routes/integrations.controller.ts
index a6ea63ef2,52c655c8f..b69d856f9
--- a/apps/backend/src/api/routes/integrations.controller.ts
+++ b/apps/backend/src/api/routes/integrations.controller.ts
@@@ -22,8 -30,11 +22,12 @@@ import { PostsService } from '@gitroom/
import { IntegrationTimeDto } from '@gitroom/nestjs-libraries/dtos/integrations/integration.time.dto';
import { AuthService } from '@gitroom/helpers/auth/auth.service';
import { AuthTokenDetails } from '@gitroom/nestjs-libraries/integrations/social/social.integrations.interface';
- import { NotEnoughScopes } from '@gitroom/nestjs-libraries/integrations/social.abstract';
+import { PlugDto } from '@gitroom/nestjs-libraries/dtos/plugs/plug.dto';
+ import {
+ NotEnoughScopes,
+ RefreshToken,
+ } from '@gitroom/nestjs-libraries/integrations/social.abstract';
+ import { timer } from '@gitroom/helpers/utils/timer';
@ApiTags('Integrations')
@Controller('/integrations')
diff --cc apps/frontend/src/components/plugs/plugs.tsx
index c399a723e,000000000..296874478
mode 100644,000000..100644
--- a/apps/frontend/src/components/plugs/plugs.tsx
+++ b/apps/frontend/src/components/plugs/plugs.tsx
@@@ -1,174 -1,0 +1,173 @@@
+'use client';
+
+import useSWR from 'swr';
+import { useCallback, useMemo, useState } from 'react';
+import { capitalize, orderBy } from 'lodash';
+import clsx from 'clsx';
+import ImageWithFallback from '@gitroom/react/helpers/image.with.fallback';
+import Image from 'next/image';
+import { useFetch } from '@gitroom/helpers/utils/custom.fetch';
+import { Select } from '@gitroom/react/form/select';
+import { Button } from '@gitroom/react/form/button';
+import { useRouter } from 'next/navigation';
+import { useToaster } from '@gitroom/react/toaster/toaster';
+import { PlugsContext } from '@gitroom/frontend/components/plugs/plugs.context';
+import { Plug } from '@gitroom/frontend/components/plugs/plug';
+
+export const Plugs = () => {
+ const fetch = useFetch();
+ const router = useRouter();
+ const [current, setCurrent] = useState(0);
+ const [refresh, setRefresh] = useState(false);
+ const toaster = useToaster();
+ const load = useCallback(async () => {
+ return (await (await fetch('/integrations/list')).json()).integrations;
+ }, []);
+
+ const load2 = useCallback(async (path: string) => {
+ return await (await fetch(path)).json();
+ }, []);
+
+ const { data: plugList, isLoading: plugLoading } = useSWR(
+ '/integrations/plug/list',
+ load2,
+ {
+ fallbackData: [],
+ }
+ );
+
+ const { data, isLoading } = useSWR('analytics-list', load, {
+ fallbackData: [],
+ });
+
+ const sortedIntegrations = useMemo(() => {
+ return orderBy(
+ data.filter((integration: any) =>
+ plugList?.plugs?.some(
+ (f: any) => f.identifier === integration.identifier
+ )
+ ),
+ // data.filter((integration) => !integration.disabled),
+ ['type', 'disabled', 'identifier'],
+ ['desc', 'asc', 'asc']
+ );
+ }, [data, plugList]);
+
+ const currentIntegration = useMemo(() => {
+ return sortedIntegrations[current];
+ }, [current, sortedIntegrations]);
+
+ const currentIntegrationPlug = useMemo(() => {
+ const plug = plugList?.plugs?.find(
+ (f: any) => f?.identifier === currentIntegration?.identifier
+ );
+
+ if (!plug) {
+ return null;
+ }
+ return {
+ providerId: currentIntegration.id,
+ ...plug,
+ };
+ }, [currentIntegration, plugList]);
+
- console.log(currentIntegrationPlug);
+ if (isLoading || plugLoading) {
+ return null;
+ }
+
+ if (!sortedIntegrations.length && !isLoading) {
+ return (
+ <div className="flex flex-col items-center mt-[100px] gap-[27px] text-center">
+ <div>
+ <img src="/peoplemarketplace.svg" />
+ </div>
+ <div className="text-[48px]">
- Can{"'"}t show analytics yet
++ There are not plugs matching your channels
+ <br />
- You have to add Social Media channels
++ You have to add: X or LinkedIn or Threads
+ </div>
+ <Button onClick={() => router.push('/launches')}>
+ Go to the calendar to add channels
+ </Button>
+ </div>
+ );
+ }
+
+ return (
+ <div className="flex gap-[30px] flex-1">
+ <div className="p-[16px] bg-customColor48 overflow-hidden flex w-[220px]">
+ <div className="flex gap-[16px] flex-col overflow-hidden">
+ <div className="text-[20px] mb-[8px]">Channels</div>
+ {sortedIntegrations.map((integration, index) => (
+ <div
+ key={integration.id}
+ onClick={() => {
+ if (integration.refreshNeeded) {
+ toaster.show(
+ 'Please refresh the integration from the calendar',
+ 'warning'
+ );
+ return;
+ }
+ setRefresh(true);
+ setTimeout(() => {
+ setRefresh(false);
+ }, 10);
+ setCurrent(index);
+ }}
+ className={clsx(
+ 'flex gap-[8px] items-center',
+ currentIntegration.id !== integration.id &&
+ 'opacity-20 hover:opacity-100 cursor-pointer'
+ )}
+ >
+ <div
+ className={clsx(
+ 'relative w-[34px] h-[34px] rounded-full flex justify-center items-center bg-fifth',
+ integration.disabled && 'opacity-50'
+ )}
+ >
+ {(integration.inBetweenSteps || integration.refreshNeeded) && (
+ <div className="absolute left-0 top-0 w-[39px] h-[46px] cursor-pointer">
+ <div className="bg-red-500 w-[15px] h-[15px] rounded-full left-0 -top-[5px] absolute z-[200] text-[10px] flex justify-center items-center">
+ !
+ </div>
+ <div className="bg-primary/60 w-[39px] h-[46px] left-0 top-0 absolute rounded-full z-[199]" />
+ </div>
+ )}
+ <ImageWithFallback
+ fallbackSrc={`/icons/platforms/${integration.identifier}.png`}
+ src={integration.picture}
+ className="rounded-full"
+ alt={integration.identifier}
+ width={32}
+ height={32}
+ />
+ <Image
+ src={`/icons/platforms/${integration.identifier}.png`}
+ className="rounded-full absolute z-10 -bottom-[5px] -right-[5px] border border-fifth"
+ alt={integration.identifier}
+ width={20}
+ height={20}
+ />
+ </div>
+ <div
+ className={clsx(
+ 'flex-1 whitespace-nowrap text-ellipsis overflow-hidden',
+ integration.disabled && 'opacity-50'
+ )}
+ >
+ {integration.name}
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ <div className="flex-1 flex flex-col gap-[14px]">
+ <PlugsContext.Provider value={currentIntegrationPlug}>
+ <Plug />
+ </PlugsContext.Provider>
+ </div>
+ </div>
+ );
+};
diff --cc apps/workers/src/app/plugs.controller.ts
index a91916d53,000000000..36e4f7d1b
mode 100644,000000..100644
--- a/apps/workers/src/app/plugs.controller.ts
+++ b/apps/workers/src/app/plugs.controller.ts
@@@ -1,52 -1,0 +1,21 @@@
+import { Controller } from '@nestjs/common';
+import { EventPattern, Transport } from '@nestjs/microservices';
- import { BullMqClient } from '@gitroom/nestjs-libraries/bull-mq-transport-new/client';
+import { IntegrationService } from '@gitroom/nestjs-libraries/database/prisma/integrations/integration.service';
+
+@Controller()
+export class PlugsController {
+ constructor(
- private _workerServiceProducer: BullMqClient,
+ private _integrationService: IntegrationService
+ ) {}
+
+ @EventPattern('plugs', Transport.REDIS)
+ async plug(data: {
- orgId: string;
- integrationId: string;
- funcName: string;
- retry: number;
++ plugId: string;
++ postId: string;
+ delay: number;
++ totalRuns: number;
++ currentRun: number;
+ }) {
- try {
- await this._integrationService.startPlug(data);
-
- if (process.env.NODE_ENV && process.env.NODE_ENV !== 'development') {
- return this._workerServiceProducer.emit('plugs', {
- id: data.integrationId + '-' + data.funcName,
- options: {
- delay: 6000, // delay,
- },
- payload: {
- ...data,
- retry: data.retry,
- },
- });
- }
- } catch (e) {
- if (data.retry > 3) {
- return;
- }
- return this._workerServiceProducer.emit('plugs', {
- id: data.integrationId + '-' + data.funcName,
- options: {
- delay: data.delay, // delay,
- },
- payload: {
- ...data,
- retry: data.retry + 1,
- },
- });
- }
++ return this._integrationService.processPlugs(data);
+ }
+}
diff --cc libraries/helpers/src/decorators/plug.decorator.ts
index a16a02dac,000000000..56b208249
mode 100644,000000..100644
--- a/libraries/helpers/src/decorators/plug.decorator.ts
+++ b/libraries/helpers/src/decorators/plug.decorator.ts
@@@ -1,25 -1,0 +1,27 @@@
+import 'reflect-metadata';
+
+export function Plug(params: {
++ identifier: string;
+ title: string;
+ description: string;
+ runEveryMilliseconds: number;
++ totalRuns: number;
+ fields: {
+ name: string;
+ description: string;
+ type: string;
+ placeholder: string;
+ validation?: RegExp;
+ }[];
+}) {
+ return function (target: Object, propertyKey: string | symbol, descriptor: any) {
+ // Retrieve existing metadata or initialize an empty array
+ const existingMetadata = Reflect.getMetadata('custom:plug', target) || [];
+
+ // Add the metadata information for this method
+ existingMetadata.push({ methodName: propertyKey, ...params });
+
+ // Define metadata on the class prototype (so it can be retrieved from the class)
+ Reflect.defineMetadata('custom:plug', existingMetadata, target);
+ };
+}
diff --cc libraries/nestjs-libraries/src/database/prisma/integrations/integration.repository.ts
index 845d0b10b,87d459941..1ee7c2af2
--- a/libraries/nestjs-libraries/src/database/prisma/integrations/integration.repository.ts
+++ b/libraries/nestjs-libraries/src/database/prisma/integrations/integration.repository.ts
@@@ -12,9 -11,8 +12,10 @@@ export class IntegrationRepository
private storage = UploadFactory.createStorage();
constructor(
private _integration: PrismaRepository<'integration'>,
- private _customers: PrismaRepository<'customer'>,
- private _posts: PrismaRepository<'post'>
+ private _posts: PrismaRepository<'post'>,
+ private _plugs: PrismaRepository<'plugs'>,
- private _exisingPlugData: PrismaRepository<'exisingPlugData'>
++ private _exisingPlugData: PrismaRepository<'exisingPlugData'>,
++ private _customers: PrismaRepository<'customer'>
) {}
async setTimes(org: string, id: string, times: IntegrationTimeDto) {
@@@ -32,6 -30,6 +33,35 @@@
});
}
++ getPlug(plugId: string) {
++ return this._plugs.model.plugs.findFirst({
++ where: {
++ id: plugId,
++ },
++ include: {
++ integration: true
++ }
++ });
++ }
++
++ async getPlugs(orgId: string, integrationId: string) {
++ return this._plugs.model.plugs.findMany({
++ where: {
++ integrationId,
++ organizationId: orgId,
++ activated: true,
++ },
++ include: {
++ integration: {
++ select: {
++ id: true,
++ providerIdentifier: true,
++ },
++ },
++ },
++ });
++ }
++
async updateIntegration(id: string, params: Partial<Integration>) {
if (
params.picture &&
diff --cc libraries/nestjs-libraries/src/database/prisma/integrations/integration.service.ts
index c3f9e4735,c9687bdca..f2306dba4
--- a/libraries/nestjs-libraries/src/database/prisma/integrations/integration.service.ts
+++ b/libraries/nestjs-libraries/src/database/prisma/integrations/integration.service.ts
@@@ -54,7 -47,7 +54,9 @@@ export class IntegrationService
timezone?: number,
customInstanceDetails?: string
) {
- const uploadedPicture = await this.storage.uploadSimple(picture);
- const uploadedPicture = picture ? await this.storage.uploadSimple(picture) : undefined;
++ const uploadedPicture = picture
++ ? await this.storage.uploadSimple(picture)
++ : undefined;
return this._integrationRepository.createOrUpdateIntegration(
org,
name,
@@@ -378,139 -371,7 +388,116 @@@
return [];
}
+ customers(orgId: string) {
+ return this._integrationRepository.customers(orgId);
+ }
++
+ getPlugsByIntegrationId(org: string, integrationId: string) {
+ return this._integrationRepository.getPlugsByIntegrationId(
+ org,
+ integrationId
+ );
+ }
+
- processPlugs(
- orgId: string,
- integrationId: string,
- delay: number,
- funcName: string
- ) {
- return this._workerServiceProducer.emit('plugs', {
- id: integrationId + '-' + funcName,
++ async processPlugs(data: {
++ plugId: string;
++ postId: string;
++ delay: number;
++ totalRuns: number;
++ currentRun: number;
++ }) {
++ const getPlugById = await this._integrationRepository.getPlug(data.plugId);
++ if (!getPlugById) {
++ return ;
++ }
++
++ const integration = this._integrationManager.getSocialIntegration(
++ getPlugById.integration.providerIdentifier
++ );
++
++ const findPlug = this._integrationManager
++ .getAllPlugs()
++ .find(
++ (p) => p.identifier === getPlugById.integration.providerIdentifier
++ )!;
++
++ console.log(data.postId);
++
++ // @ts-ignore
++ const process = await integration[getPlugById.plugFunction](
++ getPlugById.integration,
++ data.postId,
++ JSON.parse(getPlugById.data).reduce((all: any, current: any) => {
++ all[current.name] = current.value;
++ return all;
++ }, {})
++ );
++
++ if (process) {
++ return ;
++ }
++
++ if (data.totalRuns === data.currentRun) {
++ return ;
++ }
++
++ this._workerServiceProducer.emit('plugs', {
++ id: 'plug_' + data.postId + '_' + findPlug.identifier,
+ options: {
- delay: 0, // delay,
++ delay: 0, // runPlug.runEveryMilliseconds,
+ },
+ payload: {
- retry: 1,
- delay,
- orgId,
- integrationId: integrationId,
- funcName: funcName,
++ plugId: data.plugId,
++ postId: data.postId,
++ delay: data.delay,
++ totalRuns: data.totalRuns,
++ currentRun: data.currentRun + 1,
+ },
+ });
+ }
+
- async activatedPlug(
- orgId: string,
- integrationId: string,
- funcName: string,
- type: 'add' | 'remove'
- ) {
- const loadIntegration = await this.getIntegrationById(orgId, integrationId);
- const allPlugs = this._integrationManager.getAllPlugs();
- const findPlug = allPlugs.find(
- (p) => p.identifier === loadIntegration?.providerIdentifier!
- )!;
- const plug = findPlug.plugs.find((p: any) => p.methodName === funcName)!;
-
- if (type === 'add') {
- return this.processPlugs(
- orgId,
- integrationId,
- plug.runEveryMilliseconds,
- funcName
- );
- } else {
- console.log(integrationId + '-' + funcName);
- return this._workerServiceProducer.delete(
- 'plugs',
- integrationId + '-' + funcName
- );
- }
- }
-
+ async createOrUpdatePlug(
+ orgId: string,
+ integrationId: string,
+ body: PlugDto
+ ) {
+ const { activated } = await this._integrationRepository.createOrUpdatePlug(
+ orgId,
+ integrationId,
+ body
+ );
+
- if (activated) {
- await this.activatedPlug(orgId, integrationId, body.func, 'add');
- }
++ return {
++ activated,
++ };
+ }
+
+ async changePlugActivation(orgId: string, plugId: string, status: boolean) {
+ const { id, integrationId, plugFunction } =
+ await this._integrationRepository.changePlugActivation(
+ orgId,
+ plugId,
+ status
+ );
+
- if (status) {
- await this.activatedPlug(orgId, integrationId, plugFunction, 'add');
- } else {
- await this.activatedPlug(orgId, integrationId, plugFunction, 'remove');
- }
-
+ return { id };
+ }
+
- async loadExisingData (methodName: string, integrationId: string, id: string[]) {
- const exisingData = await this._integrationRepository.loadExisingData(methodName, integrationId, id);
- const loadOnlyIds = exisingData.map(p => p.value);
- return difference(id, loadOnlyIds);
++ async getPlugs(orgId: string, integrationId: string) {
++ return this._integrationRepository.getPlugs(orgId, integrationId);
+ }
+
- async startPlug(data: {
- orgId: string;
- integrationId: string;
- funcName: string;
- retry: number;
- delay: number;
- }) {
- const integration = await this.getIntegrationById(
- data.orgId,
- data.integrationId
- );
-
- if (!integration) {
- return;
- }
-
- const plugInformation = (
- await this._integrationRepository.getPlugsByIntegrationId(
- data.orgId,
- data.integrationId
- )
- ).find((p) => p.plugFunction === data.funcName)!;
-
- const plugData = JSON.parse(plugInformation.data).reduce(
- (all: any, current: any) => ({
- ...all,
- [current.name]: current.value,
- }),
- {}
- );
-
- const integrationInstance = this._integrationManager.getSocialIntegration(
- integration.providerIdentifier
++ async loadExisingData(
++ methodName: string,
++ integrationId: string,
++ id: string[]
++ ) {
++ const exisingData = await this._integrationRepository.loadExisingData(
++ methodName,
++ integrationId,
++ id
+ );
-
- // @ts-ignore
- const ids = await integrationInstance[data.funcName](integration, plugData, this.loadExisingData.bind(this));
- return this._integrationRepository.saveExisingData(data.funcName, data.integrationId, ids);
++ const loadOnlyIds = exisingData.map((p) => p.value);
++ return difference(id, loadOnlyIds);
+ }
}
diff --cc libraries/nestjs-libraries/src/database/prisma/posts/posts.service.ts
index 272b80c20,272b80c20..791b27430
--- a/libraries/nestjs-libraries/src/database/prisma/posts/posts.service.ts
+++ b/libraries/nestjs-libraries/src/database/prisma/posts/posts.service.ts
@@@ -299,6 -299,6 +299,13 @@@ export class PostsService
true
);
++ await this.checkPlugs(
++ integration.organizationId,
++ getIntegration.identifier,
++ integration.id,
++ publishedPosts[0].postId
++ );
++
return {
postId: publishedPosts[0].postId,
releaseURL: publishedPosts[0].releaseURL,
@@@ -312,6 -312,6 +319,42 @@@
}
}
++ private async checkPlugs(
++ orgId: string,
++ providerName: string,
++ integrationId: string,
++ postId: string
++ ) {
++ const loadAllPlugs = this._integrationManager.getAllPlugs();
++ const getPlugs = await this._integrationService.getPlugs(
++ orgId,
++ integrationId
++ );
++
++ const currentPlug = loadAllPlugs.find((p) => p.identifier === providerName);
++
++ for (const plug of getPlugs) {
++ const runPlug = currentPlug?.plugs?.find((p: any) => p.methodName === plug.plugFunction)!;
++ if (!runPlug) {
++ continue;
++ }
++
++ this._workerServiceProducer.emit('plugs', {
++ id: 'plug_' + postId + '_' + runPlug.identifier,
++ options: {
++ delay: 0, // runPlug.runEveryMilliseconds,
++ },
++ payload: {
++ plugId: plug.id,
++ postId,
++ delay: 0, // runPlug.runEveryMilliseconds,
++ totalRuns: runPlug.totalRuns,
++ currentRun: 1,
++ },
++ });
++ }
++ }
++
private async postArticle(integration: Integration, posts: Post[]) {
const getIntegration = this._integrationManager.getArticlesIntegration(
integration.providerIdentifier
diff --cc libraries/nestjs-libraries/src/database/prisma/schema.prisma
index ca128f261,7cd6ac59f..3edef3cee
--- a/libraries/nestjs-libraries/src/database/prisma/schema.prisma
+++ b/libraries/nestjs-libraries/src/database/prisma/schema.prisma
@@@ -29,7 -29,7 +29,8 @@@ model Organization
buyerOrganization MessagesGroup[]
usedCodes UsedCodes[]
credits Credits[]
+ plugs Plugs[]
+ customers Customer[]
}
model User {
@@@ -265,8 -278,8 +279,10 @@@ model Integration
refreshNeeded Boolean @default(false)
postingTimes String @default("[{\"time\":120}, {\"time\":400}, {\"time\":700}]")
customInstanceDetails String?
+ customerId String?
+ customer Customer? @relation(fields: [customerId], references: [id])
+ plugs Plugs[]
+ exisingPlugData ExisingPlugData[]
@@index([updatedAt])
@@index([deletedAt])
diff --cc libraries/nestjs-libraries/src/integrations/social/bluesky.provider.ts
index f7ce1309a,f7ce1309a..bac06423e
--- a/libraries/nestjs-libraries/src/integrations/social/bluesky.provider.ts
+++ b/libraries/nestjs-libraries/src/integrations/social/bluesky.provider.ts
@@@ -11,6 -11,6 +11,8 @@@ import dayjs from 'dayjs'
import { Integration } from '@prisma/client';
import { AuthService } from '@gitroom/helpers/auth/auth.service';
import sharp from 'sharp';
++import { Plug } from '@gitroom/helpers/decorators/plug.decorator';
++import { timer } from '@gitroom/helpers/utils/timer';
export class BlueskyProvider extends SocialAbstract implements SocialProvider {
identifier = 'bluesky';
@@@ -116,7 -116,7 +118,7 @@@
let loadCid = '';
let loadUri = '';
-- const cidUrl = [] as { cid: string; url: string, rev: string }[];
++ const cidUrl = [] as { cid: string; url: string; rev: string }[];
for (const post of postDetails) {
const images = await Promise.all(
post.media?.map(async (p) => {
@@@ -134,9 -134,9 +136,9 @@@
const rt = new RichText({
text: post.message,
-- })
++ });
-- await rt.detectFacets(agent)
++ await rt.detectFacets(agent);
// @ts-ignore
const { cid, uri, commit } = await agent.post({
@@@ -179,9 -179,9 +181,143 @@@
return postDetails.map((p, index) => ({
id: p.id,
-- postId: cidUrl[index].cid,
++ postId: cidUrl[index].url,
status: 'completed',
-- releaseURL: `https://bsky.app/profile/${id}/post/${cidUrl[index].url.split('/').pop()}`,
++ releaseURL: `https://bsky.app/profile/${id}/post/${cidUrl[index].url
++ .split('/')
++ .pop()}`,
}));
}
++
++ @Plug({
++ identifier: 'bluesky-autoRepostPost',
++ title: 'Auto Repost Posts',
++ description:
++ 'When a post reached a certain number of likes, repost it to increase engagement (1 week old posts)',
++ runEveryMilliseconds: 21600000,
++ totalRuns: 3,
++ fields: [
++ {
++ name: 'likesAmount',
++ type: 'number',
++ placeholder: 'Amount of likes',
++ description: 'The amount of likes to trigger the repost',
++ validation: /^\d+$/,
++ },
++ ],
++ })
++ async autoRepostPost(
++ integration: Integration,
++ id: string,
++ fields: { likesAmount: string }
++ ) {
++ const body = JSON.parse(
++ AuthService.fixedDecryption(integration.customInstanceDetails!)
++ );
++ const agent = new BskyAgent({
++ service: body.service,
++ });
++
++ await agent.login({
++ identifier: body.identifier,
++ password: body.password,
++ });
++
++ const getThread = await agent.getPostThread({
++ uri: id,
++ depth: 0,
++ });
++
++ // @ts-ignore
++ if (getThread.data.thread.post?.likeCount >= +fields.likesAmount) {
++ await timer(2000);
++ await agent.repost(
++ // @ts-ignore
++ getThread.data.thread.post?.uri,
++ // @ts-ignore
++ getThread.data.thread.post?.cid
++ );
++ return true;
++ }
++
++ return true;
++ }
++
++ @Plug({
++ identifier: 'bluesky-autoPlugPost',
++ title: 'Auto plug post',
++ description:
++ 'When a post reached a certain number of likes, add another post to it so you followers get a notification about your promotion',
++ runEveryMilliseconds: 21600000,
++ totalRuns: 3,
++ fields: [
++ {
++ name: 'likesAmount',
++ type: 'number',
++ placeholder: 'Amount of likes',
++ description: 'The amount of likes to trigger the repost',
++ validation: /^\d+$/,
++ },
++ {
++ name: 'post',
++ type: 'richtext',
++ placeholder: 'Post to plug',
++ description: 'Message content to plug',
++ validation: /^[\s\S]{3,}$/g,
++ },
++ ],
++ })
++ async autoPlugPost(
++ integration: Integration,
++ id: string,
++ fields: { likesAmount: string; post: string }
++ ) {
++ const body = JSON.parse(
++ AuthService.fixedDecryption(integration.customInstanceDetails!)
++ );
++ const agent = new BskyAgent({
++ service: body.service,
++ });
++
++ await agent.login({
++ identifier: body.identifier,
++ password: body.password,
++ });
++
++ const getThread = await agent.getPostThread({
++ uri: id,
++ depth: 0,
++ });
++
++ // @ts-ignore
++ if (getThread.data.thread.post?.likeCount >= +fields.likesAmount) {
++ await timer(2000);
++ const rt = new RichText({
++ text: fields.post,
++ });
++
++ await agent.post({
++ text: rt.text,
++ facets: rt.facets,
++ createdAt: new Date().toISOString(),
++ reply: {
++ root: {
++ // @ts-ignore
++ uri: getThread.data.thread.post?.uri,
++ // @ts-ignore
++ cid: getThread.data.thread.post?.cid,
++ },
++ parent: {
++ // @ts-ignore
++ uri: getThread.data.thread.post?.uri,
++ // @ts-ignore
++ cid: getThread.data.thread.post?.cid,
++ },
++ },
++ });
++ return true;
++ }
++
++ return true;
++ }
}
diff --cc libraries/nestjs-libraries/src/integrations/social/linkedin.page.provider.ts
index 59ae0a71c,3536c39fa..9c1aacce8
--- a/libraries/nestjs-libraries/src/integrations/social/linkedin.page.provider.ts
+++ b/libraries/nestjs-libraries/src/integrations/social/linkedin.page.provider.ts
@@@ -9,7 -9,6 +9,8 @@@ import { makeId } from '@gitroom/nestjs
import { LinkedinProvider } from '@gitroom/nestjs-libraries/integrations/social/linkedin.provider';
import dayjs from 'dayjs';
import { Integration } from '@prisma/client';
+import { Plug } from '@gitroom/helpers/decorators/plug.decorator';
++import { timer } from '@gitroom/helpers/utils/timer';
export class LinkedinPageProvider
extends LinkedinProvider
@@@ -361,126 -360,6 +362,77 @@@
percentageChange: 5,
}));
}
+
+ @Plug({
++ identifier: 'linkedin-page-autoRepostPost',
+ title: 'Auto Repost Posts',
+ description:
+ 'When a post reached a certain number of likes, repost it to increase engagement (1 week old posts)',
- runEveryMilliseconds: 7200000,
++ runEveryMilliseconds: 21600000,
++ totalRuns: 3,
+ fields: [
+ {
+ name: 'likesAmount',
+ type: 'number',
+ placeholder: 'Amount of likes',
- description: 'The amount of likes to trigger the post',
++ description: 'The amount of likes to trigger the repost',
+ validation: /^\d+$/,
+ },
+ ],
+ })
+ async autoRepostPost(
+ integration: Integration,
- fields: { likesAmount: number },
- loadExisingData: (
- methodName: string,
- integrationId: string,
- id: string[]
- ) => Promise<string[]>
++ id: string,
++ fields: { likesAmount: string }
+ ) {
- const all = await // const { elements } = await (
- (
++ const {
++ likesSummary: { totalLikes },
++ } = await (
+ await this.fetch(
- `https://api.linkedin.com/rest/posts?author=${encodeURIComponent(
- `urn:li:organization:${integration.internalId}`
- )}&q=author&count=10&sortBy=LAST_MODIFIED`,
++ `https://api.linkedin.com/v2/socialActions/${encodeURIComponent(id)}`,
+ {
+ method: 'GET',
+ headers: {
+ 'X-Restli-Protocol-Version': '2.0.0',
+ 'Content-Type': 'application/json',
+ 'LinkedIn-Version': '202402',
+ Authorization: `Bearer ${integration.token}`,
+ },
+ }
+ )
+ ).json();
+
- // only post published in the last week
- const lastWeekPosts = all.elements.filter((element: any) => {
- const postDate = new Date(element.publishedAt).getTime();
- const weekAgo = new Date().getTime() - 604800000;
- return postDate > weekAgo;
- });
-
- const getLastFiveLikes = await Promise.all(
- lastWeekPosts.map(async (element: any) => {
- const {
- likesSummary: { totalLikes },
- } = await (
- await this.fetch(
- `https://api.linkedin.com/v2/socialActions/${encodeURIComponent(
- element.id
- )}`,
- {
- method: 'GET',
- headers: {
- 'X-Restli-Protocol-Version': '2.0.0',
- 'Content-Type': 'application/json',
- 'LinkedIn-Version': '202402',
- Authorization: `Bearer ${integration.token}`,
- },
- }
- )
- ).json();
-
- return { id: element.id, totalLikes };
- })
- );
-
- const findLikes = getLastFiveLikes.filter(
- (element) => element.totalLikes >= fields.likesAmount
- );
-
- if (findLikes.length === 0) {
- return [];
- }
-
- const checkIfAlreadyPosted = await loadExisingData(
- 'autoRepostPost',
- integration.id,
- findLikes.map((p) => p.id)
- );
-
- if (checkIfAlreadyPosted.length === 0) {
- return [];
- }
-
- await this.fetch(`https://api.linkedin.com/rest/posts`, {
- body: JSON.stringify({
- author: `urn:li:organization:${integration.internalId}`,
- commentary: '',
- visibility: 'PUBLIC',
- distribution: {
- feedDistribution: 'MAIN_FEED',
- targetEntities: [],
- thirdPartyDistributionChannels: [],
- },
- lifecycleState: 'PUBLISHED',
- isReshareDisabledByAuthor: false,
- reshareContext: {
- parent: checkIfAlreadyPosted[0],
++ if (totalLikes >= +fields.likesAmount) {
++ await timer(2000);
++ await this.fetch(`https://api.linkedin.com/rest/posts`, {
++ body: JSON.stringify({
++ author: `urn:li:organization:${integration.internalId}`,
++ commentary: '',
++ visibility: 'PUBLIC',
++ distribution: {
++ feedDistribution: 'MAIN_FEED',
++ targetEntities: [],
++ thirdPartyDistributionChannels: [],
++ },
++ lifecycleState: 'PUBLISHED',
++ isReshareDisabledByAuthor: false,
++ reshareContext: {
++ parent: id,
++ },
++ }),
++ method: 'POST',
++ headers: {
++ 'X-Restli-Protocol-Version': '2.0.0',
++ 'Content-Type': 'application/json',
++ 'LinkedIn-Version': '202402',
++ Authorization: `Bearer ${integration.token}`,
+ },
- }),
- method: 'POST',
- headers: {
- 'X-Restli-Protocol-Version': '2.0.0',
- 'Content-Type': 'application/json',
- 'LinkedIn-Version': '202402',
- Authorization: `Bearer ${integration.token}`,
- },
- });
++ });
++ return true;
++ }
+
- return [checkIfAlreadyPosted[0]];
++ return false;
+ }
}
export interface Root {
diff --cc libraries/nestjs-libraries/src/integrations/social/linkedin.provider.ts
index ab4d3b0a8,bff406777..00fcd76ab
--- a/libraries/nestjs-libraries/src/integrations/social/linkedin.provider.ts
+++ b/libraries/nestjs-libraries/src/integrations/social/linkedin.provider.ts
@@@ -14,8 -14,6 +14,9 @@@ import
SocialAbstract,
} from '@gitroom/nestjs-libraries/integrations/social.abstract';
import { Integration } from '@prisma/client';
+import { Plug } from '@gitroom/helpers/decorators/plug.decorator';
+import { string } from 'yup';
++import { timer } from '@gitroom/helpers/utils/timer';
export class LinkedinProvider extends SocialAbstract implements SocialProvider {
identifier = 'linkedin';
diff --cc libraries/nestjs-libraries/src/integrations/social/x.provider.ts
index d78548f14,63e59041f..ad9de0370
--- a/libraries/nestjs-libraries/src/integrations/social/x.provider.ts
+++ b/libraries/nestjs-libraries/src/integrations/social/x.provider.ts
@@@ -10,9 -10,6 +10,9 @@@ import sharp from 'sharp'
import { readOrFetch } from '@gitroom/helpers/utils/read.or.fetch';
import removeMd from 'remove-markdown';
import { SocialAbstract } from '@gitroom/nestjs-libraries/integrations/social.abstract';
+import { Plug } from '@gitroom/helpers/decorators/plug.decorator';
- import { string } from 'yup';
+import { Integration } from '@prisma/client';
++import { timer } from '@gitroom/helpers/utils/timer';
export class XProvider extends SocialAbstract implements SocialProvider {
identifier = 'x';
@@@ -20,10 -17,10 +20,112 @@@
isBetweenSteps = false;
scopes = [];
++ @Plug({
++ identifier: 'x-autoRepostPost',
++ title: 'Auto Repost Posts',
++ description:
++ 'When a post reached a certain number of likes, repost it to increase engagement (1 week old posts)',
++ runEveryMilliseconds: 21600000,
++ totalRuns: 3,
++ fields: [
++ {
++ name: 'likesAmount',
++ type: 'number',
++ placeholder: 'Amount of likes',
++ description: 'The amount of likes to trigger the repost',
++ validation: /^\d+$/,
++ },
++ ],
++ })
++ async autoRepostPost(
++ integration: Integration,
++ id: string,
++ fields: { likesAmount: string }
++ ) {
++ // @ts-ignore
++ // eslint-disable-next-line prefer-rest-params
++ const [accessTokenSplit, accessSecretSplit] = integration.token.split(':');
++ const client = new TwitterApi({
++ appKey: process.env.X_API_KEY!,
++ appSecret: process.env.X_API_SECRET!,
++ accessToken: accessTokenSplit,
++ accessSecret: accessSecretSplit,
++ });
++
++ if (
++ (await client.v2.tweetLikedBy(id)).meta.result_count >=
++ +fields.likesAmount
++ ) {
++ await timer(2000);
++ await client.v2.retweet(integration.internalId, id);
++ return true;
++ }
++
++ return false;
++ }
++
++ @Plug({
++ identifier: 'x-autoPlugPost',
++ title: 'Auto plug post',
++ description:
++ 'When a post reached a certain number of likes, add another post to it so you followers get a notification about your promotion',
++ runEveryMilliseconds: 21600000,
++ totalRuns: 3,
++ fields: [
++ {
++ name: 'likesAmount',
++ type: 'number',
++ placeholder: 'Amount of likes',
++ description: 'The amount of likes to trigger the repost',
++ validation: /^\d+$/,
++ },
++ {
++ name: 'post',
++ type: 'richtext',
++ placeholder: 'Post to plug',
++ description: 'Message content to plug',
++ validation: /^[\s\S]{3,}$/g,
++ },
++ ],
++ })
++ async autoPlugPost(
++ integration: Integration,
++ id: string,
++ fields: { likesAmount: string; post: string }
++ ) {
++ // @ts-ignore
++ // eslint-disable-next-line prefer-rest-params
++ const [accessTokenSplit, accessSecretSplit] = integration.token.split(':');
++ const client = new TwitterApi({
++ appKey: process.env.X_API_KEY!,
++ appSecret: process.env.X_API_SECRET!,
++ accessToken: accessTokenSplit,
++ accessSecret: accessSecretSplit,
++ });
++
++ if (
++ (await client.v2.tweetLikedBy(id)).meta.result_count >=
++ +fields.likesAmount
++ ) {
++ await timer(2000);
++
++ await client.v2.tweet({
++ text: removeMd(fields.post.replace('\n', '𝔫𝔒𝔴𝔩𝔦𝔫𝔒')).replace(
++ '𝔫𝔒𝔴𝔩𝔦𝔫𝔒',
++ '\n'
++ ),
++ reply: { in_reply_to_tweet_id: id },
++ });
++ return true;
++ }
++
++ return false;
++ }
++
async refreshToken(refreshToken: string): Promise<AuthTokenDetails> {
const startingClient = new TwitterApi({
- clientId: process.env.TWITTER_CLIENT_ID!,
- clientSecret: process.env.TWITTER_CLIENT_SECRET!,
- clientId: process.env.TWITTER_CLIENT_ID! || process.env.X_CLIENT_ID!,
- clientSecret: process.env.TWITTER_CLIENT_SECRET! || process.env.X_CLIENT_SECRET!,
++ appKey: process.env.X_API_KEY!,
++ appSecret: process.env.X_API_SECRET!,
});
const {
accessToken,