Skip to content

Commit

Permalink
refactor:Push Prefix added
Browse files Browse the repository at this point in the history
  • Loading branch information
MdTeach committed Jun 2, 2023
1 parent b756d9d commit 6d39d18
Show file tree
Hide file tree
Showing 18 changed files with 252 additions and 56 deletions.
7 changes: 6 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -543,6 +543,7 @@ let message = try await Chats.Latest(
### **Fetching chat history between two users**
```swift
const chatHistory:[Message] = await Chat.History(
threadhash: String;
Expand Down Expand Up @@ -692,4 +693,8 @@ let messages:[Message] = try await Chats.History(
</details>
-----
-----
2 changes: 1 addition & 1 deletion Sources/Chat/Conversation.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import Foundation

extension Chats {
extension PushChat {
struct Hash: Codable { var threadHash: String? }

public static func ConversationHash(
Expand Down
2 changes: 1 addition & 1 deletion Sources/Chat/Inbox.swift
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ enum ChatError: Error {
case chatError(String)
}

public struct Chats {
public struct PushChat {
public static func getChats(options: GetChatsOptions) async throws -> [Feeds] {
if !isValidETHAddress(address: options.account) {
throw ChatError.invalidAddress
Expand Down
13 changes: 13 additions & 0 deletions Sources/Chat/Requests.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
// extension Chats {
// public struct RequestOptionsType: Codable {
// var account: String
// var pgpPrivateKey: String
// var env: ENV
// var toDecrypt: Bool = true
// var page: Int = 1
// var limit: Int = 10
// }
// public static func requests() async throws {

// }
// }
92 changes: 87 additions & 5 deletions Sources/Chat/Send.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import Foundation

extension Chats {
extension PushChat {
struct SendIntentAPIOptions {

}
Expand Down Expand Up @@ -116,10 +116,10 @@ extension Chats {
try await ConversationHash(conversationId: receiverAddress, account: senderAddress) == nil

if isConversationFirst {
return try await Chats.sendIntent(chatOptions)
return try await PushChat.sendIntent(chatOptions)
} else {
// send regular message
return try await Chats.sendMessage(chatOptions)
return try await PushChat.sendMessage(chatOptions)
}
}

Expand All @@ -133,13 +133,13 @@ extension Chats {

public static func sendIntent(_ sendOptions: SendOptions) async throws -> Message {
// check if user exists
let anotherUser = try await User.get(account: sendOptions.receiverAddress, env: .STAGING)
let anotherUser = try await PushUser.get(account: sendOptions.receiverAddress, env: .STAGING)

// else create the user frist and send unencrypted intent message
var enctyptMessage = true

if anotherUser == nil {
let _ = try await User.createUserEmpty(
let _ = try await PushUser.createUserEmpty(
userAddress: sendOptions.receiverAddress, env: sendOptions.env)
enctyptMessage = false
}
Expand All @@ -162,6 +162,88 @@ extension Chats {
return try await sendIntentService(payload: sendMessagePayload, env: sendOptions.env)
}

public static func approve(_ approveOptions: ApproveOptions) async throws {
let acceptIntentPayload = try await getApprovePayload(approveOptions)
print(acceptIntentPayload)

let url = try PushEndpoint.acceptChatRequest(env: approveOptions.env).url
var request = URLRequest(url: url)
request.httpMethod = "PUT"
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
request.httpBody = try JSONEncoder().encode(acceptIntentPayload)
print(url)

let (data, res) = try await URLSession.shared.data(for: request)

print(String(data: data, encoding: .utf8)!)
guard let httpResponse = res as? HTTPURLResponse else {
throw URLError(.badServerResponse)
}

guard (200...299).contains(httpResponse.statusCode) else {
throw URLError(.badServerResponse)
}

// do {
// return try JSONDecoder().decode(Message.self, from: data)
// } catch {
// print("[Push SDK] - API \(error.localizedDescription)")
// throw error
// }

}

static func getApprovePayload(_ approveOptions: ApproveOptions) async throws
-> ApproveRequestPayload
{
struct AcceptHashData: Encodable {
var fromDID: String
var toDID: String
var status: String
}

let apiData = AcceptHashData(
fromDID: approveOptions.fromDID,
toDID: approveOptions.toDID, status: "Approved")

let hash = generateSHA256Hash(
msg:
String(data: try JSONEncoder().encode(apiData), encoding: .utf8)!
)

let sig = try Pgp.sign(message: hash, privateKey: approveOptions.privateKey)
print("mess",String(data: try JSONEncoder().encode(apiData), encoding: .utf8)!)
print("hash",hash)
print("sig",sig)

return ApproveRequestPayload(
fromDID: approveOptions.fromDID, toDID: approveOptions.toDID, signature: sig,
status: "Approved", sigType: "pgp", verificationProof: "pgp:\(sig)")
}

public struct ApproveOptions {
var fromDID: String
var toDID: String
var privateKey: String
var env: ENV

public init(fromAddress: String, toAddress: String, privateKey: String, env: ENV) {
self.fromDID = walletToPCAIP10(account: fromAddress)
self.toDID = walletToPCAIP10(account: toAddress)
self.privateKey = privateKey
self.env = env
}
}

struct ApproveRequestPayload: Codable {
var fromDID: String
var toDID: String
var signature: String
var status: String = "Approved"
var sigType: String
var verificationProof: String
}

}

// let bodyToBeHashed = "{\"fromDID\":\"\(sendOptions.account)\",\"toDID\":\"\(sendOptions.receiverAddress)\",\"messageContent\":\"\(sendOptions.messageContent)\",\"messageType\":\"\(sendOptions.messageType)\"}"
Expand Down
9 changes: 9 additions & 0 deletions Sources/Endpoints/ChatEndpoint.swift
Original file line number Diff line number Diff line change
Expand Up @@ -69,4 +69,13 @@ extension PushEndpoint {
)
}

static func acceptChatRequest(
env: ENV
) throws -> Self {
return PushEndpoint(
env: env,
path: "chat/request/accept"
)
}

}
6 changes: 3 additions & 3 deletions Sources/Helpers/Chat/GetInboxList.swift
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ private func decryptAndVerifySignature(

private func decryptFeeds(
feeds: [Feeds],
connectedUser: User,
connectedUser: PushUser,
pgpPrivateKey: String?,
env: ENV
) async throws -> [Feeds] {
Expand All @@ -57,7 +57,7 @@ private func decryptFeeds(
throw ChatError.decryptedPrivateKeyNecessary
}

let decryptedMsg = try Chats.decryptMessage(
let decryptedMsg = try PushChat.decryptMessage(
message: currentFeed.msg!, privateKeyArmored: pgpPrivateKey!)
currentFeed.msg?.messageContent = decryptedMsg
}
Expand All @@ -73,7 +73,7 @@ public func getInboxLists(
pgpPrivateKey: String?,
env: ENV
) async throws -> [Feeds] {
let connectedUser = try await User.get(account: user, env: env)
let connectedUser = try await PushUser.get(account: user, env: env)
if connectedUser == nil {
throw ChatError.invalidAddress
}
Expand Down
10 changes: 5 additions & 5 deletions Sources/User/CreateUser.swift
Original file line number Diff line number Diff line change
Expand Up @@ -71,8 +71,8 @@ public struct CreateUserResponse: Decodable {
public var allowedNumMsg: Int
}

extension User {
public static func create(options: CreateUserOptions) async throws -> User {
extension PushUser {
public static func create(options: CreateUserOptions) async throws -> PushUser {
do {
let wallet = try await Wallet(signer: options.signer)
let address = wallet.account
Expand Down Expand Up @@ -169,7 +169,7 @@ extension User {
}

// orut
let createdUser = try JSONDecoder().decode(User.self, from: data)
let createdUser = try JSONDecoder().decode(PushUser.self, from: data)

options.progressHook?(
ProgressHookType(
Expand All @@ -193,7 +193,7 @@ extension User {
}
}

public static func createUserEmpty(userAddress: String, env: ENV) async throws -> User {
public static func createUserEmpty(userAddress: String, env: ENV) async throws -> PushUser {
let caip10 = walletToPCAIP10(account: userAddress)

let updatedData = CreateUserAPIOptions(
Expand Down Expand Up @@ -224,7 +224,7 @@ extension User {
}

// orut
let createdUser = try JSONDecoder().decode(User.self, from: data)
let createdUser = try JSONDecoder().decode(PushUser.self, from: data)
return createdUser
}
}
2 changes: 1 addition & 1 deletion Sources/User/DecryptPgp.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import Foundation

extension User {
extension PushUser {
struct EncryptedPrivateKey: Codable {
var ciphertext: String
var version: String
Expand Down
2 changes: 1 addition & 1 deletion Sources/User/GetFeeds.swift
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ public struct FeedsOptionsType {
}
}

extension User {
extension PushUser {
public static func getFeeds(
options: FeedsOptionsType
) async throws -> FeedResponse {
Expand Down
10 changes: 5 additions & 5 deletions Sources/User/User.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import Foundation

public struct User: Decodable {
public struct PushUser: Decodable {
public let about: String?
public let name: String?
public let allowedNumMsg: Int
Expand All @@ -19,11 +19,11 @@ public struct User: Decodable {
public let nfts: [String]?
}

extension User {
extension PushUser {
public static func get(
account userAddress: String,
env: ENV
) async throws -> User? {
) async throws -> PushUser? {
let caipAddress = walletToPCAIP10(account: userAddress)
let url = PushEndpoint.user(
account: caipAddress,
Expand All @@ -45,13 +45,13 @@ extension User {
return nil
}

let userProfile = try JSONDecoder().decode(User.self, from: data)
let userProfile = try JSONDecoder().decode(PushUser.self, from: data)
return userProfile

}

public static func userProfileCreated(account: String, env: ENV) async throws -> Bool {
let userInfo = try await User.get(account: account, env: env)
let userInfo = try await PushUser.get(account: account, env: env)
return userInfo != nil
}
}
4 changes: 2 additions & 2 deletions Tests/Chat/ConversationTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,11 @@ class ConversationTests: XCTestCase {

func testConversationHash() async throws {
let userAddress = "0xD26A7BF7fa0f8F1f3f73B056c9A67565A6aFE63c"
let converationHash = try await Chats.ConversationHash(
let converationHash = try await PushChat.ConversationHash(
conversationId: "0xACEe0D180d0118FD4F3027Ab801cc862520570d1", account: userAddress)!

// For empty conversation return nil
let converationHashNil = try await Chats.ConversationHash(
let converationHashNil = try await PushChat.ConversationHash(
conversationId: "0xACFe0D180d0118FD4F3027Ab801cc862520570d1", account: userAddress)

XCTAssertEqual(converationHash, "bafyreib3kfifq4qcxr634xlyxlf5gs3fmmaffokyew7tet6acqj7m3zdxu")
Expand Down
14 changes: 7 additions & 7 deletions Tests/Chat/GetChatsTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -8,11 +8,11 @@ class GetChatsTests: XCTestCase {
privateKey: "c39d17b1575c8d5e6e615767e19dc285d1f803d21882fb0c60f7f5b7edb759b2")
let userAddress = try await signer.getAddress()

let user = try await User.get(account: userAddress, env: .STAGING)!
let pgpPrivateKey = try await User.DecryptPGPKey(
let user = try await PushUser.get(account: userAddress, env: .STAGING)!
let pgpPrivateKey = try await PushUser.DecryptPGPKey(
encryptedPrivateKey: user.encryptedPrivateKey, signer: signer)

let chats = try await Push.Chats.getChats(
let chats = try await Push.PushChat.getChats(
options: GetChatsOptions(
account: userAddress,
pgpPrivateKey: pgpPrivateKey,
Expand All @@ -32,14 +32,14 @@ class GetChatsTests: XCTestCase {
let signer = try SignerPrivateKey(
privateKey: "c39d17b1575c8d5e6e615767e19dc285d1f803d21882fb0c60f7f5b7edb759b2")
let userAddress = try await signer.getAddress()
let user = try await User.get(account: userAddress, env: .STAGING)!
let pgpPrivateKey = try await User.DecryptPGPKey(
let user = try await PushUser.get(account: userAddress, env: .STAGING)!
let pgpPrivateKey = try await PushUser.DecryptPGPKey(
encryptedPrivateKey: user.encryptedPrivateKey, signer: signer)

let converationHash = try await Chats.ConversationHash(
let converationHash = try await PushChat.ConversationHash(
conversationId: "0x4D5bE92D510300ceF50a2FC03534A95b60028950", account: userAddress)!

let messages = try await Chats.History(
let messages = try await PushChat.History(
threadHash: converationHash, limit: 5, pgpPrivateKey: pgpPrivateKey, env: .STAGING)

for msg in messages {
Expand Down
Loading

0 comments on commit 6d39d18

Please sign in to comment.