Skip to content

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

feat: tiktok business

Nevo Davidcae2565e5f8f
diff --git a/.env.example b/.env.example
index 0ef05c5e0..8eda5c0cd 100644
--- a/.env.example
+++ b/.env.example
@@ -39,6 +39,15 @@ STORAGE_PROVIDER="local"
# Your upload directory path if you host your files locally, otherwise Cloudflare will be used.
#NEXT_PUBLIC_UPLOAD_STATIC_DIRECTORY=""
+# Sign in with Apple (login provider)
+# APPLE_BUNDLE_ID: iOS app bundle id (native mobile sign-in)
+# APPLE_SERVICE_ID / TEAM_ID / KEY_ID / PRIVATE_KEY: web sign-in (Services ID + .p8 key)
+APPLE_BUNDLE_ID=""
+APPLE_SERVICE_ID=""
+APPLE_TEAM_ID=""
+APPLE_KEY_ID=""
+APPLE_PRIVATE_KEY=""
+
# Social Media API Settings
X_URL=""
X_API_KEY=""
@@ -133,3 +142,7 @@ POSTIZ_OAUTH_CLIENT_SECRET=""
# LINK_DRIP_API_KEY="" # Your LinkDrip API key
# LINK_DRIP_API_ENDPOINT="https://api.linkdrip.com/v1/" # Your self-hosted LinkDrip API endpoint
# LINK_DRIP_SHORT_LINK_DOMAIN="dripl.ink" # Your self-hosted LinkDrip domain
+
+# Provider visibility / migration
+# HIDDEN_PROVIDERS="tiktok" # comma-separated identifiers hidden from the add-channel screen
+# MIGRATE_PROVIDERS="tiktok:tiktok-business" # comma-separated "old:new" pairs, a reconnect of "old" goes through "new" and the channel is migrated in place
diff --git a/apps/backend/src/api/routes/integrations.controller.ts b/apps/backend/src/api/routes/integrations.controller.ts
index 024a89043..3b719f2a6 100644
--- a/apps/backend/src/api/routes/integrations.controller.ts
+++ b/apps/backend/src/api/routes/integrations.controller.ts
@@ -21,7 +21,10 @@ import { GetUserFromRequest } from '@gitroom/nestjs-libraries/user/user.from.req
import { PostsService } from '@gitroom/nestjs-libraries/database/prisma/posts/posts.service';
import { IntegrationTimeDto } from '@gitroom/nestjs-libraries/dtos/integrations/integration.time.dto';
import { PlugDto } from '@gitroom/nestjs-libraries/dtos/plugs/plug.dto';
-import { RefreshToken } from '@gitroom/nestjs-libraries/integrations/social.abstract';
+import {
+ Disconnect,
+ RefreshToken,
+} from '@gitroom/nestjs-libraries/integrations/social.abstract';
import { timer } from '@gitroom/helpers/utils/timer';
import { TelegramProvider } from '@gitroom/nestjs-libraries/integrations/social/telegram.provider';
@@ -208,8 +211,16 @@ export class IntegrationsController {
throw new Error('Integration not allowed');
}
- const integrationProvider =
- this._integrationManager.getSocialIntegration(integration);
+ // A provider migrated via MIGRATE_PROVIDERS reconnects through its target
+ // provider's OAuth: the callback lands on the target and the channel is
+ // migrated in place (see migrateIntegration).
+ const migrateTo = refresh
+ ? this._integrationManager.getMigrationTarget(integration)
+ : undefined;
+
+ const integrationProvider = this._integrationManager.getSocialIntegration(
+ migrateTo || integration
+ );
if (integrationProvider.externalUrl && !externalUrl) {
throw new Error('Missing external url');
@@ -351,6 +362,16 @@ export class IntegrationsController {
return load;
} catch (err) {
+ // The platform will keep rejecting this channel until the user
+ // re-connects it: mark it as needing a refresh instead of retrying.
+ if (err instanceof Disconnect) {
+ await this._integrationService.disconnectChannel(
+ org.id,
+ getIntegration
+ );
+ return false;
+ }
+
if (err instanceof RefreshToken) {
const data = await this._refreshIntegrationService.refresh(
getIntegration
diff --git a/apps/backend/src/api/routes/no.auth.integrations.controller.ts b/apps/backend/src/api/routes/no.auth.integrations.controller.ts
index 3ac67cb54..f5260b9aa 100644
--- a/apps/backend/src/api/routes/no.auth.integrations.controller.ts
+++ b/apps/backend/src/api/routes/no.auth.integrations.controller.ts
@@ -184,12 +184,6 @@ export class NoAuthIntegrationsController {
throw new NotEnoughScopes('Invalid API key');
}
- if (refresh && String(id) !== String(refresh)) {
- throw new NotEnoughScopes(
- 'Please refresh the channel that needs to be refreshed'
- );
- }
-
let validName = name;
if (!validName) {
if (username) {
@@ -210,6 +204,30 @@ export class NoAuthIntegrationsController {
throw new HttpException('', 412);
}
+ if (refresh && String(id) !== String(refresh)) {
+ // A reconnect that returns a different id is either the wrong account or
+ // a channel migrating to another provider (MIGRATE_PROVIDERS) - the two
+ // apps return different app-scoped ids, so the channel is matched by
+ // profile and moved in place. Throws for anything else. Runs after every
+ // check that can reject the connect, so a rejection can never leave a
+ // half-migrated channel behind.
+ await this._integrationService.migrateIntegration(
+ org.id,
+ refresh,
+ integration,
+ { id: String(id), username }
+ );
+ } else if (!refresh) {
+ // A fresh connect of a migration target for an account the org already
+ // has on the source provider adopts that channel instead of creating a
+ // duplicate. No-op for everything else.
+ await this._integrationService.migrateIntegrationOnConnect(
+ org.id,
+ integration,
+ { id: String(id), username }
+ );
+ }
+
const createUpdate =
await this._integrationService.createOrUpdateIntegration(
additionalSettings,
diff --git a/apps/backend/src/public-api/routes/v1/public.integrations.controller.ts b/apps/backend/src/public-api/routes/v1/public.integrations.controller.ts
index 5c569e8a0..7ca1316f2 100644
--- a/apps/backend/src/public-api/routes/v1/public.integrations.controller.ts
+++ b/apps/backend/src/public-api/routes/v1/public.integrations.controller.ts
@@ -340,8 +340,16 @@ export class PublicIntegrationsController {
throw new HttpException({ msg: 'Integration not allowed' }, 400);
}
- const integrationProvider =
- this._integrationManager.getSocialIntegration(integration);
+ // A provider migrated via MIGRATE_PROVIDERS reconnects through its target
+ // provider's OAuth: the callback lands on the target and the channel is
+ // migrated in place (see migrateIntegration).
+ const migrateTo = refresh
+ ? this._integrationManager.getMigrationTarget(integration)
+ : undefined;
+
+ const integrationProvider = this._integrationManager.getSocialIntegration(
+ migrateTo || integration
+ );
if (integrationProvider.externalUrl) {
throw new HttpException(
diff --git a/apps/orchestrator/src/activities/post.activity.ts b/apps/orchestrator/src/activities/post.activity.ts
index f7fc6f1d7..6071a8440 100644
--- a/apps/orchestrator/src/activities/post.activity.ts
+++ b/apps/orchestrator/src/activities/post.activity.ts
@@ -25,6 +25,10 @@ import {
} from '@gitroom/nestjs-libraries/temporal/temporal.search.attribute';
import { SubscriptionService } from '@gitroom/nestjs-libraries/database/prisma/subscriptions/subscription.service';
import { withHeartbeat } from '@gitroom/nestjs-libraries/temporal/temporal.heartbeat';
+import {
+ BadBody,
+ Disconnect,
+} from '@gitroom/nestjs-libraries/integrations/social.abstract';
// Drops fields the workflow and downstream activities never read β€” biggest wins are `error` (grows per retry) and `childrenPost` (Prisma side-loads it on every recursive row).
function slimPost(post: any) {
@@ -173,43 +177,45 @@ export class PostActivity {
// conversion and the platform call can both take minutes), so it
// heartbeats end to end - under older workflow versions that set no
// heartbeatTimeout this is a no-op
- return withHeartbeat(async () => {
- const getIntegration = this._integrationManager.getSocialIntegration(
- integration.providerIdentifier
- );
-
- const newPosts = await this._postService.updateTags(
- integration.organizationId,
- posts
- );
-
- return getIntegration.comment(
- integration.internalId,
- postId,
- lastPostId,
- integration.token,
- await Promise.all(
- (newPosts || []).map(async (p) => ({
- id: p.id,
- message: stripHtmlValidation(
- getIntegration.editor,
- p.content,
- true,
- false,
- !/<\/?[a-z][\s\S]*>/i.test(p.content),
- getIntegration.mentionFormat
- ),
- settings: JSON.parse(p.settings || '{}'),
- media: await this._postService.updateMedia(
- p.id,
- JSON.parse(p.image || '[]'),
- getIntegration?.convertToJPEG || false
- ),
- }))
- ),
- integration
- );
- });
+ return withHeartbeat(() =>
+ this.handleDisconnect(integration, async () => {
+ const getIntegration = this._integrationManager.getSocialIntegration(
+ integration.providerIdentifier
+ );
+
+ const newPosts = await this._postService.updateTags(
+ integration.organizationId,
+ posts
+ );
+
+ return getIntegration.comment(
+ integration.internalId,
+ postId,
+ lastPostId,
+ integration.token,
+ await Promise.all(
+ (newPosts || []).map(async (p) => ({
+ id: p.id,
+ message: stripHtmlValidation(
+ getIntegration.editor,
+ p.content,
+ true,
+ false,
+ !/<\/?[a-z][\s\S]*>/i.test(p.content),
+ getIntegration.mentionFormat
+ ),
+ settings: JSON.parse(p.settings || '{}'),
+ media: await this._postService.updateMedia(
+ p.id,
+ JSON.parse(p.image || '[]'),
+ getIntegration?.convertToJPEG || false
+ ),
+ }))
+ ),
+ integration
+ );
+ })
+ );
}
@ActivityMethod()
@@ -226,6 +232,41 @@ export class PostActivity {
return this.postSocialInternal(integration, posts, true);
}
+ // A Disconnect error means the platform will keep rejecting this channel no
+ // matter how many token refreshes (e.g. TikTok's daily active user cap):
+ // mark the channel as needing a re-connect and notify the user, then rethrow
+ // as BadBody so every workflow version - frozen once on main - treats it as
+ // a terminal error without needing a new workflow.
+ private async handleDisconnect<T>(
+ integration: Integration,
+ func: () => Promise<T>
+ ): Promise<T> {
+ try {
+ return await func();
+ } catch (err) {
+ if (err instanceof Disconnect) {
+ try {
+ await this._integrationService.disconnectChannel(
+ integration.organizationId,
+ integration,
+ err.message
+ );
+ } catch (e) {
+ /**empty**/
+ }
+
+ throw new BadBody(
+ integration.providerIdentifier,
+ JSON.stringify({}),
+ Buffer.from('{}'),
+ err.message
+ );
+ }
+
+ throw err;
+ }
+ }
+
private async postSocialInternal(
integration: Integration,
posts: Post[],
@@ -236,7 +277,9 @@ export class PostActivity {
// heartbeats end to end - under older workflow versions that set no
// heartbeatTimeout this is a no-op
return withHeartbeat(() =>
- this.postSocialBody(integration, posts, allowPending)
+ this.handleDisconnect(integration, () =>
+ this.postSocialBody(integration, posts, allowPending)
+ )
);
}
@@ -329,10 +372,8 @@ export class PostActivity {
integration.providerIdentifier
);
- return getIntegration.checkPostStatus(
- integration.token,
- pendingData,
- integration
+ return this.handleDisconnect(integration, () =>
+ getIntegration.checkPostStatus(integration.token, pendingData, integration)
);
}
@@ -343,7 +384,9 @@ export class PostActivity {
);
return withHeartbeat(() =>
- getIntegration.finalizePost(integration.token, pendingData, integration)
+ this.handleDisconnect(integration, () =>
+ getIntegration.finalizePost(integration.token, pendingData, integration)
+ )
);
}
diff --git a/libraries/nestjs-libraries/src/database/prisma/integrations/integration.repository.ts b/libraries/nestjs-libraries/src/database/prisma/integrations/integration.repository.ts
index 15434d6c8..4c4a4f45b 100644
--- a/libraries/nestjs-libraries/src/database/prisma/integrations/integration.repository.ts
+++ b/libraries/nestjs-libraries/src/database/prisma/integrations/integration.repository.ts
@@ -205,6 +205,65 @@ export class IntegrationRepository {
});
}
+ getIntegrationByInternalId(org: string, internalId: string) {
+ return this._integration.model.integration.findFirst({
+ where: {
+ organizationId: org,
+ internalId,
+ deletedAt: null,
+ },
+ });
+ }
+
+ // Moves a channel to another provider in place (MIGRATE_PROVIDERS): only the
+ // provider and the app-scoped ids change, so the integration id - and with it
+ // scheduled posts, settings and customers - survives the migration. The
+ // follow-up createOrUpdateIntegration upsert matches the new internalId and
+ // stores the fresh tokens.
+ async migrateIntegration(
+ org: string,
+ id: string,
+ internalId: string,
+ providerIdentifier: string,
+ rootInternalId: string
+ ) {
+ // A soft-deleted channel can still hold the target internalId
+ // (deleteChannel keeps it): rename it out of the way like updateIntegration
+ // does, otherwise the organizationId_internalId unique constraint rejects
+ // the migration. Live channels are rejected by the service before this.
+ const existing = await this._integration.model.integration.findUnique({
+ where: {
+ organizationId_internalId: {
+ organizationId: org,
+ internalId,
+ },
+ },
+ });
+
+ if (existing && existing.deletedAt) {
+ await this._integration.model.integration.update({
+ where: {
+ id: existing.id,
+ },
+ data: {
+ internalId: `deleted_${internalId}_${makeId(10)}`,
+ },
+ });
+ }
+
+ return this._integration.model.integration.update({
+ where: {
+ id,
+ organizationId: org,
+ },
+ data: {
+ internalId,
+ providerIdentifier,
+ rootInternalId,
+ },
+ });
+ }
+
async createOrUpdateIntegration(
additionalSettings:
| {
diff --git a/libraries/nestjs-libraries/src/database/prisma/integrations/integration.service.ts b/libraries/nestjs-libraries/src/database/prisma/integrations/integration.service.ts
index a129641bf..884ce9578 100644
--- a/libraries/nestjs-libraries/src/database/prisma/integrations/integration.service.ts
+++ b/libraries/nestjs-libraries/src/database/prisma/integrations/integration.service.ts
@@ -16,7 +16,10 @@ import { NotificationService } from '@gitroom/nestjs-libraries/database/prisma/n
import dayjs from 'dayjs';
import { timer } from '@gitroom/helpers/utils/timer';
import { ioRedis } from '@gitroom/nestjs-libraries/redis/redis.service';
-import { RefreshToken } from '@gitroom/nestjs-libraries/integrations/social.abstract';
+import {
+ NotEnoughScopes,
+ RefreshToken,
+} from '@gitroom/nestjs-libraries/integrations/social.abstract';
import { IntegrationTimeDto } from '@gitroom/nestjs-libraries/dtos/integrations/integration.time.dto';
import { UploadFactory } from '@gitroom/nestjs-libraries/upload/upload.factory';
import { PlugDto } from '@gitroom/nestjs-libraries/dtos/plugs/plug.dto';
@@ -183,9 +186,116 @@ export class IntegrationService {
}
}
- async disconnectChannel(orgId: string, integration: Integration) {
+ async disconnectChannel(orgId: string, integration: Integration, err = '') {
await this._integrationRepository.disconnectChannel(orgId, integration.id);
- await this.informAboutRefreshError(orgId, integration);
+ await this.informAboutRefreshError(orgId, integration, err);
+ }
+
+ // A reconnect that came back from a different provider (MIGRATE_PROVIDERS):
+ // match the disconnected channel by profile and move it to the new provider
+ // in place, so scheduled posts, settings and customers survive. Throws the
+ // same error as a mismatched reconnect when the migration is not configured
+ // or the user connected a different account.
+ async migrateIntegration(
+ org: string,
+ oldInternalId: string,
+ newProvider: string,
+ auth: { id: string; username: string }
+ ) {
+ const existing = await this._integrationRepository.getIntegrationByInternalId(
+ org,
+ oldInternalId
+ );
+
+ if (
+ !existing ||
+ this._integrationManager.getMigrationTarget(
+ existing.providerIdentifier
+ ) !== newProvider
+ ) {
+ throw new NotEnoughScopes(
+ 'Please refresh the channel that needs to be refreshed'
+ );
+ }
+
+ const oldProvider = this._integrationManager.getSocialIntegration(
+ existing.providerIdentifier
+ );
+
+ if (!oldProvider.migrationMatch(auth, existing)) {
+ throw new NotEnoughScopes(
+ `Please connect the same account (@${existing.profile}) that needs to be refreshed`
+ );
+ }
+
+ if (
+ await this._integrationRepository.getIntegrationByInternalId(org, auth.id)
+ ) {
+ throw new NotEnoughScopes(
+ 'This account is already connected as another channel, please delete one of them first'
+ );
+ }
+
+ return this._integrationRepository.migrateIntegration(
+ org,
+ existing.id,
+ auth.id,
+ newProvider,
+ existing.rootInternalId === existing.internalId
+ ? auth.id
+ : existing.rootInternalId
+ );
+ }
+
+ // A fresh connect of a migration target (MIGRATE_PROVIDERS) for an account
+ // the org already has on the source provider: adopt that channel instead of
+ // creating a confusing duplicate - the channel is migrated in place exactly
+ // like a reconnect, and the follow-up upsert stores the fresh tokens. A no-op
+ // when nothing matches, so a genuinely new account still creates a channel.
+ async migrateIntegrationOnConnect(
+ org: string,
+ newProvider: string,
+ auth: { id: string; username: string }
+ ) {
+ const sources = this._integrationManager.getMigrationSources(newProvider);
+ if (
+ !sources.length ||
+ this._integrationManager.getSocialIntegration(newProvider).isBetweenSteps
+ ) {
+ return;
+ }
+
+ // the account already exists on the new provider: the normal upsert
+ // updates it, nothing to adopt
+ if (
+ await this._integrationRepository.getIntegrationByInternalId(org, auth.id)
+ ) {
+ return;
+ }
+
+ const existing = (
+ await this._integrationRepository.getIntegrationsList(org)
+ ).find(
+ (p) =>
+ sources.includes(p.providerIdentifier) &&
+ this._integrationManager
+ .getSocialIntegration(p.providerIdentifier)
+ .migrationMatch(auth, p)
+ );
+
+ if (!existing) {
+ return;
+ }
+
+ return this._integrationRepository.migrateIntegration(
+ org,
+ existing.id,
+ auth.id,
+ newProvider,
+ existing.rootInternalId === existing.internalId
+ ? auth.id
+ : existing.rootInternalId
+ );
}
async informAboutRefreshError(
diff --git a/libraries/nestjs-libraries/src/integrations/integration.manager.ts b/libraries/nestjs-libraries/src/integrations/integration.manager.ts
index 0e7e882da..1770fd657 100644
--- a/libraries/nestjs-libraries/src/integrations/integration.manager.ts
+++ b/libraries/nestjs-libraries/src/integrations/integration.manager.ts
@@ -80,22 +80,69 @@ export const socialIntegrationList: Array<SocialAbstract & SocialProvider> = [
@Injectable()
export class IntegrationManager {
+ // Both are env-driven so cloud and self-hosted instances can differ:
+ // HIDDEN_PROVIDERS ("tiktok,x") hides providers from the add-channel screen,
+ // MIGRATE_PROVIDERS ("tiktok:tiktok-business") routes a reconnect of the old
+ // provider through the new provider's OAuth and migrates the channel in
+ // place, keeping its id, scheduled posts and settings.
+ isHiddenProvider(identifier: string) {
+ return (process.env.HIDDEN_PROVIDERS || '')
+ .split(',')
+ .map((p) => p.trim())
+ .includes(identifier);
+ }
+
+ // Note: a target provider that implements `reConnect` is not supported - the
+ // connect callback would run reConnect with the old app-scoped id before the
+ // migration is attempted.
+ getMigrationTarget(identifier: string): string | undefined {
+ const [, target] =
+ (process.env.MIGRATE_PROVIDERS || '')
+ .split(',')
+ .map((p) => p.trim().split(':'))
+ .find(([from, to]) => from === identifier && !!to) || [];
+
+ return target &&
+ target !== identifier &&
+ this.getAllowedSocialsIntegrations().includes(target)
+ ? target
+ : undefined;
+ }
+
+ // Reverse lookup of MIGRATE_PROVIDERS: the providers whose channels a fresh
+ // connect of `identifier` should adopt instead of creating a duplicate.
+ getMigrationSources(identifier: string): string[] {
+ return (process.env.MIGRATE_PROVIDERS || '')
+ .split(',')
+ .map((p) => p.trim().split(':'))
+ .filter(
+ ([from, to]) =>
+ to === identifier &&
+ !!from &&
+ from !== identifier &&
+ this.getAllowedSocialsIntegrations().includes(from)
+ )
+ .map(([from]) => from);
+ }
+
async getAllIntegrations() {
return {
social: await Promise.all(
- socialIntegrationList.map(async (p) => ({
- name: p.name,
- identifier: p.identifier,
- toolTip: p.toolTip,
- editor: p.editor,
- isExternal: !!p.externalUrl,
- isWeb3: !!p.isWeb3,
- isChromeExtension: !!p.isChromeExtension,
- ...(p.extensionCookies
- ? { extensionCookies: p.extensionCookies }
- : {}),
- ...(p.customFields ? { customFields: await p.customFields() } : {}),
- }))
+ socialIntegrationList
+ .filter((p) => !this.isHiddenProvider(p.identifier))
+ .map(async (p) => ({
+ name: p.name,
+ identifier: p.identifier,
+ toolTip: p.toolTip,
+ editor: p.editor,
+ isExternal: !!p.externalUrl,
+ isWeb3: !!p.isWeb3,
+ isChromeExtension: !!p.isChromeExtension,
+ ...(p.extensionCookies
+ ? { extensionCookies: p.extensionCookies }
+ : {}),
+ ...(p.customFields ? { customFields: await p.customFields() } : {}),
+ }))
),
article: [] as any[],
};
diff --git a/libraries/nestjs-libraries/src/integrations/social.abstract.ts b/libraries/nestjs-libraries/src/integrations/social.abstract.ts
index 0b6a1cb3d..451e5015f 100644
--- a/libraries/nestjs-libraries/src/integrations/social.abstract.ts
+++ b/libraries/nestjs-libraries/src/integrations/social.abstract.ts
@@ -1,6 +1,9 @@
import { timer } from '@gitroom/helpers/utils/timer';
import { Integration } from '@prisma/client';
-import { PendingCheckResponse } from '@gitroom/nestjs-libraries/integrations/social/social.integrations.interface';
+import {
+ AuthTokenDetails,
+ PendingCheckResponse,
+} from '@gitroom/nestjs-libraries/integrations/social/social.integrations.interface';
import { ApplicationFailure } from '@temporalio/activity';
import { readOrFetch } from '@gitroom/helpers/utils/read.or.fetch';
import {
@@ -54,6 +57,27 @@ export class RefreshToken extends ApplicationFailure {
}
}
+// A `disconnect` error means the platform will keep rejecting this channel no
+// matter how many times the token is refreshed (e.g. TikTok's daily active
+// user cap): the channel must be disconnected so the user re-connects it,
+// possibly through another provider (see MIGRATE_PROVIDERS).
+export class Disconnect extends ApplicationFailure {
+ constructor(identifier: string, json: string, body: BodyInit, message = '') {
+ super(
+ truncateForTemporal(message, MAX_FAILURE_MESSAGE),
+ 'disconnect',
+ true,
+ [
+ {
+ identifier,
+ json: truncateForTemporal(json, MAX_FAILURE_FIELD),
+ body: truncateForTemporal(body, MAX_FAILURE_FIELD),
+ },
+ ]
+ );
+ }
+}
+
export class BadBody extends ApplicationFailure {
constructor(identifier: string, json: string, body: BodyInit, message = '') {
super(truncateForTemporal(message, MAX_FAILURE_MESSAGE), 'bad_body', true, [
@@ -94,11 +118,27 @@ export abstract class SocialAbstract {
body: string,
status: number
):
- | { type: 'refresh-token' | 'bad-body' | 'retry'; value: string }
+ | {
+ type: 'refresh-token' | 'bad-body' | 'retry' | 'disconnect';
+ value: string;
+ }
| undefined {
return undefined;
}
+ /**
+ * When a provider is migrated to another one (MIGRATE_PROVIDERS env), the two
+ * apps return different app-scoped ids, so a reconnect is matched to the
+ * existing channel by profile instead. Override when a provider pair needs a
+ * different matching rule.
+ */
+ public migrationMatch(
+ auth: Pick<AuthTokenDetails, 'id' | 'username'>,
+ integration: Integration
+ ): boolean {
+ return !!auth.username && auth.username === integration.profile;
+ }
+
/**
* Server-side replacement for the old client-side `checkValidity`.
* Validates the media attached to a post (and its comments) against the
@@ -324,6 +364,10 @@ export abstract class SocialAbstract {
return this.runStreamedUpload(func, identifier, totalRetries + 1);
}
+ if (handleError?.type === 'disconnect') {
+ throw new Disconnect(identifier, json, '{}', handleError?.value);
+ }
+
if (
(status === 401 &&
(handleError?.type === 'refresh-token' || !handleError)) ||
@@ -376,6 +420,14 @@ export abstract class SocialAbstract {
value.value || ''
);
}
+ if (value.type === 'disconnect') {
+ throw new Disconnect(
+ '',
+ safeStringify(globalErr),
+ {} as any,
+ value.value || ''
+ );
+ }
throw new BadBody(
'',
safeStringify(globalErr),
@@ -449,6 +501,15 @@ export abstract class SocialAbstract {
);
}
+ if (handleError?.type === 'disconnect') {
+ throw new Disconnect(
+ identifier,
+ json,
+ options.body!,
+ handleError?.value
+ );
+ }
+
if (
(request.status === 401 &&
(handleError?.type === 'refresh-token' || !handleError)) ||
diff --git a/libraries/nestjs-libraries/src/integrations/social/social.integrations.interface.ts b/libraries/nestjs-libraries/src/integrations/social/social.integrations.interface.ts
index fb9db3cf7..a8a29c600 100644
--- a/libraries/nestjs-libraries/src/integrations/social/social.integrations.interface.ts
+++ b/libraries/nestjs-libraries/src/integrations/social/social.integrations.interface.ts
@@ -179,6 +179,10 @@ export interface SocialProvider
pendingData: any,
integration: Integration
): Promise<PendingCheckResponse>;
+ migrationMatch(
+ auth: Pick<AuthTokenDetails, 'id' | 'username'>,
+ integration: Integration
+ ): boolean;
finalizePost(
accessToken: string,
pendingData: any,
diff --git a/libraries/nestjs-libraries/src/integrations/social/tiktok.business.provider.ts b/libraries/nestjs-libraries/src/integrations/social/tiktok.business.provider.ts
index c2163b7ef..d60e954c8 100644
--- a/libraries/nestjs-libraries/src/integrations/social/tiktok.business.provider.ts
+++ b/libraries/nestjs-libraries/src/integrations/social/tiktok.business.provider.ts
@@ -9,6 +9,7 @@ import {
import dayjs from 'dayjs';
import {
BadBody,
+ Disconnect,
RefreshToken,
SocialAbstract,
ValidityMedia,
@@ -33,7 +34,7 @@ export class TiktokBusinessProvider
implements SocialProvider
{
identifier = 'tiktok-business';
- name = 'TikTok\n(Business)';
+ name = 'TikTok';
isBetweenSteps = false;
convertToJPEG = true;
scopes = [
@@ -91,7 +92,7 @@ export class TiktokBusinessProvider
override handleErrors(body: string):
| {
- type: 'refresh-token' | 'bad-body';
+ type: 'refresh-token' | 'bad-body' | 'disconnect';
value: string;
}
| undefined {
@@ -187,6 +188,17 @@ export class TiktokBusinessProvider
};
}
+ // Unlike the legacy app there is no migration target configured for this
+ // provider, so the cap stays a failed post (re-connecting cannot reset a
+ // daily quota) - if this app is ever migrated too, switch to 'disconnect'.
+ if (body.indexOf('reached_active_user_cap') > -1) {
+ return {
+ type: 'bad-body' as const,
+ value:
+ 'TikTok daily user limit reached, please try again tomorrow',
+ };
+ }
+
if (body.indexOf('url_ownership_unverified') > -1) {
return {
type: 'bad-body' as const,
@@ -324,6 +336,7 @@ export class TiktokBusinessProvider
`&redirect_uri=${encodeURIComponent(this.redirectUri())}` +
`&state=${state}` +
`&response_type=code` +
+ `&disable_auto_auth=1` +
`&scope=${encodeURIComponent(this.scopes.join(','))}`,
codeVerifier: state,
state,
@@ -397,7 +410,7 @@ export class TiktokBusinessProvider
)
).json();
} catch (err) {
- if (err instanceof RefreshToken) {
+ if (err instanceof RefreshToken || err instanceof Disconnect) {
throw err;
}
@@ -416,6 +429,9 @@ export class TiktokBusinessProvider
if (handleError?.type === 'refresh-token') {
throw new RefreshToken('tiktok-business', asString, '{}', handleError.value);
}
+ if (handleError?.type === 'disconnect') {
+ throw new Disconnect('tiktok-business', asString, '{}', handleError.value);
+ }
return { status: 'pending', pendingData };
}
@@ -580,6 +596,14 @@ export class TiktokBusinessProvider
handleError.value
);
}
+ if (handleError?.type === 'disconnect') {
+ throw new Disconnect(
+ 'tiktok-business',
+ asString,
+ JSON.stringify(body),
+ handleError.value
+ );
+ }
throw new BadBody(
'tiktok-business-error-upload',
asString,
diff --git a/libraries/nestjs-libraries/src/integrations/social/tiktok.provider.ts b/libraries/nestjs-libraries/src/integrations/social/tiktok.provider.ts
index c1eb7c323..654d6285c 100644
--- a/libraries/nestjs-libraries/src/integrations/social/tiktok.provider.ts
+++ b/libraries/nestjs-libraries/src/integrations/social/tiktok.provider.ts
@@ -9,6 +9,7 @@ import {
import dayjs from 'dayjs';
import {
BadBody,
+ Disconnect,
RefreshToken,
SocialAbstract,
ValidityMedia,
@@ -72,7 +73,7 @@ export class TiktokProvider extends SocialAbstract implements SocialProvider {
override handleErrors(body: string):
| {
- type: 'refresh-token' | 'bad-body';
+ type: 'refresh-token' | 'bad-body' | 'disconnect';
value: string;
}
| undefined {
@@ -197,10 +198,14 @@ export class TiktokProvider extends SocialAbstract implements SocialProvider {
};
}
+ // TikTok limits how many users of this app can post per day: refreshing
+ // the token cannot help, the channel must be re-connected (and can be
+ // migrated to another app via MIGRATE_PROVIDERS).
if (body.indexOf('reached_active_user_cap') > -1) {
return {
- type: 'bad-body' as const,
- value: 'Daily active user quota reached, please try again later',
+ type: 'disconnect' as const,
+ value:
+ 'TikTok daily user limit reached, please re-connect your account',
};
}
@@ -445,7 +450,7 @@ export class TiktokProvider extends SocialAbstract implements SocialProvider {
)
).json();
} catch (err) {
- if (err instanceof RefreshToken) {
+ if (err instanceof RefreshToken || err instanceof Disconnect) {
throw err;
}