-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathMessagesViewController.swift
431 lines (393 loc) · 17.8 KB
/
MessagesViewController.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
//
// MessagesViewController.swift
// SampleApp
//
// Created by Temasys on 26/7/17.
// Copyright © 2017 Temasys. All rights reserved.
//
import UIKit
import AVFoundation
import SKYLINK_MESSAGE_CACHE
struct SAMessage {
var data: String?
var timeStamp: Int64?
var sender: String?
var target: String?
var type: MessageType?
enum MessageType {
case Signaling
case P2P
func toString() -> String{
switch self {
case .Signaling:
return "Signaling"
default:
return "P2P"
}
}
}
func isPublic() -> Bool{
return (target == nil)
}
func timeStapmString() -> String?{
if let timeStamp = timeStamp {
let dateTS = Date.datefrom(timeStamp: timeStamp)
return Date.skylinkString(from: dateTS)
}
return nil
}
}
class MessagesViewController: SKConnectableVC, SKYLINKConnectionLifeCycleDelegate, SKYLINKConnectionMessagesDelegate, SKYLINKConnectionRemotePeerDelegate, UITextFieldDelegate, UITableViewDataSource, UITableViewDelegate {
lazy var peers = [String : Any]()
weak var topView: UIView!
@IBOutlet weak var activityIndicator: UIActivityIndicatorView!
@IBOutlet weak var sendButton: UIButton!
@IBOutlet weak var peersButton: UIButton!
@IBOutlet weak var nicknameTextField: UITextField!
@IBOutlet weak var encryptKeyTextField: UITextField!
@IBOutlet weak var messageTextField: UITextField!
@IBOutlet weak var tableView: UITableView!
@IBOutlet weak var messageTypeSegmentControl: UISegmentedControl!
@IBOutlet weak var isPublicSwitch: UISwitch!
@IBOutlet weak var pickerViewContainer: UIView!
@IBOutlet weak var pickerView: UIPickerView!
@IBOutlet weak var persistSwitch: UISwitch!
var messages: [SAMessage] = []
var encryptSecretIds: [String] = ["No Key"]
//MARK: - INIT
override func initData() {
super.initData()
if roomName.count==0{
roomName = ROOM_MESSAGES
}
nicknameTextField.delegate = self
messageTextField.delegate = self
joinRoom()
}
override func initUI() {
super.initUI()
title = "Messaging"
updatePeersButtonTitle()
tableView.rowHeight = UITableView.automaticDimension
tableView.estimatedRowHeight = 70
loadStoredMessage()
messageTypeSegmentControl.selectedSegmentIndex = 1
encryptSecretIds.append(contentsOf: Array(ENCRYPTION_SECRETS.keys).sorted(by:<))
encryptKeyTextField.text = encryptSecretIds.first
// skylinkConnection.selectedSecretId = encryptKeyTextField.text
}
override func initSkylinkConnection() -> SKYLINKConnection {
let config = SKYLINKConnectionConfig()
config.setAudioVideoSend(AudioVideoConfig_NO_AUDIO_NO_VIDEO)
config.setAudioVideoReceive(AudioVideoConfig_NO_AUDIO_NO_VIDEO)
config.hasP2PMessaging = true
config.setTimeout(3, skylinkAction: SkylinkAction_CONNECT_TO_ROOM)
config.isMessageCacheEnabled = true;
// config.hasDataTransfer = true
// config.dataChannel = true // for data chanel messages
if let skylinkConnection = SKYLINKConnection(config: config, callback: nil){
skylinkConnection.lifeCycleDelegate = self
skylinkConnection.messagesDelegate = self
skylinkConnection.remotePeerDelegate = self
skylinkConnection.enableLogs = true;
skylinkConnection.encryptSecrets = ENCRYPTION_SECRETS
skylinkConnection.messagePersist = true
return skylinkConnection
}else{
return SKYLINKConnection()
}
}
// MARK: SKYLINKConnectionLifeCycleDelegate
func connectionDidConnect(toRoomSuccessful connection: SKYLINKConnection){
skylinkLog("Inside \(#function)")
DispatchQueue.main.async { [unowned self] in
self.messageTextField.isEnabled = true
self.messageTextField.isHidden = false
self.nicknameTextField.isEnabled = true
self.nicknameTextField.isHidden = false
self.sendButton.isEnabled = true
self.sendButton.isHidden = false
self.messageTextField.becomeFirstResponder()
}
self.activityIndicator.stopAnimating()
}
func connection(_ connection: SKYLINKConnection, didConnectWithMessage errorMessage: String!, success isSuccess: Bool) {
if isSuccess {
skylinkLog("Inside \(#function)")
DispatchQueue.main.async { [weak weakSelf = self] in
weakSelf?.messageTextField.isEnabled = true
weakSelf?.messageTextField.isHidden = false
weakSelf?.nicknameTextField.isEnabled = true
weakSelf?.nicknameTextField.isHidden = false
weakSelf?.sendButton.isEnabled = true
weakSelf?.sendButton.isHidden = false
weakSelf?.messageTextField.becomeFirstResponder()
}
} else {
let msgTitle = "Connection failed"
let msg = errorMessage
saAlert(title: msgTitle, msg: msg)
dismissVC()
}
activityIndicator.stopAnimating()
}
func connection(_ connection: SKYLINKConnection, didDisconnectWithMessage errorMessage: String!) {
let alert = UIAlertController(title: "Disconnected", message: errorMessage, preferredStyle: .alert)
let cancelAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alert.addAction(cancelAction)
present(alert, animated: true) { [unowned self] in
self.dismissVC()
}
}
func connection(_ connection: SKYLINKConnection, didReceiveError error: Error!) {
if let error = error {
saAlert(title: "Error: \(error.code)", msg: error.localizedDescription)
}
}
// MARK: SKYLINKConnectionRemotePeerDelegate
func connection(_ connection: SKYLINKConnection, didConnectWithRemotePeer remotePeerId: String!, userInfo: Any!, hasDataChannel: Bool) {
var displayNickName = "\(String(describing: remotePeerId ?? "No name"))"
if let dict = userInfo as? [String : Any], let name = dict["nickname"] as? String {
displayNickName = name
}
if remotePeerId != nil {
peers[remotePeerId] = displayNickName
updatePeersButtonTitle()
}
tableView.reloadData()
self.activityIndicator.stopAnimating()
}
func connection(_ connection: SKYLINKConnection, didReceiveRemotePeerLeaveRoom remotePeerId: String!, userInfo: Any!, skylinkInfo: [AnyHashable : Any]?) {
peers.removeValue(forKey: remotePeerId)
updatePeersButtonTitle()
}
// MARK: SKYLINKConnectionMessagesDelegate
func connection(_ connection: SKYLINKConnection, didReceiveServerMessage message: Any!, isPublic: Bool, timeStamp: Int64, remotePeerId: String!) {
print("SIG message ---> ", message ?? "nil")
print("SIG timeStamp ---> ", timeStamp)
if let message = message as? String{
let receivedMessage = SAMessage(data: message,
timeStamp: timeStamp,
sender: self.getUserNameFrom(peerId: remotePeerId),
target: (isPublic ? nil : skylinkConnection.localPeerId),
type: .Signaling)
messages.append(receivedMessage)
}
tableView.reloadSections(IndexSet(integer: 0), with: .fade)
}
func connection(_ connection: SKYLINKConnection, didReceiveP2PMessage message: Any!, isPublic: Bool, timeStamp: Int64, remotePeerId: String!) {
print("P2P message ---> ", message ?? "nil")
print("P2P timeStamp ---> ", timeStamp)
if let message = message as? String{
let receivedMessage = SAMessage(data: message,
timeStamp: timeStamp,
sender: self.getUserNameFrom(peerId: remotePeerId),
target: (isPublic ? nil : skylinkConnection.localPeerId),
type: .P2P)
messages.append(receivedMessage)
}
tableView.reloadSections(IndexSet(integer: 0), with: .fade)
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return messages.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "messageCell", for: indexPath)
let msg = messages[messages.count - indexPath.row - 1]
cell.textLabel?.text = (msg.timeStapmString() ?? "") + "~~~" + (msg.data ?? "")
cell.detailTextLabel?.text = "From \(msg.sender ?? "") via \(msg.type?.toString() ?? "") • " + (msg.isPublic() ? "Public" : "Private")
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
tableView.deselectRow(at: indexPath, animated: true)
let message = messages[messages.count - indexPath.row - 1]
let msg = String(format:"Message \n %@ \n\n From: \n %@ \n\n %@", message.data ?? "", (message.sender == USER_NAME) ? "me" : (message.sender ?? ""), message.isPublic() ? "Public" : "Private")
let msgTitle = "Message Details"
saAlert(title: msgTitle, msg: msg)
}
// MARK: - Utils
private func loadStoredMessage(){
// Message caching is enabled?
if (SkylinkMessageCache.instance().isEnabled) {
// Display caches messages if available
DispatchQueue.main.async {
let cachedMessages = SkylinkMessageCache.instance().getReadableCacheSession(forRoomName: self.roomName).cachedMessages()
if (!cachedMessages.isEmpty) {
for m in cachedMessages {
if let dict = m as? [String: Any] {
let message = SAMessage(data: dict["data"] as? String,
timeStamp: (dict["timeStamp"] as? Int64),
sender: self.getUserNameFrom(peerId: dict["peerId"] as? String),
target: nil,
type: .Signaling)
self.messages.append(message)
}
}
self.tableView.reloadSections(IndexSet(integer: 0), with: .fade)
}
}
}
DispatchQueue.main.asyncAfter(deadline: .now() + 5) {
self.skylinkConnection.getStoredMessages { storedMessages, errorMap in
guard let _ = self.view.window else{
return
}
if let errorMap = errorMap{
saAlert(title: "Error map", msg: errorMap.description)
}
// Remove messages retrieved from cache before append messages from server
self.messages.removeAll()
for item in storedMessages ?? []{
print("storedMessage: \(storedMessages ?? [])")
if let dict = item as? [String: Any] {
let message = SAMessage(data: dict["data"] as? String,
timeStamp: (dict["timeStamp"] as? Int64),
sender: self.getUserNameFrom(peerId: dict["peerId"] as? String),
target: nil,
type: .Signaling)
self.messages.append(message)
}
}
self.tableView.reloadSections(IndexSet(integer: 0), with: .fade)
}
}
}
func sendMessage(message: String, forPeerId peerId: String?) {
//Message as JSON
// let message = ["senderId" : USER_NAME,
// "data" : message]
if messageTypeSegmentControl.selectedSegmentIndex == 0{
//Send P2P Message
skylinkConnection.sendP2PMessage(message, toRemotePeerId: peerId) { (error) in
processResponse(error: error, type: .P2P)
}
}else{
//Send Server Message
skylinkConnection.sendServerMessage(message, toRemotePeerId: peerId) { (error) in
processResponse(error: error, type: .Signaling)
}
}
func processResponse(error: Error?, type: SAMessage.MessageType){
if let error = error{
saAlert(title:"ERROR: \(error.code)", msg: error.localizedDescription)
}else{
let sentMessage = SAMessage(data: message, timeStamp: Date().toTimeStamp(), sender: USER_NAME, target: peerId, type: type)
messages.append(sentMessage)
self.messageTextField.text = ""
self.tableView.reloadSections(IndexSet(integer: 0), with: .fade)
saAlert(title: message, msg: (peerId != nil) ? peerId : "All")
}
}
}
fileprivate func updatePeersButtonTitle() {
let peersCount = peers.count
if peersCount == 0 {
peersButton.setTitle("No Peer", for: .normal)
} else {
peersButton.setTitle("\(peersCount) peer" + (peersCount > 1 ? "s " : ""), for: .normal)
}
}
func updateNickname() {
if nicknameTextField.hasText {
skylinkConnection.sendLocalUserData(["nickname" : nicknameTextField.text], callback: nil)
} else {
let msgTitle = "Empty nickname"
let msg = "\nType the nickname to set."
saAlert(title: msgTitle, msg: msg)
}
}
func hideKeyboardIfNeeded() {
messageTextField.resignFirstResponder()
nicknameTextField.resignFirstResponder()
}
private func getUserNameFrom(peerId: String?) -> String?{
if let userInfo = skylinkConnection.getUserInfo(peerId) as? [String: Any]{
return userInfo["userData"] as? String
}
return peerId
}
// MARK: - UITextField delegate
func textFieldShouldReturn(_ textField: UITextField) -> Bool {
if textField == nicknameTextField {
updateNickname()
}
hideKeyboardIfNeeded()
return true
}
func textFieldDidChangeSelection(_ textField: UITextField) {
print("change")
if textField == encryptKeyTextField{
// ENCRYPTION_SECRETS = textField.text!
// skylinkConnection.encryptSecret = ENCRYPTION_SECRET
}
}
func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool {
if textField == encryptKeyTextField {
hideKeyboardIfNeeded()
pickerViewContainer.isHidden = false
return false
}
return true
}
// MARK: IBFuction
@IBAction func sendTap() {
skylinkConnection.messagePersist = persistSwitch.isOn
guard let message = messageTextField.text else {
saAlert(title: "Empty message", msg: "\nType the message to be sent.");
return
}
if peers.count<=0{
saAlert(title: "No peer connected.", msg: "nYou can't define a private recipient since there is no peer connected.")
}
if isPublicSwitch.isOn {
//Send to all peer
sendMessage(message: message, forPeerId: nil)
} else {
//Send to a specific peer
let alert = UIAlertController(title: "Choose a private recipient.", message: "\nYou're about to send a private message\nWho do you want to send it to ?", preferredStyle: .alert)
let noAction = UIAlertAction(title: "Cancel", style: .default)
for peerDicKey in peers.keys {
let yesAction = UIAlertAction(title: peers[peerDicKey] as? String, style: .default) { [weak weakSelf = self] _ in
weakSelf?.sendMessage(message: message, forPeerId: peerDicKey)
}
alert.addAction(yesAction)
}
alert.addAction(noAction)
present(alert, animated: true, completion: nil)
}
}
@IBAction func diswmissKeyboardTap() {
hideKeyboardIfNeeded()
}
@IBAction func peersTap(sender: UIButton) {
let msgTitle = sender.titleLabel?.text
let msg = peers.keys.description
let alertController = UIAlertController(title: msgTitle , message: msg, preferredStyle: .alert)
let OKAction = UIAlertAction(title: "OK", style: .default)
alertController.addAction(OKAction)
present(alertController, animated: true) {
}
}
func scrollViewDidScroll(_ scrollView: UIScrollView) {
view.endEditing(true)
}
@IBAction func doneEncryptSecret(sender: UIButton) {
pickerViewContainer.isHidden = true
}
}
extension MessagesViewController: UIPickerViewDataSource, UIPickerViewDelegate{
func numberOfComponents(in pickerView: UIPickerView) -> Int {
return 1
}
func pickerView(_ pickerView: UIPickerView, numberOfRowsInComponent component: Int) -> Int {
return encryptSecretIds.count
}
func pickerView(_ pickerView: UIPickerView, titleForRow row: Int, forComponent component: Int) -> String? {
return encryptSecretIds[row]
}
func pickerView(_ pickerView: UIPickerView, didSelectRow row: Int, inComponent component: Int) {
let selectedEncryptSecret: String? = (row == 0) ? nil : encryptSecretIds[row]
skylinkConnection.selectedSecretId = selectedEncryptSecret
encryptKeyTextField.text = encryptSecretIds[row]
}
}