Papermark is the open-source DocSend alternative and secure data rooms with built-in analytics and custom domains.
improvement
Ashish Viradiyafcda408df9a1
diff --git a/lib/slack/client.ts b/lib/slack/client.tsindex e4394e00..66c46c38 100644--- a/lib/slack/client.ts+++ b/lib/slack/client.ts@@ -1,4 +1,4 @@-import { SlackOAuthResponse, SlackChannel, SlackMessage, SlackWorkspaceInfo } from './types';+import { SlackOAuthResponse, SlackChannel, SlackMessage, SlackWorkspaceInfo } from '@/lib/types/slack';import { decryptSlackToken } from '@/lib/utils';export class SlackClient {@@ -40,6 +40,8 @@ export class SlackClient {* Exchange authorization code for access token*/async exchangeCodeForToken(code: string, redirectUri: string): Promise<SlackOAuthResponse> {+ const ac = new AbortController();+ const t = setTimeout(() => ac.abort(), 10000);const response = await fetch(`${this.baseUrl}/oauth.v2.access`, {method: 'POST',headers: {@@ -51,7 +53,11 @@ export class SlackClient {code: code,redirect_uri: redirectUri,}),- });+ signal: ac.signal,+ }).catch((e) => {+ throw new Error(`Slack OAuth network error: ${e}`);+ }).finally(() => clearTimeout(t));+if (!response.ok) {throw new Error(`Slack OAuth failed: ${response.statusText}`);@@ -74,7 +80,7 @@ export class SlackClient {const response = await fetch(`${this.baseUrl}/team.info`, {headers: {'Authorization': `Bearer ${decryptedToken}`,- 'Content-Type': 'application/json',+ 'Content-Type': 'application/x-www-form-urlencoded',},});@@ -91,7 +97,7 @@ export class SlackClient {return {id: data.team.id,name: data.team.name,- url: data.team.url,+ url: `https://${data.team.domain}.slack.com`, // not in usedomain: data.team.domain,};}@@ -124,42 +130,39 @@ export class SlackClient {};}- /**- * Get list of channels- */async getChannels(accessToken: string): Promise<SlackChannel[]> {- try {- const decryptedToken = this.decryptToken(accessToken);- const response = await fetch(`${this.baseUrl}/conversations.list?types=public_channel,private_channel`, {+ const decryptedToken = this.decryptToken(accessToken);+ const channels: SlackChannel[] = [];+ let cursor: string | undefined = undefined;+ do {+ const url = new URL(`${this.baseUrl}/conversations.list`);+ url.searchParams.set('types', 'public_channel,private_channel');+ url.searchParams.set('exclude_archived', 'true');+ if (cursor) url.searchParams.set('cursor', cursor);+ const resp = await fetch(url.toString(), {headers: {'Authorization': `Bearer ${decryptedToken}`,'Content-Type': 'application/json',},});-- if (!response.ok) {- throw new Error(`Failed to get channels: ${response.statusText}`);- }-- const data = await response.json();-- if (!data.ok) {- throw new Error(`Slack API error: ${data.error}`);- }-- return data.channels.map((channel: any) => ({- id: channel.id,- name: channel.name,- is_private: channel.is_private,- is_archived: channel.is_archived,- is_member: channel.is_member,- }));- } catch (error) {- console.error('SlackClient.getChannels error:', error);- throw error;- }+ if (!resp.ok) throw new Error(`Failed to get channels: ${resp.status} ${resp.statusText}`);+ const data = await resp.json();+ if (!data.ok) throw new Error(`Slack API error: ${data.error}`);+ channels.push(+ ...data.channels.map((channel: any) => ({+ id: channel.id,+ name: channel.name,+ is_private: channel.is_private,+ is_archived: channel.is_archived,+ is_member: channel.is_member,+ }))+ );+ cursor = data.response_metadata?.next_cursor || undefined;+ } while (cursor);+ return channels;}+/*** Send message to Slack channel*/diff --git a/lib/slack/templates.ts b/lib/slack/templates.tsindex c796e2b0..e3de0b15 100644--- a/lib/slack/templates.ts+++ b/lib/slack/templates.ts@@ -1,22 +1,7 @@+import { SlackMessage } from "../types/slack";import { SlackEventData } from "./events";import prisma from "@/lib/prisma";-export interface SlackChannelConfig {- id: string;- name: string;- enabled: boolean;- notificationTypes: string[];-}--export interface SlackMessage {- channel?: string;- text?: string;- blocks?: any[];- thread_ts?: string;- unfurl_links?: boolean;- unfurl_media?: boolean;-}-export async function createSlackMessage(eventData: SlackEventData,): Promise<SlackMessage | null> {diff --git a/lib/slack/types.ts b/lib/slack/types.tsdeleted file mode 100644index c2309f44..00000000--- a/lib/slack/types.ts+++ /dev/null@@ -1,71 +0,0 @@-export interface SlackWorkspaceInfo {- id: string;- name: string;- url: string;- domain: string;-}--export interface SlackBotInfo {- id: string;- name: string;- team_id: string;-}--export interface SlackChannel {- id: string;- name: string;- is_private: boolean;- is_archived: boolean;- is_member?: boolean;-}--export interface SlackOAuthResponse {- ok: boolean;- access_token: string;- token_type: string;- scope: string;- bot_user_id: string;- team: {- name: string;- id: string;- };- enterprise?: {- name: string;- id: string;- };- authed_user: {- id: string;- scope: string;- access_token: string;- token_type: string;- };-}--export interface SlackMessage {- channel: string;- text?: string;- blocks?: any[];- thread_ts?: string;- unfurl_links?: boolean;- unfurl_media?: boolean;-}--export interface SlackNotificationConfig {- document_view: boolean;- dataroom_access: boolean;- document_download: boolean;-}--export interface SlackChannelConfig {- id: string;- name: string;- enabled: boolean;- notificationTypes: string[];-}--export interface SlackIntegrationConfig {- enabled: boolean;- notificationTypes: SlackNotificationConfig;- defaultChannel?: string;- enabledChannels: Record<string, SlackChannelConfig>;-}\ No newline at end of filediff --git a/lib/types/slack.ts b/lib/types/slack.tsindex 90efefc2..ac652901 100644--- a/lib/types/slack.ts+++ b/lib/types/slack.ts@@ -3,13 +3,7 @@ export interface SlackChannel {name: string;is_archived: boolean;is_private: boolean;-}--export interface SlackChannelConfig {- id: string;- name: string;- enabled: boolean;- notificationTypes: string[];+ is_member?: boolean;}export interface SlackIntegration {@@ -44,4 +38,51 @@ export interface SlackChannelsResponse {channels: SlackChannel[];}-export interface SlackIntegrationResponse extends SlackIntegration { }\ No newline at end of file+export interface SlackIntegrationResponse extends SlackIntegration { }++export interface SlackWorkspaceInfo {+ id: string;+ name: string;+ url: string;+ domain: string;+}++export interface SlackOAuthResponse {+ ok: boolean;+ access_token: string;+ token_type: string;+ scope: string;+ bot_user_id: string;+ team: {+ name: string;+ id: string;+ };+ enterprise?: {+ name: string;+ id: string;+ };+ authed_user: {+ id: string;+ scope: string;+ access_token: string;+ token_type: string;+ };+}++export interface SlackMessage {+ channel?: string;+ text?: string;+ blocks?: any[];+ thread_ts?: string;+ unfurl_links?: boolean;+ unfurl_media?: boolean;+}++export type SlackNotificationType = 'document_view' | 'dataroom_access' | 'document_download';++export interface SlackChannelConfig {+ id: string;+ name: string;+ enabled: boolean;+ notificationTypes: SlackNotificationType[];+}\ No newline at end of filediff --git a/pages/api/teams/[teamId]/slack/index.ts b/pages/api/teams/[teamId]/slack/index.tsindex 6f979964..6b138e32 100644--- a/pages/api/teams/[teamId]/slack/index.ts+++ b/pages/api/teams/[teamId]/slack/index.ts@@ -3,7 +3,20 @@ import { getServerSession } from 'next-auth/next';import { authOptions } from '@/pages/api/auth/[...nextauth]';import { CustomUser } from '@/lib/types';import prisma from '@/lib/prisma';-+import { z } from 'zod';++const slackIntegrationUpdateSchema = z.object({+ enabled: z.boolean().optional(),+ defaultChannel: z.string().nullable().optional(),+ enabledChannels: z.record(z.string(), z.boolean()).optional(),+ notificationTypes: z.object({+ document_view: z.boolean().optional(),+ document_download: z.boolean().optional(),+ dataroom_access: z.boolean().optional(),+ document_comment: z.boolean().optional(),+ document_reaction: z.boolean().optional(),+ }).optional(),+});export default async function handler(req: NextApiRequest,@@ -83,14 +96,23 @@ async function handleUpdate(teamId: string) {try {+ const validationResult = slackIntegrationUpdateSchema.safeParse(req.body);++ if (!validationResult.success) {+ return res.status(400).json({+ error: 'Invalid request payload',+ details: validationResult.error.errors+ });+ }+const {enabled,notificationTypes,defaultChannel,enabledChannels,- } = req.body;+ } = validationResult.data;- if (enabledChannels && Object.keys(req.body).length === 1) {+ if (enabledChannels && Object.keys(validationResult.data).length === 1) {await prisma.slackIntegration.update({where: { teamId },data: { enabledChannels },@@ -102,7 +124,19 @@ async function handleUpdate(updatedAt: new Date().toISOString()});}- const updateData: any = {};++ const updateData: {+ enabled?: boolean;+ notificationTypes?: {+ document_view?: boolean;+ document_download?: boolean;+ dataroom_access?: boolean;+ document_comment?: boolean;+ document_reaction?: boolean;+ };+ defaultChannel?: string | null;+ enabledChannels?: Record<string, boolean>;+ } = {};if (enabled !== undefined) updateData.enabled = enabled;if (notificationTypes) updateData.notificationTypes = notificationTypes;diff --git a/pages/settings/slack.tsx b/pages/settings/slack.tsxindex a7c21f57..47eed3af 100644--- a/pages/settings/slack.tsx+++ b/pages/settings/slack.tsx@@ -221,8 +221,6 @@ export default function SlackSettings() {});const endTime = performance.now();- // Log performance for debugging- console.log(`Channel update API call took ${endTime - startTime}ms`);if (!response.ok) {const errorData = await response.json();@@ -298,7 +296,6 @@ export default function SlackSettings() {);const requestBody: UpdateSlackIntegrationRequest = {- ...integration,enabled: checked,};@@ -530,4 +527,4 @@ export default function SlackSettings() {</main></AppLayout>);-}+}\ No newline at end of file