11import { db } from '@sim/db'
22import { webhook , workflow } from '@sim/db/schema'
33import { createLogger } from '@sim/logger'
4+ import type { InferSelectModel } from 'drizzle-orm'
45import { and , eq , sql } from 'drizzle-orm'
56import type { FetchMessageObject , MailboxLockObject } from 'imapflow'
67import { ImapFlow } from 'imapflow'
@@ -11,6 +12,8 @@ import { MAX_CONSECUTIVE_FAILURES } from '@/triggers/constants'
1112
1213const logger = createLogger ( 'ImapPollingService' )
1314
15+ type WebhookRecord = InferSelectModel < typeof webhook >
16+
1417interface ImapWebhookConfig {
1518 host : string
1619 port : number
@@ -489,6 +492,27 @@ function extractAttachmentsFromSource(
489492 return attachments
490493}
491494
495+ /**
496+ * Checks if a body structure contains attachments by examining disposition
497+ */
498+ function hasAttachmentsInBodyStructure ( structure : FetchMessageObject [ 'bodyStructure' ] ) : boolean {
499+ if ( ! structure ) return false
500+
501+ if ( structure . disposition === 'attachment' ) {
502+ return true
503+ }
504+
505+ if ( structure . disposition === 'inline' && structure . dispositionParameters ?. filename ) {
506+ return true
507+ }
508+
509+ if ( structure . childNodes && Array . isArray ( structure . childNodes ) ) {
510+ return structure . childNodes . some ( ( child ) => hasAttachmentsInBodyStructure ( child ) )
511+ }
512+
513+ return false
514+ }
515+
492516async function processEmails (
493517 emails : Array < {
494518 uid : number
@@ -497,7 +521,7 @@ async function processEmails(
497521 bodyStructure : FetchMessageObject [ 'bodyStructure' ]
498522 source ?: Buffer
499523 } > ,
500- webhookData : any ,
524+ webhookData : WebhookRecord ,
501525 config : ImapWebhookConfig ,
502526 requestId : string
503527) {
@@ -539,9 +563,7 @@ async function processEmails(
539563 : { text : '' , html : '' }
540564
541565 let attachments : ImapAttachment [ ] = [ ]
542- const hasAttachments = email . bodyStructure
543- ? JSON . stringify ( email . bodyStructure ) . toLowerCase ( ) . includes ( 'attachment' )
544- : false
566+ const hasAttachments = hasAttachmentsInBodyStructure ( email . bodyStructure )
545567
546568 if ( config . includeAttachments && hasAttachments && email . source ) {
547569 attachments = extractAttachmentsFromSource ( email . source , email . bodyStructure )
@@ -573,7 +595,7 @@ async function processEmails(
573595 method : 'POST' ,
574596 headers : {
575597 'Content-Type' : 'application/json' ,
576- 'X-Webhook-Secret' : webhookData . secret || '' ,
598+ 'X-Webhook-Secret' : '' ,
577599 'User-Agent' : 'Sim/1.0' ,
578600 } ,
579601 body : JSON . stringify ( payload ) ,
0 commit comments