2019-08-19 04:07:09 +02:00
import PromiseKit
2019-10-15 01:29:41 +02:00
@objc ( LKPublicChatAPI )
public final class LokiPublicChatAPI : LokiDotNetAPI {
2019-09-12 07:06:20 +02:00
private static var moderators : [ String : [ UInt64 : Set < String > ] ] = [ : ] // S e r v e r U R L t o ( c h a n n e l I D t o s e t o f m o d e r a t o r I D s )
2020-04-21 02:36:23 +02:00
@objc public static let defaultChats : [ LokiPublicChat ] = [ ] // C u r r e n t l y u n u s e d
2019-11-15 01:13:55 +01:00
public static var displayNameUpdatees : [ String : Set < String > ] = [ : ]
2019-09-12 07:06:20 +02:00
2019-08-27 02:56:02 +02:00
// MARK: S e t t i n g s
2019-10-21 00:32:28 +02:00
private static let attachmentType = " net.app.core.oembed "
2020-04-21 02:36:23 +02:00
private static let channelInfoType = " net.patter-app.settings "
private static let fallbackBatchCount = 64
private static let maxRetryCount : UInt = 4
2020-02-10 02:01:23 +01:00
public static let profilePictureType = " network.loki.messenger.avatar "
2019-10-15 01:29:41 +02:00
@objc public static let publicChatMessageType = " network.loki.messenger.publicChat "
2020-04-21 02:36:23 +02:00
2019-08-27 02:56:02 +02:00
// MARK: C o n v e n i e n c e
private static var userDisplayName : String {
2020-05-07 03:57:55 +02:00
return SSKEnvironment . shared . contactsManager . displayName ( forPhoneIdentifier : getUserHexEncodedPublicKey ( ) ) ? ? " Anonymous "
2019-08-27 02:56:02 +02:00
}
// MARK: D a t a b a s e
2020-02-02 01:33:34 +01:00
override internal class var authTokenCollection : String { " LokiGroupChatAuthTokenCollection " }
@objc public static let lastMessageServerIDCollection = " LokiGroupChatLastMessageServerIDCollection "
@objc public static let lastDeletionServerIDCollection = " LokiGroupChatLastDeletionServerIDCollection "
2019-08-27 02:56:02 +02:00
2019-08-28 02:04:15 +02:00
private static func getLastMessageServerID ( for group : UInt64 , on server : String ) -> UInt ? {
2019-08-27 02:56:02 +02:00
var result : UInt ? = nil
storage . dbReadConnection . read { transaction in
result = transaction . object ( forKey : " \( server ) . \( group ) " , inCollection : lastMessageServerIDCollection ) as ! UInt ?
}
return result
}
2019-08-28 02:04:15 +02:00
private static func setLastMessageServerID ( for group : UInt64 , on server : String , to newValue : UInt64 ) {
2019-08-27 02:56:02 +02:00
storage . dbReadWriteConnection . readWrite { transaction in
transaction . setObject ( newValue , forKey : " \( server ) . \( group ) " , inCollection : lastMessageServerIDCollection )
}
}
2019-10-09 07:19:58 +02:00
private static func removeLastMessageServerID ( for group : UInt64 , on server : String ) {
storage . dbReadWriteConnection . readWrite { transaction in
transaction . removeObject ( forKey : " \( server ) . \( group ) " , inCollection : lastMessageServerIDCollection )
}
}
2019-08-30 07:27:59 +02:00
private static func getLastDeletionServerID ( for group : UInt64 , on server : String ) -> UInt ? {
2019-08-27 02:56:02 +02:00
var result : UInt ? = nil
storage . dbReadConnection . read { transaction in
2019-08-30 07:27:59 +02:00
result = transaction . object ( forKey : " \( server ) . \( group ) " , inCollection : lastDeletionServerIDCollection ) as ! UInt ?
2019-08-27 02:56:02 +02:00
}
return result
}
2019-08-30 07:27:59 +02:00
private static func setLastDeletionServerID ( for group : UInt64 , on server : String , to newValue : UInt64 ) {
2019-08-27 02:56:02 +02:00
storage . dbReadWriteConnection . readWrite { transaction in
2019-08-30 07:27:59 +02:00
transaction . setObject ( newValue , forKey : " \( server ) . \( group ) " , inCollection : lastDeletionServerIDCollection )
2019-08-27 02:56:02 +02:00
}
}
2019-08-22 04:34:24 +02:00
2019-10-09 07:19:58 +02:00
private static func removeLastDeletionServerID ( for group : UInt64 , on server : String ) {
storage . dbReadWriteConnection . readWrite { transaction in
transaction . removeObject ( forKey : " \( server ) . \( group ) " , inCollection : lastDeletionServerIDCollection )
}
}
2020-02-10 02:01:23 +01:00
public static func clearCaches ( for channel : UInt64 , on server : String ) {
removeLastMessageServerID ( for : channel , on : server )
removeLastDeletionServerID ( for : channel , on : server )
}
2019-08-27 02:56:02 +02:00
// MARK: P u b l i c A P I
2020-04-21 02:36:23 +02:00
@objc ( getMessagesForGroup : onServer : )
public static func objc_getMessages ( for group : UInt64 , on server : String ) -> AnyPromise {
return AnyPromise . from ( getMessages ( for : group , on : server ) )
}
2019-10-15 01:29:41 +02:00
public static func getMessages ( for channel : UInt64 , on server : String ) -> Promise < [ LokiPublicChatMessage ] > {
2019-08-27 02:56:02 +02:00
var queryParameters = " include_annotations=1 "
2019-10-15 01:29:41 +02:00
if let lastMessageServerID = getLastMessageServerID ( for : channel , on : server ) {
2019-08-27 02:56:02 +02:00
queryParameters += " &since_id= \( lastMessageServerID ) "
} else {
2019-11-26 04:47:32 +01:00
queryParameters += " &count= \( fallbackBatchCount ) &include_deleted=0 "
2019-08-27 02:56:02 +02:00
}
2019-10-15 01:29:41 +02:00
let url = URL ( string : " \( server ) /channels/ \( channel ) /messages? \( queryParameters ) " ) !
2019-08-19 04:07:09 +02:00
let request = TSRequest ( url : url )
2020-02-19 03:55:58 +01:00
return LokiFileServerProxy ( for : server ) . perform ( request ) . map ( on : DispatchQueue . global ( ) ) { rawResponse in
2019-08-19 04:07:09 +02:00
guard let json = rawResponse as ? JSON , let rawMessages = json [ " data " ] as ? [ JSON ] else {
2019-10-15 01:29:41 +02:00
print ( " [Loki] Couldn't parse messages for public chat channel with ID: \( channel ) on server: \( server ) from: \( rawResponse ) . " )
2020-02-14 00:16:53 +01:00
throw LokiDotNetAPIError . parsingFailed
2019-08-19 04:07:09 +02:00
}
return rawMessages . flatMap { message in
2019-09-11 03:53:47 +02:00
let isDeleted = ( message [ " is_deleted " ] as ? Int = = 1 )
guard ! isDeleted else { return nil }
2019-10-21 00:32:28 +02:00
guard let annotations = message [ " annotations " ] as ? [ JSON ] , let annotation = annotations . first ( where : { $0 [ " type " ] as ? String = = publicChatMessageType } ) , let value = annotation [ " value " ] as ? JSON ,
2019-10-02 07:44:44 +02:00
let serverID = message [ " id " ] as ? UInt64 , let hexEncodedSignatureData = value [ " sig " ] as ? String , let signatureVersion = value [ " sigver " ] as ? UInt64 ,
let body = message [ " text " ] as ? String , let user = message [ " user " ] as ? JSON , let hexEncodedPublicKey = user [ " username " ] as ? String ,
2019-08-23 08:14:19 +02:00
let timestamp = value [ " timestamp " ] as ? UInt64 else {
2019-10-15 01:29:41 +02:00
print ( " [Loki] Couldn't parse message for public chat channel with ID: \( channel ) on server: \( server ) from: \( message ) . " )
2019-08-19 04:07:09 +02:00
return nil
}
2020-02-13 06:51:07 +01:00
var profilePicture : LokiPublicChatMessage . ProfilePicture ? = nil
2019-10-02 07:44:44 +02:00
let displayName = user [ " name " ] as ? String ? ? NSLocalizedString ( " Anonymous " , comment : " " )
2020-02-13 06:51:07 +01:00
if let userAnnotations = user [ " annotations " ] as ? [ JSON ] , let profilePictureAnnotation = userAnnotations . first ( where : { $0 [ " type " ] as ? String = = profilePictureType } ) ,
let profilePictureValue = profilePictureAnnotation [ " value " ] as ? JSON , let profileKeyString = profilePictureValue [ " profileKey " ] as ? String , let profileKey = Data ( base64Encoded : profileKeyString ) , let url = profilePictureValue [ " url " ] as ? String {
profilePicture = LokiPublicChatMessage . ProfilePicture ( profileKey : profileKey , url : url )
2019-11-29 04:14:02 +01:00
}
2019-10-15 01:29:41 +02:00
let lastMessageServerID = getLastMessageServerID ( for : channel , on : server )
if serverID > ( lastMessageServerID ? ? 0 ) { setLastMessageServerID ( for : channel , on : server , to : serverID ) }
let quote : LokiPublicChatMessage . Quote ?
2020-02-10 02:01:23 +01:00
if let quoteAsJSON = value [ " quote " ] as ? JSON , let quotedMessageTimestamp = quoteAsJSON [ " id " ] as ? UInt64 , let quoteeHexEncodedPublicKey = quoteAsJSON [ " author " ] as ? String ,
let quotedMessageBody = quoteAsJSON [ " text " ] as ? String {
2019-10-02 05:34:34 +02:00
let quotedMessageServerID = message [ " reply_to " ] as ? UInt64
2020-02-10 02:01:23 +01:00
quote = LokiPublicChatMessage . Quote ( quotedMessageTimestamp : quotedMessageTimestamp , quoteeHexEncodedPublicKey : quoteeHexEncodedPublicKey , quotedMessageBody : quotedMessageBody ,
quotedMessageServerID : quotedMessageServerID )
2019-09-11 03:53:47 +02:00
} else {
quote = nil
}
2019-10-15 01:29:41 +02:00
let signature = LokiPublicChatMessage . Signature ( data : Data ( hex : hexEncodedSignatureData ) , version : signatureVersion )
2019-10-21 00:32:28 +02:00
let attachmentsAsJSON = annotations . filter { $0 [ " type " ] as ? String = = attachmentType }
let attachments : [ LokiPublicChatMessage . Attachment ] = attachmentsAsJSON . compactMap { attachmentAsJSON in
2020-02-10 02:01:23 +01:00
guard let value = attachmentAsJSON [ " value " ] as ? JSON , let kindAsString = value [ " lokiType " ] as ? String , let kind = LokiPublicChatMessage . Attachment . Kind ( rawValue : kindAsString ) ,
let serverID = value [ " id " ] as ? UInt64 , let contentType = value [ " contentType " ] as ? String , let size = value [ " size " ] as ? UInt , let url = value [ " url " ] as ? String else { return nil }
2019-10-23 04:53:36 +02:00
let fileName = value [ " fileName " ] as ? String ? ? UUID ( ) . description
let width = value [ " width " ] as ? UInt ? ? 0
let height = value [ " height " ] as ? UInt ? ? 0
2019-10-21 02:51:15 +02:00
let flags = ( value [ " flags " ] as ? UInt ) ? ? 0
2019-10-21 00:32:28 +02:00
let caption = value [ " caption " ] as ? String
2019-10-21 02:43:46 +02:00
let linkPreviewURL = value [ " linkPreviewUrl " ] as ? String
let linkPreviewTitle = value [ " linkPreviewTitle " ] as ? String
if kind = = . linkPreview {
2019-11-26 04:47:32 +01:00
guard linkPreviewURL != nil && linkPreviewTitle != nil else {
print ( " [Loki] Ignoring public chat message with invalid link preview. " )
return nil
}
2019-10-21 02:43:46 +02:00
}
2020-02-10 02:01:23 +01:00
return LokiPublicChatMessage . Attachment ( kind : kind , server : server , serverID : serverID , contentType : contentType , size : size , fileName : fileName , flags : flags ,
width : width , height : height , caption : caption , url : url , linkPreviewURL : linkPreviewURL , linkPreviewTitle : linkPreviewTitle )
2019-10-21 00:32:28 +02:00
}
2020-02-13 06:51:07 +01:00
let result = LokiPublicChatMessage ( serverID : serverID , hexEncodedPublicKey : hexEncodedPublicKey , displayName : displayName , profilePicture : profilePicture ,
2020-02-10 02:01:23 +01:00
body : body , type : publicChatMessageType , timestamp : timestamp , quote : quote , attachments : attachments , signature : signature )
2019-10-02 05:34:34 +02:00
guard result . hasValidSignature ( ) else {
2019-10-15 01:29:41 +02:00
print ( " [Loki] Ignoring public chat message with invalid signature. " )
2019-10-02 05:34:34 +02:00
return nil
}
2019-11-15 03:56:35 +01:00
var existingMessageID : String ? = nil
storage . dbReadConnection . read { transaction in
existingMessageID = storage . getIDForMessage ( withServerID : UInt ( result . serverID ! ) , in : transaction )
}
guard existingMessageID = = nil else {
2019-11-26 04:47:32 +01:00
print ( " [Loki] Ignoring duplicate public chat message. " )
2019-11-15 03:56:35 +01:00
return nil
}
2019-10-02 05:34:34 +02:00
return result
2019-09-18 07:45:50 +02:00
} . sorted { $0 . timestamp < $1 . timestamp }
2019-08-19 04:07:09 +02:00
}
}
2020-04-21 02:36:23 +02:00
@objc ( sendMessage : toGroup : onServer : )
public static func objc_sendMessage ( _ message : LokiPublicChatMessage , to group : UInt64 , on server : String ) -> AnyPromise {
return AnyPromise . from ( sendMessage ( message , to : group , on : server ) )
}
2019-10-15 01:29:41 +02:00
public static func sendMessage ( _ message : LokiPublicChatMessage , to channel : UInt64 , on server : String ) -> Promise < LokiPublicChatMessage > {
2020-04-14 01:30:38 +02:00
print ( " [Loki] Sending message to public chat channel with ID: \( channel ) on server: \( server ) . " )
let ( promise , seal ) = Promise < LokiPublicChatMessage > . pending ( )
let queue = DispatchQueue . global ( )
queue . async { [ privateKey = userKeyPair . privateKey ] in
guard let signedMessage = message . sign ( with : privateKey ) else { return seal . reject ( LokiDotNetAPIError . signingFailed ) }
attempt ( maxRetryCount : maxRetryCount , recoveringOn : queue ) {
2020-02-19 03:55:58 +01:00
getAuthToken ( for : server ) . then { token -> Promise < LokiPublicChatMessage > in
let url = URL ( string : " \( server ) /channels/ \( channel ) /messages " ) !
let parameters = signedMessage . toJSON ( )
let request = TSRequest ( url : url , method : " POST " , parameters : parameters )
request . allHTTPHeaderFields = [ " Content-Type " : " application/json " , " Authorization " : " Bearer \( token ) " ]
let displayName = userDisplayName
return LokiFileServerProxy ( for : server ) . perform ( request ) . map { rawResponse in
// I S O 8 6 0 1 D a t e F o r m a t t e r d o e s n ' t s u p p o r t m i l l i s e c o n d s b e f o r e i O S 1 1
let dateFormatter = DateFormatter ( )
dateFormatter . dateFormat = " yyyy-MM-dd'T'HH:mm:ss.SSSZ "
guard let json = rawResponse as ? JSON , let messageAsJSON = json [ " data " ] as ? JSON , let serverID = messageAsJSON [ " id " ] as ? UInt64 , let body = messageAsJSON [ " text " ] as ? String ,
let dateAsString = messageAsJSON [ " created_at " ] as ? String , let date = dateFormatter . date ( from : dateAsString ) else {
print ( " [Loki] Couldn't parse message for public chat channel with ID: \( channel ) on server: \( server ) from: \( rawResponse ) . " )
throw LokiDotNetAPIError . parsingFailed
}
let timestamp = UInt64 ( date . timeIntervalSince1970 ) * 1000
2020-05-07 03:57:55 +02:00
return LokiPublicChatMessage ( serverID : serverID , hexEncodedPublicKey : getUserHexEncodedPublicKey ( ) , displayName : displayName , profilePicture : signedMessage . profilePicture , body : body , type : publicChatMessageType , timestamp : timestamp , quote : signedMessage . quote , attachments : signedMessage . attachments , signature : signedMessage . signature )
2020-02-19 03:55:58 +01:00
}
} . recover { error -> Promise < LokiPublicChatMessage > in
if let error = error as ? NetworkManagerError , error . statusCode = = 401 {
print ( " [Loki] Group chat auth token for: \( server ) expired; dropping it. " )
storage . dbReadWriteConnection . removeObject ( forKey : server , inCollection : authTokenCollection )
}
throw error
2019-08-22 05:14:35 +02:00
}
2020-04-14 01:30:38 +02:00
} . done { message in
seal . fulfill ( message )
} . catch { error in
seal . reject ( error )
2019-08-27 02:56:02 +02:00
}
2020-02-19 03:55:58 +01:00
}
2020-04-14 01:30:38 +02:00
return promise
2019-08-27 02:56:02 +02:00
}
2019-10-15 01:29:41 +02:00
public static func getDeletedMessageServerIDs ( for channel : UInt64 , on server : String ) -> Promise < [ UInt64 ] > {
print ( " [Loki] Getting deleted messages for public chat channel with ID: \( channel ) on server: \( server ) . " )
2019-08-30 07:27:59 +02:00
let queryParameters : String
2019-10-15 01:29:41 +02:00
if let lastDeletionServerID = getLastDeletionServerID ( for : channel , on : server ) {
2019-08-30 07:27:59 +02:00
queryParameters = " since_id= \( lastDeletionServerID ) "
} else {
queryParameters = " count= \( fallbackBatchCount ) "
}
2019-10-15 01:29:41 +02:00
let url = URL ( string : " \( server ) /loki/v1/channel/ \( channel ) /deletes? \( queryParameters ) " ) !
2019-08-27 02:56:02 +02:00
let request = TSRequest ( url : url )
2020-02-19 03:55:58 +01:00
return LokiFileServerProxy ( for : server ) . perform ( request ) . map { rawResponse in
2019-08-30 07:27:59 +02:00
guard let json = rawResponse as ? JSON , let deletions = json [ " data " ] as ? [ JSON ] else {
2019-10-15 01:29:41 +02:00
print ( " [Loki] Couldn't parse deleted messages for public chat channel with ID: \( channel ) on server: \( server ) from: \( rawResponse ) . " )
2020-02-14 00:16:53 +01:00
throw LokiDotNetAPIError . parsingFailed
2019-08-27 02:56:02 +02:00
}
2019-08-30 07:27:59 +02:00
return deletions . flatMap { deletion in
guard let serverID = deletion [ " id " ] as ? UInt64 , let messageServerID = deletion [ " message_id " ] as ? UInt64 else {
2019-10-15 01:29:41 +02:00
print ( " [Loki] Couldn't parse deleted message for public chat channel with ID: \( channel ) on server: \( server ) from: \( deletion ) . " )
2019-08-27 02:56:02 +02:00
return nil
2019-08-23 08:25:12 +02:00
}
2019-10-15 01:29:41 +02:00
let lastDeletionServerID = getLastDeletionServerID ( for : channel , on : server )
if serverID > ( lastDeletionServerID ? ? 0 ) { setLastDeletionServerID ( for : channel , on : server , to : serverID ) }
2019-08-30 07:27:59 +02:00
return messageServerID
2019-08-27 02:56:02 +02:00
}
}
2019-08-19 04:07:09 +02:00
}
2020-04-21 02:36:23 +02:00
@objc ( deleteMessageWithID : forGroup : onServer : isSentByUser : )
public static func objc_deleteMessage ( with messageID : UInt , for group : UInt64 , on server : String , isSentByUser : Bool ) -> AnyPromise {
return AnyPromise . from ( deleteMessage ( with : messageID , for : group , on : server , isSentByUser : isSentByUser ) )
}
2019-08-19 04:07:09 +02:00
2019-10-15 01:29:41 +02:00
public static func deleteMessage ( with messageID : UInt , for channel : UInt64 , on server : String , isSentByUser : Bool ) -> Promise < Void > {
2020-04-14 01:30:38 +02:00
return attempt ( maxRetryCount : maxRetryCount , recoveringOn : DispatchQueue . global ( ) ) {
getAuthToken ( for : server ) . then { token -> Promise < Void > in
let isModerationRequest = ! isSentByUser
print ( " [Loki] Deleting message with ID: \( messageID ) for public chat channel with ID: \( channel ) on server: \( server ) (isModerationRequest = \( isModerationRequest ) ). " )
let urlAsString = isSentByUser ? " \( server ) /channels/ \( channel ) /messages/ \( messageID ) " : " \( server ) /loki/v1/moderation/message/ \( messageID ) "
let url = URL ( string : urlAsString ) !
let request = TSRequest ( url : url , method : " DELETE " , parameters : [ : ] )
request . allHTTPHeaderFields = [ " Content-Type " : " application/json " , " Authorization " : " Bearer \( token ) " ]
return LokiFileServerProxy ( for : server ) . perform ( request ) . done { result -> Void in
print ( " [Loki] Deleted message with ID: \( messageID ) on server: \( server ) . " )
}
}
2019-08-28 08:07:14 +02:00
}
}
2019-10-15 01:29:41 +02:00
public static func getModerators ( for channel : UInt64 , on server : String ) -> Promise < Set < String > > {
let url = URL ( string : " \( server ) /loki/v1/channel/ \( channel ) /get_moderators " ) !
2019-09-12 05:59:57 +02:00
let request = TSRequest ( url : url )
2020-02-19 03:55:58 +01:00
return LokiFileServerProxy ( for : server ) . perform ( request ) . map { rawResponse in
2019-09-12 05:59:57 +02:00
guard let json = rawResponse as ? JSON , let moderators = json [ " moderators " ] as ? [ String ] else {
2019-10-15 01:29:41 +02:00
print ( " [Loki] Couldn't parse moderators for public chat channel with ID: \( channel ) on server: \( server ) from: \( rawResponse ) . " )
2020-02-14 00:16:53 +01:00
throw LokiDotNetAPIError . parsingFailed
2019-09-12 05:59:57 +02:00
}
2019-09-12 07:06:20 +02:00
let moderatorAsSet = Set ( moderators ) ;
if self . moderators . keys . contains ( server ) {
2019-10-15 01:29:41 +02:00
self . moderators [ server ] ! [ channel ] = moderatorAsSet
2019-09-12 05:59:57 +02:00
} else {
2019-10-15 01:29:41 +02:00
self . moderators [ server ] = [ channel : moderatorAsSet ]
2019-09-12 05:59:57 +02:00
}
2019-09-12 07:06:20 +02:00
return moderatorAsSet
2019-09-12 05:59:57 +02:00
}
}
2020-01-21 23:53:29 +01:00
public static func join ( _ channel : UInt64 , on server : String ) -> Promise < Void > {
2020-04-14 01:30:38 +02:00
return attempt ( maxRetryCount : maxRetryCount , recoveringOn : DispatchQueue . global ( ) ) {
getAuthToken ( for : server ) . then { token -> Promise < Void > in
let url = URL ( string : " \( server ) /channels/ \( channel ) /subscribe " ) !
let request = TSRequest ( url : url , method : " POST " , parameters : [ : ] )
request . allHTTPHeaderFields = [ " Content-Type " : " application/json " , " Authorization " : " Bearer \( token ) " ]
return LokiFileServerProxy ( for : server ) . perform ( request ) . done { result -> Void in
print ( " [Loki] Joined channel with ID: \( channel ) on server: \( server ) . " )
}
}
2020-01-21 23:53:29 +01:00
}
}
public static func leave ( _ channel : UInt64 , on server : String ) -> Promise < Void > {
2020-04-14 01:30:38 +02:00
return attempt ( maxRetryCount : maxRetryCount , recoveringOn : DispatchQueue . global ( ) ) {
getAuthToken ( for : server ) . then { token -> Promise < Void > in
let url = URL ( string : " \( server ) /channels/ \( channel ) /subscribe " ) !
let request = TSRequest ( url : url , method : " DELETE " , parameters : [ : ] )
request . allHTTPHeaderFields = [ " Content-Type " : " application/json " , " Authorization " : " Bearer \( token ) " ]
return LokiFileServerProxy ( for : server ) . perform ( request ) . done { result -> Void in
print ( " [Loki] Left channel with ID: \( channel ) on server: \( server ) . " )
}
}
2020-01-21 23:53:29 +01:00
}
}
2019-11-15 01:13:55 +01:00
public static func getDisplayNames ( for channel : UInt64 , on server : String ) -> Promise < Void > {
let publicChatID = " \( server ) . \( channel ) "
guard let hexEncodedPublicKeys = displayNameUpdatees [ publicChatID ] else { return Promise . value ( ( ) ) }
displayNameUpdatees [ publicChatID ] = [ ]
print ( " [Loki] Getting display names for: \( hexEncodedPublicKeys ) . " )
2020-02-19 03:55:58 +01:00
return getAuthToken ( for : server ) . then { token -> Promise < Void > in
2019-11-15 01:13:55 +01:00
let queryParameters = " ids= \( hexEncodedPublicKeys . map { " @ \( $0 ) " } . joined ( separator : " , " ) ) &include_user_annotations=1 "
let url = URL ( string : " \( server ) /users? \( queryParameters ) " ) !
let request = TSRequest ( url : url )
2020-02-19 03:55:58 +01:00
return LokiFileServerProxy ( for : server ) . perform ( request ) . map { rawResponse in
2019-11-15 01:13:55 +01:00
guard let json = rawResponse as ? JSON , let data = json [ " data " ] as ? [ JSON ] else {
print ( " [Loki] Couldn't parse display names for users: \( hexEncodedPublicKeys ) from: \( rawResponse ) . " )
2020-02-14 00:16:53 +01:00
throw LokiDotNetAPIError . parsingFailed
2019-11-15 01:13:55 +01:00
}
storage . dbReadWriteConnection . readWrite { transaction in
data . forEach { data in
guard let user = data [ " user " ] as ? JSON , let hexEncodedPublicKey = user [ " username " ] as ? String , let rawDisplayName = user [ " name " ] as ? String else { return }
let endIndex = hexEncodedPublicKey . endIndex
let cutoffIndex = hexEncodedPublicKey . index ( endIndex , offsetBy : - 8 )
let displayName = " \( rawDisplayName ) (... \( hexEncodedPublicKey [ cutoffIndex . . < endIndex ] ) ) "
transaction . setObject ( displayName , forKey : hexEncodedPublicKey , inCollection : " \( server ) . \( channel ) " )
}
}
}
}
}
2020-02-10 02:01:23 +01:00
@objc ( isUserModerator : forChannel : onServer : )
2019-10-15 01:29:41 +02:00
public static func isUserModerator ( _ hexEncodedPublicString : String , for channel : UInt64 , on server : String ) -> Bool {
return moderators [ server ] ? [ channel ] ? . contains ( hexEncodedPublicString ) ? ? false
2019-09-12 07:06:20 +02:00
}
2020-04-21 02:36:23 +02:00
@objc ( setDisplayName : on : )
public static func objc_setDisplayName ( to newDisplayName : String ? , on server : String ) -> AnyPromise {
return AnyPromise . from ( setDisplayName ( to : newDisplayName , on : server ) )
}
2019-10-03 06:09:31 +02:00
public static func setDisplayName ( to newDisplayName : String ? , on server : String ) -> Promise < Void > {
print ( " [Loki] Updating display name on server: \( server ) . " )
2020-04-14 01:30:38 +02:00
return attempt ( maxRetryCount : maxRetryCount , recoveringOn : DispatchQueue . global ( ) ) {
getAuthToken ( for : server ) . then { token -> Promise < Void > in
let parameters : JSON = [ " name " : ( newDisplayName ? ? " " ) ]
let url = URL ( string : " \( server ) /users/me " ) !
let request = TSRequest ( url : url , method : " PATCH " , parameters : parameters )
request . allHTTPHeaderFields = [ " Content-Type " : " application/json " , " Authorization " : " Bearer \( token ) " ]
return LokiFileServerProxy ( for : server ) . perform ( request ) . map { _ in } . recover { error in
print ( " Couldn't update display name due to error: \( error ) . " )
throw error
}
2019-10-03 06:09:31 +02:00
}
2020-04-14 01:30:38 +02:00
}
2019-10-03 06:09:31 +02:00
}
2020-04-21 02:36:23 +02:00
@objc ( setProfilePictureURL : usingProfileKey : on : )
public static func objc_setProfilePicture ( to url : String ? , using profileKey : Data , on server : String ) -> AnyPromise {
return AnyPromise . from ( setProfilePictureURL ( to : url , using : profileKey , on : server ) )
}
2019-12-02 03:10:01 +01:00
public static func setProfilePictureURL ( to url : String ? , using profileKey : Data , on server : String ) -> Promise < Void > {
print ( " [Loki] Updating profile picture on server: \( server ) . " )
2020-04-14 01:30:38 +02:00
return attempt ( maxRetryCount : maxRetryCount , recoveringOn : DispatchQueue . global ( ) ) {
getAuthToken ( for : server ) . then { token -> Promise < Void > in
var annotation : JSON = [ " type " : profilePictureType ]
if let url = url {
annotation [ " value " ] = [ " profileKey " : profileKey . base64EncodedString ( ) , " url " : url ]
}
let parameters : JSON = [ " annotations " : [ annotation ] ]
let url = URL ( string : " \( server ) /users/me " ) !
let request = TSRequest ( url : url , method : " PATCH " , parameters : parameters )
request . allHTTPHeaderFields = [ " Content-Type " : " application/json " , " Authorization " : " Bearer \( token ) " ]
return LokiFileServerProxy ( for : server ) . perform ( request ) . map { _ in } . recover { error in
print ( " [Loki] Couldn't update profile picture due to error: \( error ) . " )
throw error
}
2019-11-29 03:47:41 +01:00
}
2020-04-14 01:30:38 +02:00
}
2019-11-29 03:47:41 +01:00
}
2020-05-27 03:34:24 +02:00
@objc ( getInfoForChannelWithID : onServer : )
public static func objc_getInfo ( for channel : UInt64 , on server : String ) -> AnyPromise {
return AnyPromise . from ( getInfo ( for : channel , on : server ) )
}
2019-10-15 01:29:41 +02:00
public static func getInfo ( for channel : UInt64 , on server : String ) -> Promise < LokiPublicChatInfo > {
2019-10-09 03:40:39 +02:00
let url = URL ( string : " \( server ) /channels/ \( channel ) ?include_annotations=1 " ) !
let request = TSRequest ( url : url )
2020-02-19 03:55:58 +01:00
return LokiFileServerProxy ( for : server ) . perform ( request ) . map { rawResponse in
2019-10-09 03:40:39 +02:00
guard let json = rawResponse as ? JSON ,
let data = json [ " data " ] as ? JSON ,
let annotations = data [ " annotations " ] as ? [ JSON ] ,
2019-10-15 01:29:41 +02:00
let annotation = annotations . first ,
let info = annotation [ " value " ] as ? JSON ,
2020-05-27 03:34:24 +02:00
let displayName = info [ " name " ] as ? String ,
let countInfo = data [ " counts " ] as ? JSON ,
let memberCount = countInfo [ " subscribers " ] as ? Int else {
2019-10-15 01:29:41 +02:00
print ( " [Loki] Couldn't parse info for public chat channel with ID: \( channel ) on server: \( server ) from: \( rawResponse ) . " )
2020-02-14 00:16:53 +01:00
throw LokiDotNetAPIError . parsingFailed
2019-10-09 03:40:39 +02:00
}
2020-05-27 03:34:24 +02:00
let storage = OWSPrimaryStorage . shared ( )
storage . dbReadWriteConnection . readWrite { transaction in
storage . setUserCount ( memberCount , forPublicChatWithID : " \( server ) . \( channel ) " , in : transaction )
}
// TODO: U s e t h i s t o u p d a t e o p e n g r o u p n a m e s a s n e e d e d
return LokiPublicChatInfo ( displayName : displayName , memberCount : memberCount )
2019-10-09 03:40:39 +02:00
}
}
2020-04-21 02:36:23 +02:00
@objc ( reportMessageWithID : inChannel : onServer : )
public static func objc_reportMessageWithID ( _ messageID : UInt64 , in channel : UInt64 , on server : String ) -> AnyPromise {
return AnyPromise . from ( reportMessageWithID ( messageID , in : channel , on : server ) )
}
2020-02-06 04:13:07 +01:00
public static func reportMessageWithID ( _ messageID : UInt64 , in channel : UInt64 , on server : String ) -> Promise < Void > {
let url = URL ( string : " \( server ) /loki/v1/channels/ \( channel ) /messages/ \( messageID ) /report " ) !
let request = TSRequest ( url : url , method : " POST " , parameters : [ : ] )
return LokiFileServerProxy ( for : server ) . perform ( request ) . map { _ in }
}
2019-08-19 04:07:09 +02:00
}