Skip to content

Fix Message.Status as String #1046

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Nov 11, 2024

Conversation

rafwell
Copy link
Contributor

@rafwell rafwell commented Nov 8, 2024

Identifiquei que o campo status na tabela Message era tratado como string, mas o ultimo migration o criava como int. Isso causou erros aqui em uma instalação nova na versão 2.2.0. As mensagens estavam sendo enviadas mas o servidor gerava um erro 500 ao tentar inserir na tabela.

@rafwell
Copy link
Contributor Author

rafwell commented Nov 8, 2024

LOG:

2024-11-07 18:22:40 evolution_api  | > evolution-api@2.2.0 start:prod
2024-11-07 18:22:40 evolution_api  | > node dist/main
2024-11-07 18:22:40 evolution_api  | 
2024-11-07 18:22:56 evolution_api  | Cache request for group: 120363360637004078@g.us
2024-11-07 18:22:56 evolution_api  | Cache request for group: 120363360637004078@g.us
2024-11-07 18:22:57 evolution_api  | [Evolution API]  [minhainstancia.local.c6ace8e0-97d0-11ef-a8a5-0b8cfd192ad1]  v2.2.0  163   -  Thu Nov 07 2024 18:22:57     ERROR   [ChannelStartupService]  [object]   
2024-11-07 18:22:57 evolution_api  | PrismaClientUnknownRequestError: 
2024-11-07 18:22:57 evolution_api  | Invalid `this.prismaRepository.contact.findMany()` invocation in
2024-11-07 18:22:57 evolution_api  | /evolution/dist/main.js:259:10997
2024-11-07 18:22:57 evolution_api  | 
2024-11-07 18:22:57 evolution_api  |   256         wuid: ${r}
2024-11-07 18:22:57 evolution_api  |   257         name: ${n}
2024-11-07 18:22:57 evolution_api  |   258       `),await this.prismaRepository.instance.update({where:{id:this.instanceId},data:{ownerJid:this.instance.wuid,profileName:await this.getProfileName(),profilePicUrl:this.instance.profilePictureUrl,connectionStatus:"open"}}),this.configService.get("CHATWOOT").ENABLED&&this.localChatwoot?.enabled&&(this.chatwootService.eventWhatsapp("connection.update",{instanceName:this.instance.name,instanceId:this.instanceId},{instance:this.instance.name,status:"open"}),this.syncChatwootLostMessages())}}async getMessage(e,t=!1){try{let s=await this.prismaRepository.message.findMany({where:{instanceId:this.instanceId,key:{path:["id"],equals:e.id}}});if(t)return s[0];if(s[0].message?.pollCreationMessage){let r=s[0].message?.messageContextInfo?.messageSecret;if(typeof r=="string")return{messageContextInfo:{messageSecret:Buffer.from(r,"base64")},pollCreationMessage:s[0].message?.pollCreationMessage}}return s[0].message}catch{return{conversation:""}}}async defineAuthState(){let e=this.configService.get("DATABASE"),t=this.configService.get("CACHE");if(this.configService.get("PROVIDER")?.ENABLED)return await this.authStateProvider.authStateProvider(this.instance.id);if(t?.REDIS.ENABLED&&t?.REDIS.SAVE_INSTANCES)return this.logger.info("Redis enabled"),await yo(this.instance.id,this.cache);if(e.SAVE_DATA.INSTANCE)return await Qn(this.instance.id,this.cache)}async createClient(e){this.instance.authState=await this.defineAuthState();let t=this.configService.get("CONFIG_SESSION_PHONE"),s={};if(e||this.phoneNumber)this.phoneNumber=e,this.logger.info(`Phone number: ${e}`);else{let c=[t.CLIENT,t.NAME,(0,Io.release)()];s={browser:c},this.logger.info(`Browser: ${c}`)}let r,n;t.VERSION?(r=t.VERSION.split("."),n=`Baileys version env: ${r}`):(r=(await(0,R.fetchLatestBaileysVersion)()).version,n=`Baileys version: ${r}`),this.logger.info(n),this.logger.info(`Group Ignore: ${this.localSettings.groupsIgnore}`);let o;if(this.localProxy?.enabled)if(this.logger.info("Proxy enabled: "+this.localProxy?.host),this.localProxy?.host?.includes("proxyscrape"))try{let d=(await xe.default.get(this.localProxy?.host)).data.split(`\r
2024-11-07 18:22:57 evolution_api  | → 259 `),l=Math.floor(Math.random()*Math.floor(d.length)),g="http://"+d[l];o={agent:Ee(g),fetchAgent:Ee(g)}}catch{this.localProxy.enabled=!1}else o={agent:Ee({host:this.localProxy.host,port:this.localProxy.port,protocol:this.localProxy.protocol,username:this.localProxy.username,password:this.localProxy.password}),fetchAgent:Ee({host:this.localProxy.host,port:this.localProxy.port,protocol:this.localProxy.protocol,username:this.localProxy.username,password:this.localProxy.password})};let a={...o,version:r,logger:(0,at.default)({level:this.logBaileys}),printQRInTerminal:!1,auth:{creds:this.instance.authState.state.creds,keys:(0,R.makeCacheableSignalKeyStore)(this.instance.authState.state.keys,(0,at.default)({level:"error"}))},msgRetryCounterCache:this.msgRetryCounterCache,generateHighQualityLinkPreview:!0,getMessage:async c=>await this.getMessage(c),...s,markOnlineOnConnect:this.localSettings.alwaysOnline,retryRequestDelayMs:350,maxMsgRetryCount:4,fireInitQueries:!0,connectTimeoutMs:3e4,keepAliveIntervalMs:3e4,qrTimeout:45e3,emitOwnEvents:!1,shouldIgnoreJid:c=>{let u=this.localSettings.groupsIgnore&&(0,R.isJidGroup)(c),d=!this.localSettings.readStatus&&(0,R.isJidBroadcast)(c),l=(0,R.isJidNewsletter)(c);return u||d||l},syncFullHistory:this.localSettings.syncFullHistory,shouldSyncHistoryMessage:c=>this.historySyncNotification(c),cachedGroupMetadata:this.getGroupMetadataCache,userDevicesCache:this.userDevicesCache,transactionOpts:{maxCommitRetries:10,delayBetweenTriesMs:3e3},patchMessageBeforeSending(c){return c.deviceSentMessage?.message?.listMessage?.listType===R.proto.Message.ListMessage.ListType.PRODUCT_LIST&&(c=JSON.parse(JSON.stringify(c)),c.deviceSentMessage.message.listMessage.listType=R.proto.Message.ListMessage.ListType.SINGLE_SELECT),c.listMessage?.listType==R.proto.Message.ListMessage.ListType.PRODUCT_LIST&&(c=JSON.parse(JSON.stringify(c)),c.listMessage.listType=R.proto.Message.ListMessage.ListType.SINGLE_SELECT),c}};return this.endSession=!1,this.client=(0,R.default)(a),this.eventHandler(),this.phoneNumber=e,this.client}async connectToWhatsapp(e){try{return this.loadChatwoot(),this.loadSettings(),this.loadWebhook(),this.loadProxy(),await this.createClient(e)}catch(t){throw this.logger.error(t),new F(t?.toString())}}async reloadConnection(){try{return await this.createClient(this.phoneNumber)}catch(e){throw this.logger.error(e),new F(e?.toString())}}eventHandler(){this.client.ev.process(async e=>{if(!this.endSession){let t=this.configService.get("DATABASE"),s=await this.findSettings();if(e.call){let r=e.call[0];if(s?.rejectCall&&r.status=="offer"&&this.client.rejectCall(r.id,r.from),s?.msgCall?.trim().length>0&&r.status=="offer"){let n=await this.client.sendMessage(r.from,{text:s.msgCall});this.client.ev.emit("messages.upsert",{messages:[n],type:"notify"})}this.sendDataWebhook("call",r)}if(e["connection.update"]&&this.connectionUpdate(e["connection.update"]),e["creds.update"]&&this.instance.authState.saveCreds(),e["messaging-history.set"]){let r=e["messaging-history.set"];this.messageHandle["messaging-history.set"](r)}if(e["messages.upsert"]){let r=e["messages.upsert"];this.messageHandle["messages.upsert"](r,s)}if(e["messages.update"]){let r=e["messages.update"];this.messageHandle["messages.update"](r,s)}if(e["message-receipt.update"]){let r=e["message-receipt.update"],n={};for(let o of r)typeof o.key.remoteJid=="string"&&typeof o.receipt.readTimestamp=="number"&&(n[o.key.remoteJid]=o.receipt.readTimestamp);await Promise.all(Object.keys(n).map(async o=>this.updateMessagesReadedByTimestamp(o,n[o])))}if(e["presence.update"]){let r=e["presence.update"];if(s?.groupsIgnore&&r.id.includes("@g.us"))return;this.sendDataWebhook("presence.update",r)}if(!s?.groupsIgnore){if(e["groups.upsert"]){let r=e["groups.upsert"];this.groupHandler["groups.upsert"](r)}if(e["groups.update"]){let r=e["groups.update"];this.groupHandler["groups.update"](r)}if(e["group-participants.update"]){let r=e["group-participants.update"];this.groupHandler["group-participants.update"](r)}}if(e["chats.upsert"]){let r=e["chats.upsert"];this.chatHandle["chats.upsert"](r)}if(e["chats.update"]){let r=e["chats.update"];this.chatHandle["chats.update"](r)}if(e["chats.delete"]){let r=e["chats.delete"];this.chatHandle["chats.delete"](r)}if(e["contacts.upsert"]){let r=e["contacts.upsert"];this.contactHandle["contacts.upsert"](r)}if(e["contacts.update"]){let r=e["contacts.update"];this.contactHandle["contacts.update"](r)}if(e["labels.association"]){let r=e["labels.association"];this.labelHandle["labels.association"](r,t);return}if(e["labels.edit"]){let r=e["labels.edit"];this.labelHandle["labels.edit"](r);return}}})}historySyncNotification(e){let t={instanceName:this.instance.name};return this.configService.get("CHATWOOT").ENABLED&&this.localChatwoot?.enabled&&this.localChatwoot.importMessages&&this.isSyncNotificationFromUsedSyncType(e)&&(e.chunkOrder===1&&this.chatwootService.startImportHistoryMessages(t),e.progress===100&&setTimeout(()=>{this.chatwootService.importHistoryMessages(t)},1e4)),!0}isSyncNotificationFromUsedSyncType(e){return this.localSettings.syncFullHistory&&e?.syncType===2||!this.localSettings.syncFullHistory&&e?.syncType===3}async profilePicture(e){let t=this.createJid(e);try{let s=await this.client.profilePictureUrl(t,"image");return{wuid:t,profilePictureUrl:s}}catch{return{wuid:t,profilePictureUrl:null}}}async getStatus(e){let t=this.createJid(e);try{return{wuid:t,status:(await this.client.fetchStatus(t))?.status}}catch{return{wuid:t,status:null}}}async fetchProfile(e,t){let s=t?this.createJid(t):this.client?.user?.id,r=(await this.whatsappNumber({numbers:[s]}))?.shift();if(!r.exists)throw new y(r);try{if(t){let n=(await this.whatsappNumber({numbers:[s]}))?.shift(),o=await this.profilePicture(n?.jid),a=await this.getStatus(n?.jid),c=await this.fetchBusinessProfile(n?.jid);return{wuid:n?.jid||s,name:n?.name,numberExists:n?.exists,picture:o?.profilePictureUrl,status:a?.status,isBusiness:c.isBusiness,email:c?.email,description:c?.description,website:c?.website?.shift()}}else{let n=e?[e]:null,o=await k.instanceInfo(n),a=await this.fetchBusinessProfile(s);return{wuid:s,name:o?.profileName,numberExists:!0,picture:o?.profilePicUrl,status:o?.connectionStatus,isBusiness:a.isBusiness,email:a?.email,description:a?.description,website:a?.website?.shift()}}}catch{return{wuid:s,name:null,picture:null,status:null,os:null,isBusiness:!1}}}async offerCall({number:e,isVideo:t,callDuration:s}){let r=this.createJid(e);try{let n=await this.client.offerCall(r,t);return setTimeout(()=>this.client.terminateCall(n.id,n.to),s*1e3),n}catch(n){return n}}async sendMessage(e,t,s,r,n,o,a){e=e.toLowerCase();let c={quoted:n};if((0,R.isJidGroup)(e)&&(c.useCachedGroupMetadata=!0),a&&(c.ephemeralExpiration=a),o?c.messageId=o:c.messageId="3EB0"+(0,wo.randomBytes)(18).toString("hex").toUpperCase(),t.viewOnceMessage){let u=(0,R.generateWAMessageFromContent)(e,t,{timestamp:new Date,userJid:this.instance.wuid,messageId:o,quoted:n}),d=await this.client.relayMessage(e,t,{messageId:o});u.key={id:d,remoteJid:e,participant:(0,R.isJidUser)(e)?e:void 0,fromMe:!0};for(let[l,g]of Object.entries(u))(!g||((0,Z.isArray)(g)&&g.length)===0)&&delete u[l];return u}if(!t.audio&&!t.poll&&!t.sticker&&!t.conversation&&e!=="status@broadcast"&&t.reactionMessage)return await this.client.sendMessage(e,{react:{text:t.reactionMessage.text,key:t.reactionMessage.key}},c);if(t.conversation)return await this.client.sendMessage(e,{text:t.conversation,mentions:s,linkPreview:r},c);if(!t.audio&&!t.poll&&!t.sticker&&e!="status@broadcast")return await this.client.sendMessage(e,{forward:{key:{remoteJid:this.instance.wuid,fromMe:!0},message:t},mentions:s},c);if(e==="status@broadcast"){let u;t.status.option.allContacts?u=(await this.prismaRepository.contact.findMany(
2024-11-07 18:22:57 evolution_api  | Error occurred during query execution:
2024-11-07 18:22:57 evolution_api  | ConnectorError(ConnectorError { user_facing_error: None, kind: QueryError(Server(MysqlError { code: 1366, message: "Incorrect integer value: 'PENDING' for column 'status' at row 1", state: "HY000" })), transient: false })
2024-11-07 18:22:57 evolution_api  |     at Mn.handleRequestError (/evolution/node_modules/@prisma/client/runtime/library.js:121:7943)
2024-11-07 18:22:57 evolution_api  |     at Mn.handleAndLogRequestError (/evolution/node_modules/@prisma/client/runtime/library.js:121:7061)
2024-11-07 18:22:57 evolution_api  |     at Mn.request (/evolution/node_modules/@prisma/client/runtime/library.js:121:6745)
2024-11-07 18:22:57 evolution_api  |     at async l (/evolution/node_modules/@prisma/client/runtime/library.js:130:9633)
2024-11-07 18:22:57 evolution_api  |     at async Rs.sendMessageWithTyping (/evolution/dist/main.js:259:10961)
2024-11-07 18:22:57 evolution_api  |     at async Rs.textMessage (/evolution/dist/main.js:259:13418)
2024-11-07 18:22:57 evolution_api  |     at async ts.sendText (/evolution/dist/main.js:2:21646)
2024-11-07 18:22:57 evolution_api  |     at async mn.dataValidate (/evolution/dist/main.js:282:61390)
2024-11-07 18:22:57 evolution_api  |     at async /evolution/dist/main.js:282:123723 {
2024-11-07 18:22:57 evolution_api  |   clientVersion: '5.21.1'
2024-11-07 18:22:57 evolution_api  | } 
2024-11-07 18:22:57 evolution_api  | 
2024-11-07 18:22:57 evolution_api  | Cache request for group: 120363360637004078@g.us
2024-11-07 18:24:05 evolution_api  | {"level":50,"time":1731014645960,"pid":163,"hostname":"dddbff846559","node":{"tag":"stream:error","attrs":{"code":"503"}},"msg":"stream errored out"}
2024-11-07 18:24:42 evolution_api  | [Evolution API]    v2.2.0  163   -  Thu Nov 07 2024 18:24:42     ERROR   [unhandledRejection]  [object]   
2024-11-07 18:24:42 evolution_api  | {X
2024-11-07 18:24:42 evolution_api  |   origin: Promise {
2024-11-07 18:24:42 evolution_api  |     <rejected> PrismaClientValidationError: 
2024-11-07 18:24:42 evolution_api  |     Invalid `this.prismaRepository.contact.findMany()` invocation in
2024-11-07 18:24:42 evolution_api  |     /evolution/dist/main.js:273:2999
2024-11-07 18:24:42 evolution_api  |     
2024-11-07 18:24:42 evolution_api  |       270 item1.X-ABLabel:Celular
2024-11-07 18:24:42 evolution_api  |       271 END:VCARD`,n};return e.contact.length===1?t.contactMessage={displayName:e.contact[0].fullName,vcard:s(e.contact[0])}:t.contactsArrayMessage={displayName:`${e.contact.length} contacts`,contacts:e.contact.map(r=>({displayName:r.fullName,vcard:s(r)}))},await this.sendMessageWithTyping(e.number,{...t},{})}async reactionMessage(e){return await this.sendMessageWithTyping(e.key.remoteJid,{reactionMessage:{key:e.key,text:e.reaction}})}async whatsappNumber(e){let t={groups:[],broadcast:[],users:[]};e.numbers.forEach(l=>{let g=this.createJid(l);(0,R.isJidGroup)(g)?t.groups.push({number:l,jid:g}):g==="status@broadcast"?t.broadcast.push({number:l,jid:g}):t.users.push({number:l,jid:g})});let s=[];s.push(...t.broadcast.map(({jid:l,number:g})=>new rt(l,!1,g)));let r=await Promise.all(t.groups.map(async({jid:l,number:g})=>{let h=await this.findGroup({groupJid:l},"inner");return h||new rt(l,!1,g),new rt(h.id,!!h?.id,g,h?.subject)}));s.push(...r);let n=await this.prismaRepository.contact.findMany({where:{instanceId:this.instanceId,remoteJid:{in:t.users.map(({jid:l})=>l)}}}),o=t.users.map(({jid:l})=>l.replace("+","")),a=await lo(o),c=o.filter(l=>!a.some(g=>g.jidOptions.includes(l))),u=await this.client.onWhatsApp(...c),d=await Promise.all(t.users.map(async l=>{let g=null,h=a.find(f=>f.jidOptions.includes(l.jid.replace("+","")));if(h)return{exists:!0,jid:h.remoteJid,name:n.find(f=>f.remoteJid===h.remoteJid)?.pushName,number:l.number};if(l.number.startsWith("55")){let f=l.number.slice(4,5)==="9"&&l.number.length===13?l.number:`${l.number.slice(0,4)}9${l.number.slice(4)}`,b=l.number.length===12?l.number:l.number.slice(0,4)+l.number.slice(5);g=u.find(S=>S.jid===`${f}@s.whatsapp.net`||S.jid===`${b}@s.whatsapp.net`)}if(!g&&(l.number.startsWith("52")||l.number.startsWith("54"))){let f="";l.number.startsWith("52")&&(f=""),l.number.startsWith("54")&&(f="9");let b=l.number.slice(2,3)===f&&l.number.length===13?l.number:`${l.number.slice(0,2)}${f}${l.number.slice(2)}`,S=l.number.length===12?l.number:l.number.slice(0,2)+l.number.slice(3);g=u.find(w=>w.jid===`${b}@s.whatsapp.net`||w.jid===`${S}@s.whatsapp.net`)}g||(g=u.find(f=>f.jid===l.jid));let m=g?.jid||l.jid;return{exists:!!g?.exists,jid:m,name:n.find(f=>f.remoteJid===m)?.pushName,number:l.number}}));return await Ke(d.filter(l=>l.exists).map(l=>({remoteJid:l.jid}))),s.push(...d),s}async markMessageAsRead(e){try{let t=[];return e.readMessages.forEach(s=>{((0,R.isJidGroup)(s.remoteJid)||(0,R.isJidUser)(s.remoteJid))&&t.push({remoteJid:s.remoteJid,fromMe:s.fromMe,id:s.id})}),await this.client.readMessages(t),{message:"Read messages",read:"success"}}catch(t){throw new F("Read messages fail",t.toString())}}async getLastMessage(e){let t={key:{remoteJid:e},instanceId:this.instance.id},s=await this.prismaRepository.message.findMany({where:t,orderBy:{messageTimestamp:"desc"},take:1});if(s.length===0)throw new W("Messages not found");let r=s.pop();for(let n of s)n.messageTimestamp>=r.messageTimestamp&&(r=n);return r}async archiveChat(e){try{let t=e.lastMessage,s=e.chat;if(!t&&s?t=await this.getLastMessage(s):(t=e.lastMessage,t.messageTimestamp=t?.messageTimestamp??Date.now(),s=t?.key?.remoteJid),!t||Object.keys(t).length===0)throw new W("Last message not found");return await this.client.chatModify({archive:e.archive,lastMessages:[t]},this.createJid(s)),{chatId:s,archived:!0}}catch(t){throw new F({archived:!1,message:["An error occurred while archiving the chat. Open a calling.",t.toString()]})}}async markChatUnread(e){try{let t=e.lastMessage,s=e.chat;if(!t&&s?t=await this.getLastMessage(s):(t=e.lastMessage,t.messageTimestamp=t?.messageTimestamp??Date.now(),s=t?.key?.remoteJid),!t||Object.keys(t).length===0)throw new W("Last message not found");return await this.client.chatModify({markRead:!1,lastMessages:[t]},this.createJid(s)),{chatId:s,markedChatUnread:!0}}catch(t){throw new F({markedChatUnread:!1,message:["An error occurred while marked unread the chat. Open a calling.",t.toString()]})}}async deleteMessage(e){try{let t=await this.client.sendMessage(e.remoteJid,{delete:e});if(t){let s=t.message?.protocolMessage?.key?.id;if(s){let r=M.get("DATABASE").DELETE_DATA.LOGICAL_MESSAGE_DELETE,n=await this.prismaRepository.message.findUnique({where:{id:s}});if(r){if(!n)return t;let o=typeof n?.key=="object"&&n.key!==null?n.key:{};n=await this.prismaRepository.message.update({where:{id:s},data:{key:{...o,deleted:!0}}})}else await this.prismaRepository.message.deleteMany({where:{id:s}});this.sendDataWebhook("messages.delete",{id:n.id,instanceId:n.instanceId,key:n.key,messageType:n.messageType,status:n.status,source:n.source,messageTimestamp:n.messageTimestamp,pushName:n.pushName,participant:n.participant,message:n.message})}}return t}catch(t){throw new F("Error while deleting message for everyone",t?.toString())}}async getBase64FromMediaMessage(e,t=!1){try{let s=e?.message,r=e?.convertToMp4??!1,n=s?.message?s:await this.getMessage(s.key,!0);if(!n)throw"Message not found";for(let g of Gr)n.message[g]&&(n.message=n.message[g].message);let o,a;for(let g of qr)if(o=n.message[g],o){a=g;break}if(!o)throw"The message is not of the media type";typeof o.mediaKey=="object"&&(n.message=JSON.parse(JSON.stringify(n.message)));let c=await(0,R.downloadMediaMessage)({key:n?.key,message:n?.message},"buffer",{},{logger:(0,at.default)({level:"error"}),reuploadRequest:this.client.updateMediaMessage}),u=(0,R.getContentType)(n.message),d=vt.default.getExtension(o?.mimetype),l=o?.fileName||`${n.key.id}.${d}`||`${(0,As.v4)()}.${d}`;if(r&&u==="audioMessage")try{let g=await this.processAudioMp4(c.toString("base64"));if(Buffer.isBuffer(g))return{mediaType:a,fileName:l,caption:o.caption,size:{fileLength:o.fileLength,height:o.height,width:o.width},mimetype:"audio/mp4",base64:g.toString("base64"),buffer:t?g:null}}catch(g){throw this.logger.error("Error converting audio to mp4:"),this.logger.error(g),new y("Failed to convert audio to MP4")}return{mediaType:a,fileName:l,caption:o.caption,size:{fileLength:o.fileLength,height:o.height,width:o.width},mimetype:o.mimetype,base64:c.toString("base64"),buffer:t?c:null}}catch(s){throw this.logger.error("Error processing media message:"),this.logger.error(s),new y(s.toString())}}async fetchPrivacySettings(){let e=await this.client.fetchPrivacySettings();return{readreceipts:e.readreceipts,profile:e.profile,status:e.status,online:e.online,last:e.last,groupadd:e.groupadd}}async updatePrivacySettings(e){try{return await this.client.updateReadReceiptsPrivacy(e.readreceipts),await this.client.updateProfilePicturePrivacy(e.profile),await this.client.updateStatusPrivacy(e.status),await this.client.updateOnlinePrivacy(e.online),await this.client.updateLastSeenPrivacy(e.last),await this.client.updateGroupsAddPrivacy(e.groupadd),this.reloadConnection(),{update:"success",data:{readreceipts:e.readreceipts,profile:e.profile,status:e.status,online:e.online,last:e.last,groupadd:e.groupadd}}}catch(t){throw new F("Error updating privacy settings",t.toString())}}async fetchBusinessProfile(e){try{let t=e?this.createJid(e):this.instance.wuid,s=await this.client.getBusinessProfile(t);return s?{isBusiness:!0,...s}:{isBusiness:!1,message:"Not is business profile",...(await this.whatsappNumber({numbers:[t]}))?.shift()}}catch(t){throw new F("Error updating profile name",t.toString())}}async updateProfileName(e){try{return await this.client.updateProfileName(e),{update:"success"}}catch(t){throw new F("Error updating profile name",t.toString())}}async updateProfileStatus(e){try{return await this.client.updateProfileStatus(e),{update:"success"}}catch(t){throw new F("Error updating profile status",t.toString())}}async updateProfilePicture(e){try{let t;if((0,Z.isURL)(e)){let s=new Date().getTime(),r=`${e}?timestamp=${s}`,n={responseType:"arraybuffer"};this.localProxy?.enabled&&(n={...n,httpsAgent:Ee({host:this.localProxy.host,port:this.localProxy.port,protocol:this.localProxy.protocol,username:this.localProxy.username,password:this.localProxy.password})}),t=(await xe.default.get(r,n)).data}else if((0,Z.isBase64)(e))t=Buffer.from(e,"base64");else throw new y('"profilePicture" must be a url or a base64');return await this.client.updateProfilePicture(this.instance.wuid,t),this.reloadConnection(),{update:"success"}}catch(t){throw new F("Error updating profile picture",t.toString())}}async removeProfilePicture(){try{return await this.client.removeProfilePicture(this.instance.wuid),this.reloadConnection(),{update:"success"}}catch(e){throw new F("Error removing profile picture",e.toString())}}async blockUser(e){try{let{number:t}=e,s=(await this.whatsappNumber({numbers:[t]}))?.shift();if(!s.exists&&!(0,R.isJidGroup)(s.jid)&&!s.jid.includes("@broadcast"))throw new y(s);let r=s.jid;return await this.client.updateBlockStatus(r,e.status),{block:"success"}}catch(t){throw new F("Error blocking user",t.toString())}}async formatUpdateMessage(e){try{let t=await this.getMessage(e.key,!0);return t?.messageType==="conversation"||t?.messageType==="extendedTextMessage"?{text:e.text}:t?.messageType==="imageMessage"?{image:t?.message?.imageMessage,caption:e.text}:t?.messageType==="videoMessage"?{video:t?.message?.videoMessage,caption:e.text}:null}catch(t){throw this.logger.error(t),new y(t.toString())}}async updateMessage(e){let t=this.createJid(e.number),s=await this.formatUpdateMessage(e);if(!s)throw this.logger.error("Message not compatible"),new y("Message not compatible");try{return await this.client.sendMessage(t,{...s,edit:e.key})}catch(r){throw this.logger.error(r),new y(r.toString())}}async fetchLabels(){return(await this.prismaRepository.label.findMany({where:{instanceId:this.instanceId}})).map(t=>({color:t.color,name:t.name,id:t.labelId,predefinedId:t.predefinedId}))}async handleLabel(e){let t=await this.whatsappNumber({numbers:[e.number]});if(t.length===0)throw new W("Number not found");let s=t[0];if(!s.exists)throw new W("Number is not on WhatsApp");try{if(e.action==="add")return await this.client.addChatLabel(s.jid,e.labelId),{numberJid:s.jid,labelId:e.labelId,add:!0};if(e.action==="remove")return await this.client.removeChatLabel(s.jid,e.labelId),{numberJid:s.jid,labelId:e.labelId,remove:!0}}catch(r){throw new y(`Unable to ${e.action} label to chat`,r.toString())}}async updateGroupMetadataCache(e){try{let t=await this.client.groupMetadata(e),s=this.configService.get("CACHE");return(s?.REDIS?.ENABLED&&s?.REDIS?.URI!==""||s?.LOCAL?.ENABLED)&&(this.logger.verbose(`Updating cache for group: ${e}`),await zn.set(e,{timestamp:Date.now(),data:t})),t}catch(t){return this.logger.error(t),null}}async createGroup(e){try{let t=(await this.whatsappNumber({numbers:e.participants})).filter(n=>n.exists).map(n=>n.jid),{id:s}=await this.client.groupCreate(e.subject,t);return e?.description&&await this.client.groupUpdateDescription(s,e.description),e?.promoteParticipants&&await this.updateGParticipant({groupJid:s,action:"promote",participants:t}),await this.client.groupMetadata(s)}catch(t){throw this.logger.error(t),new F("Error creating group",t.toString())}}async updateGroupPicture(e){try{let t;if((0,Z.isURL)(e.image)){let s=new Date().getTime(),r=`${e.image}?timestamp=${s}`,n={responseType:"arraybuffer"};this.localProxy?.enabled&&(n={...n,httpsAgent:Ee({host:this.localProxy.host,port:this.localProxy.port,protocol:this.localProxy.protocol,username:this.localProxy.username,password:this.localProxy.password})}),t=(await xe.default.get(r,n)).data}else if((0,Z.isBase64)(e.image))t=Buffer.from(e.image,"base64");else throw new y('"profilePicture" must be a url or a base64');return await this.client.updateProfilePicture(e.groupJid,t),{update:"success"}}catch(t){throw new F("Error update group picture",t.toString())}}async updateGroupSubject(e){try{return await this.client.groupUpdateSubject(e.groupJid,e.subject),{update:"success"}}catch(t){throw new F("Error updating group subject",t.toString())}}async updateGroupDescription(e){try{return await this.client.groupUpdateDescription(e.groupJid,e.description),{update:"success"}}catch(t){throw new F("Error updating group description",t.toString())}}async findGroup(e,t="out"){try{let s=await this.client.groupMetadata(e.groupJid);if(!s)return this.logger.error("Group not found"),null;let r=await this.profilePicture(s.id);return{id:s.id,subject:s.subject,subjectOwner:s.subjectOwner,subjectTime:s.subjectTime,pictureUrl:r.profilePictureUrl,size:s.participants.length,creation:s.creation,owner:s.owner,desc:s.desc,descId:s.descId,restrict:s.restrict,announce:s.announce,participants:s.participants,isCommunity:s.isCommunity,isCommunityAnnounce:s.isCommunityAnnounce,linkedParent:s.linkedParent}}catch(s){if(t==="inner")return;throw new W("Error fetching group",s.toString())}}async fetchAllGroups(e){let t=Object.values(await this?.client?.groupFetchAllParticipating()),s=[];for(let r of t){let n=await this.profilePicture(r.id),o={id:r.id,subject:r.subject,subjectOwner:r.subjectOwner,subjectTime:r.subjectTime,pictureUrl:n?.profilePictureUrl,size:r.participants.length,creation:r.creation,owner:r.owner,desc:r.desc,descId:r.descId,restrict:r.restrict,announce:r.announce,isCommunity:r.isCommunity,isCommunityAnnounce:r.isCommunityAnnounce,linkedParent:r.linkedParent};e.getParticipants=="true"&&(o.participants=r.participants),s=[...s,o]}return s}async inviteCode(e){try{let t=await this.client.groupInviteCode(e.groupJid);return{inviteUrl:`https://chat.whatsapp.com/${t}`,inviteCode:t}}catch(t){throw new W("No invite code",t.toString())}}async inviteInfo(e){try{return await this.client.groupGetInviteInfo(e.inviteCode)}catch{throw new W("No invite info",e.inviteCode)}}async sendInvite(e){try{let s=(await this.inviteCode({groupJid:e.groupJid})).inviteUrl,r=e.numbers.map(c=>this.createJid(c)),a={conversation:`${e.description??""}
2024-11-07 18:24:42 evolution_api  |       272 
2024-11-07 18:24:42 evolution_api  |     → 273 ${s}`};for await(let c of r)await this.sendMessageWithTyping(c,a);return{send:!0,inviteUrl:s}}catch{throw new W("No send invite")}}async acceptInviteCode(e){try{return{accepted:!0,groupJid:await this.client.groupAcceptInvite(e.inviteCode)}}catch(t){throw new W("Accept invite error",t.toString())}}async revokeInviteCode(e){try{return{revoked:!0,inviteCode:await this.client.groupRevokeInvite(e.groupJid)}}catch(t){throw new W("Revoke error",t.toString())}}async findParticipants(e){try{let t=(await this.client.groupMetadata(e.groupJid)).participants,s=await this.prismaRepository.contact.findMany({
2024-11-07 18:24:42 evolution_api  |             where: {
2024-11-07 18:24:42 evolution_api  |               AND: [
2024-11-07 18:24:42 evolution_api  |                 {
2024-11-07 18:24:42 evolution_api  |                   key: {
2024-11-07 18:24:42 evolution_api  |                     path: [
2024-11-07 18:24:42 evolution_api  |                       "remoteJid"
2024-11-07 18:24:42 evolution_api  |                     ],
2024-11-07 18:24:42 evolution_api  |                     equals: "120363030959578559@g.us"
2024-11-07 18:24:42 evolution_api  |                   }
2024-11-07 18:24:42 evolution_api  |                 },
2024-11-07 18:24:42 evolution_api  |                 {
2024-11-07 18:24:42 evolution_api  |                   key: {
2024-11-07 18:24:42 evolution_api  |                     path: [
2024-11-07 18:24:42 evolution_api  |                       "fromMe"
2024-11-07 18:24:42 evolution_api  |                     ],
2024-11-07 18:24:42 evolution_api  |                     equals: false
2024-11-07 18:24:42 evolution_api  |                   }
2024-11-07 18:24:42 evolution_api  |                 },
2024-11-07 18:24:42 evolution_api  |                 {
2024-11-07 18:24:42 evolution_api  |                   messageTimestamp: {
2024-11-07 18:24:42 evolution_api  |                     lte: 1731014682
2024-11-07 18:24:42 evolution_api  |                   }
2024-11-07 18:24:42 evolution_api  |                 },
2024-11-07 18:24:42 evolution_api  |                 {
2024-11-07 18:24:42 evolution_api  |                   OR: [
2024-11-07 18:24:42 evolution_api  |                     {
2024-11-07 18:24:42 evolution_api  |                       status: null
2024-11-07 18:24:42 evolution_api  |                     },
2024-11-07 18:24:42 evolution_api  |                     {
2024-11-07 18:24:42 evolution_api  |                       status: "DELIVERY_ACK"
2024-11-07 18:24:42 evolution_api  |                     }
2024-11-07 18:24:42 evolution_api  |                   ]
2024-11-07 18:24:42 evolution_api  |                 }
2024-11-07 18:24:42 evolution_api  |               ]
2024-11-07 18:24:42 evolution_api  |             },
2024-11-07 18:24:42 evolution_api  |             data: {
2024-11-07 18:24:42 evolution_api  |               status: "READ"
2024-11-07 18:24:42 evolution_api  |             }
2024-11-07 18:24:42 evolution_api  |           })
2024-11-07 18:24:42 evolution_api  |     
2024-11-07 18:24:42 evolution_api  |     Argument `path`: Invalid value provided. Expected String, provided (String).
2024-11-07 18:24:42 evolution_api  |         at Dn (/evolution/node_modules/@prisma/client/runtime/library.js:114:8082)
2024-11-07 18:24:42 evolution_api  |         at Mn.handleRequestError (/evolution/node_modules/@prisma/client/runtime/library.js:121:7396)
2024-11-07 18:24:42 evolution_api  |         at Mn.handleAndLogRequestError (/evolution/node_modules/@prisma/client/runtime/library.js:121:7061)
2024-11-07 18:24:42 evolution_api  |         at Mn.request (/evolution/node_modules/@prisma/client/runtime/library.js:121:6745)
2024-11-07 18:24:42 evolution_api  |         at async l (/evolution/node_modules/@prisma/client/runtime/library.js:130:9633)
2024-11-07 18:24:42 evolution_api  |         at async Rs.updateMessagesReadedByTimestamp (/evolution/dist/main.js:273:2963)
2024-11-07 18:24:42 evolution_api  |         at async Promise.all (index 0)
2024-11-07 18:24:42 evolution_api  |         at async /evolution/dist/main.js:259:3472 {
2024-11-07 18:24:42 evolution_api  |       clientVersion: '5.21.1'
2024-11-07 18:24:42 evolution_api  |     }
2024-11-07 18:24:42 evolution_api  |   },
2024-11-07 18:24:42 evolution_api  |   stderr: 2
2024-11-07 18:24:42 evolution_api  | } 
2024-11-07 18:24:42 evolution_api  | 

@DavidsonGomes DavidsonGomes changed the base branch from main to develop November 11, 2024 18:44
@DavidsonGomes DavidsonGomes merged commit 8f855b4 into EvolutionAPI:develop Nov 11, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants