Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,6 @@ import com.wallet.core.primitives.Rewards
import com.wallet.core.primitives.ScanTransaction
import com.wallet.core.primitives.ScanTransactionPayload
import com.wallet.core.primitives.SupportAction
import com.wallet.core.primitives.SupportConversation
import com.wallet.core.primitives.SupportMessage
import com.wallet.core.primitives.SupportMessageInput
import com.wallet.core.primitives.Transaction
Expand Down Expand Up @@ -118,9 +117,6 @@ interface GemDeviceApiClient {
@POST("/v2/devices/scan/transaction")
suspend fun getScanTransaction(@Body payload: ScanTransactionPayload): ScanTransaction

@GET("/v2/devices/support")
suspend fun getSupportConversation(): SupportConversation?

@GET("/v2/devices/support/messages")
suspend fun getSupportMessages(
@Query("from_timestamp") fromTimestamp: Long,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ sealed class StreamEvent {
data class FiatTransaction(val data: StreamWalletUpdate): StreamEvent()
@Serializable
@SerialName("support")
data class Support(val data: SupportStreamEvent): StreamEvent()
data class Support(val data: SupportMessage): StreamEvent()
}

@Serializable
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,24 +13,6 @@ data class SupportAgent (
val avatarUrl: String? = null
)

@Serializable
enum class SupportConversationStatus(val string: String) {
@SerialName("open")
Open("open"),
@SerialName("resolved")
Resolved("resolved"),
}

@Serializable
data class SupportConversation (
val id: String,
val status: SupportConversationStatus,
val firstMessage: String? = null,
val lastMessage: String? = null,
val lastActivityAt: SerializedDate,
val unreadCount: Int
)

@Serializable
sealed class SupportMessageSender {
@Serializable
Expand Down Expand Up @@ -65,7 +47,6 @@ data class SupportMessageImage (
@Serializable
data class SupportMessage (
val id: String,
val conversationId: String,
val content: String,
val sender: SupportMessageSender,
val deliveryStatus: SupportMessageDeliveryStatus,
Expand All @@ -88,16 +69,6 @@ sealed class SupportAction {
object LastSeen: SupportAction()
}

@Serializable
sealed class SupportStreamEvent {
@Serializable
@SerialName("message")
data class Message(val data: SupportMessage): SupportStreamEvent()
@Serializable
@SerialName("conversation")
data class Conversation(val data: SupportConversation): SupportStreamEvent()
}

@Serializable
enum class SupportTypingStatus(val string: String) {
@SerialName("on")
Expand Down
1 change: 0 additions & 1 deletion core/apps/api/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -133,7 +133,6 @@ fn mount_routes(rocket: Rocket<Build>, admin_enabled: bool) -> Rocket<Build> {
devices::create_device_referral_v2,
devices::use_device_referral_code_v2,
devices::redeem_device_rewards_v2,
support::get_support_conversation,
support::get_support_messages,
support::post_support_action,
support::post_support_image,
Expand Down
6 changes: 1 addition & 5 deletions core/apps/api/src/support/client.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use primitives::{SupportAction, SupportConversation, SupportMessage, SupportMessageInput};
use primitives::{SupportAction, SupportMessage, SupportMessageInput};
use std::{error::Error, future::Future};
use storage::models::DeviceRow;

Expand All @@ -15,10 +15,6 @@ impl SupportApiClient {
}
}

pub async fn conversation(&self, device: &DeviceRow) -> Result<Option<SupportConversation>, Box<dyn Error + Send + Sync>> {
self.with_session(device, |session| async move { self.chatwoot.conversation(&session).await }).await
}

pub async fn messages(&self, device: &DeviceRow, from_timestamp: Option<u64>) -> Result<Vec<SupportMessage>, Box<dyn Error + Send + Sync>> {
self.with_session(device, |session| async move { self.chatwoot.messages(&session, from_timestamp).await })
.await
Expand Down
7 changes: 1 addition & 6 deletions core/apps/api/src/support/mod.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
mod client;

pub use client::SupportApiClient;
use primitives::{SupportAction, SupportConversation, SupportMessage, SupportMessageInput};
use primitives::{SupportAction, SupportMessage, SupportMessageInput};
use rocket::{Data, State, data::ToByteUnit, get, http::ContentType, post, serde::json::Json, tokio::sync::Mutex};

use crate::{
Expand All @@ -11,11 +11,6 @@ use crate::{

const MAX_SUPPORT_IMAGE_BYTES: u64 = 10 * 1024 * 1024;

#[get("/devices/support")]
pub async fn get_support_conversation(device: AuthenticatedDevice, client: &State<Mutex<SupportApiClient>>) -> Result<ApiResponse<Option<SupportConversation>>, ApiError> {
Ok(client.lock().await.conversation(&device.device_row).await?.into())
}

#[get("/devices/support/messages?<from_timestamp>")]
pub async fn get_support_messages(
device: AuthenticatedDevice,
Expand Down
3 changes: 1 addition & 2 deletions core/crates/primitives/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -226,8 +226,7 @@ pub mod stream;
pub use self::stream::{StreamBalanceUpdate, StreamEvent, StreamMessage, StreamMessagePrices, StreamTransactionsUpdate, StreamWalletUpdate, device_stream_channel};
pub mod support;
pub use self::support::{
SupportAction, SupportAgent, SupportConversation, SupportConversationStatus, SupportMessage, SupportMessageDeliveryStatus, SupportMessageImage, SupportMessageInput,
SupportMessageSender, SupportStreamEvent, SupportTypingStatus,
SupportAction, SupportAgent, SupportMessage, SupportMessageDeliveryStatus, SupportMessageImage, SupportMessageInput, SupportMessageSender, SupportTypingStatus,
};
pub mod asset_balance;
pub use self::asset_balance::{AddressBalances, AssetBalance, Balance};
Expand Down
4 changes: 2 additions & 2 deletions core/crates/primitives/src/stream.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use serde::{Deserialize, Serialize};
use typeshare::typeshare;

use crate::{AssetId, InAppNotification, SupportStreamEvent, TransactionId, WalletId, WebSocketPricePayload};
use crate::{AssetId, InAppNotification, SupportMessage, TransactionId, WalletId, WebSocketPricePayload};

pub const DEVICE_STREAM_CHANNEL_PREFIX: &str = "stream:device:";

Expand All @@ -22,7 +22,7 @@ pub enum StreamEvent {
Perpetual(StreamWalletUpdate),
InAppNotification(StreamNotificationUpdate),
FiatTransaction(StreamWalletUpdate),
Support(SupportStreamEvent),
Support(SupportMessage),
}

#[derive(Debug, Clone, Serialize, Deserialize)]
Expand Down
30 changes: 0 additions & 30 deletions core/crates/primitives/src/support.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,6 @@ use chrono::{DateTime, Utc};
use serde::{Deserialize, Serialize};
use typeshare::typeshare;

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[typeshare(swift = "Equatable, CaseIterable, Sendable")]
#[serde(rename_all = "lowercase")]
pub enum SupportConversationStatus {
Open,
Resolved,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[typeshare(swift = "Equatable, CaseIterable, Sendable")]
#[serde(rename_all = "lowercase")]
Expand Down Expand Up @@ -53,20 +45,6 @@ impl SupportMessageSender {
}
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[typeshare(swift = "Sendable, Equatable, Hashable, Identifiable")]
#[serde(rename_all = "camelCase")]
pub struct SupportConversation {
pub id: String,
pub status: SupportConversationStatus,
#[serde(skip_serializing_if = "Option::is_none")]
pub first_message: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
pub last_message: Option<String>,
pub last_activity_at: DateTime<Utc>,
pub unread_count: i32,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[typeshare(swift = "Sendable, Equatable")]
#[serde(rename_all = "camelCase")]
Expand All @@ -90,7 +68,6 @@ pub struct SupportMessageImage {
#[serde(rename_all = "camelCase")]
pub struct SupportMessage {
pub id: String,
pub conversation_id: String,
pub content: String,
pub sender: SupportMessageSender,
pub delivery_status: SupportMessageDeliveryStatus,
Expand Down Expand Up @@ -121,10 +98,3 @@ pub enum SupportAction {
LastSeen,
}

#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(tag = "type", content = "data", rename_all = "camelCase")]
#[typeshare(swift = "Sendable")]
pub enum SupportStreamEvent {
Message(SupportMessage),
Conversation(SupportConversation),
}
29 changes: 3 additions & 26 deletions core/crates/support/src/chatwoot.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use chrono::Utc;
use primitives::{Device, SupportConversation, SupportMessage, SupportTypingStatus};
use primitives::{Device, SupportMessage, SupportTypingStatus};
use reqwest::header::{HeaderMap, HeaderName, HeaderValue};
use reqwest::multipart::{Form, Part};
use reqwest::{Client, RequestBuilder, Response};
Expand All @@ -8,11 +8,8 @@ use std::error::Error;
use std::io;

use crate::{
ChatwootConfigResponse, ChatwootContactResponse, ChatwootContactUpdate, ChatwootConversationResponse, ChatwootMessageInput, ChatwootMessagesResponse, ChatwootSession,
ChatwootTypingInput, Message,
constants::{
PATH_CONFIG, PATH_CONTACT_SET_USER, PATH_CONVERSATIONS, PATH_MESSAGES, PATH_TOGGLE_TYPING, PATH_UPDATE_LAST_SEEN, QUERY_CHATWOOT_AFTER, QUERY_WIDGET_PUBLIC_TOKEN,
},
ChatwootConfigResponse, ChatwootContactResponse, ChatwootContactUpdate, ChatwootMessageInput, ChatwootMessagesResponse, ChatwootSession, ChatwootTypingInput, Message,
constants::{PATH_CONFIG, PATH_CONTACT_SET_USER, PATH_MESSAGES, PATH_TOGGLE_TYPING, PATH_UPDATE_LAST_SEEN, QUERY_CHATWOOT_AFTER, QUERY_WIDGET_PUBLIC_TOKEN},
support_messages,
};

Expand Down Expand Up @@ -52,26 +49,6 @@ impl ChatwootClient {
})
}

pub async fn conversation(&self, session: &ChatwootSession) -> Result<Option<SupportConversation>, Box<dyn Error + Send + Sync>> {
let conversation: ChatwootConversationResponse = self
.json(
self.authenticated(self.client.get(self.widget_url(PATH_CONVERSATIONS)), &session.auth_token)?
.send()
.await?,
)
.await?;

let Some(id) = conversation.id else {
return Ok(None);
};

let messages = self.messages(session, None).await?;
let conversation = conversation
.support_conversation(&messages)
.ok_or_else(|| io::Error::other(format!("conversation {id} has no activity timestamp")))?;
Ok(Some(conversation))
}

pub async fn messages(&self, session: &ChatwootSession, from_timestamp: Option<u64>) -> Result<Vec<SupportMessage>, Box<dyn Error + Send + Sync>> {
let mut request = self.authenticated(self.client.get(self.widget_url(PATH_MESSAGES)), &session.auth_token)?;
if let Some(from_timestamp) = from_timestamp {
Expand Down
32 changes: 6 additions & 26 deletions core/crates/support/src/client.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
use crate::{
ChatwootWebhookPayload,
constants::{EVENT_CONVERSATION_STATUS_CHANGED, EVENT_CONVERSATION_UPDATED, EVENT_MESSAGE_CREATED},
};
use crate::{ChatwootWebhookPayload, constants::EVENT_MESSAGE_CREATED};
use cacher::CacherClient;
use localizer::LanguageLocalizer;
use primitives::{
Device, GorushNotification, PushNotification, PushNotificationTypes, StreamEvent, SupportStreamEvent, device_stream_channel, push_notification::PushNotificationSupport,
Device, GorushNotification, PushNotification, PushNotificationTypes, StreamEvent, device_stream_channel, push_notification::PushNotificationSupport,
};
use std::error::Error;
use storage::database::devices::DevicesStore;
Expand All @@ -32,14 +29,10 @@ impl SupportClient {
}

pub async fn process_webhook(&self, device: &Device, payload: &ChatwootWebhookPayload) -> Result<(usize, usize), Box<dyn Error + Send + Sync>> {
match payload.event.as_str() {
EVENT_MESSAGE_CREATED => self.process_message_created(device, payload).await,
EVENT_CONVERSATION_UPDATED | EVENT_CONVERSATION_STATUS_CHANGED => self.process_conversation_updated(device, payload).await,
_ => Ok((0, 0)),
if payload.event.as_str() != EVENT_MESSAGE_CREATED {
return Ok((0, 0));
}
}

async fn process_message_created(&self, device: &Device, payload: &ChatwootWebhookPayload) -> Result<(usize, usize), Box<dyn Error + Send + Sync>> {
let notifications_count = if let Some(notification) = Self::build_notification(device, payload) {
self.stream_producer.publish_notifications_support(NotificationsPayload::new(vec![notification])).await?;
1
Expand All @@ -52,15 +45,6 @@ impl SupportClient {
Ok((notifications_count, stream_events_count))
}

async fn process_conversation_updated(&self, device: &Device, payload: &ChatwootWebhookPayload) -> Result<(usize, usize), Box<dyn Error + Send + Sync>> {
if let Some(conversation) = payload.support_conversation() {
self.publish_stream_event(device, SupportStreamEvent::Conversation(conversation)).await?;
Ok((0, 1))
} else {
Ok((0, 0))
}
}

fn build_notification(device: &Device, payload: &ChatwootWebhookPayload) -> Option<GorushNotification> {
if !payload.is_public_outgoing_message() {
return None;
Expand All @@ -81,13 +65,9 @@ impl SupportClient {
return Ok(0);
};

self.publish_stream_event(device, SupportStreamEvent::Message(message)).await?;
Ok(1)
}

async fn publish_stream_event(&self, device: &Device, event: SupportStreamEvent) -> Result<(), Box<dyn Error + Send + Sync>> {
let channel = device_stream_channel(&device.id);
self.cacher.publish(&channel, &StreamEvent::Support(event)).await
self.cacher.publish(&channel, &StreamEvent::Support(message)).await?;
Ok(1)
}
}

Expand Down
4 changes: 0 additions & 4 deletions core/crates/support/src/constants.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,11 @@ pub(crate) const CHATWOOT_DELIVERY_STATUS_DELIVERED: &str = "delivered";
pub(crate) const CHATWOOT_DELIVERY_STATUS_READ: &str = "read";
pub(crate) const CHATWOOT_DELIVERY_STATUS_SENT: &str = "sent";
pub(crate) const CHATWOOT_FILE_TYPE_IMAGE: &str = "image";
pub(crate) const CHATWOOT_STATUS_RESOLVED: &str = "resolved";

pub(crate) const EVENT_CONVERSATION_STATUS_CHANGED: &str = "conversation_status_changed";
pub(crate) const EVENT_CONVERSATION_UPDATED: &str = "conversation_updated";
pub(crate) const EVENT_MESSAGE_CREATED: &str = "message_created";

pub(crate) const PATH_CONFIG: &str = "config";
pub(crate) const PATH_CONTACT_SET_USER: &str = "contact/set_user";
pub(crate) const PATH_CONVERSATIONS: &str = "conversations";
pub(crate) const PATH_MESSAGES: &str = "messages";
pub(crate) const PATH_TOGGLE_TYPING: &str = "conversations/toggle_typing";
pub(crate) const PATH_UPDATE_LAST_SEEN: &str = "conversations/update_last_seen";
Expand Down
Loading
Loading