├── .gitignore
├── Android
├── .gitignore
├── .idea
│ ├── .gitignore
│ ├── .name
│ ├── codeStyles
│ │ ├── Project.xml
│ │ └── codeStyleConfig.xml
│ ├── compiler.xml
│ ├── gradle.xml
│ ├── jarRepositories.xml
│ └── misc.xml
├── app
│ ├── .gitignore
│ ├── build.gradle
│ ├── proguard-rules.pro
│ └── src
│ │ ├── androidTest
│ │ └── java
│ │ │ └── io
│ │ │ └── agora
│ │ │ └── typing
│ │ │ └── ExampleInstrumentedTest.kt
│ │ ├── main
│ │ ├── AndroidManifest.xml
│ │ ├── java
│ │ │ └── io
│ │ │ │ └── agora
│ │ │ │ └── typing
│ │ │ │ ├── App.kt
│ │ │ │ ├── base
│ │ │ │ ├── BuildConfig.kt
│ │ │ │ ├── Logger.kt
│ │ │ │ ├── Message.kt
│ │ │ │ └── Service.kt
│ │ │ │ ├── server
│ │ │ │ └── server.kt
│ │ │ │ └── ui
│ │ │ │ ├── ChatActivity.kt
│ │ │ │ ├── MainActivity.kt
│ │ │ │ ├── chat
│ │ │ │ ├── ChatFragment.kt
│ │ │ │ └── ChatModel.kt
│ │ │ │ └── login
│ │ │ │ ├── LoginFragment.kt
│ │ │ │ └── LoginModel.kt
│ │ └── res
│ │ │ ├── anim
│ │ │ └── shake.xml
│ │ │ ├── drawable-v24
│ │ │ └── ic_launcher_foreground.xml
│ │ │ ├── drawable
│ │ │ ├── button.xml
│ │ │ ├── cursor.xml
│ │ │ ├── ic_launcher_background.xml
│ │ │ ├── offline.xml
│ │ │ ├── online.xml
│ │ │ └── round.xml
│ │ │ ├── layout
│ │ │ ├── chat_fragment.xml
│ │ │ ├── login_fragment.xml
│ │ │ └── main_activity.xml
│ │ │ ├── mipmap-anydpi-v26
│ │ │ ├── ic_launcher.xml
│ │ │ └── ic_launcher_round.xml
│ │ │ ├── mipmap-hdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-mdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xhdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxhdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ │ ├── mipmap-xxxhdpi
│ │ │ ├── ic_launcher.png
│ │ │ └── ic_launcher_round.png
│ │ │ ├── values-night
│ │ │ └── themes.xml
│ │ │ └── values
│ │ │ ├── colors.xml
│ │ │ ├── strings.xml
│ │ │ └── themes.xml
│ │ └── test
│ │ └── java
│ │ └── io
│ │ └── agora
│ │ └── typing
│ │ └── ExampleUnitTest.kt
├── build.gradle
├── gradle.properties
├── gradle
│ └── wrapper
│ │ ├── gradle-wrapper.jar
│ │ └── gradle-wrapper.properties
├── gradlew
├── gradlew.bat
└── settings.gradle
├── README.md
├── README.zh.md
└── iOS
├── .gitignore
├── Podfile
├── Typing.xcodeproj
└── project.pbxproj
└── Typing
├── Assets.xcassets
├── AccentColor.colorset
│ └── Contents.json
├── AppIcon.appiconset
│ └── Contents.json
├── Contents.json
└── background.imageset
│ ├── Contents.json
│ └── background.png
├── Base
├── Logger.swift
├── Message.swift
└── Service.swift
├── Component
├── ChatTextField.swift
├── InputView.swift
├── KeyboardAdaptive.swift
├── RoundButton.swift
├── Shake.swift
└── TouchDown.swift
├── Extension.swift
├── Info.plist
├── KeyCenter.swift
├── Preview Content
└── Preview Assets.xcassets
│ └── Contents.json
├── Server
└── Server.swift
├── Typing.entitlements
├── TypingApp.swift
└── View
├── Chat
├── ChatModel.swift
└── ChatView.swift
└── Login
├── LoginModel.swift
└── LoginView.swift
/.gitignore:
--------------------------------------------------------------------------------
1 | xcuserdata
2 | .DS_Store
3 | AgoraRtcKit.framework
4 |
--------------------------------------------------------------------------------
/Android/.gitignore:
--------------------------------------------------------------------------------
1 | *.iml
2 | .gradle
3 | /local.properties
4 | /.idea/caches
5 | /.idea/libraries
6 | /.idea/modules.xml
7 | /.idea/workspace.xml
8 | /.idea/navEditor.xml
9 | /.idea/assetWizardSettings.xml
10 | .DS_Store
11 | /build
12 | /captures
13 | .externalNativeBuild
14 | .cxx
15 | local.properties
16 |
--------------------------------------------------------------------------------
/Android/.idea/.gitignore:
--------------------------------------------------------------------------------
1 | # Default ignored files
2 | /shelf/
3 | /workspace.xml
4 |
--------------------------------------------------------------------------------
/Android/.idea/.name:
--------------------------------------------------------------------------------
1 | Typing
--------------------------------------------------------------------------------
/Android/.idea/codeStyles/Project.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
11 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 | xmlns:android
34 |
35 | ^$
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 | xmlns:.*
45 |
46 | ^$
47 |
48 |
49 | BY_NAME
50 |
51 |
52 |
53 |
54 |
55 |
56 | .*:id
57 |
58 | http://schemas.android.com/apk/res/android
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 | .*:name
68 |
69 | http://schemas.android.com/apk/res/android
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 | name
79 |
80 | ^$
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 | style
90 |
91 | ^$
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 | .*
101 |
102 | ^$
103 |
104 |
105 | BY_NAME
106 |
107 |
108 |
109 |
110 |
111 |
112 | .*
113 |
114 | http://schemas.android.com/apk/res/android
115 |
116 |
117 | ANDROID_ATTRIBUTE_ORDER
118 |
119 |
120 |
121 |
122 |
123 |
124 | .*
125 |
126 | .*
127 |
128 |
129 | BY_NAME
130 |
131 |
132 |
133 |
134 |
135 |
136 |
137 |
138 |
139 |
--------------------------------------------------------------------------------
/Android/.idea/codeStyles/codeStyleConfig.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/Android/.idea/compiler.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/Android/.idea/gradle.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
21 |
22 |
--------------------------------------------------------------------------------
/Android/.idea/jarRepositories.xml:
--------------------------------------------------------------------------------
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 |
--------------------------------------------------------------------------------
/Android/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
--------------------------------------------------------------------------------
/Android/app/.gitignore:
--------------------------------------------------------------------------------
1 | /build
--------------------------------------------------------------------------------
/Android/app/build.gradle:
--------------------------------------------------------------------------------
1 | plugins {
2 | id 'com.android.application'
3 | id 'kotlin-android'
4 | }
5 |
6 | android {
7 | compileSdkVersion 30
8 | buildToolsVersion "30.0.3"
9 |
10 | defaultConfig {
11 | applicationId "io.agora.typing"
12 | minSdkVersion 16
13 | targetSdkVersion 30
14 | versionCode 1
15 | versionName "1.0"
16 | multiDexEnabled true
17 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
18 |
19 | ndk {
20 | abiFilters 'armeabi-v7a', 'arm64-v8a', 'x86', 'x86_64'
21 | }
22 | }
23 |
24 | buildTypes {
25 | debug {
26 | minifyEnabled true
27 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
28 | }
29 | release {
30 | minifyEnabled true
31 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
32 | }
33 | }
34 |
35 | sourceSets {
36 | main {
37 | jniLibs.srcDirs = ['src/main/jniLibs']
38 | }
39 | }
40 |
41 | compileOptions {
42 | sourceCompatibility JavaVersion.VERSION_1_8
43 | targetCompatibility JavaVersion.VERSION_1_8
44 | }
45 | kotlinOptions {
46 | jvmTarget = '1.8'
47 | }
48 | }
49 |
50 | dependencies {
51 | implementation 'androidx.multidex:multidex:2.0.1'
52 | implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
53 | implementation "androidx.core:core-ktx:$core_ktx"
54 | implementation "androidx.appcompat:appcompat:$appcompat"
55 | implementation "com.google.android.material:material:$material"
56 | implementation "androidx.constraintlayout:constraintlayout:$constraintlayout"
57 | implementation "androidx.lifecycle:lifecycle-livedata-ktx:$lifecycle_livedata_ktx"
58 | implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:$lifecycle_viewmodel_ktx"
59 | implementation "io.agora.rtm:rtm-sdk:$rtm_sdk"
60 | testImplementation 'junit:junit:4.+'
61 | androidTestImplementation 'androidx.test.ext:junit:1.1.2'
62 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
63 | }
--------------------------------------------------------------------------------
/Android/app/proguard-rules.pro:
--------------------------------------------------------------------------------
1 | # Add project specific ProGuard rules here.
2 | # You can control the set of applied configuration files using the
3 | # proguardFiles setting in build.gradle.
4 | #
5 | # For more details, see
6 | # http://developer.android.com/guide/developing/tools/proguard.html
7 |
8 | # If your project uses WebView with JS, uncomment the following
9 | # and specify the fully qualified class name to the JavaScript interface
10 | # class:
11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview {
12 | # public *;
13 | #}
14 |
15 | # Uncomment this to preserve the line number information for
16 | # debugging stack traces.
17 | #-keepattributes SourceFile,LineNumberTable
18 |
19 | # If you keep the line number information, uncomment this to
20 | # hide the original source file name.
21 | #-renamesourcefileattribute SourceFile
22 | -keep class io.agora.common.**{*;}
23 | -keep class io.agora.rtm.**{*;}
--------------------------------------------------------------------------------
/Android/app/src/androidTest/java/io/agora/typing/ExampleInstrumentedTest.kt:
--------------------------------------------------------------------------------
1 | package com.agora.typing
2 |
3 | import androidx.test.platform.app.InstrumentationRegistry
4 | import androidx.test.ext.junit.runners.AndroidJUnit4
5 |
6 | import org.junit.Test
7 | import org.junit.runner.RunWith
8 |
9 | import org.junit.Assert.*
10 |
11 | /**
12 | * Instrumented test, which will execute on an Android device.
13 | *
14 | * See [testing documentation](http://d.android.com/tools/testing).
15 | */
16 | @RunWith(AndroidJUnit4::class)
17 | class ExampleInstrumentedTest {
18 | @Test
19 | fun useAppContext() {
20 | // Context of the app under test.
21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext
22 | assertEquals("com.agora.openchat", appContext.packageName)
23 | }
24 | }
--------------------------------------------------------------------------------
/Android/app/src/main/AndroidManifest.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
28 |
29 |
30 |
--------------------------------------------------------------------------------
/Android/app/src/main/java/io/agora/typing/App.kt:
--------------------------------------------------------------------------------
1 | package io.agora.typing
2 |
3 | import androidx.multidex.MultiDexApplication
4 |
5 | class App : MultiDexApplication() {
6 | companion object {
7 | lateinit var instance: App
8 | }
9 |
10 | override fun onCreate() {
11 | super.onCreate()
12 | instance = this
13 | }
14 | }
--------------------------------------------------------------------------------
/Android/app/src/main/java/io/agora/typing/base/BuildConfig.kt:
--------------------------------------------------------------------------------
1 | package io.agora.typing.base
2 |
3 | class BuildConfig {
4 | companion object {
5 | val appId: String = <#Your App Id#>
6 | val token: String? = <#Temp Access Token#>
7 | }
8 | }
--------------------------------------------------------------------------------
/Android/app/src/main/java/io/agora/typing/base/Logger.kt:
--------------------------------------------------------------------------------
1 | package io.agora.typing.base
2 |
3 | import android.util.Log
4 |
5 | enum class LogLevel {
6 | Info, Warning, Error
7 | }
8 |
9 | class Logger {
10 | companion object {
11 | const val debug = true
12 | const val tag = "chat"
13 |
14 | fun log(message: String, level: LogLevel) {
15 | if (!debug && level != LogLevel.Error) {
16 | return
17 | }
18 | when (level) {
19 | LogLevel.Info -> Log.d(tag, "$message (${Thread.currentThread().name})")
20 | LogLevel.Warning -> Log.w(tag, message)
21 | LogLevel.Error -> Log.e(tag, message)
22 | }
23 | }
24 | }
25 | }
--------------------------------------------------------------------------------
/Android/app/src/main/java/io/agora/typing/base/Message.kt:
--------------------------------------------------------------------------------
1 | package io.agora.typing.base
2 |
3 | enum class MessageType {
4 | Text, Vibrate
5 | }
6 |
7 | class Message {
8 |
9 | companion object {
10 | fun text(raw: String): Message {
11 | return Message(MessageType.Text, raw)
12 | }
13 |
14 | fun vibrate(): Message {
15 | return Message(MessageType.Vibrate, "")
16 | }
17 | }
18 |
19 | val type: MessageType
20 | val data: String
21 |
22 | constructor(raw: String) {
23 | if (raw.startsWith("vibrate://")) {
24 | this.type = MessageType.Vibrate
25 | this.data = ""
26 | } else {
27 | this.type = MessageType.Text
28 | this.data = raw.replace("^text://".toRegex(), "")
29 | }
30 | }
31 |
32 | private constructor(type: MessageType, data: String) {
33 | this.type = type
34 | this.data = data
35 | }
36 |
37 | override fun toString(): String {
38 | return when (type) {
39 | MessageType.Text -> "text://${this.data}"
40 | MessageType.Vibrate -> "vibrate://${this.data}"
41 | }
42 | }
43 | }
--------------------------------------------------------------------------------
/Android/app/src/main/java/io/agora/typing/base/Service.kt:
--------------------------------------------------------------------------------
1 | package io.agora.typing.base
2 |
3 | import io.agora.rtm.RtmMessage
4 | import kotlinx.coroutines.flow.Flow
5 |
6 | data class Result(val success: Boolean, val data: T? = null, val message: String? = null)
7 | data class UserMessage(val name: String? = null, val message: RtmMessage? = null)
8 |
9 | interface Service {
10 | fun login(user: String): Flow>
11 | fun logout(): Flow>
12 | fun sendMessage(message: Message, toUser: String): Flow>
13 | fun subscribeUserOnlineState(user: String): Flow>
14 | fun subscribeFriendMessage(user: String): Flow>
15 | }
--------------------------------------------------------------------------------
/Android/app/src/main/java/io/agora/typing/server/server.kt:
--------------------------------------------------------------------------------
1 | package io.agora.typing.server
2 |
3 | import io.agora.typing.App
4 | import io.agora.typing.base.*
5 | import io.agora.rtm.*
6 | import kotlinx.coroutines.*
7 | import kotlinx.coroutines.channels.ConflatedBroadcastChannel
8 | import kotlinx.coroutines.channels.awaitClose
9 | import kotlinx.coroutines.flow.*
10 | import java.util.concurrent.CancellationException
11 |
12 | enum class UserStatus {
13 | Online, Offline
14 | }
15 |
16 | data class User(val name: String, var status: UserStatus = UserStatus.Offline)
17 |
18 | class WithErrorInfoError(override val message: String, val info: ErrorInfo? = null) : CancellationException(message)
19 |
20 | @FlowPreview
21 | @ExperimentalCoroutinesApi
22 | class Server : Service, RtmClientListener {
23 |
24 | companion object {
25 | val Instance: Server by lazy(mode = LazyThreadSafetyMode.SYNCHRONIZED) {
26 | Server()
27 | }
28 | }
29 |
30 | private var account: User? = null
31 | private val agoraRtmKit = RtmClient.createInstance(App.instance, BuildConfig.appId, this)
32 |
33 | override fun login(user: String): Flow> {
34 | Logger.log("login with id:$user", LogLevel.Info)
35 | var needLogout = false
36 | if (account?.status == UserStatus.Online) {
37 | if (account?.name == user) {
38 | return flowOf(Result(true))
39 | } else {
40 | needLogout = true
41 | }
42 | }
43 | return flowOf(needLogout).flatMapConcat {
44 | if (!it) {
45 | flowOf(Result(true))
46 | } else {
47 | logout()
48 | }
49 | }.flatMapConcat {
50 | if (it.success) {
51 | callbackFlow {
52 | val callback = object : ResultCallback {
53 | override fun onSuccess(p0: Void?) {
54 | account = User(user, UserStatus.Online)
55 | offer(Result(true))
56 | channel.close()
57 | }
58 |
59 | override fun onFailure(error: ErrorInfo?) {
60 | val errorCode = error?.errorCode
61 | val message = error?.errorDescription ?: "unknown error"
62 | Logger.log("login fail ($errorCode $message)", LogLevel.Error)
63 | cancel(WithErrorInfoError(message, error))
64 | }
65 | }
66 | agoraRtmKit.login(BuildConfig.token, user, callback)
67 | awaitClose()
68 | }
69 | } else {
70 | flowOf(it)
71 | }
72 | }
73 | }
74 |
75 | override fun logout(): Flow> {
76 | Logger.log("logout", LogLevel.Info)
77 | return if (account?.status != UserStatus.Online) {
78 | flowOf(Result(true))
79 | } else {
80 | callbackFlow {
81 | val callback = object : ResultCallback {
82 | override fun onSuccess(p0: Void?) {
83 | account = null
84 | offer(Result(true))
85 | channel.close()
86 | }
87 |
88 | override fun onFailure(error: ErrorInfo?) {
89 | val errorCode = error?.errorCode
90 | val message = error?.errorDescription ?: "unknown error"
91 | Logger.log("logout fail ($errorCode $message)", LogLevel.Error)
92 | cancel(WithErrorInfoError(message, error))
93 | channel.close()
94 | }
95 | }
96 | agoraRtmKit.logout(callback)
97 | awaitClose()
98 | }
99 | }
100 | }
101 |
102 | override fun subscribeUserOnlineState(user: String): Flow> {
103 | val callback = object : ResultCallback {
104 | override fun onSuccess(p0: Void?) {
105 | GlobalScope.launch(Dispatchers.Default) {
106 | peerStatusChangeChannel.send(Result(true, User(user)))
107 | }
108 | }
109 |
110 | override fun onFailure(error: ErrorInfo?) {
111 | GlobalScope.launch(Dispatchers.Default) {
112 | peerStatusChangeChannel.send(
113 | Result(
114 | false,
115 | User(user),
116 | message = error?.errorDescription ?: "unknown error"
117 | )
118 | )
119 | }
120 | }
121 | }
122 | agoraRtmKit.subscribePeersOnlineStatus(setOf(user), callback)
123 | return peerStatusChangeChannel.asFlow().filter { result ->
124 | result.data?.name == user
125 | }.map { result ->
126 | Logger.log("user: ${result.data?.name} status: ${result.data?.status}", LogLevel.Info)
127 | Result(
128 | result.success,
129 | data = result.data?.status == UserStatus.Online,
130 | message = result.message
131 | )
132 | }.flowOn(Dispatchers.IO)
133 | }
134 |
135 | override fun sendMessage(
136 | message: Message,
137 | toUser: String
138 | ): Flow> {
139 | return callbackFlow {
140 | val callback = object : ResultCallback {
141 | override fun onSuccess(p0: Void?) {
142 | offer(Result(true))
143 | channel.close()
144 | }
145 |
146 | override fun onFailure(error: ErrorInfo?) {
147 | val errorCode = error?.errorCode
148 | val errorDescription = error?.errorDescription ?: "unknown error"
149 | Logger.log("sendMessage ($errorCode $errorDescription)", LogLevel.Error)
150 | if (errorCode == RtmStatusCode.PeerMessageError.PEER_MESSAGE_ERR_CACHED_BY_SERVER) {
151 | offer(Result(true, errorCode))
152 | } else {
153 | //cancel(WithErrorInfoError(message, error))
154 | offer(Result(false, errorCode, errorDescription))
155 | }
156 | channel.close()
157 | }
158 | }
159 |
160 | val status = peersStatus[toUser] ?: PeerOnlineState.UNREACHABLE
161 | val option = SendMessageOptions()
162 | option.enableOfflineMessaging = status != PeerOnlineState.ONLINE
163 | agoraRtmKit.sendMessageToPeer(
164 | toUser,
165 | agoraRtmKit.createMessage(message.toString()),
166 | option,
167 | callback
168 | )
169 | Logger.log("sendMessage to: $toUser", LogLevel.Info)
170 | awaitClose()
171 | }
172 | }
173 |
174 | override fun subscribeFriendMessage(user: String): Flow> {
175 | return peerMessageChannel.asFlow().filter { result ->
176 | result.success && result.data?.name == user && result.data.message != null
177 | }.flowOn(Dispatchers.IO)
178 | }
179 |
180 | override fun onTokenExpired() {
181 | Logger.log("onTokenExpired", LogLevel.Info)
182 | }
183 |
184 | private val peersStatus = HashMap()
185 | private val peerStatusChangeChannel = ConflatedBroadcastChannel>()
186 |
187 | override fun onPeersOnlineStatusChanged(peersStatus: MutableMap?) {
188 | Logger.log("onPeersOnlineStatusChanged", LogLevel.Info)
189 | peersStatus?.forEach { item ->
190 | val peerId = item.key
191 | val status =
192 | if (item.value == PeerOnlineState.ONLINE) UserStatus.Online else UserStatus.Offline
193 | peersStatus[peerId] = item.value
194 | peerStatusChangeChannel.offer(Result(true, data = User(peerId, status)))
195 | }
196 | }
197 |
198 | override fun onConnectionStateChanged(state: Int, reason: Int) {
199 | Logger.log("onConnectionStateChanged", LogLevel.Info)
200 | }
201 |
202 | private val peerMessageChannel = ConflatedBroadcastChannel>()
203 |
204 | override fun onMessageReceived(message: RtmMessage?, peerId: String?) {
205 | Logger.log("onMessageReceived from:$peerId", LogLevel.Info)
206 | peerMessageChannel.offer(Result(true, UserMessage(peerId, message)))
207 | }
208 | }
--------------------------------------------------------------------------------
/Android/app/src/main/java/io/agora/typing/ui/ChatActivity.kt:
--------------------------------------------------------------------------------
1 | package io.agora.typing.ui
2 |
3 | import android.content.Context
4 | import android.content.Intent
5 | import androidx.appcompat.app.AppCompatActivity
6 | import android.os.Bundle
7 | import io.agora.typing.R
8 | import io.agora.typing.base.LogLevel
9 | import io.agora.typing.base.Logger
10 | import io.agora.typing.server.Server
11 | import io.agora.typing.ui.chat.ChatFragment
12 | import kotlinx.coroutines.*
13 | import kotlinx.coroutines.flow.collect
14 |
15 | @ExperimentalCoroutinesApi
16 | @FlowPreview
17 | class ChatActivity : AppCompatActivity() {
18 |
19 | companion object {
20 | const val FRIEND_NAME = "friend_name"
21 | fun newInstance(context: Context, friend: String): Intent {
22 | return Intent(context, ChatActivity::class.java).apply {
23 | putExtra(FRIEND_NAME, friend)
24 | }
25 | }
26 | }
27 |
28 | override fun onCreate(savedInstanceState: Bundle?) {
29 | super.onCreate(savedInstanceState)
30 | setContentView(R.layout.main_activity)
31 | if (savedInstanceState == null) {
32 | val friend = intent.getStringExtra(FRIEND_NAME)
33 | if (friend.isNullOrEmpty()) {
34 | finish()
35 | } else {
36 | supportActionBar?.setDisplayHomeAsUpEnabled(true)
37 | supportActionBar?.setDisplayShowTitleEnabled(true)
38 | supportActionBar?.title = "chat($friend)"
39 | supportFragmentManager.beginTransaction()
40 | .replace(R.id.container, ChatFragment.newInstance(friend))
41 | .commitNow()
42 | }
43 | }
44 | }
45 |
46 | override fun onSupportNavigateUp(): Boolean {
47 | GlobalScope.launch(Dispatchers.Main) {
48 | Server.Instance.logout().collect {
49 | Logger.log("logout", LogLevel.Info)
50 | }
51 | }
52 | finish()
53 | return true
54 | }
55 | }
--------------------------------------------------------------------------------
/Android/app/src/main/java/io/agora/typing/ui/MainActivity.kt:
--------------------------------------------------------------------------------
1 | package io.agora.typing.ui
2 |
3 | import androidx.appcompat.app.AppCompatActivity
4 | import android.os.Bundle
5 | import io.agora.typing.R
6 | import io.agora.typing.ui.login.LoginFragment
7 |
8 | class MainActivity : AppCompatActivity() {
9 |
10 | override fun onCreate(savedInstanceState: Bundle?) {
11 | super.onCreate(savedInstanceState)
12 | setContentView(R.layout.main_activity)
13 | if (savedInstanceState == null) {
14 | supportFragmentManager.beginTransaction()
15 | .replace(R.id.container, LoginFragment.newInstance())
16 | .commitNow()
17 | }
18 |
19 | supportActionBar?.hide()
20 | }
21 | }
--------------------------------------------------------------------------------
/Android/app/src/main/java/io/agora/typing/ui/chat/ChatFragment.kt:
--------------------------------------------------------------------------------
1 | package io.agora.typing.ui.chat
2 |
3 | import android.content.Context
4 | import android.os.Build
5 | import android.os.Bundle
6 | import android.os.VibrationEffect
7 | import android.os.Vibrator
8 | import android.view.LayoutInflater
9 | import android.view.View
10 | import android.view.ViewGroup
11 | import android.view.animation.Animation
12 | import android.view.animation.AnimationUtils
13 | import android.widget.EditText
14 | import android.widget.TextView
15 | import androidx.core.widget.addTextChangedListener
16 | import androidx.fragment.app.Fragment
17 | import androidx.lifecycle.ViewModelProvider
18 | import androidx.lifecycle.observe
19 | import io.agora.typing.R
20 | import io.agora.typing.base.Message
21 | import io.agora.typing.base.MessageType
22 | import com.google.android.material.snackbar.Snackbar
23 | import kotlinx.coroutines.*
24 |
25 |
26 | @ExperimentalCoroutinesApi
27 | @FlowPreview
28 | class ChatFragment(var friend: String) : Fragment() {
29 |
30 | companion object {
31 | fun newInstance(friend: String) = ChatFragment(friend)
32 | }
33 |
34 | private lateinit var messageBox: View
35 | private lateinit var viewModel: ChatModel
36 | private lateinit var inputMessage: EditText
37 | private lateinit var messageView: TextView
38 | private lateinit var onlineView: View
39 |
40 | private lateinit var animShake: Animation
41 |
42 | override fun onCreateView(
43 | inflater: LayoutInflater, container: ViewGroup?,
44 | savedInstanceState: Bundle?
45 | ): View {
46 | val root = inflater.inflate(R.layout.chat_fragment, container, false)
47 | messageBox = root.findViewById(R.id.frameLayout)
48 | inputMessage = root.findViewById(R.id.inputMessage)
49 | messageView = root.findViewById(R.id.message)
50 | onlineView = root.findViewById(R.id.online)
51 | return root
52 | }
53 |
54 | override fun onActivityCreated(savedInstanceState: Bundle?) {
55 | super.onActivityCreated(savedInstanceState)
56 | viewModel = ViewModelProvider(this).get(ChatModel::class.java)
57 | animShake = AnimationUtils.loadAnimation(context, R.anim.shake)
58 |
59 | messageBox.setOnClickListener {
60 | messageBox.startAnimation(animShake)
61 | viewModel.vibrate()
62 | }
63 |
64 | inputMessage.setHorizontallyScrolling(false)
65 | inputMessage.maxLines = Int.MAX_VALUE
66 | inputMessage.setOnEditorActionListener { _, _, _ ->
67 | inputMessage.text = null
68 | viewModel.sendMessage("")
69 | true
70 | }
71 |
72 | inputMessage.addTextChangedListener {
73 | viewModel.sendMessage(it.toString())
74 | }
75 |
76 | viewModel.onlineStatus(friend).observe(this) { result ->
77 | if (result.success) {
78 | result.data?.let {
79 | onlineView.setBackgroundResource(if (it) R.drawable.online else R.drawable.offline)
80 | }
81 | } else {
82 | result.message?.let {
83 | viewModel.snackBar.value = it
84 | }
85 | }
86 | }
87 |
88 | viewModel.receivedMessage(friend).observe(this) { result ->
89 | if (result.success) {
90 | val message = Message(result.data?.message?.text ?: "")
91 | when (message.type) {
92 | MessageType.Vibrate -> vibrate()
93 | MessageType.Text -> messageView.text = message.data
94 | }
95 | } else {
96 | result.message?.let {
97 | viewModel.snackBar.value = it
98 | }
99 | }
100 | }
101 |
102 | viewModel.onInputMessage(friend).observe(this) { result ->
103 | if (!result.success) {
104 | result.message?.let {
105 | viewModel.snackBar.value = it
106 | }
107 | }
108 | }
109 |
110 | viewModel.onVibrateMessage(friend).observe(this) { result ->
111 | if (!result.success) {
112 | result.message?.let {
113 | viewModel.snackBar.value = it
114 | }
115 | }
116 | }
117 |
118 | // Show a snackbar whenever the [ViewModel.snackbar] is updated a non-null value
119 | viewModel.snackBar.observe(this) { text ->
120 | text?.let {
121 | this.view?.let { it1 -> Snackbar.make(it1, it, Snackbar.LENGTH_SHORT).show() }
122 | viewModel.onSnackbarShown()
123 | }
124 | }
125 | }
126 |
127 | private fun vibrate() {
128 | inputMessage.startAnimation(animShake)
129 | val vibrator = context?.getSystemService(Context.VIBRATOR_SERVICE) as Vibrator
130 | if (Build.VERSION.SDK_INT >= 26) {
131 | vibrator.vibrate(VibrationEffect.createOneShot(200, VibrationEffect.DEFAULT_AMPLITUDE))
132 | } else {
133 | vibrator.vibrate(200)
134 | }
135 | }
136 | }
--------------------------------------------------------------------------------
/Android/app/src/main/java/io/agora/typing/ui/chat/ChatModel.kt:
--------------------------------------------------------------------------------
1 | package io.agora.typing.ui.chat
2 |
3 | import androidx.lifecycle.*
4 | import io.agora.typing.base.Message
5 | import io.agora.typing.server.Server
6 | import kotlinx.coroutines.*
7 | import kotlinx.coroutines.channels.ConflatedBroadcastChannel
8 | import kotlinx.coroutines.flow.*
9 |
10 | @FlowPreview
11 | @ExperimentalCoroutinesApi
12 | class ChatModel : ViewModel() {
13 |
14 | private var inputMessage = ConflatedBroadcastChannel()
15 | private var vibrateMessage = ConflatedBroadcastChannel()
16 | /**
17 | * Request a snackbar to display a string.
18 | */
19 | val snackBar = MutableLiveData()
20 |
21 | /**
22 | * Called immediately after the UI shows the snackbar.
23 | */
24 | fun onSnackbarShown() {
25 | snackBar.value = null
26 | }
27 |
28 | fun sendMessage(message: String) {
29 | inputMessage.offer(message)
30 | }
31 |
32 | fun vibrate() {
33 | vibrateMessage.offer(true)
34 | }
35 |
36 | fun receivedMessage(name: String) =
37 | Server.Instance.subscribeFriendMessage(name).asLiveData(Dispatchers.Main)
38 |
39 | fun onlineStatus(name: String) =
40 | Server.Instance.subscribeUserOnlineState(name).asLiveData(Dispatchers.Main)
41 |
42 | fun onInputMessage(name: String) =
43 | inputMessage
44 | .asFlow()
45 | .distinctUntilChanged()
46 | .debounce(50)
47 | .flatMapMerge { message ->
48 | Server.Instance.sendMessage(Message.text(message), name)
49 | }
50 | .flowOn(Dispatchers.Default)
51 | .asLiveData(Dispatchers.Main)
52 |
53 | fun onVibrateMessage(name: String) =
54 | vibrateMessage
55 | .asFlow()
56 | .debounce(200)
57 | .flatMapMerge {
58 | Server.Instance.sendMessage(Message.vibrate(), name)
59 | }
60 | .flowOn(Dispatchers.Default)
61 | .asLiveData(Dispatchers.Main)
62 | }
--------------------------------------------------------------------------------
/Android/app/src/main/java/io/agora/typing/ui/login/LoginFragment.kt:
--------------------------------------------------------------------------------
1 | package io.agora.typing.ui.login
2 |
3 | import androidx.lifecycle.ViewModelProvider
4 | import android.os.Bundle
5 | import androidx.fragment.app.Fragment
6 | import android.view.LayoutInflater
7 | import android.view.View
8 | import android.view.ViewGroup
9 | import android.widget.Button
10 | import android.widget.EditText
11 | import android.widget.ProgressBar
12 | import androidx.lifecycle.observe
13 | import io.agora.typing.ui.ChatActivity
14 | import io.agora.typing.R
15 | import com.google.android.material.snackbar.Snackbar
16 | import kotlinx.coroutines.ExperimentalCoroutinesApi
17 | import kotlinx.coroutines.FlowPreview
18 |
19 | @ExperimentalCoroutinesApi
20 | @FlowPreview
21 | class LoginFragment : Fragment() {
22 |
23 | companion object {
24 | fun newInstance() = LoginFragment()
25 | }
26 |
27 | private lateinit var viewModel: LoginModel
28 | private lateinit var userInput: EditText
29 | private lateinit var friendInput: EditText
30 | private lateinit var startButton: Button
31 | private lateinit var progressBar: ProgressBar
32 |
33 | override fun onCreateView(
34 | inflater: LayoutInflater, container: ViewGroup?,
35 | savedInstanceState: Bundle?
36 | ): View {
37 | val root = inflater.inflate(R.layout.login_fragment, container, false)
38 | userInput = root.findViewById(R.id.user)
39 | friendInput = root.findViewById(R.id.friend)
40 | startButton = root.findViewById(R.id.start)
41 | progressBar = root.findViewById(R.id.connecting)
42 | return root
43 | }
44 |
45 | override fun onActivityCreated(savedInstanceState: Bundle?) {
46 | super.onActivityCreated(savedInstanceState)
47 | viewModel = ViewModelProvider(this).get(LoginModel::class.java)
48 |
49 | startButton.setOnClickListener {
50 | viewModel.userName = userInput.text.toString()
51 | viewModel.friendName = friendInput.text.toString()
52 | viewModel.onClickLoginButton()
53 | }
54 |
55 | viewModel.online.observe(this) { success ->
56 | if (success) {
57 | //startActivity()
58 | context?.let { _context ->
59 | viewModel.friendName?.let { _name ->
60 | startActivity(ChatActivity.newInstance(_context, _name))
61 | }
62 | }
63 | }
64 | }
65 |
66 | viewModel.spinner.observe(this) { value ->
67 | value.let { show ->
68 | userInput.isEnabled = !show
69 | friendInput.isEnabled = !show
70 | progressBar.visibility = if (show) View.VISIBLE else View.INVISIBLE
71 | startButton.visibility = if (show) View.INVISIBLE else View.VISIBLE
72 | }
73 | }
74 |
75 | // Show a snackbar whenever the [ViewModel.snackbar] is updated a non-null value
76 | viewModel.snackbar.observe(this) { text ->
77 | text?.let {
78 | this.view?.let { it1 -> Snackbar.make(it1, it, Snackbar.LENGTH_SHORT).show() }
79 | viewModel.onSnackbarShown()
80 | }
81 | }
82 | }
83 |
84 | }
--------------------------------------------------------------------------------
/Android/app/src/main/java/io/agora/typing/ui/login/LoginModel.kt:
--------------------------------------------------------------------------------
1 | package io.agora.typing.ui.login
2 |
3 | import io.agora.typing.base.Result
4 | import io.agora.typing.server.Server
5 | import kotlinx.coroutines.*
6 | import kotlinx.coroutines.flow.*
7 | import androidx.lifecycle.*
8 | import io.agora.typing.base.LogLevel
9 | import io.agora.typing.base.Logger
10 | import io.agora.typing.server.WithErrorInfoError
11 |
12 | @FlowPreview
13 | @ExperimentalCoroutinesApi
14 | class LoginModel : ViewModel() {
15 |
16 | var userName: String? = null
17 | var friendName: String? = null
18 |
19 | private val _snackBar = MutableLiveData()
20 | private var _spinner = MutableLiveData()
21 | private var _online = MutableLiveData()
22 |
23 | /**
24 | * Request a snackbar to display a string.
25 | */
26 | val snackbar: LiveData
27 | get() = _snackBar
28 |
29 | /**
30 | * Show a loading spinner if true
31 | */
32 | val spinner: LiveData
33 | get() = _spinner
34 |
35 | /**
36 | * notify login action result
37 | */
38 | val online: LiveData
39 | get() = _online
40 |
41 | /**
42 | * Called immediately after the UI shows the snackbar.
43 | */
44 | fun onSnackbarShown() {
45 | _snackBar.value = null
46 | }
47 |
48 | fun onClickLoginButton() {
49 | loginAction()
50 | }
51 |
52 | private fun loginAction() = launchDataLoad {
53 | login().collect {
54 | Logger.log("login success", LogLevel.Info)
55 | _snackBar.value = "Login Success!"
56 | _online.value = true
57 | }
58 | }
59 |
60 | private suspend fun login(): Flow> {
61 | return withContext(Dispatchers.IO) {
62 | if (userName?.isEmpty() == true || friendName?.isEmpty() == true) {
63 | throw WithErrorInfoError("Input user's name or friend's name!")
64 | } else {
65 | Server.Instance.login(userName!!)
66 | }
67 | }
68 | }
69 |
70 | /**
71 | * Helper function to call a data load function with a loading spinner, errors will trigger a
72 | * snackbar.
73 | *
74 | * By marking `block` as `suspend` this creates a suspend lambda which can call suspend
75 | * functions.
76 | *
77 | * @param block lambda to actually load data. It is called in the viewModelScope. Before calling the
78 | * lambda the loading spinner will display, after completion or error the loading
79 | * spinner will stop
80 | */
81 | private fun launchDataLoad(block: suspend () -> Unit): Unit {
82 | viewModelScope.launch {
83 | try {
84 | _spinner.value = true
85 | block()
86 | } catch (error: WithErrorInfoError) {
87 | _snackBar.value = error.message
88 | } finally {
89 | _spinner.value = false
90 | }
91 | }
92 | }
93 | }
--------------------------------------------------------------------------------
/Android/app/src/main/res/anim/shake.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
--------------------------------------------------------------------------------
/Android/app/src/main/res/drawable-v24/ic_launcher_foreground.xml:
--------------------------------------------------------------------------------
1 |
7 |
8 |
9 |
15 |
18 |
21 |
22 |
23 |
24 |
30 |
--------------------------------------------------------------------------------
/Android/app/src/main/res/drawable/button.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
--------------------------------------------------------------------------------
/Android/app/src/main/res/drawable/cursor.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/Android/app/src/main/res/drawable/ic_launcher_background.xml:
--------------------------------------------------------------------------------
1 |
2 |
7 |
10 |
15 |
20 |
25 |
30 |
35 |
40 |
45 |
50 |
55 |
60 |
65 |
70 |
75 |
80 |
85 |
90 |
95 |
100 |
105 |
110 |
115 |
120 |
125 |
130 |
135 |
140 |
145 |
150 |
155 |
160 |
165 |
170 |
171 |
--------------------------------------------------------------------------------
/Android/app/src/main/res/drawable/offline.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Android/app/src/main/res/drawable/online.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/Android/app/src/main/res/drawable/round.xml:
--------------------------------------------------------------------------------
1 |
2 |
4 |
6 |
7 |
--------------------------------------------------------------------------------
/Android/app/src/main/res/layout/chat_fragment.xml:
--------------------------------------------------------------------------------
1 |
2 |
10 |
11 |
24 |
25 |
33 |
34 |
40 |
41 |
42 |
43 |
52 |
53 |
73 |
74 |
75 |
76 |
77 |
--------------------------------------------------------------------------------
/Android/app/src/main/res/layout/login_fragment.xml:
--------------------------------------------------------------------------------
1 |
2 |
8 |
9 |
22 |
23 |
40 |
41 |
42 |
43 |
44 |
57 |
58 |
72 |
73 |
90 |
91 |
101 |
102 |
112 |
113 |
121 |
122 |
123 |
--------------------------------------------------------------------------------
/Android/app/src/main/res/layout/main_activity.xml:
--------------------------------------------------------------------------------
1 |
2 |
--------------------------------------------------------------------------------
/Android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/Android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/Android/app/src/main/res/mipmap-hdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AgoraIO-Community/typing/bf5c90400321f2fc1673ae72f80621152e7e7e75/Android/app/src/main/res/mipmap-hdpi/ic_launcher.png
--------------------------------------------------------------------------------
/Android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AgoraIO-Community/typing/bf5c90400321f2fc1673ae72f80621152e7e7e75/Android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/Android/app/src/main/res/mipmap-mdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AgoraIO-Community/typing/bf5c90400321f2fc1673ae72f80621152e7e7e75/Android/app/src/main/res/mipmap-mdpi/ic_launcher.png
--------------------------------------------------------------------------------
/Android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AgoraIO-Community/typing/bf5c90400321f2fc1673ae72f80621152e7e7e75/Android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/Android/app/src/main/res/mipmap-xhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AgoraIO-Community/typing/bf5c90400321f2fc1673ae72f80621152e7e7e75/Android/app/src/main/res/mipmap-xhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/Android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AgoraIO-Community/typing/bf5c90400321f2fc1673ae72f80621152e7e7e75/Android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/Android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AgoraIO-Community/typing/bf5c90400321f2fc1673ae72f80621152e7e7e75/Android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/Android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AgoraIO-Community/typing/bf5c90400321f2fc1673ae72f80621152e7e7e75/Android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/Android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AgoraIO-Community/typing/bf5c90400321f2fc1673ae72f80621152e7e7e75/Android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png
--------------------------------------------------------------------------------
/Android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AgoraIO-Community/typing/bf5c90400321f2fc1673ae72f80621152e7e7e75/Android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png
--------------------------------------------------------------------------------
/Android/app/src/main/res/values-night/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
17 |
21 |
--------------------------------------------------------------------------------
/Android/app/src/main/res/values/colors.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 | #FFBB86FC
4 | #FF6200EE
5 | #FF3700B3
6 | #FF03DAC5
7 | #FF018786
8 | #FF000000
9 | #FFFFFFFF
10 | #099dfd
11 |
--------------------------------------------------------------------------------
/Android/app/src/main/res/values/strings.xml:
--------------------------------------------------------------------------------
1 |
2 | Typing
3 | Chat
4 | Your Name
5 | Friend\'s Name
6 | GO
7 | type something
8 |
--------------------------------------------------------------------------------
/Android/app/src/main/res/values/themes.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
17 |
18 |
22 |
--------------------------------------------------------------------------------
/Android/app/src/test/java/io/agora/typing/ExampleUnitTest.kt:
--------------------------------------------------------------------------------
1 | package com.agora.typing
2 |
3 | import org.junit.Test
4 |
5 | import org.junit.Assert.*
6 |
7 | /**
8 | * Example local unit test, which will execute on the development machine (host).
9 | *
10 | * See [testing documentation](http://d.android.com/tools/testing).
11 | */
12 | class ExampleUnitTest {
13 | @Test
14 | fun addition_isCorrect() {
15 | assertEquals(4, 2 + 2)
16 | }
17 | }
--------------------------------------------------------------------------------
/Android/build.gradle:
--------------------------------------------------------------------------------
1 | // Top-level build file where you can add configuration options common to all sub-projects/modules.
2 | buildscript {
3 | ext {
4 | kotlin_version = "1.3.72"
5 | rtm_sdk = "1.2.2"
6 | core_ktx = "1.3.2"
7 | appcompat = "1.2.0"
8 | material = "1.2.1"
9 | constraintlayout = "2.0.4"
10 | lifecycle_livedata_ktx = "2.2.0"
11 | lifecycle_viewmodel_ktx = "2.2.0"
12 | }
13 | repositories {
14 | google()
15 | jcenter()
16 | }
17 | dependencies {
18 | classpath "com.android.tools.build:gradle:4.1.1"
19 | classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
20 |
21 | // NOTE: Do not place your application dependencies here; they belong
22 | // in the individual module build.gradle files
23 | }
24 | }
25 |
26 | allprojects {
27 | repositories {
28 | google()
29 | jcenter()
30 | }
31 | }
32 |
33 | task clean(type: Delete) {
34 | delete rootProject.buildDir
35 | }
--------------------------------------------------------------------------------
/Android/gradle.properties:
--------------------------------------------------------------------------------
1 | # Project-wide Gradle settings.
2 | # IDE (e.g. Android Studio) users:
3 | # Gradle settings configured through the IDE *will override*
4 | # any settings specified in this file.
5 | # For more details on how to configure your build environment visit
6 | # http://www.gradle.org/docs/current/userguide/build_environment.html
7 | # Specifies the JVM arguments used for the daemon process.
8 | # The setting is particularly useful for tweaking memory settings.
9 | org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8
10 | # When configured, Gradle will run in incubating parallel mode.
11 | # This option should only be used with decoupled projects. More details, visit
12 | # http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
13 | # org.gradle.parallel=true
14 | # AndroidX package structure to make it clearer which packages are bundled with the
15 | # Android operating system, and which are packaged with your app"s APK
16 | # https://developer.android.com/topic/libraries/support-library/androidx-rn
17 | android.useAndroidX=true
18 | # Automatically convert third-party libraries to use AndroidX
19 | android.enableJetifier=true
20 | # Kotlin code style for this project: "official" or "obsolete":
21 | kotlin.code.style=official
22 | # Disables R8 for Android Library modules only.
23 | android.enableR8.libraries = false
24 | # Disables R8 for all modules.
25 | #android.enableR8 = false
--------------------------------------------------------------------------------
/Android/gradle/wrapper/gradle-wrapper.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AgoraIO-Community/typing/bf5c90400321f2fc1673ae72f80621152e7e7e75/Android/gradle/wrapper/gradle-wrapper.jar
--------------------------------------------------------------------------------
/Android/gradle/wrapper/gradle-wrapper.properties:
--------------------------------------------------------------------------------
1 | #Mon Jan 18 11:18:50 CST 2021
2 | distributionBase=GRADLE_USER_HOME
3 | distributionPath=wrapper/dists
4 | zipStoreBase=GRADLE_USER_HOME
5 | zipStorePath=wrapper/dists
6 | distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-all.zip
7 |
--------------------------------------------------------------------------------
/Android/gradlew:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env sh
2 |
3 | ##############################################################################
4 | ##
5 | ## Gradle start up script for UN*X
6 | ##
7 | ##############################################################################
8 |
9 | # Attempt to set APP_HOME
10 | # Resolve links: $0 may be a link
11 | PRG="$0"
12 | # Need this for relative symlinks.
13 | while [ -h "$PRG" ] ; do
14 | ls=`ls -ld "$PRG"`
15 | link=`expr "$ls" : '.*-> \(.*\)$'`
16 | if expr "$link" : '/.*' > /dev/null; then
17 | PRG="$link"
18 | else
19 | PRG=`dirname "$PRG"`"/$link"
20 | fi
21 | done
22 | SAVED="`pwd`"
23 | cd "`dirname \"$PRG\"`/" >/dev/null
24 | APP_HOME="`pwd -P`"
25 | cd "$SAVED" >/dev/null
26 |
27 | APP_NAME="Gradle"
28 | APP_BASE_NAME=`basename "$0"`
29 |
30 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
31 | DEFAULT_JVM_OPTS=""
32 |
33 | # Use the maximum available, or set MAX_FD != -1 to use that value.
34 | MAX_FD="maximum"
35 |
36 | warn () {
37 | echo "$*"
38 | }
39 |
40 | die () {
41 | echo
42 | echo "$*"
43 | echo
44 | exit 1
45 | }
46 |
47 | # OS specific support (must be 'true' or 'false').
48 | cygwin=false
49 | msys=false
50 | darwin=false
51 | nonstop=false
52 | case "`uname`" in
53 | CYGWIN* )
54 | cygwin=true
55 | ;;
56 | Darwin* )
57 | darwin=true
58 | ;;
59 | MINGW* )
60 | msys=true
61 | ;;
62 | NONSTOP* )
63 | nonstop=true
64 | ;;
65 | esac
66 |
67 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar
68 |
69 | # Determine the Java command to use to start the JVM.
70 | if [ -n "$JAVA_HOME" ] ; then
71 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then
72 | # IBM's JDK on AIX uses strange locations for the executables
73 | JAVACMD="$JAVA_HOME/jre/sh/java"
74 | else
75 | JAVACMD="$JAVA_HOME/bin/java"
76 | fi
77 | if [ ! -x "$JAVACMD" ] ; then
78 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME
79 |
80 | Please set the JAVA_HOME variable in your environment to match the
81 | location of your Java installation."
82 | fi
83 | else
84 | JAVACMD="java"
85 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
86 |
87 | Please set the JAVA_HOME variable in your environment to match the
88 | location of your Java installation."
89 | fi
90 |
91 | # Increase the maximum file descriptors if we can.
92 | if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then
93 | MAX_FD_LIMIT=`ulimit -H -n`
94 | if [ $? -eq 0 ] ; then
95 | if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then
96 | MAX_FD="$MAX_FD_LIMIT"
97 | fi
98 | ulimit -n $MAX_FD
99 | if [ $? -ne 0 ] ; then
100 | warn "Could not set maximum file descriptor limit: $MAX_FD"
101 | fi
102 | else
103 | warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT"
104 | fi
105 | fi
106 |
107 | # For Darwin, add options to specify how the application appears in the dock
108 | if $darwin; then
109 | GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\""
110 | fi
111 |
112 | # For Cygwin, switch paths to Windows format before running java
113 | if $cygwin ; then
114 | APP_HOME=`cygpath --path --mixed "$APP_HOME"`
115 | CLASSPATH=`cygpath --path --mixed "$CLASSPATH"`
116 | JAVACMD=`cygpath --unix "$JAVACMD"`
117 |
118 | # We build the pattern for arguments to be converted via cygpath
119 | ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`
120 | SEP=""
121 | for dir in $ROOTDIRSRAW ; do
122 | ROOTDIRS="$ROOTDIRS$SEP$dir"
123 | SEP="|"
124 | done
125 | OURCYGPATTERN="(^($ROOTDIRS))"
126 | # Add a user-defined pattern to the cygpath arguments
127 | if [ "$GRADLE_CYGPATTERN" != "" ] ; then
128 | OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)"
129 | fi
130 | # Now convert the arguments - kludge to limit ourselves to /bin/sh
131 | i=0
132 | for arg in "$@" ; do
133 | CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -`
134 | CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option
135 |
136 | if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition
137 | eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"`
138 | else
139 | eval `echo args$i`="\"$arg\""
140 | fi
141 | i=$((i+1))
142 | done
143 | case $i in
144 | (0) set -- ;;
145 | (1) set -- "$args0" ;;
146 | (2) set -- "$args0" "$args1" ;;
147 | (3) set -- "$args0" "$args1" "$args2" ;;
148 | (4) set -- "$args0" "$args1" "$args2" "$args3" ;;
149 | (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;;
150 | (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;;
151 | (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;;
152 | (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;;
153 | (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;;
154 | esac
155 | fi
156 |
157 | # Escape application args
158 | save () {
159 | for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done
160 | echo " "
161 | }
162 | APP_ARGS=$(save "$@")
163 |
164 | # Collect all arguments for the java command, following the shell quoting and substitution rules
165 | eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS"
166 |
167 | # by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong
168 | if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then
169 | cd "$(dirname "$0")"
170 | fi
171 |
172 | exec "$JAVACMD" "$@"
173 |
--------------------------------------------------------------------------------
/Android/gradlew.bat:
--------------------------------------------------------------------------------
1 | @if "%DEBUG%" == "" @echo off
2 | @rem ##########################################################################
3 | @rem
4 | @rem Gradle startup script for Windows
5 | @rem
6 | @rem ##########################################################################
7 |
8 | @rem Set local scope for the variables with windows NT shell
9 | if "%OS%"=="Windows_NT" setlocal
10 |
11 | set DIRNAME=%~dp0
12 | if "%DIRNAME%" == "" set DIRNAME=.
13 | set APP_BASE_NAME=%~n0
14 | set APP_HOME=%DIRNAME%
15 |
16 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.
17 | set DEFAULT_JVM_OPTS=
18 |
19 | @rem Find java.exe
20 | if defined JAVA_HOME goto findJavaFromJavaHome
21 |
22 | set JAVA_EXE=java.exe
23 | %JAVA_EXE% -version >NUL 2>&1
24 | if "%ERRORLEVEL%" == "0" goto init
25 |
26 | echo.
27 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.
28 | echo.
29 | echo Please set the JAVA_HOME variable in your environment to match the
30 | echo location of your Java installation.
31 |
32 | goto fail
33 |
34 | :findJavaFromJavaHome
35 | set JAVA_HOME=%JAVA_HOME:"=%
36 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe
37 |
38 | if exist "%JAVA_EXE%" goto init
39 |
40 | echo.
41 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%
42 | echo.
43 | echo Please set the JAVA_HOME variable in your environment to match the
44 | echo location of your Java installation.
45 |
46 | goto fail
47 |
48 | :init
49 | @rem Get command-line arguments, handling Windows variants
50 |
51 | if not "%OS%" == "Windows_NT" goto win9xME_args
52 |
53 | :win9xME_args
54 | @rem Slurp the command line arguments.
55 | set CMD_LINE_ARGS=
56 | set _SKIP=2
57 |
58 | :win9xME_args_slurp
59 | if "x%~1" == "x" goto execute
60 |
61 | set CMD_LINE_ARGS=%*
62 |
63 | :execute
64 | @rem Setup the command line
65 |
66 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar
67 |
68 | @rem Execute Gradle
69 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%
70 |
71 | :end
72 | @rem End local scope for the variables with windows NT shell
73 | if "%ERRORLEVEL%"=="0" goto mainEnd
74 |
75 | :fail
76 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of
77 | rem the _cmd.exe /c_ return code!
78 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1
79 | exit /b 1
80 |
81 | :mainEnd
82 | if "%OS%"=="Windows_NT" endlocal
83 |
84 | :omega
85 |
--------------------------------------------------------------------------------
/Android/settings.gradle:
--------------------------------------------------------------------------------
1 | include ':app'
2 | rootProject.name = "Typing"
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Typing App
2 |
3 | _English | [中文](README.zh.md)_
4 |
5 | This project shows you how to use AgoraRTM sdk to build an app like Honk
6 |
7 | ## Quick Start
8 |
9 | This section shows you how to prepare, build, and run the application.
10 |
11 | ### Prepare Dependencies
12 |
13 | #### iOS
14 |
15 | Change directory into **iOS** folder, run following command to install project dependencies,
16 |
17 | ```
18 | pod install
19 | ```
20 |
21 | Verify `Typing.xcworkspace` has been properly generated.
22 |
23 | ### Obtain an App Id
24 |
25 | To build and run the sample application, get an App Id:
26 |
27 | 1. Create a developer account at [agora.io](https://dashboard.agora.io/signin/). Once you finish the signup process, you will be redirected to the Dashboard.
28 | 2. Navigate in the Dashboard tree on the left to **Projects** > **Project List**.
29 | 3. Save the **App Id** from the Dashboard for later use.
30 | 4. Generate the **Access Token**, you can follow the step by step at [agora.io](https://docs.agora.io/en/Real-time-Messaging/rtm_token?platform=All%20Platforms#generate-an-rtm-token).
31 |
32 | #### iOS
33 |
34 | Open `Typing.xcworkspace` and edit the `KeyCenter.swift` file. In the `KeyCenter` struct, update `<#Your App Id#>` with your App Id, and change `<#Temp Access Token#>` with the temp Access Token generated from dashboard. Note you can leave the token variable `nil` if your project has not turned on security token.
35 |
36 | ``` Swift
37 | struct KeyCenter {
38 | static let AppId: String = <#Your App Id#>
39 |
40 | // assign token to nil if you have not enabled app certificate
41 | static var Token: String? = <#Temp Access Token#>
42 | }
43 | ```
44 |
45 | You are all set. Now connect your iPhone or iPad device and run the project.
46 |
47 | #### Android
48 |
49 | Open `Android` and edit the `app/src/main/java/io/agora/typing/base/BuildConfig.kt` file. Update `<#Your App Id#>` with your App Id, and change `<#Temp Access Token#>` with the temp Access Token generated from dashboard. Note you can leave the token variable `null` if your project has not turned on security token.
50 |
51 | ``` kotlin
52 | val appId: String = YOUR APP ID
53 | val token: String? = YOUR ACCESS TOKEN
54 | ```
55 |
56 | You are all set. Now connect your Android device and run the project.
57 |
--------------------------------------------------------------------------------
/README.zh.md:
--------------------------------------------------------------------------------
1 | # Typing App
2 |
3 | _[English](README.md) | 中文_
4 |
5 | 这个开源示例项目演示了如何使用 AgoraRTM 实现类似 Honk 的聊天效果,实现了实时文字聊天和震一震的效果
6 |
7 | ## 运行示例程序
8 |
9 | 这个段落主要讲解了如何编译和运行实例程序。
10 |
11 | ### 安装依赖库
12 |
13 | #### iOS
14 |
15 | 切换到 **iOS** 目录,运行以下命令使用 CocoaPods 安装依赖。
16 |
17 | ```
18 | pod install
19 | ```
20 |
21 | 运行后确认 `Typing.xcworkspace` 正常生成即可。
22 |
23 | ### 创建 Agora 账号并获取 AppId
24 |
25 | 在编译和启动实例程序前,你需要首先获取一个可用的 App Id:
26 |
27 | 1. 在[agora.io](https://dashboard.agora.io/signin/)创建一个开发者账号
28 | 2. 前往后台页面,点击左部导航栏的 **项目 > 项目列表** 菜单
29 | 3. 复制后台的 **App Id** 并备注,稍后启动应用时会用到它
30 | 4. 如果你想使用 **Access Token**,参考文档[agora.io](https://docs.agora.io/cn/Real-time-Messaging/rtm_token?platform=All%20Platforms#a-name--tokena%E4%BD%BF%E7%94%A8-rtm-token-%E9%89%B4%E6%9D%83)。
31 |
32 | #### iOS
33 |
34 | 打开 `Typing.xcworkspace` 并编辑 `KeyCenter.swift`,将你的 AppID 和 Token 分别替换到 `<#Your App Id#>` 与 `<#Temp Access Token#>`
35 |
36 | ```
37 | let AppID: String = <#Your App Id#>
38 | // 如果你没有打开Token功能,token可以直接给nil
39 | let Token: String? = <#Temp Access Token#>
40 | ```
41 |
42 | 然后你就可以使用 `Typing.xcworkspace` 编译并运行项目了。
43 |
44 | #### Android
45 |
46 | 打开 `Android` 并编辑 `app/src/main/java/io/agora/typing/base/BuildConfig.kt`,将你的 AppID 和 Token 分别替换到 `<#Your App Id#>` 和 `<#Temp Access Token#>`
47 |
48 | ``` kotlin
49 | val appId: String = YOUR APP ID
50 | val token: String? = YOUR ACCESS TOKEN
51 | ```
52 |
53 | 然后你就可以编译并运行项目了。
54 |
--------------------------------------------------------------------------------
/iOS/.gitignore:
--------------------------------------------------------------------------------
1 | .vscode
2 | *.xcuserdata
3 | *.DS_Store
4 | *.xcscmblueprint
5 | *.framework
6 | *.xcworkspacedata
7 | xcshareddata
8 |
9 | *.zip
10 | agora_sdk
11 | *.xcarchive
12 |
13 | DistributionSummary.plist
14 | ExportOptions.plist
15 | Packaging.log
16 | *.app
17 |
18 | # Xcode
19 | #
20 | # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore
21 |
22 | ## User settings
23 | xcuserdata/
24 |
25 | ## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9)
26 | *.xcscmblueprint
27 | *.xccheckout
28 |
29 | ## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4)
30 | build/
31 | DerivedData/
32 | *.moved-aside
33 | *.pbxuser
34 | !default.pbxuser
35 | *.mode1v3
36 | !default.mode1v3
37 | *.mode2v3
38 | !default.mode2v3
39 | *.perspectivev3
40 | !default.perspectivev3
41 |
42 | ## Obj-C/Swift specific
43 | *.hmap
44 |
45 | ## App packaging
46 | *.ipa
47 | *.dSYM.zip
48 | *.dSYM
49 |
50 | ## Playgrounds
51 | timeline.xctimeline
52 | playground.xcworkspace
53 |
54 | # Swift Package Manager
55 | #
56 | # Add this line if you want to avoid checking in source code from Swift Package Manager dependencies.
57 | # Packages/
58 | # Package.pins
59 | # Package.resolved
60 | # *.xcodeproj
61 | #
62 | # Xcode automatically generates this directory with a .xcworkspacedata file and xcuserdata
63 | # hence it is not needed unless you have added a package configuration file to your project
64 | # .swiftpm
65 |
66 | .build/
67 |
68 | # CocoaPods
69 | #
70 | # We recommend against adding the Pods directory to your .gitignore. However
71 | # you should judge for yourself, the pros and cons are mentioned at:
72 | # https://guides.cocoapods.org/using/using-cocoapods.html#should-i-check-the-pods-directory-into-source-control
73 |
74 | Pods/
75 | Podfile.lock
76 |
77 | # Add this line if you want to avoid checking in source code from the Xcode workspace
78 | *.xcworkspace
79 |
80 | # Carthage
81 | #
82 | # Add this line if you want to avoid checking in source code from Carthage dependencies.
83 | # Carthage/Checkouts
84 |
85 | Carthage/Build/
86 |
87 | # Accio dependency management
88 | Dependencies/
89 | .accio/
90 |
91 | # fastlane
92 | #
93 | # It is recommended to not store the screenshots in the git repo.
94 | # Instead, use fastlane to re-generate the screenshots whenever they are needed.
95 | # For more information about the recommended setup visit:
96 | # https://docs.fastlane.tools/best-practices/source-control/#source-control
97 |
98 | fastlane/report.xml
99 | fastlane/Preview.html
100 | fastlane/screenshots/**/*.png
101 | fastlane/test_output
102 |
103 | # Code Injection
104 | #
105 | # After new code Injection tools there's a generated folder /iOSInjectionProject
106 | # https://github.com/johnno1962/injectionforxcode
107 |
108 | iOSInjectionProject/
109 |
--------------------------------------------------------------------------------
/iOS/Podfile:
--------------------------------------------------------------------------------
1 | # Uncomment the next line to define a global platform for your project
2 | # platform :ios, '13.0'
3 |
4 | target 'Typing' do
5 | # Comment the next line if you don't want to use dynamic frameworks
6 | use_frameworks!
7 |
8 | # Pods for OpenChat
9 | pod 'AgoraRtm_iOS', '~> 1.2.2'
10 | # pod "Introspect"
11 | pod 'ExytePopupView'
12 | end
13 |
--------------------------------------------------------------------------------
/iOS/Typing.xcodeproj/project.pbxproj:
--------------------------------------------------------------------------------
1 | // !$*UTF8*$!
2 | {
3 | archiveVersion = 1;
4 | classes = {
5 | };
6 | objectVersion = 51;
7 | objects = {
8 |
9 | /* Begin PBXBuildFile section */
10 | 572F83EF25BAEF38005F595B /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 572F83D425BAEF38005F595B /* Assets.xcassets */; };
11 | 572F83F025BAEF38005F595B /* Shake.swift in Sources */ = {isa = PBXBuildFile; fileRef = 572F83D625BAEF38005F595B /* Shake.swift */; };
12 | 572F83F125BAEF38005F595B /* KeyboardAdaptive.swift in Sources */ = {isa = PBXBuildFile; fileRef = 572F83D725BAEF38005F595B /* KeyboardAdaptive.swift */; };
13 | 572F83F225BAEF38005F595B /* TouchDown.swift in Sources */ = {isa = PBXBuildFile; fileRef = 572F83D825BAEF38005F595B /* TouchDown.swift */; };
14 | 572F83F325BAEF38005F595B /* RoundButton.swift in Sources */ = {isa = PBXBuildFile; fileRef = 572F83D925BAEF38005F595B /* RoundButton.swift */; };
15 | 572F83F425BAEF38005F595B /* ChatTextField.swift in Sources */ = {isa = PBXBuildFile; fileRef = 572F83DA25BAEF38005F595B /* ChatTextField.swift */; };
16 | 572F83F525BAEF38005F595B /* InputView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 572F83DB25BAEF38005F595B /* InputView.swift */; };
17 | 572F83F625BAEF38005F595B /* Server.swift in Sources */ = {isa = PBXBuildFile; fileRef = 572F83DD25BAEF38005F595B /* Server.swift */; };
18 | 572F83F725BAEF38005F595B /* Preview Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 572F83DF25BAEF38005F595B /* Preview Assets.xcassets */; };
19 | 572F83F825BAEF38005F595B /* Extension.swift in Sources */ = {isa = PBXBuildFile; fileRef = 572F83E025BAEF38005F595B /* Extension.swift */; };
20 | 572F83F925BAEF38005F595B /* ChatModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 572F83E325BAEF38005F595B /* ChatModel.swift */; };
21 | 572F83FA25BAEF38005F595B /* ChatView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 572F83E425BAEF38005F595B /* ChatView.swift */; };
22 | 572F83FB25BAEF38005F595B /* LoginModel.swift in Sources */ = {isa = PBXBuildFile; fileRef = 572F83E625BAEF38005F595B /* LoginModel.swift */; };
23 | 572F83FC25BAEF38005F595B /* LoginView.swift in Sources */ = {isa = PBXBuildFile; fileRef = 572F83E725BAEF38005F595B /* LoginView.swift */; };
24 | 572F83FD25BAEF38005F595B /* TypingApp.swift in Sources */ = {isa = PBXBuildFile; fileRef = 572F83E825BAEF38005F595B /* TypingApp.swift */; };
25 | 572F83FF25BAEF38005F595B /* Service.swift in Sources */ = {isa = PBXBuildFile; fileRef = 572F83EB25BAEF38005F595B /* Service.swift */; };
26 | 572F840025BAEF38005F595B /* Logger.swift in Sources */ = {isa = PBXBuildFile; fileRef = 572F83EC25BAEF38005F595B /* Logger.swift */; };
27 | 572F840125BAEF38005F595B /* Message.swift in Sources */ = {isa = PBXBuildFile; fileRef = 572F83ED25BAEF38005F595B /* Message.swift */; };
28 | 572F840225BAEF38005F595B /* KeyCenter.swift in Sources */ = {isa = PBXBuildFile; fileRef = 572F83EE25BAEF38005F595B /* KeyCenter.swift */; };
29 | EBA3C5DC1E44366CA436FBDD /* Pods_Typing.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = EBD6D8A4112DA8DA92071C6F /* Pods_Typing.framework */; };
30 | /* End PBXBuildFile section */
31 |
32 | /* Begin PBXFileReference section */
33 | 15AD4AD38F1A170E6F732054 /* Pods-Chat.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Chat.debug.xcconfig"; path = "Target Support Files/Pods-Chat/Pods-Chat.debug.xcconfig"; sourceTree = ""; };
34 | 572F83D325BAEF38005F595B /* Typing.entitlements */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.entitlements; path = Typing.entitlements; sourceTree = ""; };
35 | 572F83D425BAEF38005F595B /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; };
36 | 572F83D625BAEF38005F595B /* Shake.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Shake.swift; sourceTree = ""; };
37 | 572F83D725BAEF38005F595B /* KeyboardAdaptive.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = KeyboardAdaptive.swift; sourceTree = ""; };
38 | 572F83D825BAEF38005F595B /* TouchDown.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TouchDown.swift; sourceTree = ""; };
39 | 572F83D925BAEF38005F595B /* RoundButton.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = RoundButton.swift; sourceTree = ""; };
40 | 572F83DA25BAEF38005F595B /* ChatTextField.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ChatTextField.swift; sourceTree = ""; };
41 | 572F83DB25BAEF38005F595B /* InputView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = InputView.swift; sourceTree = ""; };
42 | 572F83DD25BAEF38005F595B /* Server.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Server.swift; sourceTree = ""; };
43 | 572F83DF25BAEF38005F595B /* Preview Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = "Preview Assets.xcassets"; sourceTree = ""; };
44 | 572F83E025BAEF38005F595B /* Extension.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Extension.swift; sourceTree = ""; };
45 | 572F83E325BAEF38005F595B /* ChatModel.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ChatModel.swift; sourceTree = ""; };
46 | 572F83E425BAEF38005F595B /* ChatView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = ChatView.swift; sourceTree = ""; };
47 | 572F83E625BAEF38005F595B /* LoginModel.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LoginModel.swift; sourceTree = ""; };
48 | 572F83E725BAEF38005F595B /* LoginView.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = LoginView.swift; sourceTree = ""; };
49 | 572F83E825BAEF38005F595B /* TypingApp.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = TypingApp.swift; sourceTree = ""; };
50 | 572F83E925BAEF38005F595B /* Info.plist */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; };
51 | 572F83EB25BAEF38005F595B /* Service.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Service.swift; sourceTree = ""; };
52 | 572F83EC25BAEF38005F595B /* Logger.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Logger.swift; sourceTree = ""; };
53 | 572F83ED25BAEF38005F595B /* Message.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = Message.swift; sourceTree = ""; };
54 | 572F83EE25BAEF38005F595B /* KeyCenter.swift */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.swift; path = KeyCenter.swift; sourceTree = ""; };
55 | 576EA5AF25B01835000B3D79 /* Typing.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = Typing.app; sourceTree = BUILT_PRODUCTS_DIR; };
56 | 69D042DA3B78968CD18C8F3F /* Pods-OpenChat.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-OpenChat.debug.xcconfig"; path = "Target Support Files/Pods-OpenChat/Pods-OpenChat.debug.xcconfig"; sourceTree = ""; };
57 | 910C3BFF6101B0B203B9550B /* Pods-Typing.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Typing.debug.xcconfig"; path = "Target Support Files/Pods-Typing/Pods-Typing.debug.xcconfig"; sourceTree = ""; };
58 | 96FB7F6AFBC7ECB91DF54DAC /* Pods-Chat.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Chat.release.xcconfig"; path = "Target Support Files/Pods-Chat/Pods-Chat.release.xcconfig"; sourceTree = ""; };
59 | B955455B4AB7E9D1C8A5499A /* Pods-OpenChat.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-OpenChat.release.xcconfig"; path = "Target Support Files/Pods-OpenChat/Pods-OpenChat.release.xcconfig"; sourceTree = ""; };
60 | D066D47F554876A3EE4C2CD7 /* Pods-Typing.release.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Typing.release.xcconfig"; path = "Target Support Files/Pods-Typing/Pods-Typing.release.xcconfig"; sourceTree = ""; };
61 | EBD6D8A4112DA8DA92071C6F /* Pods_Typing.framework */ = {isa = PBXFileReference; explicitFileType = wrapper.framework; includeInIndex = 0; path = Pods_Typing.framework; sourceTree = BUILT_PRODUCTS_DIR; };
62 | /* End PBXFileReference section */
63 |
64 | /* Begin PBXFrameworksBuildPhase section */
65 | 576EA5AC25B01835000B3D79 /* Frameworks */ = {
66 | isa = PBXFrameworksBuildPhase;
67 | buildActionMask = 2147483647;
68 | files = (
69 | EBA3C5DC1E44366CA436FBDD /* Pods_Typing.framework in Frameworks */,
70 | );
71 | runOnlyForDeploymentPostprocessing = 0;
72 | };
73 | /* End PBXFrameworksBuildPhase section */
74 |
75 | /* Begin PBXGroup section */
76 | 572F83D225BAEF38005F595B /* Typing */ = {
77 | isa = PBXGroup;
78 | children = (
79 | 572F83D325BAEF38005F595B /* Typing.entitlements */,
80 | 572F83D425BAEF38005F595B /* Assets.xcassets */,
81 | 572F83D525BAEF38005F595B /* Component */,
82 | 572F83DC25BAEF38005F595B /* Server */,
83 | 572F83DE25BAEF38005F595B /* Preview Content */,
84 | 572F83E025BAEF38005F595B /* Extension.swift */,
85 | 572F83E125BAEF38005F595B /* View */,
86 | 572F83E825BAEF38005F595B /* TypingApp.swift */,
87 | 572F83E925BAEF38005F595B /* Info.plist */,
88 | 572F83EA25BAEF38005F595B /* Base */,
89 | 572F83EE25BAEF38005F595B /* KeyCenter.swift */,
90 | );
91 | path = Typing;
92 | sourceTree = "";
93 | };
94 | 572F83D525BAEF38005F595B /* Component */ = {
95 | isa = PBXGroup;
96 | children = (
97 | 572F83D625BAEF38005F595B /* Shake.swift */,
98 | 572F83D725BAEF38005F595B /* KeyboardAdaptive.swift */,
99 | 572F83D825BAEF38005F595B /* TouchDown.swift */,
100 | 572F83D925BAEF38005F595B /* RoundButton.swift */,
101 | 572F83DA25BAEF38005F595B /* ChatTextField.swift */,
102 | 572F83DB25BAEF38005F595B /* InputView.swift */,
103 | );
104 | path = Component;
105 | sourceTree = "";
106 | };
107 | 572F83DC25BAEF38005F595B /* Server */ = {
108 | isa = PBXGroup;
109 | children = (
110 | 572F83DD25BAEF38005F595B /* Server.swift */,
111 | );
112 | path = Server;
113 | sourceTree = "";
114 | };
115 | 572F83DE25BAEF38005F595B /* Preview Content */ = {
116 | isa = PBXGroup;
117 | children = (
118 | 572F83DF25BAEF38005F595B /* Preview Assets.xcassets */,
119 | );
120 | path = "Preview Content";
121 | sourceTree = "";
122 | };
123 | 572F83E125BAEF38005F595B /* View */ = {
124 | isa = PBXGroup;
125 | children = (
126 | 572F83E225BAEF38005F595B /* Chat */,
127 | 572F83E525BAEF38005F595B /* Login */,
128 | );
129 | path = View;
130 | sourceTree = "";
131 | };
132 | 572F83E225BAEF38005F595B /* Chat */ = {
133 | isa = PBXGroup;
134 | children = (
135 | 572F83E325BAEF38005F595B /* ChatModel.swift */,
136 | 572F83E425BAEF38005F595B /* ChatView.swift */,
137 | );
138 | path = Chat;
139 | sourceTree = "";
140 | };
141 | 572F83E525BAEF38005F595B /* Login */ = {
142 | isa = PBXGroup;
143 | children = (
144 | 572F83E625BAEF38005F595B /* LoginModel.swift */,
145 | 572F83E725BAEF38005F595B /* LoginView.swift */,
146 | );
147 | path = Login;
148 | sourceTree = "";
149 | };
150 | 572F83EA25BAEF38005F595B /* Base */ = {
151 | isa = PBXGroup;
152 | children = (
153 | 572F83EB25BAEF38005F595B /* Service.swift */,
154 | 572F83EC25BAEF38005F595B /* Logger.swift */,
155 | 572F83ED25BAEF38005F595B /* Message.swift */,
156 | );
157 | path = Base;
158 | sourceTree = "";
159 | };
160 | 576EA5A625B01835000B3D79 = {
161 | isa = PBXGroup;
162 | children = (
163 | 572F83D225BAEF38005F595B /* Typing */,
164 | 576EA5B025B01835000B3D79 /* Products */,
165 | E9811493FB60F2A6E9110384 /* Pods */,
166 | 754FA441367E59961F9BC611 /* Frameworks */,
167 | );
168 | sourceTree = "";
169 | };
170 | 576EA5B025B01835000B3D79 /* Products */ = {
171 | isa = PBXGroup;
172 | children = (
173 | 576EA5AF25B01835000B3D79 /* Typing.app */,
174 | );
175 | name = Products;
176 | sourceTree = "";
177 | };
178 | 754FA441367E59961F9BC611 /* Frameworks */ = {
179 | isa = PBXGroup;
180 | children = (
181 | EBD6D8A4112DA8DA92071C6F /* Pods_Typing.framework */,
182 | );
183 | name = Frameworks;
184 | sourceTree = "";
185 | };
186 | E9811493FB60F2A6E9110384 /* Pods */ = {
187 | isa = PBXGroup;
188 | children = (
189 | 69D042DA3B78968CD18C8F3F /* Pods-OpenChat.debug.xcconfig */,
190 | B955455B4AB7E9D1C8A5499A /* Pods-OpenChat.release.xcconfig */,
191 | 15AD4AD38F1A170E6F732054 /* Pods-Chat.debug.xcconfig */,
192 | 96FB7F6AFBC7ECB91DF54DAC /* Pods-Chat.release.xcconfig */,
193 | 910C3BFF6101B0B203B9550B /* Pods-Typing.debug.xcconfig */,
194 | D066D47F554876A3EE4C2CD7 /* Pods-Typing.release.xcconfig */,
195 | );
196 | path = Pods;
197 | sourceTree = "";
198 | };
199 | /* End PBXGroup section */
200 |
201 | /* Begin PBXNativeTarget section */
202 | 576EA5AE25B01835000B3D79 /* Typing */ = {
203 | isa = PBXNativeTarget;
204 | buildConfigurationList = 576EA5BE25B0183A000B3D79 /* Build configuration list for PBXNativeTarget "Typing" */;
205 | buildPhases = (
206 | 2850F2C7FE41828EDF454EC0 /* [CP] Check Pods Manifest.lock */,
207 | 576EA5AB25B01835000B3D79 /* Sources */,
208 | 576EA5AC25B01835000B3D79 /* Frameworks */,
209 | 576EA5AD25B01835000B3D79 /* Resources */,
210 | 69054E97CFE6AE4B504F4EC7 /* [CP] Embed Pods Frameworks */,
211 | );
212 | buildRules = (
213 | );
214 | dependencies = (
215 | );
216 | name = Typing;
217 | productName = OpenChat;
218 | productReference = 576EA5AF25B01835000B3D79 /* Typing.app */;
219 | productType = "com.apple.product-type.application";
220 | };
221 | /* End PBXNativeTarget section */
222 |
223 | /* Begin PBXProject section */
224 | 576EA5A725B01835000B3D79 /* Project object */ = {
225 | isa = PBXProject;
226 | attributes = {
227 | LastSwiftUpdateCheck = 1230;
228 | LastUpgradeCheck = 1230;
229 | TargetAttributes = {
230 | 576EA5AE25B01835000B3D79 = {
231 | CreatedOnToolsVersion = 12.3;
232 | };
233 | };
234 | };
235 | buildConfigurationList = 576EA5AA25B01835000B3D79 /* Build configuration list for PBXProject "Typing" */;
236 | compatibilityVersion = "Xcode 9.3";
237 | developmentRegion = en;
238 | hasScannedForEncodings = 0;
239 | knownRegions = (
240 | en,
241 | Base,
242 | );
243 | mainGroup = 576EA5A625B01835000B3D79;
244 | productRefGroup = 576EA5B025B01835000B3D79 /* Products */;
245 | projectDirPath = "";
246 | projectRoot = "";
247 | targets = (
248 | 576EA5AE25B01835000B3D79 /* Typing */,
249 | );
250 | };
251 | /* End PBXProject section */
252 |
253 | /* Begin PBXResourcesBuildPhase section */
254 | 576EA5AD25B01835000B3D79 /* Resources */ = {
255 | isa = PBXResourcesBuildPhase;
256 | buildActionMask = 2147483647;
257 | files = (
258 | 572F83F725BAEF38005F595B /* Preview Assets.xcassets in Resources */,
259 | 572F83EF25BAEF38005F595B /* Assets.xcassets in Resources */,
260 | );
261 | runOnlyForDeploymentPostprocessing = 0;
262 | };
263 | /* End PBXResourcesBuildPhase section */
264 |
265 | /* Begin PBXShellScriptBuildPhase section */
266 | 2850F2C7FE41828EDF454EC0 /* [CP] Check Pods Manifest.lock */ = {
267 | isa = PBXShellScriptBuildPhase;
268 | buildActionMask = 2147483647;
269 | files = (
270 | );
271 | inputFileListPaths = (
272 | );
273 | inputPaths = (
274 | "${PODS_PODFILE_DIR_PATH}/Podfile.lock",
275 | "${PODS_ROOT}/Manifest.lock",
276 | );
277 | name = "[CP] Check Pods Manifest.lock";
278 | outputFileListPaths = (
279 | );
280 | outputPaths = (
281 | "$(DERIVED_FILE_DIR)/Pods-Typing-checkManifestLockResult.txt",
282 | );
283 | runOnlyForDeploymentPostprocessing = 0;
284 | shellPath = /bin/sh;
285 | shellScript = "diff \"${PODS_PODFILE_DIR_PATH}/Podfile.lock\" \"${PODS_ROOT}/Manifest.lock\" > /dev/null\nif [ $? != 0 ] ; then\n # print error to STDERR\n echo \"error: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update your CocoaPods installation.\" >&2\n exit 1\nfi\n# This output is used by Xcode 'outputs' to avoid re-running this script phase.\necho \"SUCCESS\" > \"${SCRIPT_OUTPUT_FILE_0}\"\n";
286 | showEnvVarsInLog = 0;
287 | };
288 | 69054E97CFE6AE4B504F4EC7 /* [CP] Embed Pods Frameworks */ = {
289 | isa = PBXShellScriptBuildPhase;
290 | buildActionMask = 2147483647;
291 | files = (
292 | );
293 | inputFileListPaths = (
294 | "${PODS_ROOT}/Target Support Files/Pods-Typing/Pods-Typing-frameworks-${CONFIGURATION}-input-files.xcfilelist",
295 | );
296 | name = "[CP] Embed Pods Frameworks";
297 | outputFileListPaths = (
298 | "${PODS_ROOT}/Target Support Files/Pods-Typing/Pods-Typing-frameworks-${CONFIGURATION}-output-files.xcfilelist",
299 | );
300 | runOnlyForDeploymentPostprocessing = 0;
301 | shellPath = /bin/sh;
302 | shellScript = "\"${PODS_ROOT}/Target Support Files/Pods-Typing/Pods-Typing-frameworks.sh\"\n";
303 | showEnvVarsInLog = 0;
304 | };
305 | /* End PBXShellScriptBuildPhase section */
306 |
307 | /* Begin PBXSourcesBuildPhase section */
308 | 576EA5AB25B01835000B3D79 /* Sources */ = {
309 | isa = PBXSourcesBuildPhase;
310 | buildActionMask = 2147483647;
311 | files = (
312 | 572F83FD25BAEF38005F595B /* TypingApp.swift in Sources */,
313 | 572F83FC25BAEF38005F595B /* LoginView.swift in Sources */,
314 | 572F83FB25BAEF38005F595B /* LoginModel.swift in Sources */,
315 | 572F83F425BAEF38005F595B /* ChatTextField.swift in Sources */,
316 | 572F83F125BAEF38005F595B /* KeyboardAdaptive.swift in Sources */,
317 | 572F840125BAEF38005F595B /* Message.swift in Sources */,
318 | 572F83F525BAEF38005F595B /* InputView.swift in Sources */,
319 | 572F840025BAEF38005F595B /* Logger.swift in Sources */,
320 | 572F83FA25BAEF38005F595B /* ChatView.swift in Sources */,
321 | 572F83F025BAEF38005F595B /* Shake.swift in Sources */,
322 | 572F83F225BAEF38005F595B /* TouchDown.swift in Sources */,
323 | 572F83FF25BAEF38005F595B /* Service.swift in Sources */,
324 | 572F840225BAEF38005F595B /* KeyCenter.swift in Sources */,
325 | 572F83F825BAEF38005F595B /* Extension.swift in Sources */,
326 | 572F83F925BAEF38005F595B /* ChatModel.swift in Sources */,
327 | 572F83F325BAEF38005F595B /* RoundButton.swift in Sources */,
328 | 572F83F625BAEF38005F595B /* Server.swift in Sources */,
329 | );
330 | runOnlyForDeploymentPostprocessing = 0;
331 | };
332 | /* End PBXSourcesBuildPhase section */
333 |
334 | /* Begin XCBuildConfiguration section */
335 | 576EA5BC25B0183A000B3D79 /* Debug */ = {
336 | isa = XCBuildConfiguration;
337 | buildSettings = {
338 | ALWAYS_SEARCH_USER_PATHS = NO;
339 | CLANG_ANALYZER_NONNULL = YES;
340 | CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
341 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
342 | CLANG_CXX_LIBRARY = "libc++";
343 | CLANG_ENABLE_MODULES = YES;
344 | CLANG_ENABLE_OBJC_ARC = YES;
345 | CLANG_ENABLE_OBJC_WEAK = YES;
346 | CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
347 | CLANG_WARN_BOOL_CONVERSION = YES;
348 | CLANG_WARN_COMMA = YES;
349 | CLANG_WARN_CONSTANT_CONVERSION = YES;
350 | CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
351 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
352 | CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
353 | CLANG_WARN_EMPTY_BODY = YES;
354 | CLANG_WARN_ENUM_CONVERSION = YES;
355 | CLANG_WARN_INFINITE_RECURSION = YES;
356 | CLANG_WARN_INT_CONVERSION = YES;
357 | CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
358 | CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
359 | CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
360 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
361 | CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
362 | CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
363 | CLANG_WARN_STRICT_PROTOTYPES = YES;
364 | CLANG_WARN_SUSPICIOUS_MOVE = YES;
365 | CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
366 | CLANG_WARN_UNREACHABLE_CODE = YES;
367 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
368 | COPY_PHASE_STRIP = NO;
369 | DEBUG_INFORMATION_FORMAT = dwarf;
370 | ENABLE_STRICT_OBJC_MSGSEND = YES;
371 | ENABLE_TESTABILITY = YES;
372 | GCC_C_LANGUAGE_STANDARD = gnu11;
373 | GCC_DYNAMIC_NO_PIC = NO;
374 | GCC_NO_COMMON_BLOCKS = YES;
375 | GCC_OPTIMIZATION_LEVEL = 0;
376 | GCC_PREPROCESSOR_DEFINITIONS = (
377 | "DEBUG=1",
378 | "$(inherited)",
379 | );
380 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
381 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
382 | GCC_WARN_UNDECLARED_SELECTOR = YES;
383 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
384 | GCC_WARN_UNUSED_FUNCTION = YES;
385 | GCC_WARN_UNUSED_VARIABLE = YES;
386 | IPHONEOS_DEPLOYMENT_TARGET = 14.3;
387 | MTL_ENABLE_DEBUG_INFO = INCLUDE_SOURCE;
388 | MTL_FAST_MATH = YES;
389 | ONLY_ACTIVE_ARCH = YES;
390 | SDKROOT = iphoneos;
391 | SWIFT_ACTIVE_COMPILATION_CONDITIONS = DEBUG;
392 | SWIFT_OPTIMIZATION_LEVEL = "-Onone";
393 | };
394 | name = Debug;
395 | };
396 | 576EA5BD25B0183A000B3D79 /* Release */ = {
397 | isa = XCBuildConfiguration;
398 | buildSettings = {
399 | ALWAYS_SEARCH_USER_PATHS = NO;
400 | CLANG_ANALYZER_NONNULL = YES;
401 | CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE;
402 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++14";
403 | CLANG_CXX_LIBRARY = "libc++";
404 | CLANG_ENABLE_MODULES = YES;
405 | CLANG_ENABLE_OBJC_ARC = YES;
406 | CLANG_ENABLE_OBJC_WEAK = YES;
407 | CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES;
408 | CLANG_WARN_BOOL_CONVERSION = YES;
409 | CLANG_WARN_COMMA = YES;
410 | CLANG_WARN_CONSTANT_CONVERSION = YES;
411 | CLANG_WARN_DEPRECATED_OBJC_IMPLEMENTATIONS = YES;
412 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR;
413 | CLANG_WARN_DOCUMENTATION_COMMENTS = YES;
414 | CLANG_WARN_EMPTY_BODY = YES;
415 | CLANG_WARN_ENUM_CONVERSION = YES;
416 | CLANG_WARN_INFINITE_RECURSION = YES;
417 | CLANG_WARN_INT_CONVERSION = YES;
418 | CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES;
419 | CLANG_WARN_OBJC_IMPLICIT_RETAIN_SELF = YES;
420 | CLANG_WARN_OBJC_LITERAL_CONVERSION = YES;
421 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR;
422 | CLANG_WARN_QUOTED_INCLUDE_IN_FRAMEWORK_HEADER = YES;
423 | CLANG_WARN_RANGE_LOOP_ANALYSIS = YES;
424 | CLANG_WARN_STRICT_PROTOTYPES = YES;
425 | CLANG_WARN_SUSPICIOUS_MOVE = YES;
426 | CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE;
427 | CLANG_WARN_UNREACHABLE_CODE = YES;
428 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES;
429 | COPY_PHASE_STRIP = NO;
430 | DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym";
431 | ENABLE_NS_ASSERTIONS = NO;
432 | ENABLE_STRICT_OBJC_MSGSEND = YES;
433 | GCC_C_LANGUAGE_STANDARD = gnu11;
434 | GCC_NO_COMMON_BLOCKS = YES;
435 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES;
436 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR;
437 | GCC_WARN_UNDECLARED_SELECTOR = YES;
438 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE;
439 | GCC_WARN_UNUSED_FUNCTION = YES;
440 | GCC_WARN_UNUSED_VARIABLE = YES;
441 | IPHONEOS_DEPLOYMENT_TARGET = 14.3;
442 | MTL_ENABLE_DEBUG_INFO = NO;
443 | MTL_FAST_MATH = YES;
444 | SDKROOT = iphoneos;
445 | SWIFT_COMPILATION_MODE = wholemodule;
446 | SWIFT_OPTIMIZATION_LEVEL = "-O";
447 | VALIDATE_PRODUCT = YES;
448 | };
449 | name = Release;
450 | };
451 | 576EA5BF25B0183A000B3D79 /* Debug */ = {
452 | isa = XCBuildConfiguration;
453 | baseConfigurationReference = 910C3BFF6101B0B203B9550B /* Pods-Typing.debug.xcconfig */;
454 | buildSettings = {
455 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
456 | ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
457 | CODE_SIGN_ENTITLEMENTS = Typing/Typing.entitlements;
458 | CODE_SIGN_IDENTITY = "Apple Development";
459 | CODE_SIGN_STYLE = Manual;
460 | DEVELOPMENT_ASSET_PATHS = "Typing/\"Preview Content\"";
461 | DEVELOPMENT_TEAM = "";
462 | ENABLE_PREVIEWS = YES;
463 | INFOPLIST_FILE = "$(SRCROOT)/Typing/Info.plist";
464 | IPHONEOS_DEPLOYMENT_TARGET = 14.0;
465 | LD_RUNPATH_SEARCH_PATHS = (
466 | "$(inherited)",
467 | "@executable_path/Frameworks",
468 | );
469 | PRODUCT_BUNDLE_IDENTIFIER = io.agora.typing;
470 | PRODUCT_NAME = "$(TARGET_NAME)";
471 | PROVISIONING_PROFILE_SPECIFIER = "";
472 | SUPPORTS_MACCATALYST = NO;
473 | SWIFT_VERSION = 5.0;
474 | TARGETED_DEVICE_FAMILY = "1,2";
475 | };
476 | name = Debug;
477 | };
478 | 576EA5C025B0183A000B3D79 /* Release */ = {
479 | isa = XCBuildConfiguration;
480 | baseConfigurationReference = D066D47F554876A3EE4C2CD7 /* Pods-Typing.release.xcconfig */;
481 | buildSettings = {
482 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon;
483 | ASSETCATALOG_COMPILER_GLOBAL_ACCENT_COLOR_NAME = AccentColor;
484 | CODE_SIGN_ENTITLEMENTS = Typing/Typing.entitlements;
485 | CODE_SIGN_IDENTITY = "Apple Development";
486 | CODE_SIGN_STYLE = Manual;
487 | DEVELOPMENT_ASSET_PATHS = "Typing/\"Preview Content\"";
488 | DEVELOPMENT_TEAM = "";
489 | ENABLE_PREVIEWS = YES;
490 | INFOPLIST_FILE = "$(SRCROOT)/Typing/Info.plist";
491 | IPHONEOS_DEPLOYMENT_TARGET = 14.0;
492 | LD_RUNPATH_SEARCH_PATHS = (
493 | "$(inherited)",
494 | "@executable_path/Frameworks",
495 | );
496 | PRODUCT_BUNDLE_IDENTIFIER = io.agora.typing;
497 | PRODUCT_NAME = "$(TARGET_NAME)";
498 | PROVISIONING_PROFILE_SPECIFIER = "";
499 | SUPPORTS_MACCATALYST = NO;
500 | SWIFT_VERSION = 5.0;
501 | TARGETED_DEVICE_FAMILY = "1,2";
502 | };
503 | name = Release;
504 | };
505 | /* End XCBuildConfiguration section */
506 |
507 | /* Begin XCConfigurationList section */
508 | 576EA5AA25B01835000B3D79 /* Build configuration list for PBXProject "Typing" */ = {
509 | isa = XCConfigurationList;
510 | buildConfigurations = (
511 | 576EA5BC25B0183A000B3D79 /* Debug */,
512 | 576EA5BD25B0183A000B3D79 /* Release */,
513 | );
514 | defaultConfigurationIsVisible = 0;
515 | defaultConfigurationName = Release;
516 | };
517 | 576EA5BE25B0183A000B3D79 /* Build configuration list for PBXNativeTarget "Typing" */ = {
518 | isa = XCConfigurationList;
519 | buildConfigurations = (
520 | 576EA5BF25B0183A000B3D79 /* Debug */,
521 | 576EA5C025B0183A000B3D79 /* Release */,
522 | );
523 | defaultConfigurationIsVisible = 0;
524 | defaultConfigurationName = Release;
525 | };
526 | /* End XCConfigurationList section */
527 | };
528 | rootObject = 576EA5A725B01835000B3D79 /* Project object */;
529 | }
530 |
--------------------------------------------------------------------------------
/iOS/Typing/Assets.xcassets/AccentColor.colorset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "colors" : [
3 | {
4 | "idiom" : "universal"
5 | }
6 | ],
7 | "info" : {
8 | "author" : "xcode",
9 | "version" : 1
10 | }
11 | }
12 |
--------------------------------------------------------------------------------
/iOS/Typing/Assets.xcassets/AppIcon.appiconset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "images" : [
3 | {
4 | "idiom" : "iphone",
5 | "scale" : "2x",
6 | "size" : "20x20"
7 | },
8 | {
9 | "idiom" : "iphone",
10 | "scale" : "3x",
11 | "size" : "20x20"
12 | },
13 | {
14 | "idiom" : "iphone",
15 | "scale" : "2x",
16 | "size" : "29x29"
17 | },
18 | {
19 | "idiom" : "iphone",
20 | "scale" : "3x",
21 | "size" : "29x29"
22 | },
23 | {
24 | "idiom" : "iphone",
25 | "scale" : "2x",
26 | "size" : "40x40"
27 | },
28 | {
29 | "idiom" : "iphone",
30 | "scale" : "3x",
31 | "size" : "40x40"
32 | },
33 | {
34 | "idiom" : "iphone",
35 | "scale" : "2x",
36 | "size" : "60x60"
37 | },
38 | {
39 | "idiom" : "iphone",
40 | "scale" : "3x",
41 | "size" : "60x60"
42 | },
43 | {
44 | "idiom" : "ipad",
45 | "scale" : "1x",
46 | "size" : "20x20"
47 | },
48 | {
49 | "idiom" : "ipad",
50 | "scale" : "2x",
51 | "size" : "20x20"
52 | },
53 | {
54 | "idiom" : "ipad",
55 | "scale" : "1x",
56 | "size" : "29x29"
57 | },
58 | {
59 | "idiom" : "ipad",
60 | "scale" : "2x",
61 | "size" : "29x29"
62 | },
63 | {
64 | "idiom" : "ipad",
65 | "scale" : "1x",
66 | "size" : "40x40"
67 | },
68 | {
69 | "idiom" : "ipad",
70 | "scale" : "2x",
71 | "size" : "40x40"
72 | },
73 | {
74 | "idiom" : "ipad",
75 | "scale" : "1x",
76 | "size" : "76x76"
77 | },
78 | {
79 | "idiom" : "ipad",
80 | "scale" : "2x",
81 | "size" : "76x76"
82 | },
83 | {
84 | "idiom" : "ipad",
85 | "scale" : "2x",
86 | "size" : "83.5x83.5"
87 | },
88 | {
89 | "idiom" : "ios-marketing",
90 | "scale" : "1x",
91 | "size" : "1024x1024"
92 | }
93 | ],
94 | "info" : {
95 | "author" : "xcode",
96 | "version" : 1
97 | }
98 | }
99 |
--------------------------------------------------------------------------------
/iOS/Typing/Assets.xcassets/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "info" : {
3 | "author" : "xcode",
4 | "version" : 1
5 | }
6 | }
7 |
--------------------------------------------------------------------------------
/iOS/Typing/Assets.xcassets/background.imageset/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "images" : [
3 | {
4 | "filename" : "background.png",
5 | "idiom" : "universal",
6 | "scale" : "1x"
7 | },
8 | {
9 | "idiom" : "universal",
10 | "scale" : "2x"
11 | },
12 | {
13 | "idiom" : "universal",
14 | "scale" : "3x"
15 | }
16 | ],
17 | "info" : {
18 | "author" : "xcode",
19 | "version" : 1
20 | }
21 | }
22 |
--------------------------------------------------------------------------------
/iOS/Typing/Assets.xcassets/background.imageset/background.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/AgoraIO-Community/typing/bf5c90400321f2fc1673ae72f80621152e7e7e75/iOS/Typing/Assets.xcassets/background.imageset/background.png
--------------------------------------------------------------------------------
/iOS/Typing/Base/Logger.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Logger.swift
3 | // OpenChat
4 | //
5 | // Created by XC on 2021/1/16.
6 | //
7 |
8 | import Foundation
9 |
10 | enum LogLevel {
11 | case info, warning, error
12 |
13 | var description: String {
14 | switch self {
15 | case .info: return "Info"
16 | case .warning: return "Warning"
17 | case .error: return "Error"
18 | }
19 | }
20 | }
21 |
22 | class Logger {
23 |
24 | fileprivate static let debug = true
25 |
26 | static func log(message: String, level: LogLevel) {
27 | if !debug && level != .error {
28 | return
29 | }
30 | print("\(level.description): \(message)")
31 | }
32 | }
33 |
--------------------------------------------------------------------------------
/iOS/Typing/Base/Message.swift:
--------------------------------------------------------------------------------
1 | //
2 | // TextMessage.swift
3 | // OpenChat
4 | //
5 | // Created by XC on 2021/1/21.
6 | //
7 |
8 | import Foundation
9 |
10 | enum MessageType {
11 | case text, vibrate
12 | }
13 |
14 | struct Message {
15 |
16 | let type: MessageType
17 | let data: String
18 |
19 | init(raw: String) {
20 | if raw.starts(with: "vibrate://") {
21 | type = .vibrate
22 | data = ""
23 | } else {
24 | type = .text
25 | if let regex = try? NSRegularExpression(pattern: "^text://", options: .anchorsMatchLines) {
26 | data = regex.stringByReplacingMatches(in: raw, options: NSRegularExpression.MatchingOptions(rawValue: 0), range: NSRange(location: 0, length: raw.count), withTemplate: "")
27 | } else {
28 | data = raw
29 | }
30 | }
31 | }
32 |
33 | fileprivate init(type: MessageType, data: String) {
34 | self.type = type
35 | self.data = data
36 | }
37 |
38 | func toString() -> String {
39 | switch type {
40 | case .text:
41 | return "text://\(data)"
42 | case .vibrate:
43 | return "vibrate://\(data)"
44 | }
45 | }
46 |
47 | static func text(raw: String) -> Message {
48 | return Message(type: .text, data: raw)
49 | }
50 |
51 | static func vibrate() -> Message {
52 | return Message(type: .vibrate, data: "")
53 | }
54 | }
55 |
--------------------------------------------------------------------------------
/iOS/Typing/Base/Service.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Service.swift
3 | // OpenChat
4 | //
5 | // Created by XC on 2021/1/16.
6 | //
7 |
8 | import Foundation
9 | import Combine
10 | import AgoraRtmKit
11 |
12 | struct Result {
13 | var success: Bool
14 | var data: T?
15 | var message: String?
16 | }
17 |
18 | class PeerOnlineStatusPublisher: ObservableObject {
19 | @Published var value: Result?
20 | let peerId: String
21 |
22 | init(peerId: String) {
23 | self.peerId = peerId
24 | }
25 |
26 | func onChanged(status: AgoraRtmPeerOnlineStatus) {
27 | Logger.log(message: "onChanged peerId:\(status.peerId) status:\(status.isOnline)", level: .info)
28 | self.value = Result(success: true, data: status.isOnline)
29 | }
30 |
31 | func onError(error: AgoraRtmPeerSubscriptionStatusErrorCode) {
32 | if error != .AgoraRtmPeerSubscriptionStatusErrorOk {
33 | Logger.log(message: "PeerOnlineStatusPublisher onError:\(error.description())", level: .error)
34 | self.value = Result(success: false, message: error.description())
35 | }
36 | }
37 | }
38 |
39 | class PeerMessagePublisher: ObservableObject {
40 | @Published var message: Result?
41 | let peerId: String
42 |
43 | init(peerId: String) {
44 | self.peerId = peerId
45 | }
46 |
47 | func messageReceived(message: AgoraRtmMessage) {
48 | if message.type == .text {
49 | Logger.log(message: "messageReceived \(message.text)", level: .info)
50 | self.message = Result(success: true, data: message)
51 | }
52 | }
53 | }
54 |
55 | protocol Service {
56 | func login(user: String) -> AnyPublisher, Never>
57 | func logout() -> AnyPublisher, Never>
58 | func subscribeUserOnlineState(user: String) -> PeerOnlineStatusPublisher
59 | func unsubscribeUserOnlineState(publisher: PeerOnlineStatusPublisher) -> Void
60 | func sendMessage(message: Message, toUser: String) -> AnyPublisher, Never>
61 | func subscribeFriendMessage(user: String) -> PeerMessagePublisher
62 | func unsubscribeFriendMessage(publisher: PeerMessagePublisher) -> Void
63 | }
64 |
--------------------------------------------------------------------------------
/iOS/Typing/Component/ChatTextField.swift:
--------------------------------------------------------------------------------
1 | //
2 | // ChatTextField.swift
3 | // OpenChat
4 | //
5 | // Created by XC on 2021/1/21.
6 | //
7 |
8 | import SwiftUI
9 |
10 | struct ChatTextField: UIViewRepresentable {
11 | @Binding var text: String
12 | @Binding var height: CGFloat
13 | var onFinish: (() -> Void)?
14 |
15 | func makeUIView(context: Context) -> UITextView {
16 | let textView = UITextView()
17 |
18 | textView.isScrollEnabled = true
19 | textView.alwaysBounceVertical = true
20 | textView.alwaysBounceHorizontal = true
21 | textView.isEditable = true
22 | textView.isUserInteractionEnabled = true
23 |
24 | textView.text = text
25 | textView.backgroundColor = UIColor.clear
26 |
27 | context.coordinator.textView = textView
28 | textView.delegate = context.coordinator
29 | textView.layoutManager.delegate = context.coordinator
30 |
31 | textView.font = UIFont.preferredFont(forTextStyle: UIFont.TextStyle.title1)
32 | textView.textColor = .black
33 | textView.textAlignment = .center
34 | textView.returnKeyType = .continue
35 |
36 | return textView
37 | }
38 |
39 | func updateUIView(_ uiView: UITextView, context: Context) {
40 | uiView.text = text
41 | uiView.becomeFirstResponder()
42 | }
43 |
44 | func makeCoordinator() -> Coordinator {
45 | return Coordinator(dynamicSizeTextField: self)
46 | }
47 | }
48 |
49 | class Coordinator: NSObject, UITextViewDelegate, NSLayoutManagerDelegate {
50 |
51 | var textField: ChatTextField
52 |
53 | weak var textView: UITextView?
54 |
55 | init(dynamicSizeTextField: ChatTextField) {
56 | self.textField = dynamicSizeTextField
57 | }
58 |
59 | func textViewDidChange(_ textView: UITextView) {
60 | self.textField.text = textView.text
61 | }
62 |
63 | func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
64 | if (text == "\n") {
65 | if let onFinish = textField.onFinish {
66 | onFinish()
67 | }
68 | return false
69 | }
70 | return true
71 | }
72 |
73 | func layoutManager(_ layoutManager: NSLayoutManager, didCompleteLayoutFor textContainer: NSTextContainer?, atEnd layoutFinishedFlag: Bool) {
74 |
75 | DispatchQueue.main.async { [weak self] in
76 | guard let textView = self?.textView else {
77 | return
78 | }
79 | let size = textView.sizeThatFits(textView.bounds.size)
80 | if self?.textField.height != size.height {
81 | self?.textField.height = size.height
82 | }
83 | }
84 | }
85 | }
86 |
--------------------------------------------------------------------------------
/iOS/Typing/Component/InputView.swift:
--------------------------------------------------------------------------------
1 | //
2 | // InputView.swift
3 | // OpenChat
4 | //
5 | // Created by XC on 2021/1/14.
6 | //
7 |
8 | import SwiftUI
9 |
10 | struct InputView: View {
11 | let title: String
12 | let text: Binding
13 | var onCommit: (() -> Void)?
14 |
15 | var body: some View {
16 | TextField(title, text: text, onCommit: onCommit ?? {})
17 | .keyboardType(.default)
18 | .lineLimit(1)
19 | .overlay(VStack {
20 | Divider()
21 | .frame(height: 1.0)
22 | .background(Color.white)
23 | .offset(x: 0, y: 18)
24 | })
25 | .foregroundColor(.white)
26 | .padding(.top, 15)
27 | .padding(.bottom, 9)
28 | .font(.system(size: 18))
29 | }
30 | }
31 |
32 | struct InputViewStyle: TextFieldStyle {
33 | func _body(configuration: TextField<_Label>) -> some View {
34 | configuration
35 | .lineLimit(1)
36 | .autocapitalization(.none)
37 | .foregroundColor(.white)
38 | .padding(.top, 15)
39 | .padding(.bottom, 9)
40 | .font(.system(size: 18))
41 | .overlay(
42 | Rectangle()
43 | .fill(Color.white)
44 | .frame(height: 1)
45 | .offset(x: 0, y: 18)
46 | )
47 | }
48 | }
49 |
--------------------------------------------------------------------------------
/iOS/Typing/Component/KeyboardAdaptive.swift:
--------------------------------------------------------------------------------
1 | //
2 | // KeyboardAdaptive.swift
3 | // OpenChat
4 | //
5 | // Created by XC on 2021/1/15.
6 | //
7 |
8 | import Foundation
9 | import Combine
10 | import SwiftUI
11 |
12 | extension Notification {
13 | var keyboardHeight: CGFloat {
14 | return (userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect)?.height ?? 0
15 | }
16 | }
17 |
18 | extension Publishers {
19 | static var keyboardHeight: AnyPublisher {
20 | let willShow = NotificationCenter.default.publisher(for: UIApplication.keyboardWillShowNotification).map { $0.keyboardHeight }
21 | let willHide = NotificationCenter.default.publisher(for: UIApplication.keyboardWillHideNotification).map { _ in CGFloat(0) }
22 | return MergeMany(willShow, willHide).eraseToAnyPublisher()
23 | }
24 | }
25 |
26 | extension UIResponder {
27 | static var currentFirstResponder: UIResponder? {
28 | _currentFirstResponder = nil
29 | UIApplication.shared.sendAction(#selector(UIResponder.findFirstResponder(_:)), to: nil, from: nil, for: nil)
30 | return _currentFirstResponder
31 | }
32 |
33 | private static weak var _currentFirstResponder: UIResponder?
34 |
35 | @objc private func findFirstResponder(_ sender: Any) {
36 | UIResponder._currentFirstResponder = self
37 | }
38 |
39 | var globalFrame: CGRect? {
40 | guard let view = self as? UIView else { return nil }
41 | return view.superview?.convert(view.frame, to: nil)
42 | }
43 | }
44 |
45 | struct KeyboardAdaptive: ViewModifier {
46 | @State private var bottomPadding: CGFloat = 0
47 |
48 | func body(content: Content) -> some View {
49 | GeometryReader { geometry in
50 | content
51 | .padding(.bottom, self.bottomPadding)
52 | .onReceive(Publishers.keyboardHeight) { keyboardHeight in
53 | let keyboardTop = geometry.frame(in: .global).height - keyboardHeight
54 | let focusedTextInputBottom = UIResponder.currentFirstResponder?.globalFrame?.maxY ?? 0
55 | self.bottomPadding = max(0, focusedTextInputBottom - keyboardTop - geometry.safeAreaInsets.bottom)
56 | }
57 | .animation(.easeOut(duration: 0.16))
58 | }
59 | }
60 | }
61 |
62 | extension View {
63 | func keyboardAdaptive() -> some View {
64 | ModifiedContent(content: self, modifier: KeyboardAdaptive())
65 | }
66 | }
67 |
--------------------------------------------------------------------------------
/iOS/Typing/Component/RoundButton.swift:
--------------------------------------------------------------------------------
1 | //
2 | // RoundButton.swift
3 | // OpenChat
4 | //
5 | // Created by XC on 2021/1/14.
6 | //
7 |
8 | import SwiftUI
9 |
10 | struct RoundButton: View {
11 | let title: String
12 | let showProgress: Bool
13 | let action: () -> Void
14 |
15 | var body: some View {
16 | Button(action: action, label: {
17 | Spacer()
18 | if self.showProgress {
19 | ProgressView()
20 | .progressViewStyle(CircularProgressViewStyle(tint: .blue))
21 | } else {
22 | Text(title)
23 | .font(.system(size: 18))
24 | }
25 | Spacer()
26 | })
27 | .frame(width: .none, height: 26, alignment: .center)
28 | .padding(.vertical, 10)
29 | .foregroundColor(Color(hex: "#099dfd"))
30 | .background(Color.white)
31 | .cornerRadius(26)
32 | }
33 | }
34 |
35 | struct RoundButton_Previews: PreviewProvider {
36 | static var previews: some View {
37 | RoundButton(title: "test", showProgress: false) {
38 |
39 | }
40 | }
41 | }
42 |
--------------------------------------------------------------------------------
/iOS/Typing/Component/Shake.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Shake.swift
3 | // OpenChat
4 | //
5 | // Created by XC on 2021/1/21.
6 | //
7 |
8 | import SwiftUI
9 |
10 | struct Shake: GeometryEffect {
11 | var amount: CGFloat = 8
12 | var shakesPerUnit = 5
13 | var animatableData: CGFloat
14 |
15 | func effectValue(size: CGSize) -> ProjectionTransform {
16 | ProjectionTransform(CGAffineTransform(translationX:
17 | amount * sin(animatableData * .pi * CGFloat(shakesPerUnit)),
18 | y: 0))
19 | }
20 | }
21 |
--------------------------------------------------------------------------------
/iOS/Typing/Component/TouchDown.swift:
--------------------------------------------------------------------------------
1 | //
2 | // TouchDown.swift
3 | // OpenChat
4 | //
5 | // Created by XC on 2021/1/21.
6 | //
7 |
8 | import SwiftUI
9 |
10 | extension View {
11 | func onTouchDownGesture(callback: @escaping () -> Void) -> some View {
12 | modifier(OnTouchDownGestureModifier(callback: callback))
13 | }
14 | }
15 |
16 | private struct OnTouchDownGestureModifier: ViewModifier {
17 | @State private var tapped = false
18 | let callback: () -> Void
19 |
20 | func body(content: Content) -> some View {
21 | content
22 | .simultaneousGesture(DragGesture(minimumDistance: 0)
23 | .onChanged { _ in
24 | if !self.tapped {
25 | self.tapped = true
26 | self.callback()
27 | }
28 | }
29 | .onEnded { _ in
30 | self.tapped = false
31 | })
32 | }
33 | }
34 |
--------------------------------------------------------------------------------
/iOS/Typing/Extension.swift:
--------------------------------------------------------------------------------
1 | //
2 | // Extension.swift
3 | // OpenChat
4 | //
5 | // Created by XC on 2021/1/16.
6 | //
7 |
8 | import Foundation
9 | import SwiftUI
10 | import AgoraRtmKit
11 |
12 | extension Color {
13 | init(hex: String) {
14 | let hex = hex.trimmingCharacters(in: CharacterSet.alphanumerics.inverted)
15 | var int: UInt64 = 0
16 | Scanner(string: hex).scanHexInt64(&int)
17 | let a, r, g, b: UInt64
18 | switch hex.count {
19 | case 3: // RGB (12-bit)
20 | (a, r, g, b) = (255, (int >> 8) * 17, (int >> 4 & 0xF) * 17, (int & 0xF) * 17)
21 | case 6: // RGB (24-bit)
22 | (a, r, g, b) = (255, int >> 16, int >> 8 & 0xFF, int & 0xFF)
23 | case 8: // ARGB (32-bit)
24 | (a, r, g, b) = (int >> 24, int >> 16 & 0xFF, int >> 8 & 0xFF, int & 0xFF)
25 | default:
26 | (a, r, g, b) = (1, 1, 1, 0)
27 | }
28 | self.init(
29 | .sRGB,
30 | red: Double(r) / 255,
31 | green: Double(g) / 255,
32 | blue: Double(b) / 255,
33 | opacity: Double(a) / 255
34 | )
35 | }
36 | }
37 |
38 | extension AgoraRtmPeerSubscriptionStatusErrorCode {
39 | func description() -> String {
40 | switch self {
41 | case .AgoraRtmPeerSubscriptionStatusErrorOk:
42 | return "Ok"
43 | case .AgoraRtmPeerSubscriptionStatusErrorFailure:
44 | return "Failure"
45 | case .AgoraRtmPeerSubscriptionStatusErrorInvalidArgument:
46 | return "Invalid Argument"
47 | case .AgoraRtmPeerSubscriptionStatusErrorRejected:
48 | return "Rejected"
49 | case .AgoraRtmPeerSubscriptionStatusErrorTimeout:
50 | return "Timeout"
51 | case .AgoraRtmPeerSubscriptionStatusErrorTooOften:
52 | return "TooOften"
53 | case .PEER_SUBSCRIPTION_STATUS_ERR_OVERFLOW:
54 | return "Overflow"
55 | case .AgoraRtmPeerSubscriptionStatusErrorNotInitialized:
56 | return "NotInitialized"
57 | case .AgoraRtmPeerSubscriptionStatusErrorNotLoggedIn:
58 | return "NotLoggedIn"
59 | default:
60 | return "Unknown Error"
61 | }
62 | }
63 | }
64 |
65 | extension AgoraRtmSendPeerMessageErrorCode {
66 | func description() -> String {
67 | switch self {
68 | case .ok:
69 | return "Ok"
70 | case .failure:
71 | return "Failure"
72 | case .timeout:
73 | return "Timeout"
74 | case .peerUnreachable:
75 | return "Unreachable"
76 | case .cachedByServer:
77 | return "CachedByServer"
78 | case .tooOften:
79 | return "TooOften"
80 | case .invalidUserId:
81 | return "InvalidUserId"
82 | case .invalidMessage:
83 | return "InvalidMessage"
84 | case .notInitialized:
85 | return "NotInitialized"
86 | case .notLoggedIn:
87 | return "NotLoggedIn"
88 | default:
89 | return "Unknown Error"
90 | }
91 | }
92 | }
93 | extension AgoraRtmConnectionState {
94 | func description() -> String {
95 | switch self {
96 | case .disconnected:
97 | return "Disconnected"
98 | case .connecting:
99 | return "Connecting"
100 | case .connected:
101 | return "Connected"
102 | case .reconnecting:
103 | return "Reconnecting"
104 | case .aborted:
105 | return "Aborted"
106 | default:
107 | return "Unknown Error"
108 | }
109 | }
110 | }
111 |
--------------------------------------------------------------------------------
/iOS/Typing/Info.plist:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | CFBundleDevelopmentRegion
6 | $(DEVELOPMENT_LANGUAGE)
7 | CFBundleDisplayName
8 | Typing
9 | CFBundleExecutable
10 | $(EXECUTABLE_NAME)
11 | CFBundleIdentifier
12 | $(PRODUCT_BUNDLE_IDENTIFIER)
13 | CFBundleInfoDictionaryVersion
14 | 6.0
15 | CFBundleName
16 | $(PRODUCT_NAME)
17 | CFBundlePackageType
18 | $(PRODUCT_BUNDLE_PACKAGE_TYPE)
19 | CFBundleShortVersionString
20 | 1.0
21 | CFBundleVersion
22 | 1
23 | LSRequiresIPhoneOS
24 |
25 | UIApplicationSceneManifest
26 |
27 | UIApplicationSupportsMultipleScenes
28 |
29 |
30 | UIApplicationSupportsIndirectInputEvents
31 |
32 | UILaunchScreen
33 |
34 | UIRequiredDeviceCapabilities
35 |
36 | armv7
37 |
38 | UISupportedInterfaceOrientations
39 |
40 | UIInterfaceOrientationPortrait
41 | UIInterfaceOrientationLandscapeLeft
42 | UIInterfaceOrientationLandscapeRight
43 |
44 | UISupportedInterfaceOrientations~ipad
45 |
46 | UIInterfaceOrientationPortrait
47 | UIInterfaceOrientationPortraitUpsideDown
48 | UIInterfaceOrientationLandscapeLeft
49 | UIInterfaceOrientationLandscapeRight
50 |
51 |
52 |
53 |
--------------------------------------------------------------------------------
/iOS/Typing/KeyCenter.swift:
--------------------------------------------------------------------------------
1 | //
2 | // KeyCenter.swift
3 | // OpenChat
4 | //
5 | // Created by XC on 2021/1/15.
6 | //
7 |
8 | struct KeyCenter {
9 | static let AppId: String = <#Your App Id#>
10 |
11 | // assign token to nil if you have not enabled app certificate
12 | static var Token: String? = <#Temp Access Token#>
13 | }
14 |
15 |
--------------------------------------------------------------------------------
/iOS/Typing/Preview Content/Preview Assets.xcassets/Contents.json:
--------------------------------------------------------------------------------
1 | {
2 | "info" : {
3 | "author" : "xcode",
4 | "version" : 1
5 | }
6 | }
7 |
--------------------------------------------------------------------------------
/iOS/Typing/Server/Server.swift:
--------------------------------------------------------------------------------
1 | //
2 | // File.swift
3 | // OpenChat
4 | //
5 | // Created by XC on 2021/1/15.
6 | //
7 |
8 | import Combine
9 | import Foundation
10 | import AgoraRtmKit
11 |
12 | enum UserStatus {
13 | case online, offline
14 | }
15 |
16 | class User {
17 | let name: String
18 | var status: UserStatus = .offline
19 |
20 | init(name: String) {
21 | self.name = name
22 | }
23 | }
24 |
25 | class Server: NSObject {
26 | fileprivate static let instance = Server()
27 |
28 | static func shared() -> Service {
29 | return instance
30 | }
31 |
32 | fileprivate var agoraRtmKit = AgoraRtmKit(appId: KeyCenter.AppId, delegate: nil)
33 |
34 | fileprivate var account: User?
35 | var connectionState: AgoraRtmConnectionState = .disconnected
36 |
37 | fileprivate var peerOnlineStatusPublishers: [PeerOnlineStatusPublisher] = []
38 | fileprivate var peerMessagePublishers: [PeerMessagePublisher] = []
39 | }
40 |
41 | extension Server: Service {
42 | func login(user: String) -> AnyPublisher, Never> {
43 | agoraRtmKit?.agoraRtmDelegate = self
44 | var needLogout = false
45 | if let account = self.account {
46 | if account.status == .online {
47 | if account.name == user {
48 | return Just(Result(success: true)).eraseToAnyPublisher()
49 | } else {
50 | needLogout = true
51 | }
52 | }
53 | }
54 | return Just(needLogout)
55 | .flatMap { need -> AnyPublisher, Never> in
56 | if need {
57 | return self.logout()
58 | } else {
59 | return Just(Result(success: true)).eraseToAnyPublisher()
60 | }
61 | }
62 | .flatMap { result in
63 | return Future() { promise in
64 | guard let kit = self.agoraRtmKit else {
65 | Logger.log(message: "AgoraRtmKit nil", level: .error)
66 | promise(.success(Result(success: false, message: "AgoraRtmKit nil")))
67 | return
68 | }
69 |
70 | Logger.log(message: "login with id:\(user)", level: .info)
71 | kit.login(byToken: KeyCenter.Token, user: user) { code in
72 | guard code == AgoraRtmLoginErrorCode.ok else {
73 | Logger.log(message: "login fail:\(code.rawValue)", level: .error)
74 | promise(.success(Result(success: false, message: "login fail:\(code.rawValue)")))
75 | return
76 | }
77 | self.account = User(name: user)
78 | self.account?.status = .online
79 | promise(.success(Result(success: true)))
80 | }
81 | }
82 | }.eraseToAnyPublisher()
83 | }
84 |
85 | func logout() -> AnyPublisher, Never> {
86 | return Future() { promise in
87 | guard let kit = self.agoraRtmKit else {
88 | Logger.log(message: "AgoraRtmKit nil", level: .error)
89 | promise(.success(Result(success: false, message: "AgoraRtmKit nil")))
90 | return
91 | }
92 | if let account = self.account {
93 | if account.status == .online {
94 | kit.logout { code in
95 | guard code == .ok else {
96 | Logger.log(message: "logout fail:\(code.rawValue)", level: .error)
97 | promise(.success(Result(success: false, message: "logout fail:\(code.rawValue)")))
98 | return
99 | }
100 | Logger.log(message: "\(account) logout success", level: .info)
101 | }
102 | }
103 | }
104 | self.account = nil
105 | promise(.success(Result(success: true)))
106 | }.eraseToAnyPublisher()
107 | }
108 |
109 | func subscribeUserOnlineState(user: String) -> PeerOnlineStatusPublisher {
110 | Logger.log(message: "subscribeUserOnlineState user:\(user)", level: .info)
111 | let find = peerOnlineStatusPublishers.first { publisher in
112 | publisher.peerId == user
113 | }
114 | let publisher = find ?? PeerOnlineStatusPublisher(peerId: user)
115 | if find == nil {
116 | peerOnlineStatusPublishers.append(publisher)
117 | }
118 | guard let kit = self.agoraRtmKit else {
119 | publisher.onError(error: .AgoraRtmPeerSubscriptionStatusErrorNotInitialized)
120 | return publisher
121 | }
122 | kit.subscribePeersOnlineStatus([user]) { error in
123 | publisher.onError(error: error)
124 | }
125 | return publisher
126 | }
127 |
128 | func unsubscribeUserOnlineState(publisher: PeerOnlineStatusPublisher) {
129 | Logger.log(message: "unsubscribeUserOnlineState user:\(publisher.peerId)", level: .info)
130 | let find = peerOnlineStatusPublishers.firstIndex { publisher in
131 | publisher.peerId == publisher.peerId
132 | }
133 | guard let index = find else {
134 | return
135 | }
136 | peerOnlineStatusPublishers.remove(at: index)
137 | }
138 |
139 | func sendMessage(message: Message, toUser: String) -> AnyPublisher, Never> {
140 | Logger.log(message: "sendMessage message:\(message.toString())", level: .info)
141 | return Future() { promise in
142 | guard let kit = self.agoraRtmKit else {
143 | Logger.log(message: "AgoraRtmKit nil", level: .error)
144 | promise(.success(Result(success: false, message: "AgoraRtmKit nil")))
145 | return
146 | }
147 | let rtmMessage = AgoraRtmMessage(text: message.toString())
148 | let find = self.peerOnlineStatusPublishers.first { publisher in
149 | publisher.peerId == toUser
150 | }
151 | let isOnline = find?.value?.data ?? false
152 | let option = AgoraRtmSendMessageOptions()
153 | option.enableOfflineMessaging = !isOnline
154 |
155 | kit.send(rtmMessage, toPeer: toUser, sendMessageOptions: option) { code in
156 | if code == .ok {
157 | promise(.success(Result(success: true)))
158 | } else {
159 | promise(.success(Result(success: false, data: code, message: code.description())))
160 | }
161 | }
162 | }.eraseToAnyPublisher()
163 | }
164 |
165 | func subscribeFriendMessage(user: String) -> PeerMessagePublisher {
166 | Logger.log(message: "subscribeFriendMessage user:\(user)", level: .info)
167 | let find = peerMessagePublishers.first { publisher in
168 | publisher.peerId == user
169 | }
170 | let publisher = find ?? PeerMessagePublisher(peerId: user)
171 | if find == nil {
172 | peerMessagePublishers.append(publisher)
173 | }
174 | return publisher
175 | }
176 |
177 | func unsubscribeFriendMessage(publisher: PeerMessagePublisher) {
178 | Logger.log(message: "unsubscribeFriendMessage user:\(publisher.peerId)", level: .info)
179 | let find = peerMessagePublishers.firstIndex { publisher in
180 | publisher.peerId == publisher.peerId
181 | }
182 | guard let index = find else {
183 | return
184 | }
185 | peerMessagePublishers.remove(at: index)
186 | }
187 | }
188 |
189 | extension Server: AgoraRtmDelegate {
190 | func rtmKit(_ kit: AgoraRtmKit, peersOnlineStatusChanged onlineStatus: [AgoraRtmPeerOnlineStatus]) {
191 | Logger.log(message: "peersOnlineStatusChanged", level: .info)
192 | self.peerOnlineStatusPublishers.forEach { handler in
193 | let status = onlineStatus.first { peerOnlineStatus in
194 | return peerOnlineStatus.peerId == handler.peerId
195 | }
196 | if status != nil {
197 | handler.onChanged(status: status!)
198 | }
199 | }
200 | }
201 |
202 | func rtmKit(_ kit: AgoraRtmKit, connectionStateChanged state: AgoraRtmConnectionState, reason: AgoraRtmConnectionChangeReason) {
203 | Logger.log(message: "connectionStateChanged \(state.description())", level: .info)
204 | self.connectionState = state
205 | }
206 |
207 | func rtmKit(_ kit: AgoraRtmKit, messageReceived message: AgoraRtmMessage, fromPeer peerId: String) {
208 | Logger.log(message: "messageReceived \(message.text)", level: .info)
209 | let all = self.peerMessagePublishers.filter { publisher in
210 | return publisher.peerId == peerId
211 | }
212 | all.forEach { publisher in
213 | publisher.messageReceived(message: message)
214 | }
215 | }
216 | }
217 |
--------------------------------------------------------------------------------
/iOS/Typing/Typing.entitlements:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | com.apple.security.app-sandbox
6 |
7 | com.apple.security.network.client
8 |
9 |
10 |
11 |
--------------------------------------------------------------------------------
/iOS/Typing/TypingApp.swift:
--------------------------------------------------------------------------------
1 | //
2 | // OpenChatApp.swift
3 | // OpenChat
4 | //
5 | // Created by XC on 2021/1/14.
6 | //
7 |
8 | import SwiftUI
9 |
10 | @main
11 | struct TypingApp: App {
12 | @ObservedObject var model: LoginModel = LoginModel()
13 | var body: some Scene {
14 | WindowGroup {
15 | LoginView().environmentObject(model)
16 | }
17 | }
18 | }
19 |
--------------------------------------------------------------------------------
/iOS/Typing/View/Chat/ChatModel.swift:
--------------------------------------------------------------------------------
1 | //
2 | // ChatModel.swift
3 | // OpenChat
4 | //
5 | // Created by XC on 2021/1/14.
6 | //
7 | import Foundation
8 | import Combine
9 | import AudioToolbox
10 | import SwiftUI
11 |
12 | class ChatModel: ObservableObject {
13 |
14 | @Published var inputMessage = ""
15 | @Published var receivedMessage = ""
16 | @Published var isFriendOnline = false
17 | @Published var onTouch = false
18 | @Published var showingPopup = false
19 | @Published var friendAnimation: Int = 0
20 | @Published var userAnimation: Int = 0
21 |
22 | var message = ""
23 | func showToast(message: String) {
24 | self.message = message
25 | self.showingPopup = true
26 | }
27 |
28 | private var messagePublisher: PeerMessagePublisher?
29 | private var friendStatusPublisher: PeerOnlineStatusPublisher?
30 | private var disposables = Set()
31 |
32 | func onAppearWithFriend(name: String) {
33 | Logger.log(message: "onAppearWithFriend \(name)", level: .info)
34 | let inputScheduler: DispatchQueue = DispatchQueue(label: "input")
35 | let outputScheduler: DispatchQueue = DispatchQueue(label: "output")
36 |
37 | messagePublisher = Server.shared().subscribeFriendMessage(user: name)
38 | messagePublisher?
39 | .objectWillChange
40 | .subscribe(on: outputScheduler)
41 | .receive(on: RunLoop.main)
42 | .map { data in
43 | Message(raw: self.messagePublisher?.message?.data?.text ?? "")
44 | }
45 | .sink { message in
46 | switch message.type {
47 | case .text:
48 | self.receivedMessage = message.data
49 | case .vibrate:
50 | self.vibrate()
51 | }
52 | }
53 | .store(in: &disposables)
54 | friendStatusPublisher = Server.shared().subscribeUserOnlineState(user: name)
55 | friendStatusPublisher?
56 | .objectWillChange
57 | .subscribe(on: outputScheduler)
58 | .receive(on: RunLoop.main)
59 | .sink { data in
60 | self.isFriendOnline = self.friendStatusPublisher?.value?.data ?? false
61 | }
62 | .store(in: &disposables)
63 | $inputMessage
64 | .dropFirst(1)
65 | .debounce(for: .seconds(0.05), scheduler: inputScheduler)
66 | .flatMap({ value in
67 | Server.shared().sendMessage(message: Message.text(raw: value), toUser: name)
68 | })
69 | .filter { result in
70 | result.data != .cachedByServer
71 | }
72 | .subscribe(on: inputScheduler)
73 | .receive(on: RunLoop.main)
74 | .sink { result in
75 | if !result.success {
76 | self.showToast(message: result.message ?? "unknown error!")
77 | }
78 | }
79 | .store(in: &disposables)
80 | $onTouch
81 | .dropFirst(1)
82 | .debounce(for: .seconds(0.2), scheduler: inputScheduler)
83 | .flatMap({ _ in
84 | Server.shared().sendMessage(message: Message.vibrate(), toUser: name)
85 | })
86 | .filter { result in
87 | result.data != .cachedByServer
88 | }
89 | .subscribe(on: inputScheduler)
90 | .receive(on: RunLoop.main)
91 | .sink { result in
92 | if !result.success {
93 | self.showToast(message: result.message ?? "unknown error!")
94 | }
95 | }
96 | .store(in: &disposables)
97 | }
98 |
99 | func touchAction() {
100 | onTouch = !onTouch
101 | withAnimation(.default) {
102 | self.friendAnimation += 1
103 | }
104 | }
105 |
106 | func onFinish() {
107 | inputMessage = ""
108 | }
109 |
110 | func onDisappear() {
111 | disposables.forEach { cancellable in
112 | cancellable.cancel()
113 | }
114 | disposables.removeAll()
115 | guard let publisher = messagePublisher else {
116 | return
117 | }
118 | Server.shared().unsubscribeFriendMessage(publisher: publisher)
119 | guard let statusPublisher = friendStatusPublisher else {
120 | return
121 | }
122 | Server.shared().unsubscribeUserOnlineState(publisher: statusPublisher)
123 | _ = Server.shared().logout()
124 | }
125 |
126 | func vibrate() {
127 | withAnimation(.default) {
128 | self.userAnimation += 1
129 | }
130 | AudioServicesPlaySystemSound(1521);
131 | }
132 | }
133 |
--------------------------------------------------------------------------------
/iOS/Typing/View/Chat/ChatView.swift:
--------------------------------------------------------------------------------
1 | //
2 | // ChatView.swift
3 | // OpenChat
4 | //
5 | // Created by XC on 2021/1/14.
6 | //
7 |
8 | import SwiftUI
9 | import Combine
10 |
11 | struct ChatView: View {
12 |
13 | @State var autoFocus = true
14 | @State var textHeight: CGFloat = 50
15 | @ObservedObject var model = ChatModel()
16 | @EnvironmentObject var loginModel: LoginModel
17 |
18 | var body: some View {
19 | GeometryReader { proxy in
20 | let padding: CGFloat = 15
21 | let width = proxy.size.width - padding * 2
22 | let height = (proxy.size.height - padding * 2) / 2
23 | let offsetX = width / 2 - 10
24 | let offsetY = 10 - height / 2
25 |
26 | VStack(spacing: padding) {
27 | ZStack {
28 | VStack {
29 | Text(model.receivedMessage)
30 | .frame(alignment: .center)
31 | .padding(10)
32 | .font(.title)
33 | .foregroundColor(.black)
34 | .multilineTextAlignment(.center)
35 | }.frame(width: width, height: height,
36 | alignment: .center
37 | ).background(Color(hex: "#dfdfdf"))
38 | .cornerRadius(30)
39 | .padding(.horizontal, padding)
40 | if model.isFriendOnline {
41 | Circle()
42 | .fill(Color(hex: "#00ff00"))
43 | .frame(width: 20, height: 20)
44 | .offset(x: offsetX, y: offsetY)
45 | } else {
46 | Circle()
47 | .fill(Color.gray)
48 | .frame(width: 20, height: 20)
49 | .offset(x: offsetX, y: offsetY)
50 | }
51 | }
52 | .modifier(Shake(animatableData: CGFloat(model.friendAnimation)))
53 | .onTouchDownGesture {
54 | model.touchAction()
55 | }
56 | ZStack {
57 | if model.inputMessage.isEmpty {
58 | Text("type something")
59 | .font(.title)
60 | .foregroundColor(.gray)
61 | }
62 | ZStack {
63 | ChatTextField(text: $model.inputMessage, height: $textHeight, onFinish: model.onFinish)
64 | .padding(15)
65 | }
66 | .frame(width: width, height: textHeight + 30, alignment: .center)
67 | }
68 | .frame(width: width, height: height, alignment: .center)
69 | .background(Color(hex: "#dfdfdf"))
70 | .cornerRadius(30)
71 | .padding(.horizontal, padding)
72 | .modifier(Shake(animatableData: CGFloat(model.userAnimation)))
73 | }
74 | .navigationTitle("chat(\(loginModel.friendName))")
75 | .onAppear {
76 | model.onAppearWithFriend(name: loginModel.friendName)
77 | }
78 | .onDisappear {
79 | model.onDisappear()
80 | }
81 | }.popup(isPresented: $model.showingPopup, type: .toast, position: .top, autohideIn: 2) {
82 | VStack {
83 | HStack {
84 | Text(model.message)
85 | .padding(.horizontal, 20)
86 | .foregroundColor(.white)
87 | }
88 | .frame(height: 60)
89 | .background(Color(hex: "#099dfd"))
90 | .cornerRadius(30.0)
91 | }.padding(.top, 50)
92 | }
93 | }
94 | }
95 |
96 | struct ChatView_Previews: PreviewProvider {
97 | static var previews: some View {
98 | ChatView().environmentObject(LoginModel())
99 | }
100 | }
101 |
--------------------------------------------------------------------------------
/iOS/Typing/View/Login/LoginModel.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LoginModel.swift
3 | // OpenChat
4 | //
5 | // Created by XC on 2021/1/14.
6 | //
7 |
8 | import SwiftUI
9 | import Combine
10 |
11 | class LoginModel: ObservableObject {
12 |
13 | @Published var userName = ""
14 | @Published var friendName = ""
15 | @Published var isConnecting = false
16 | @Published var isOnline = false
17 |
18 | @Published var showingPopup = false
19 | var message = ""
20 | func showToast(message: String) {
21 | self.message = message
22 | self.showingPopup = true
23 | }
24 |
25 | private var disposables = Set()
26 |
27 | func loginAction() {
28 | self.isConnecting = true
29 | login().sink(receiveCompletion: { _ in
30 | self.isConnecting = false
31 | }, receiveValue: { result in
32 | if result.success {
33 | self.isOnline = true
34 | } else {
35 | self.showToast(message: result.message ?? "unknown error!")
36 | }
37 | })
38 | .store(in: &disposables)
39 | }
40 |
41 | private func login() -> AnyPublisher, Never> {
42 | if self.userName.isEmpty || self.friendName.isEmpty {
43 | return Just(Result(success: false, message: "Input user's name or friend's name!")).eraseToAnyPublisher()
44 | } else {
45 | return Server.shared().login(user: userName)
46 | }
47 | }
48 |
49 | func onAppear() {
50 |
51 | }
52 |
53 | func onDisappear() {
54 | disposables.forEach { cancellable in
55 | cancellable.cancel()
56 | }
57 | disposables.removeAll()
58 | }
59 | }
60 |
--------------------------------------------------------------------------------
/iOS/Typing/View/Login/LoginView.swift:
--------------------------------------------------------------------------------
1 | //
2 | // LoginView.swift
3 | // OpenChat
4 | //
5 | // Created by XC on 2021/1/14.
6 | //
7 |
8 | import SwiftUI
9 | import Combine
10 | import ExytePopupView
11 |
12 | struct LoginView: View {
13 | @EnvironmentObject var model: LoginModel
14 | var body: some View {
15 | NavigationView {
16 | VStack {
17 | Text("Typing")
18 | .fontWeight(.bold)
19 | .foregroundColor(.white)
20 | .font(.system(size: 32))
21 | .multilineTextAlignment(.center)
22 | .offset(x: 0, y: -30)
23 | TextField("Your Name", text: $model.userName)
24 | .textFieldStyle(InputViewStyle())
25 | .textContentType(.nickname)
26 | .padding(.horizontal, 30)
27 | .disabled(model.isConnecting)
28 | TextField("Friend's Name", text: $model.friendName, onCommit: { model.loginAction() })
29 | .textFieldStyle(InputViewStyle())
30 | .textContentType(.nickname)
31 | .padding(.horizontal, 30)
32 | .disabled(model.isConnecting)
33 | NavigationLink(
34 | destination: ChatView().environmentObject(model),
35 | isActive: $model.isOnline) {
36 | EmptyView()
37 | }
38 | RoundButton(title: "GO", showProgress: model.isConnecting) { model.loginAction() }
39 | .disabled(model.isConnecting)
40 | .padding(.horizontal, 30)
41 | .offset(x: 0, y: 30)
42 | Spacer()
43 | }
44 | .keyboardAdaptive()
45 | .background(Image("background"))
46 | .onAppear {
47 | model.onAppear()
48 | }
49 | .onDisappear {
50 | model.onDisappear()
51 | }
52 | }
53 | .popup(isPresented: $model.showingPopup, type: .toast, position: .top, autohideIn: 2) {
54 | VStack {
55 | HStack {
56 | Text(model.message)
57 | .padding(.horizontal, 20)
58 | .foregroundColor(.white)
59 | }
60 | .frame(height: 60)
61 | .background(Color(hex: "#099dfd"))
62 | .cornerRadius(30.0)
63 | }.padding(.top, 50)
64 | }
65 | }
66 | }
67 |
68 | struct LoginView_Previews: PreviewProvider {
69 | static var previews: some View {
70 | LoginView().environmentObject(LoginModel())
71 | }
72 | }
73 |
--------------------------------------------------------------------------------