[
  {
    "path": ".gitignore",
    "content": "*.iml\n.gradle\n/local.properties\n/.idea\n/.idea/navEditor.xml\n/.idea/assetWizardSettings.xml\n.DS_Store\n/build\n/captures\n.externalNativeBuild\n.cxx\n/.idea/\n\nmobile/\\.idea/caches/\n\nmobile/\\.idea/libraries/\n\nmobile/\\.idea/\n"
  },
  {
    "path": "README.md",
    "content": "# WebRTC for Android\n\nThis repo serves as a how-to guide for implementing basic video conferencing with WebRTC. It includes:\n\n- An Android mobile app\n- A bare-bones signalling server based on WebSocket built with Ktor.\n\nIt's based on official WebRTC native library version **`1.0.27771`**\n\n---\n## What is WebRTC\n\nThe [official](https://webrtc.org/) description \n\n\"WebRTC is a free, open project that provides browsers and mobile applications with Real-Time Communications (RTC) capabilities via simple APIs. The WebRTC components have been optimised to best serve this purpose.\"\n\n\nSimply, it's a cross-platform API that allows developers to implement peer-to-peer real-time communication. \n\nImagine an API that allows you to send voice, video and/or data (text, images...etc) across mobile apps and web apps. \n\n---\n## How does it work (The simple version)\n\nYou have a signalling server that coordinates the initiation of the communication. Once the peer-to-peer connection is established, the signalling server is out of the equation.\n\n![Simple Signalling architecture](./docs/simple_arch.png \"Simple Signalling architecture\")\n\n(A) prepares what's called SDP - [Session Description Protocol](https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Protocols#SDP) - which we will call \"offer\". \n\n(A) sends this offer to the signalling server to request to be connected to (B).\n\nThe signalling server then sends this \"offer\" to (B).\n\n(B) receives the offer and it will create an SDP of its own and send it back to the signalling server. We will call it \"answer\". \n\nThe signalling server then send this \"answer\" to (A).\n\nA peer-to-peer connection is then created to exchange data.\n\nIt's not magic. Something really important is happening is the background, both (A) &amp; (B) are also exchanging public IP addresses. This is done through ICE - [Interactive Connectivity Establishment](https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Protocols#ICE) - which uses a 3rd party server to fetch the public IP address. Those servers are known as [STUN](https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Protocols#STUN) or [TURN](https://developer.mozilla.org/en-US/docs/Web/API/WebRTC_API/Protocols#TURN).\n\n![ICE exchange](./docs/ice.png \"ICE exchange\")\n\n(A) starts sending \"ICE packets\" from the moment it creates the \"offer\". Similarly, (B) starts sending the \"answer\".\n\n---\n\n## Getting a local video stream\n\n*Branch [step/local-video](https://github.com/amrfarid140/webrtc-android-codelab/tree/step/local-video)*\n\nLet's label the device we are working on as a \"Peer\". We need to setup its connection to start communication. \n\nWebRTC library has `PeerConnectionFactory` that creates the `PeerConnection` for you. However, we need to `initialize` and `configure` this factory first.\n\n### Initialising `PeerConnectionFactory`\n\nFirst we need to say that we need to trace what's happening in the background then specify which features we want the Native library to turn on. In our case we want `H264` video format.\n\n```java\nval options = PeerConnectionFactory.InitializationOptions.builder(context)\n            .setEnableInternalTracer(true)\n            .setFieldTrials(\"WebRTC-H264HighProfile/Enabled/\")\n            .createInitializationOptions()\n        PeerConnectionFactory.initialize(options)\n```\n\n### Configuring `PeerConnectionFactory`\n\nNow we can use `PeerConnectionFactory.Builder` to build an instance of `PeerConnectionFactory`.\n\nWhen building `PeerConnectionFactory` it's crucial to specify the video codecs you are using. In this sample, we will be using the default video codecs. In addition, we will be disabling encryption.\n\n```java\nval rootEglBase: EglBase = EglBase.create()\nPeerConnectionFactory\n            .builder()\n            .setVideoDecoderFactory(DefaultVideoDecoderFactory(rootEglBase.eglBaseContext))\n            .setVideoEncoderFactory(DefaultVideoEncoderFactory(rootEglBase.eglBaseContext, true, true))\n            .setOptions(PeerConnectionFactory.Options().apply {\n                disableEncryption = true\n                disableNetworkMonitor = true\n            })\n            .createPeerConnectionFactory()\n```\n\n### Setting the video output\n\nNative WebRTC library relies on `SurfaceViewRenderer` view to output the video data. It's a `SurfaceView` that is setup to work will the callbacks of other WebRTC functionalities.\n\n```xml\n<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n    xmlns:tools=\"http://schemas.android.com/tools\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    tools:context=\".MainActivity\">\n\n    <org.webrtc.SurfaceViewRenderer\n        android:id=\"@+id/local_view\"\n        android:layout_width=\"0dp\"\n        android:layout_height=\"0dp\"\n        app:layout_constraintBottom_toBottomOf=\"parent\"\n        app:layout_constraintEnd_toEndOf=\"parent\"\n        app:layout_constraintStart_toStartOf=\"parent\"\n        app:layout_constraintTop_toTopOf=\"parent\" />\n\n</androidx.constraintlayout.widget.ConstraintLayout>\n```\n\nWe will also need to mirror the video stream we are providing and enable hardware acceleration.\n\n```java\nlocal_view.setMirror(true)\nlocal_view.setEnableHardwareScaler(true)\nlocal_view.init(rootEglBase.eglBaseContext, null)\n```\n\n### Getting the video source\n\nThe video source is simply the camera. Native WebRTC library has this handy helper - `Camera2Enumerator` - which allows use to fetch the front facing camera.\n\n```java\nCamera2Enumerator(context).run {\n    deviceNames.find {\n        isFrontFacing(it)\n    }?.let {\n        createCapturer(it, null)\n    } ?: throw IllegalStateException()\n}\n```\n\nonce we have the front facing camera we can create a `VideoSource` from the `PeerConnectionFactory` and `VideoTrack` then we attached our `SurfaceViewRenderer` to the `VideoTrack`\n\n```java\n// isScreencast=false\nval localVideoSource = peerConnectionFactory.createVideoSource(false)\n\nval surfaceTextureHelper = SurfaceTextureHelper.create(Thread.currentThread().name, rootEglBase.eglBaseContext)\n(videoCapturer as VideoCapturer).initialize(surfaceTextureHelper, localVideoOutput.context, localVideoSource.capturerObserver)\n\n// width, height, frame per second\nvideoCapturer.startCapture(320, 240, 60)\n\nval localVideoTrack = peerConnectionFactory.createVideoTrack(LOCAL_TRACK_ID, localVideoSource)\n\nlocalVideoTrack.addSink(local_view)\n```\n\n---\n\n## What's in the signalling server\n*Branch [step/remote-video](https://github.com/amrfarid140/webrtc-android-codelab/tree/step/remote-video)*\n\nFor this sample our signalling server is just a `WebSocket` that forwards what it recieves. It's built using [Ktor](https://ktor.io/).\n\nThe preffered way to run the server is\n\n- Get IntelliJ Idea\n- Import `/server`\n- Open `Application.kt` \n- Run `fun main()`\n\nThis should run the server on port `8080`. You can change the port from `application.conf` file.\n\n[Ktor](https://ktor.io/) is also used as a client in the mobile app to send/receive data from `WebSocket`. \n\nCheckout this [file](https://github.com/amrfarid140/webrtc-android-codelab/blob/step/remote-video/mobile/app/src/main/java/me/amryousef/webrtc_demo/SignallingClient.kt) for implementation details.\n\n**Note that you will beed to change `HOST_ADDRESS` to match your IP address for your laptop**\n\n---\n\n## Creating `PeerConnection`\n\nThe `PeerConnection` is what creates the \"offer\" and/or \"answer\". It's also responsible for syncing up ICE packets with other peers. \n\nThat's why when creating the peer connection we pass an observer which will get ICE packets and the remote media stream (when ready). It also has other callbacks for the state of the peer connection but they are not our focus.\n\n```java\nval stunServer = listOf(\n        PeerConnection.IceServer.builder(\"stun:stun.l.google.com:19302\")\n            .createIceServer()\n)\n\nval observer = object: PeerConnection.Observer {\n    override fun onIceCandidate(p0: IceCandidate?) {\n        super.onIceCandidate(p0)\n        signallingClient.send(p0)\n        rtcClient.addIceCandidate(p0)\n    }\n\n    override fun onAddStream(p0: MediaStream?) {\n        super.onAddStream(p0)\n        p0?.videoTracks?.get(0)?.addSink(remote_view)\n    }\n}\npeerConnectionFactory.createPeerConnection(\n    stunServer,\n    observer\n)\n```\n\n---\n\n## Starting a call <a name=\"call\"></a>\n\n\nOnce you have a `PeerConnection` instance created, you can start a call by creating the offer and sending it to the signalling server.\n\nThere are two things you need when creating the \"offer\". First is your constraint which sets what are you offering. For example video \n\n```\nval constraints = MediaConstraints().apply {\n    mandatory.add(MediaConstraints.KeyValuePair(\"OfferToReceiveVideo\", \"true\"))\n}\n```\n\nYou also need SDP observer which get called when a session description is ready.  It's worthy to mention at this point that Native WebRTC library has a callback-based API.\n\n```\npeerConnection.createOffer(object : SdpObserver {\n    override fun onCreateSuccess(desc: SessionDescription?) {\n\n        setLocalDescription(object : SdpObserver {\n            override fun onSetFailure(p0: String?) {\n            }\n\n            override fun onSetSuccess() {\n            }\n\n            override fun onCreateSuccess(p0: SessionDescription?) {\n            }\n\n            override fun onCreateFailure(p0: String?) {\n            }\n        }, desc)\n    \n        //TODO(\"Send it to your signalling server via WebSocket or other ways\")\n    }\n}, constraints)\n```\n\nYou will also need to listen to your signalling server for responses. Once the other peer accepts the call, an \"answer\" SDP message is sent back via signalling server. Once you get this \"answer\", all you have to do is set it on the `PeerConnection`\n\n```java\n peerConnection?.setRemoteDescription(object : SdpObserver {\n            override fun onSetFailure(p0: String?) {\n            }\n\n            override fun onSetSuccess() {\n            }\n\n            override fun onCreateSuccess(p0: SessionDescription?) {\n            }\n\n            override fun onCreateFailure(p0: String?) {\n            }\n}, answerSdp)\n```\n\nHere's an [example](https://github.com/amrfarid140/webrtc-android-codelab/blob/65a22c1fc735cf00b42b4246148af8402089cbc7/mobile/app/src/main/java/me/amryousef/webrtc_demo/MainActivity.kt#L89) for the code sample.\n\n---\n\n## Accepting a call\n\nSimilar to [Making a call](#call), you will need `PeerConnection` created. You also need to be listening to SDP message received from your signalling server.\n\nOnce you get SDP message you like, and similar to [Making a call](#call), you will need to set your constraint.\n\n```\nval constraints = MediaConstraints().apply {\n    mandatory.add(MediaConstraints.KeyValuePair(\"OfferToReceiveVideo\", \"true\"))\n}\n```\n\nand you will have to set the remote SDP on your `PeerConnection`\n\n```java\n peerConnection?.setRemoteDescription(object : SdpObserver {\n            override fun onSetFailure(p0: String?) {\n            }\n\n            override fun onSetSuccess() {\n            }\n\n            override fun onCreateSuccess(p0: SessionDescription?) {\n            }\n\n            override fun onCreateFailure(p0: String?) {\n            }\n}, offerSdp)\n```\n\nThen create your SDP \"answer\" message \n\n```\npeerConnection.createAnswer(object : SdpObserver {\n    override fun onCreateSuccess(desc: SessionDescription?) {\n\n        setLocalDescription(object : SdpObserver {\n            override fun onSetFailure(p0: String?) {\n            }\n\n            override fun onSetSuccess() {\n            }\n\n            override fun onCreateSuccess(p0: SessionDescription?) {\n            }\n\n            override fun onCreateFailure(p0: String?) {\n            }\n        }, desc)\n    \n        //TODO(\"Send it to your signalling server via WebSocket or other ways\")\n    }\n}, constraints)\n```\n---\n\n## Running the sample\n\n\nFirst, You will need to checkout the [master branch](https://github.com/amrfarid140/webrtc-android-codelab/). There are two directories\n- mobile which contains a mobile app\n- server which contains a signalling server\n\nSecond, Open `server` in IntelliJ Idea and run the server. Make sure it's running on port 8080. \n\nThird, Open `mobile` in Android Studio then navigate to `SignallingClient`. You find `HOST_ADDRESS`, change its value with your local IP address. \n\nFinally, use Android studio to install the application on two different devices then click the \"call\" button from one of them. If all goes well, a voice call should've started for you.\n\n<!-- Here's me testing it out.\n\n\n![Caller](./docs/caller.gif)\n*\n![Receiver](./docs/receiver.gif) -->\n\n\n\n"
  },
  {
    "path": "mobile/app/.gitignore",
    "content": "/build\n"
  },
  {
    "path": "mobile/app/build.gradle",
    "content": "apply plugin: 'com.android.application'\n\napply plugin: 'kotlin-android'\n\napply plugin: 'kotlin-android-extensions'\n\nandroid {\n    compileSdkVersion 28\n    defaultConfig {\n        applicationId \"me.amryousef.webrtc_demo\"\n        minSdkVersion 23\n        targetSdkVersion 28\n        versionCode 1\n        versionName \"1.0\"\n        testInstrumentationRunner \"androidx.test.runner.AndroidJUnitRunner\"\n    }\n    buildTypes {\n        release {\n            minifyEnabled false\n            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'\n        }\n    }\n\n    packagingOptions {\n        exclude(\"META-INF/kotlinx-io.kotlin_module\")\n        exclude(\"META-INF/atomicfu.kotlin_module\")\n        exclude(\"META-INF/kotlinx-coroutines-io.kotlin_module\")\n        exclude(\"META-INF/kotlinx-coroutines-core.kotlin_module\")\n    }\n\n    compileOptions {\n        sourceCompatibility 1.8\n        targetCompatibility 1.8\n    }\n\n    kotlinOptions {\n        jvmTarget = JavaVersion.VERSION_1_8.toString()\n    }\n}\n\ndependencies {\n    implementation fileTree(dir: 'libs', include: ['*.jar'])\n    implementation \"org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version\"\n    implementation 'androidx.appcompat:appcompat:1.0.2'\n    implementation 'androidx.core:core-ktx:1.0.2'\n    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'\n    implementation 'com.google.android.material:material:1.1.0-alpha06'\n\n    //Ktor dependencies (you can retorfit instead)\n    implementation(\"io.ktor:ktor-client-android:$ktor_version\")\n    implementation(\"io.ktor:ktor-client-websocket:$ktor_version\")\n    implementation(\"io.ktor:ktor-client-cio:$ktor_version\")\n    implementation(\"io.ktor:ktor-client-gson:$ktor_version\")\n\n    implementation(\"org.jetbrains.kotlinx:kotlinx-coroutines-android:1.2.1\")\n\n    //WebRTC dependency\n    implementation(\"org.webrtc:google-webrtc:$webrtc_version\")\n\n    testImplementation 'junit:junit:4.12'\n    androidTestImplementation 'androidx.test.ext:junit:1.1.0'\n    androidTestImplementation 'androidx.test.espresso:espresso-core:3.1.1'\n}\n"
  },
  {
    "path": "mobile/app/proguard-rules.pro",
    "content": "# Add project specific ProGuard rules here.\n# You can control the set of applied configuration files using the\n# proguardFiles setting in build.gradle.\n#\n# For more details, see\n#   http://developer.android.com/guide/developing/tools/proguard.html\n\n# If your project uses WebView with JS, uncomment the following\n# and specify the fully qualified class name to the JavaScript interface\n# class:\n#-keepclassmembers class fqcn.of.javascript.interface.for.webview {\n#   public *;\n#}\n\n# Uncomment this to preserve the line number information for\n# debugging stack traces.\n#-keepattributes SourceFile,LineNumberTable\n\n# If you keep the line number information, uncomment this to\n# hide the original source file name.\n#-renamesourcefileattribute SourceFile\n"
  },
  {
    "path": "mobile/app/src/androidTest/java/me/amryousef/webrtc_demo/ExampleInstrumentedTest.kt",
    "content": "package me.amryousef.webrtc_demo\n\nimport androidx.test.platform.app.InstrumentationRegistry\nimport androidx.test.ext.junit.runners.AndroidJUnit4\n\nimport org.junit.Test\nimport org.junit.runner.RunWith\n\nimport org.junit.Assert.*\n\n/**\n * Instrumented test, which will execute on an Android device.\n *\n * See [testing documentation](http://d.android.com/tools/testing).\n */\n@RunWith(AndroidJUnit4::class)\nclass ExampleInstrumentedTest {\n    @Test\n    fun useAppContext() {\n        // Context of the app under test.\n        val appContext = InstrumentationRegistry.getInstrumentation().targetContext\n        assertEquals(\"me.amryousef.webrtc_demo\", appContext.packageName)\n    }\n}\n"
  },
  {
    "path": "mobile/app/src/main/AndroidManifest.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<manifest xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:tools=\"http://schemas.android.com/tools\"\n    package=\"me.amryousef.webrtc_demo\">\n\n    <uses-feature android:name=\"android.hardware.camera\" />\n    <uses-feature android:name=\"android.hardware.camera.autofocus\" />\n    <uses-feature\n        android:glEsVersion=\"0x00020000\"\n        android:required=\"true\" />\n\n    <uses-permission android:name=\"android.permission.INTERNET\"/>\n    <uses-permission android:name=\"android.permission.CAMERA\"/>\n\n    <uses-permission android:name=\"android.permission.MODIFY_AUDIO_SETTINGS\" />\n    <uses-permission android:name=\"android.permission.RECORD_AUDIO\" />\n\n    <application\n        android:allowBackup=\"true\"\n        android:icon=\"@mipmap/ic_launcher\"\n        android:label=\"@string/app_name\"\n        android:roundIcon=\"@mipmap/ic_launcher_round\"\n        android:supportsRtl=\"true\"\n        android:theme=\"@style/AppTheme\"\n        tools:ignore=\"AllowBackup,GoogleAppIndexingWarning\">\n        <activity android:name=\".MainActivity\">\n            <intent-filter>\n                <action android:name=\"android.intent.action.MAIN\" />\n\n                <category android:name=\"android.intent.category.LAUNCHER\" />\n            </intent-filter>\n        </activity>\n    </application>\n\n</manifest>"
  },
  {
    "path": "mobile/app/src/main/java/me/amryousef/webrtc_demo/AppSdpObserver.kt",
    "content": "package me.amryousef.webrtc_demo\n\nimport org.webrtc.SdpObserver\nimport org.webrtc.SessionDescription\n\nopen class AppSdpObserver : SdpObserver {\n    override fun onSetFailure(p0: String?) {\n    }\n\n    override fun onSetSuccess() {\n    }\n\n    override fun onCreateSuccess(p0: SessionDescription?) {\n    }\n\n    override fun onCreateFailure(p0: String?) {\n    }\n}"
  },
  {
    "path": "mobile/app/src/main/java/me/amryousef/webrtc_demo/MainActivity.kt",
    "content": "package me.amryousef.webrtc_demo\n\nimport android.Manifest\nimport android.content.Context\nimport android.content.pm.PackageManager\nimport android.media.AudioManager\nimport android.os.Bundle\nimport android.widget.Toast\nimport androidx.appcompat.app.AlertDialog\nimport androidx.appcompat.app.AppCompatActivity\nimport androidx.core.app.ActivityCompat\nimport androidx.core.content.ContextCompat\nimport androidx.core.view.isGone\nimport io.ktor.util.KtorExperimentalAPI\nimport kotlinx.android.synthetic.main.activity_main.call_button\nimport kotlinx.android.synthetic.main.activity_main.local_view\nimport kotlinx.android.synthetic.main.activity_main.remote_view\nimport kotlinx.android.synthetic.main.activity_main.remote_view_loading\nimport kotlinx.coroutines.ExperimentalCoroutinesApi\nimport org.webrtc.IceCandidate\nimport org.webrtc.MediaStream\nimport org.webrtc.SessionDescription\n\n@ExperimentalCoroutinesApi\n@KtorExperimentalAPI\nclass MainActivity : AppCompatActivity() {\n\n    companion object {\n        private const val CAMERA_PERMISSION_REQUEST_CODE = 1\n        private const val CAMERA_PERMISSION = Manifest.permission.CAMERA\n    }\n\n    private lateinit var rtcClient: RTCClient\n    private lateinit var signallingClient: SignallingClient\n\n    private val sdpObserver = object : AppSdpObserver() {\n        override fun onCreateSuccess(p0: SessionDescription?) {\n            super.onCreateSuccess(p0)\n            signallingClient.send(p0)\n        }\n    }\n\n    override fun onCreate(savedInstanceState: Bundle?) {\n        super.onCreate(savedInstanceState)\n        setContentView(R.layout.activity_main)\n        checkCameraPermission()\n    }\n\n    private fun checkCameraPermission() {\n        if (ContextCompat.checkSelfPermission(this, CAMERA_PERMISSION) != PackageManager.PERMISSION_GRANTED) {\n            requestCameraPermission()\n        } else {\n            onCameraPermissionGranted()\n        }\n    }\n\n    private fun onCameraPermissionGranted() {\n        rtcClient = RTCClient(\n            application,\n            object : PeerConnectionObserver() {\n                override fun onIceCandidate(p0: IceCandidate?) {\n                    super.onIceCandidate(p0)\n                    signallingClient.send(p0)\n                    rtcClient.addIceCandidate(p0)\n                }\n\n                override fun onAddStream(p0: MediaStream?) {\n                    super.onAddStream(p0)\n                    p0?.videoTracks?.get(0)?.addSink(remote_view)\n                }\n            }\n        )\n        rtcClient.initSurfaceView(remote_view)\n        rtcClient.initSurfaceView(local_view)\n        rtcClient.startLocalVideoCapture(local_view)\n        signallingClient = SignallingClient(createSignallingClientListener())\n        call_button.setOnClickListener { rtcClient.call(sdpObserver) }\n    }\n\n    private fun createSignallingClientListener() = object : SignallingClientListener {\n        override fun onConnectionEstablished() {\n            call_button.isClickable = true\n        }\n\n        override fun onOfferReceived(description: SessionDescription) {\n            rtcClient.onRemoteSessionReceived(description)\n            rtcClient.answer(sdpObserver)\n            (getSystemService(Context.AUDIO_SERVICE) as AudioManager).apply {\n                stopBluetoothSco()\n                isBluetoothScoOn = false\n                isSpeakerphoneOn = true\n            }\n            remote_view_loading.isGone = true\n        }\n\n        override fun onAnswerReceived(description: SessionDescription) {\n            rtcClient.onRemoteSessionReceived(description)\n            remote_view_loading.isGone = true\n        }\n\n        override fun onIceCandidateReceived(iceCandidate: IceCandidate) {\n            rtcClient.addIceCandidate(iceCandidate)\n        }\n    }\n\n    private fun requestCameraPermission(dialogShown: Boolean = false) {\n        if (ActivityCompat.shouldShowRequestPermissionRationale(this, CAMERA_PERMISSION) && !dialogShown) {\n            showPermissionRationaleDialog()\n        } else {\n            ActivityCompat.requestPermissions(this, arrayOf(CAMERA_PERMISSION), CAMERA_PERMISSION_REQUEST_CODE)\n        }\n    }\n\n    private fun showPermissionRationaleDialog() {\n        AlertDialog.Builder(this)\n            .setTitle(\"Camera Permission Required\")\n            .setMessage(\"This app need the camera to function\")\n            .setPositiveButton(\"Grant\") { dialog, _ ->\n                dialog.dismiss()\n                requestCameraPermission(true)\n            }\n            .setNegativeButton(\"Deny\") { dialog, _ ->\n                dialog.dismiss()\n                onCameraPermissionDenied()\n            }\n            .show()\n    }\n\n    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {\n        super.onRequestPermissionsResult(requestCode, permissions, grantResults)\n        if (requestCode == CAMERA_PERMISSION_REQUEST_CODE && grantResults.all { it == PackageManager.PERMISSION_GRANTED }) {\n            onCameraPermissionGranted()\n        } else {\n            onCameraPermissionDenied()\n        }\n    }\n\n    private fun onCameraPermissionDenied() {\n        Toast.makeText(this, \"Camera Permission Denied\", Toast.LENGTH_LONG).show()\n    }\n\n    override fun onDestroy() {\n        signallingClient.destroy()\n        super.onDestroy()\n    }\n}\n"
  },
  {
    "path": "mobile/app/src/main/java/me/amryousef/webrtc_demo/PeerConnectionObserver.kt",
    "content": "package me.amryousef.webrtc_demo\n\nimport org.webrtc.DataChannel\nimport org.webrtc.IceCandidate\nimport org.webrtc.MediaStream\nimport org.webrtc.PeerConnection\nimport org.webrtc.RtpReceiver\n\nopen class PeerConnectionObserver : PeerConnection.Observer {\n    override fun onIceCandidate(p0: IceCandidate?) {\n    }\n\n    override fun onDataChannel(p0: DataChannel?) {\n    }\n\n    override fun onIceConnectionReceivingChange(p0: Boolean) {\n    }\n\n    override fun onIceConnectionChange(p0: PeerConnection.IceConnectionState?) {\n    }\n\n    override fun onIceGatheringChange(p0: PeerConnection.IceGatheringState?) {\n    }\n\n    override fun onAddStream(p0: MediaStream?) {\n    }\n\n    override fun onSignalingChange(p0: PeerConnection.SignalingState?) {\n    }\n\n    override fun onIceCandidatesRemoved(p0: Array<out IceCandidate>?) {\n    }\n\n    override fun onRemoveStream(p0: MediaStream?) {\n    }\n\n    override fun onRenegotiationNeeded() {\n    }\n\n    override fun onAddTrack(p0: RtpReceiver?, p1: Array<out MediaStream>?) {\n    }\n}"
  },
  {
    "path": "mobile/app/src/main/java/me/amryousef/webrtc_demo/RTCClient.kt",
    "content": "package me.amryousef.webrtc_demo\n\nimport android.app.Application\nimport android.content.Context\nimport org.webrtc.*\nimport org.webrtc.voiceengine.WebRtcAudioUtils\n\nclass RTCClient(\n    context: Application,\n    observer: PeerConnection.Observer\n) {\n\n    companion object {\n        private const val LOCAL_TRACK_ID = \"local_track\"\n        private const val LOCAL_STREAM_ID = \"local_track\"\n    }\n\n    private val rootEglBase: EglBase = EglBase.create()\n\n    init {\n        initPeerConnectionFactory(context)\n    }\n\n    private val iceServer = listOf(\n        PeerConnection.IceServer.builder(\"stun:stun.l.google.com:19302\")\n            .createIceServer()\n    )\n\n    private val peerConnectionFactory by lazy { buildPeerConnectionFactory() }\n    private val videoCapturer by lazy { getVideoCapturer(context) }\n    private val localVideoSource by lazy { peerConnectionFactory.createVideoSource(false) }\n    private val peerConnection by lazy { buildPeerConnection(observer) }\n    private val constraints = MediaConstraints().apply {\n        mandatory.add(MediaConstraints.KeyValuePair(\"OfferToReceiveVideo\", \"true\"))\n        mandatory.add(MediaConstraints.KeyValuePair(\"OfferToReceiveAudio\", \"true\"))\n    }\n\n    private fun initPeerConnectionFactory(context: Application) {\n        val options = PeerConnectionFactory.InitializationOptions.builder(context)\n            .setEnableInternalTracer(true)\n            .setFieldTrials(\"WebRTC-H264HighProfile/Enabled/\")\n            .createInitializationOptions()\n        PeerConnectionFactory.initialize(options)\n    }\n\n    private fun buildPeerConnectionFactory(): PeerConnectionFactory {\n        return PeerConnectionFactory\n            .builder()\n            .setVideoDecoderFactory(DefaultVideoDecoderFactory(rootEglBase.eglBaseContext))\n            .setVideoEncoderFactory(DefaultVideoEncoderFactory(rootEglBase.eglBaseContext, true, true))\n            .setOptions(PeerConnectionFactory.Options().apply {\n                disableEncryption = true\n                disableNetworkMonitor = true\n            })\n            .createPeerConnectionFactory()\n    }\n\n    private fun buildPeerConnection(observer: PeerConnection.Observer) = peerConnectionFactory.createPeerConnection(\n        iceServer,\n        observer\n    )\n\n    private fun getVideoCapturer(context: Context) =\n        Camera2Enumerator(context).run {\n            deviceNames.find {\n                isFrontFacing(it)\n            }?.let {\n                createCapturer(it, null)\n            } ?: throw IllegalStateException()\n        }\n\n    fun initSurfaceView(view: SurfaceViewRenderer) = view.run {\n        setMirror(true)\n        setEnableHardwareScaler(true)\n        init(rootEglBase.eglBaseContext, null)\n    }\n\n    fun startLocalVideoCapture(localVideoOutput: SurfaceViewRenderer) {\n        val surfaceTextureHelper = SurfaceTextureHelper.create(Thread.currentThread().name, rootEglBase.eglBaseContext)\n        (videoCapturer as VideoCapturer).initialize(surfaceTextureHelper, localVideoOutput.context, localVideoSource.capturerObserver)\n        videoCapturer.startCapture(320, 240, 60)\n        val localVideoTrack = peerConnectionFactory.createVideoTrack(LOCAL_TRACK_ID, localVideoSource)\n        localVideoTrack.addSink(localVideoOutput)\n        val localStream = peerConnectionFactory.createLocalMediaStream(LOCAL_STREAM_ID)\n        localStream.addTrack(localVideoTrack)\n        val audioSource = peerConnectionFactory.createAudioSource(MediaConstraints())\n        val audioTrack = peerConnectionFactory.createAudioTrack(\"audio_track\", audioSource).apply {\n            setEnabled(true)\n            setVolume(100.0)\n        }\n        localStream.addTrack(audioTrack)\n        peerConnection?.addStream(localStream)\n    }\n\n    private fun PeerConnection.call(sdpObserver: SdpObserver) {\n        createOffer(object : SdpObserver by sdpObserver {\n            override fun onCreateSuccess(desc: SessionDescription?) {\n\n                setLocalDescription(object : SdpObserver {\n                    override fun onSetFailure(p0: String?) {\n                    }\n\n                    override fun onSetSuccess() {\n                    }\n\n                    override fun onCreateSuccess(p0: SessionDescription?) {\n                    }\n\n                    override fun onCreateFailure(p0: String?) {\n                    }\n                }, desc)\n                sdpObserver.onCreateSuccess(desc)\n            }\n        }, constraints)\n    }\n\n    private fun PeerConnection.answer(sdpObserver: SdpObserver) {\n        createAnswer(object : SdpObserver by sdpObserver {\n            override fun onCreateSuccess(p0: SessionDescription?) {\n                setLocalDescription(object : SdpObserver {\n                    override fun onSetFailure(p0: String?) {\n                    }\n\n                    override fun onSetSuccess() {\n                    }\n\n                    override fun onCreateSuccess(p0: SessionDescription?) {\n                    }\n\n                    override fun onCreateFailure(p0: String?) {\n                    }\n                }, p0)\n                sdpObserver.onCreateSuccess(p0)\n            }\n        }, constraints)\n    }\n\n    fun call(sdpObserver: SdpObserver) = peerConnection?.call(sdpObserver)\n\n    fun answer(sdpObserver: SdpObserver) = peerConnection?.answer(sdpObserver)\n\n    fun onRemoteSessionReceived(sessionDescription: SessionDescription) {\n        peerConnection?.setRemoteDescription(object : SdpObserver {\n            override fun onSetFailure(p0: String?) {\n            }\n\n            override fun onSetSuccess() {\n            }\n\n            override fun onCreateSuccess(p0: SessionDescription?) {\n            }\n\n            override fun onCreateFailure(p0: String?) {\n            }\n        }, sessionDescription)\n    }\n\n    fun addIceCandidate(iceCandidate: IceCandidate?) {\n        peerConnection?.addIceCandidate(iceCandidate)\n    }\n}"
  },
  {
    "path": "mobile/app/src/main/java/me/amryousef/webrtc_demo/SignallingClient.kt",
    "content": "package me.amryousef.webrtc_demo\n\nimport android.util.Log\nimport com.google.gson.Gson\nimport com.google.gson.JsonObject\nimport io.ktor.client.HttpClient\nimport io.ktor.client.engine.cio.CIO\nimport io.ktor.client.features.json.GsonSerializer\nimport io.ktor.client.features.json.JsonFeature\nimport io.ktor.client.features.websocket.WebSockets\nimport io.ktor.client.features.websocket.ws\nimport io.ktor.http.cio.websocket.Frame\nimport io.ktor.http.cio.websocket.readText\nimport io.ktor.util.KtorExperimentalAPI\nimport kotlinx.coroutines.CoroutineScope\nimport kotlinx.coroutines.Dispatchers\nimport kotlinx.coroutines.ExperimentalCoroutinesApi\nimport kotlinx.coroutines.Job\nimport kotlinx.coroutines.channels.ConflatedBroadcastChannel\nimport kotlinx.coroutines.launch\nimport kotlinx.coroutines.runBlocking\nimport kotlinx.coroutines.withContext\nimport org.webrtc.IceCandidate\nimport org.webrtc.SessionDescription\n\n@ExperimentalCoroutinesApi\n@KtorExperimentalAPI\nclass SignallingClient(\n    private val listener: SignallingClientListener\n) : CoroutineScope {\n\n    companion object {\n        private const val HOST_ADDRESS = \"192.168.0.12\"\n    }\n\n    private val job = Job()\n\n    private val gson = Gson()\n\n    override val coroutineContext = Dispatchers.IO + job\n\n    private val client = HttpClient(CIO) {\n        install(WebSockets)\n        install(JsonFeature) {\n            serializer = GsonSerializer()\n        }\n    }\n\n    private val sendChannel = ConflatedBroadcastChannel<String>()\n\n    init {\n        connect()\n    }\n\n    private fun connect() = launch {\n        client.ws(host = HOST_ADDRESS, port = 8080, path = \"/connect\") {\n            listener.onConnectionEstablished()\n            val sendData = sendChannel.openSubscription()\n            try {\n                while (true) {\n\n                    sendData.poll()?.let {\n                        Log.v(this@SignallingClient.javaClass.simpleName, \"Sending: $it\")\n                        outgoing.send(Frame.Text(it))\n                    }\n                    incoming.poll()?.let { frame ->\n                        if (frame is Frame.Text) {\n                            val data = frame.readText()\n                            Log.v(this@SignallingClient.javaClass.simpleName, \"Received: $data\")\n                            val jsonObject = gson.fromJson(data, JsonObject::class.java)\n                            withContext(Dispatchers.Main) {\n                                if (jsonObject.has(\"serverUrl\")) {\n                                    listener.onIceCandidateReceived(gson.fromJson(jsonObject, IceCandidate::class.java))\n                                } else if (jsonObject.has(\"type\") && jsonObject.get(\"type\").asString == \"OFFER\") {\n                                    listener.onOfferReceived(gson.fromJson(jsonObject, SessionDescription::class.java))\n                                } else if (jsonObject.has(\"type\") && jsonObject.get(\"type\").asString == \"ANSWER\") {\n                                    listener.onAnswerReceived(gson.fromJson(jsonObject, SessionDescription::class.java))\n                                }\n                            }\n                        }\n                    }\n                }\n            } catch (exception: Throwable) {\n                Log.e(\"asd\",\"asd\",exception)\n            }\n        }\n    }\n\n    fun send(dataObject: Any?) = runBlocking {\n        sendChannel.send(gson.toJson(dataObject))\n    }\n\n    fun destroy() {\n        client.close()\n        job.complete()\n    }\n}"
  },
  {
    "path": "mobile/app/src/main/java/me/amryousef/webrtc_demo/SignallingClientListener.kt",
    "content": "package me.amryousef.webrtc_demo\n\nimport org.webrtc.IceCandidate\nimport org.webrtc.SessionDescription\n\ninterface SignallingClientListener {\n    fun onConnectionEstablished()\n    fun onOfferReceived(description: SessionDescription)\n    fun onAnswerReceived(description: SessionDescription)\n    fun onIceCandidateReceived(iceCandidate: IceCandidate)\n}"
  },
  {
    "path": "mobile/app/src/main/res/drawable/ic_launcher_background.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<vector xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    android:width=\"108dp\"\n    android:height=\"108dp\"\n    android:viewportWidth=\"108\"\n    android:viewportHeight=\"108\">\n    <path\n        android:fillColor=\"#008577\"\n        android:pathData=\"M0,0h108v108h-108z\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M9,0L9,108\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M19,0L19,108\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M29,0L29,108\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M39,0L39,108\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M49,0L49,108\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M59,0L59,108\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M69,0L69,108\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M79,0L79,108\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M89,0L89,108\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M99,0L99,108\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M0,9L108,9\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M0,19L108,19\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M0,29L108,29\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M0,39L108,39\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M0,49L108,49\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M0,59L108,59\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M0,69L108,69\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M0,79L108,79\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M0,89L108,89\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M0,99L108,99\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M19,29L89,29\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M19,39L89,39\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M19,49L89,49\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M19,59L89,59\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M19,69L89,69\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M19,79L89,79\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M29,19L29,89\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M39,19L39,89\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M49,19L49,89\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M59,19L59,89\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M69,19L69,89\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n    <path\n        android:fillColor=\"#00000000\"\n        android:pathData=\"M79,19L79,89\"\n        android:strokeWidth=\"0.8\"\n        android:strokeColor=\"#33FFFFFF\" />\n</vector>\n"
  },
  {
    "path": "mobile/app/src/main/res/drawable-v24/ic_launcher_foreground.xml",
    "content": "<vector xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:aapt=\"http://schemas.android.com/aapt\"\n    android:width=\"108dp\"\n    android:height=\"108dp\"\n    android:viewportWidth=\"108\"\n    android:viewportHeight=\"108\">\n    <path\n        android:fillType=\"evenOdd\"\n        android:pathData=\"M32,64C32,64 38.39,52.99 44.13,50.95C51.37,48.37 70.14,49.57 70.14,49.57L108.26,87.69L108,109.01L75.97,107.97L32,64Z\"\n        android:strokeWidth=\"1\"\n        android:strokeColor=\"#00000000\">\n        <aapt:attr name=\"android:fillColor\">\n            <gradient\n                android:endX=\"78.5885\"\n                android:endY=\"90.9159\"\n                android:startX=\"48.7653\"\n                android:startY=\"61.0927\"\n                android:type=\"linear\">\n                <item\n                    android:color=\"#44000000\"\n                    android:offset=\"0.0\" />\n                <item\n                    android:color=\"#00000000\"\n                    android:offset=\"1.0\" />\n            </gradient>\n        </aapt:attr>\n    </path>\n    <path\n        android:fillColor=\"#FFFFFF\"\n        android:fillType=\"nonZero\"\n        android:pathData=\"M66.94,46.02L66.94,46.02C72.44,50.07 76,56.61 76,64L32,64C32,56.61 35.56,50.11 40.98,46.06L36.18,41.19C35.45,40.45 35.45,39.3 36.18,38.56C36.91,37.81 38.05,37.81 38.78,38.56L44.25,44.05C47.18,42.57 50.48,41.71 54,41.71C57.48,41.71 60.78,42.57 63.68,44.05L69.11,38.56C69.84,37.81 70.98,37.81 71.71,38.56C72.44,39.3 72.44,40.45 71.71,41.19L66.94,46.02ZM62.94,56.92C64.08,56.92 65,56.01 65,54.88C65,53.76 64.08,52.85 62.94,52.85C61.8,52.85 60.88,53.76 60.88,54.88C60.88,56.01 61.8,56.92 62.94,56.92ZM45.06,56.92C46.2,56.92 47.13,56.01 47.13,54.88C47.13,53.76 46.2,52.85 45.06,52.85C43.92,52.85 43,53.76 43,54.88C43,56.01 43.92,56.92 45.06,56.92Z\"\n        android:strokeWidth=\"1\"\n        android:strokeColor=\"#00000000\" />\n</vector>\n"
  },
  {
    "path": "mobile/app/src/main/res/layout/activity_main.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<androidx.constraintlayout.widget.ConstraintLayout xmlns:android=\"http://schemas.android.com/apk/res/android\"\n    xmlns:app=\"http://schemas.android.com/apk/res-auto\"\n    xmlns:tools=\"http://schemas.android.com/tools\"\n    android:layout_width=\"match_parent\"\n    android:layout_height=\"match_parent\"\n    tools:context=\".MainActivity\">\n\n    <org.webrtc.SurfaceViewRenderer\n        android:id=\"@+id/local_view\"\n        android:layout_width=\"0dp\"\n        android:layout_height=\"0dp\"\n        app:layout_constraintBottom_toTopOf=\"@+id/remote_view\"\n        app:layout_constraintEnd_toEndOf=\"parent\"\n        app:layout_constraintStart_toStartOf=\"parent\"\n        app:layout_constraintTop_toTopOf=\"parent\" />\n\n    <org.webrtc.SurfaceViewRenderer\n        android:id=\"@+id/remote_view\"\n        android:layout_width=\"0dp\"\n        android:layout_height=\"0dp\"\n        app:layout_constraintBottom_toBottomOf=\"parent\"\n        app:layout_constraintEnd_toEndOf=\"parent\"\n        app:layout_constraintStart_toStartOf=\"parent\"\n        app:layout_constraintTop_toBottomOf=\"@id/local_view\" />\n\n    <ProgressBar\n        android:id=\"@+id/remote_view_loading\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:indeterminate=\"true\"\n        app:layout_constraintBottom_toBottomOf=\"@id/remote_view\"\n        app:layout_constraintEnd_toEndOf=\"@id/remote_view\"\n        app:layout_constraintStart_toStartOf=\"@id/remote_view\"\n        app:layout_constraintTop_toTopOf=\"@id/remote_view\" />\n\n    <com.google.android.material.floatingactionbutton.FloatingActionButton\n        android:id=\"@+id/call_button\"\n        android:layout_width=\"wrap_content\"\n        android:layout_height=\"wrap_content\"\n        android:layout_margin=\"20dp\"\n        android:clickable=\"false\"\n        app:layout_constraintBottom_toBottomOf=\"parent\"\n        app:layout_constraintEnd_toEndOf=\"parent\"\n        app:srcCompat=\"@android:drawable/ic_menu_call\" />\n\n</androidx.constraintlayout.widget.ConstraintLayout>"
  },
  {
    "path": "mobile/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<adaptive-icon xmlns:android=\"http://schemas.android.com/apk/res/android\">\n    <background android:drawable=\"@drawable/ic_launcher_background\" />\n    <foreground android:drawable=\"@drawable/ic_launcher_foreground\" />\n</adaptive-icon>"
  },
  {
    "path": "mobile/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<adaptive-icon xmlns:android=\"http://schemas.android.com/apk/res/android\">\n    <background android:drawable=\"@drawable/ic_launcher_background\" />\n    <foreground android:drawable=\"@drawable/ic_launcher_foreground\" />\n</adaptive-icon>"
  },
  {
    "path": "mobile/app/src/main/res/values/colors.xml",
    "content": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<resources>\n    <color name=\"colorPrimary\">#008577</color>\n    <color name=\"colorPrimaryDark\">#00574B</color>\n    <color name=\"colorAccent\">#D81B60</color>\n</resources>\n"
  },
  {
    "path": "mobile/app/src/main/res/values/strings.xml",
    "content": "<resources>\n    <string name=\"app_name\">webrtc-demo</string>\n</resources>\n"
  },
  {
    "path": "mobile/app/src/main/res/values/styles.xml",
    "content": "<resources>\n\n    <!-- Base application theme. -->\n    <style name=\"AppTheme\" parent=\"Theme.MaterialComponents.Light.NoActionBar\"/>\n\n</resources>\n"
  },
  {
    "path": "mobile/app/src/test/java/me/amryousef/webrtc_demo/ExampleUnitTest.kt",
    "content": "package me.amryousef.webrtc_demo\n\nimport org.junit.Test\n\nimport org.junit.Assert.*\n\n/**\n * Example local unit test, which will execute on the development machine (host).\n *\n * See [testing documentation](http://d.android.com/tools/testing).\n */\nclass ExampleUnitTest {\n    @Test\n    fun addition_isCorrect() {\n        assertEquals(4, 2 + 2)\n    }\n}\n"
  },
  {
    "path": "mobile/build.gradle",
    "content": "// Top-level build file where you can add configuration options common to all sub-projects/modules.\n\nbuildscript {\n    ext.kotlin_version = '1.3.31'\n    ext.webrtc_version = '1.0.27771'\n    ext.ktor_version = '1.1.4'\n    repositories {\n        google()\n        jcenter()\n        \n    }\n    dependencies {\n        classpath 'com.android.tools.build:gradle:4.2.0-beta02'\n        classpath \"org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version\"\n        // NOTE: Do not place your application dependencies here; they belong\n        // in the individual module build.gradle files\n    }\n}\n\nallprojects {\n    repositories {\n        google()\n        jcenter()\n        \n    }\n}\n\ntask clean(type: Delete) {\n    delete rootProject.buildDir\n}\n"
  },
  {
    "path": "mobile/gradle/wrapper/gradle-wrapper.properties",
    "content": "#Sun May 26 10:14:28 BST 2019\ndistributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\nzipStoreBase=GRADLE_USER_HOME\nzipStorePath=wrapper/dists\ndistributionUrl=https://services.gradle.org/distributions/gradle-6.7.1-all.zip\n"
  },
  {
    "path": "mobile/gradle.properties",
    "content": "# Project-wide Gradle settings.\n# IDE (e.g. Android Studio) users:\n# Gradle settings configured through the IDE *will override*\n# any settings specified in this file.\n# For more details on how to configure your build environment visit\n# http://www.gradle.org/docs/current/userguide/build_environment.html\n# Specifies the JVM arguments used for the daemon process.\n# The setting is particularly useful for tweaking memory settings.\norg.gradle.jvmargs=-Xmx1536m\n# When configured, Gradle will run in incubating parallel mode.\n# This option should only be used with decoupled projects. More details, visit\n# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects\n# org.gradle.parallel=true\n# AndroidX package structure to make it clearer which packages are bundled with the\n# Android operating system, and which are packaged with your app's APK\n# https://developer.android.com/topic/libraries/support-library/androidx-rn\nandroid.useAndroidX=true\n# Automatically convert third-party libraries to use AndroidX\nandroid.enableJetifier=true\n# Kotlin code style for this project: \"official\" or \"obsolete\":\nkotlin.code.style=official\n"
  },
  {
    "path": "mobile/gradlew",
    "content": "#!/usr/bin/env sh\n\n##############################################################################\n##\n##  Gradle start up script for UN*X\n##\n##############################################################################\n\n# Attempt to set APP_HOME\n# Resolve links: $0 may be a link\nPRG=\"$0\"\n# Need this for relative symlinks.\nwhile [ -h \"$PRG\" ] ; do\n    ls=`ls -ld \"$PRG\"`\n    link=`expr \"$ls\" : '.*-> \\(.*\\)$'`\n    if expr \"$link\" : '/.*' > /dev/null; then\n        PRG=\"$link\"\n    else\n        PRG=`dirname \"$PRG\"`\"/$link\"\n    fi\ndone\nSAVED=\"`pwd`\"\ncd \"`dirname \\\"$PRG\\\"`/\" >/dev/null\nAPP_HOME=\"`pwd -P`\"\ncd \"$SAVED\" >/dev/null\n\nAPP_NAME=\"Gradle\"\nAPP_BASE_NAME=`basename \"$0\"`\n\n# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.\nDEFAULT_JVM_OPTS=\"\"\n\n# Use the maximum available, or set MAX_FD != -1 to use that value.\nMAX_FD=\"maximum\"\n\nwarn () {\n    echo \"$*\"\n}\n\ndie () {\n    echo\n    echo \"$*\"\n    echo\n    exit 1\n}\n\n# OS specific support (must be 'true' or 'false').\ncygwin=false\nmsys=false\ndarwin=false\nnonstop=false\ncase \"`uname`\" in\n  CYGWIN* )\n    cygwin=true\n    ;;\n  Darwin* )\n    darwin=true\n    ;;\n  MINGW* )\n    msys=true\n    ;;\n  NONSTOP* )\n    nonstop=true\n    ;;\nesac\n\nCLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar\n\n# Determine the Java command to use to start the JVM.\nif [ -n \"$JAVA_HOME\" ] ; then\n    if [ -x \"$JAVA_HOME/jre/sh/java\" ] ; then\n        # IBM's JDK on AIX uses strange locations for the executables\n        JAVACMD=\"$JAVA_HOME/jre/sh/java\"\n    else\n        JAVACMD=\"$JAVA_HOME/bin/java\"\n    fi\n    if [ ! -x \"$JAVACMD\" ] ; then\n        die \"ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME\n\nPlease set the JAVA_HOME variable in your environment to match the\nlocation of your Java installation.\"\n    fi\nelse\n    JAVACMD=\"java\"\n    which java >/dev/null 2>&1 || die \"ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.\n\nPlease set the JAVA_HOME variable in your environment to match the\nlocation of your Java installation.\"\nfi\n\n# Increase the maximum file descriptors if we can.\nif [ \"$cygwin\" = \"false\" -a \"$darwin\" = \"false\" -a \"$nonstop\" = \"false\" ] ; then\n    MAX_FD_LIMIT=`ulimit -H -n`\n    if [ $? -eq 0 ] ; then\n        if [ \"$MAX_FD\" = \"maximum\" -o \"$MAX_FD\" = \"max\" ] ; then\n            MAX_FD=\"$MAX_FD_LIMIT\"\n        fi\n        ulimit -n $MAX_FD\n        if [ $? -ne 0 ] ; then\n            warn \"Could not set maximum file descriptor limit: $MAX_FD\"\n        fi\n    else\n        warn \"Could not query maximum file descriptor limit: $MAX_FD_LIMIT\"\n    fi\nfi\n\n# For Darwin, add options to specify how the application appears in the dock\nif $darwin; then\n    GRADLE_OPTS=\"$GRADLE_OPTS \\\"-Xdock:name=$APP_NAME\\\" \\\"-Xdock:icon=$APP_HOME/media/gradle.icns\\\"\"\nfi\n\n# For Cygwin, switch paths to Windows format before running java\nif $cygwin ; then\n    APP_HOME=`cygpath --path --mixed \"$APP_HOME\"`\n    CLASSPATH=`cygpath --path --mixed \"$CLASSPATH\"`\n    JAVACMD=`cygpath --unix \"$JAVACMD\"`\n\n    # We build the pattern for arguments to be converted via cygpath\n    ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`\n    SEP=\"\"\n    for dir in $ROOTDIRSRAW ; do\n        ROOTDIRS=\"$ROOTDIRS$SEP$dir\"\n        SEP=\"|\"\n    done\n    OURCYGPATTERN=\"(^($ROOTDIRS))\"\n    # Add a user-defined pattern to the cygpath arguments\n    if [ \"$GRADLE_CYGPATTERN\" != \"\" ] ; then\n        OURCYGPATTERN=\"$OURCYGPATTERN|($GRADLE_CYGPATTERN)\"\n    fi\n    # Now convert the arguments - kludge to limit ourselves to /bin/sh\n    i=0\n    for arg in \"$@\" ; do\n        CHECK=`echo \"$arg\"|egrep -c \"$OURCYGPATTERN\" -`\n        CHECK2=`echo \"$arg\"|egrep -c \"^-\"`                                 ### Determine if an option\n\n        if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then                    ### Added a condition\n            eval `echo args$i`=`cygpath --path --ignore --mixed \"$arg\"`\n        else\n            eval `echo args$i`=\"\\\"$arg\\\"\"\n        fi\n        i=$((i+1))\n    done\n    case $i in\n        (0) set -- ;;\n        (1) set -- \"$args0\" ;;\n        (2) set -- \"$args0\" \"$args1\" ;;\n        (3) set -- \"$args0\" \"$args1\" \"$args2\" ;;\n        (4) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" ;;\n        (5) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" ;;\n        (6) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" ;;\n        (7) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" \"$args6\" ;;\n        (8) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" \"$args6\" \"$args7\" ;;\n        (9) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" \"$args6\" \"$args7\" \"$args8\" ;;\n    esac\nfi\n\n# Escape application args\nsave () {\n    for i do printf %s\\\\n \"$i\" | sed \"s/'/'\\\\\\\\''/g;1s/^/'/;\\$s/\\$/' \\\\\\\\/\" ; done\n    echo \" \"\n}\nAPP_ARGS=$(save \"$@\")\n\n# Collect all arguments for the java command, following the shell quoting and substitution rules\neval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS \"\\\"-Dorg.gradle.appname=$APP_BASE_NAME\\\"\" -classpath \"\\\"$CLASSPATH\\\"\" org.gradle.wrapper.GradleWrapperMain \"$APP_ARGS\"\n\n# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong\nif [ \"$(uname)\" = \"Darwin\" ] && [ \"$HOME\" = \"$PWD\" ]; then\n  cd \"$(dirname \"$0\")\"\nfi\n\nexec \"$JAVACMD\" \"$@\"\n"
  },
  {
    "path": "mobile/gradlew.bat",
    "content": "@if \"%DEBUG%\" == \"\" @echo off\n@rem ##########################################################################\n@rem\n@rem  Gradle startup script for Windows\n@rem\n@rem ##########################################################################\n\n@rem Set local scope for the variables with windows NT shell\nif \"%OS%\"==\"Windows_NT\" setlocal\n\nset DIRNAME=%~dp0\nif \"%DIRNAME%\" == \"\" set DIRNAME=.\nset APP_BASE_NAME=%~n0\nset APP_HOME=%DIRNAME%\n\n@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.\nset DEFAULT_JVM_OPTS=\n\n@rem Find java.exe\nif defined JAVA_HOME goto findJavaFromJavaHome\n\nset JAVA_EXE=java.exe\n%JAVA_EXE% -version >NUL 2>&1\nif \"%ERRORLEVEL%\" == \"0\" goto init\n\necho.\necho ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.\necho.\necho Please set the JAVA_HOME variable in your environment to match the\necho location of your Java installation.\n\ngoto fail\n\n:findJavaFromJavaHome\nset JAVA_HOME=%JAVA_HOME:\"=%\nset JAVA_EXE=%JAVA_HOME%/bin/java.exe\n\nif exist \"%JAVA_EXE%\" goto init\n\necho.\necho ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%\necho.\necho Please set the JAVA_HOME variable in your environment to match the\necho location of your Java installation.\n\ngoto fail\n\n:init\n@rem Get command-line arguments, handling Windows variants\n\nif not \"%OS%\" == \"Windows_NT\" goto win9xME_args\n\n:win9xME_args\n@rem Slurp the command line arguments.\nset CMD_LINE_ARGS=\nset _SKIP=2\n\n:win9xME_args_slurp\nif \"x%~1\" == \"x\" goto execute\n\nset CMD_LINE_ARGS=%*\n\n:execute\n@rem Setup the command line\n\nset CLASSPATH=%APP_HOME%\\gradle\\wrapper\\gradle-wrapper.jar\n\n@rem Execute Gradle\n\"%JAVA_EXE%\" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% \"-Dorg.gradle.appname=%APP_BASE_NAME%\" -classpath \"%CLASSPATH%\" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%\n\n:end\n@rem End local scope for the variables with windows NT shell\nif \"%ERRORLEVEL%\"==\"0\" goto mainEnd\n\n:fail\nrem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of\nrem the _cmd.exe /c_ return code!\nif  not \"\" == \"%GRADLE_EXIT_CONSOLE%\" exit 1\nexit /b 1\n\n:mainEnd\nif \"%OS%\"==\"Windows_NT\" endlocal\n\n:omega\n"
  },
  {
    "path": "mobile/local.properties",
    "content": "## This file is automatically generated by Android Studio.\n# Do not modify this file -- YOUR CHANGES WILL BE ERASED!\n#\n# This file should *NOT* be checked into Version Control Systems,\n# as it contains information specific to your local configuration.\n#\n# Location of the SDK. This is only used by Gradle.\n# For customization when using a Version Control System, please read the\n# header note.\nsdk.dir=/Users/amryousef/Library/Android/sdk\n"
  },
  {
    "path": "mobile/settings.gradle",
    "content": "include ':app'\nrootProject.name='webrtc-demo'\n"
  },
  {
    "path": "server/.gitignore",
    "content": "/.gradle\n/.idea\n/out\n/build\n*.iml\n*.ipr\n*.iws\nservice_key.json"
  },
  {
    "path": "server/build.gradle",
    "content": "buildscript {\n    repositories {\n        jcenter()\n    }\n    \n    dependencies {\n        classpath \"org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version\"\n    }\n}\n\napply plugin: 'kotlin'\napply plugin: 'application'\n\ngroup 'homedoor'\nversion '0.0.1'\nmainClassName = \"io.ktor.server.netty.EngineMain\"\n\nsourceSets {\n    main.kotlin.srcDirs = main.java.srcDirs = ['src']\n    test.kotlin.srcDirs = test.java.srcDirs = ['test']\n    main.resources.srcDirs = ['resources']\n    test.resources.srcDirs = ['testresources']\n}\n\nrepositories {\n    mavenLocal()\n    jcenter()\n    maven { url 'https://kotlin.bintray.com/ktor' }\n}\n\ndependencies {\n    compile \"org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version\"\n    compile \"io.ktor:ktor-server-netty:$ktor_version\"\n    compile \"ch.qos.logback:logback-classic:$logback_version\"\n    compile \"io.ktor:ktor-metrics:$ktor_version\"\n    compile \"io.ktor:ktor-server-core:$ktor_version\"\n    compile \"io.ktor:ktor-websockets:$ktor_version\"\n    compile \"io.ktor:ktor-gson:$ktor_version\"\n    \n    testCompile \"io.ktor:ktor-server-tests:$ktor_version\"\n}\n"
  },
  {
    "path": "server/gradle/wrapper/gradle-wrapper.properties",
    "content": "distributionBase=GRADLE_USER_HOME\ndistributionPath=wrapper/dists\ndistributionUrl=https\\://services.gradle.org/distributions/gradle-4.10-all.zip\nzipStoreBase=GRADLE_USER_HOME\nzipStorePath=wrapper/dists\n"
  },
  {
    "path": "server/gradle.properties",
    "content": "ktor_version=1.1.4\nkotlin.code.style=official\nkotlin_version=1.3.30\nlogback_version=1.2.1\n"
  },
  {
    "path": "server/gradlew",
    "content": "#!/usr/bin/env sh\n\n##############################################################################\n##\n##  Gradle start up script for UN*X\n##\n##############################################################################\n\n# Attempt to set APP_HOME\n# Resolve links: $0 may be a link\nPRG=\"$0\"\n# Need this for relative symlinks.\nwhile [ -h \"$PRG\" ] ; do\n    ls=`ls -ld \"$PRG\"`\n    link=`expr \"$ls\" : '.*-> \\(.*\\)$'`\n    if expr \"$link\" : '/.*' > /dev/null; then\n        PRG=\"$link\"\n    else\n        PRG=`dirname \"$PRG\"`\"/$link\"\n    fi\ndone\nSAVED=\"`pwd`\"\ncd \"`dirname \\\"$PRG\\\"`/\" >/dev/null\nAPP_HOME=\"`pwd -P`\"\ncd \"$SAVED\" >/dev/null\n\nAPP_NAME=\"Gradle\"\nAPP_BASE_NAME=`basename \"$0\"`\n\n# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.\nDEFAULT_JVM_OPTS=\"\"\n\n# Use the maximum available, or set MAX_FD != -1 to use that value.\nMAX_FD=\"maximum\"\n\nwarn () {\n    echo \"$*\"\n}\n\ndie () {\n    echo\n    echo \"$*\"\n    echo\n    exit 1\n}\n\n# OS specific support (must be 'true' or 'false').\ncygwin=false\nmsys=false\ndarwin=false\nnonstop=false\ncase \"`uname`\" in\n  CYGWIN* )\n    cygwin=true\n    ;;\n  Darwin* )\n    darwin=true\n    ;;\n  MINGW* )\n    msys=true\n    ;;\n  NONSTOP* )\n    nonstop=true\n    ;;\nesac\n\nCLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar\n\n# Determine the Java command to use to start the JVM.\nif [ -n \"$JAVA_HOME\" ] ; then\n    if [ -x \"$JAVA_HOME/jre/sh/java\" ] ; then\n        # IBM's JDK on AIX uses strange locations for the executables\n        JAVACMD=\"$JAVA_HOME/jre/sh/java\"\n    else\n        JAVACMD=\"$JAVA_HOME/bin/java\"\n    fi\n    if [ ! -x \"$JAVACMD\" ] ; then\n        die \"ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME\n\nPlease set the JAVA_HOME variable in your environment to match the\nlocation of your Java installation.\"\n    fi\nelse\n    JAVACMD=\"java\"\n    which java >/dev/null 2>&1 || die \"ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.\n\nPlease set the JAVA_HOME variable in your environment to match the\nlocation of your Java installation.\"\nfi\n\n# Increase the maximum file descriptors if we can.\nif [ \"$cygwin\" = \"false\" -a \"$darwin\" = \"false\" -a \"$nonstop\" = \"false\" ] ; then\n    MAX_FD_LIMIT=`ulimit -H -n`\n    if [ $? -eq 0 ] ; then\n        if [ \"$MAX_FD\" = \"maximum\" -o \"$MAX_FD\" = \"max\" ] ; then\n            MAX_FD=\"$MAX_FD_LIMIT\"\n        fi\n        ulimit -n $MAX_FD\n        if [ $? -ne 0 ] ; then\n            warn \"Could not set maximum file descriptor limit: $MAX_FD\"\n        fi\n    else\n        warn \"Could not query maximum file descriptor limit: $MAX_FD_LIMIT\"\n    fi\nfi\n\n# For Darwin, add options to specify how the application appears in the dock\nif $darwin; then\n    GRADLE_OPTS=\"$GRADLE_OPTS \\\"-Xdock:name=$APP_NAME\\\" \\\"-Xdock:icon=$APP_HOME/media/gradle.icns\\\"\"\nfi\n\n# For Cygwin, switch paths to Windows format before running java\nif $cygwin ; then\n    APP_HOME=`cygpath --path --mixed \"$APP_HOME\"`\n    CLASSPATH=`cygpath --path --mixed \"$CLASSPATH\"`\n    JAVACMD=`cygpath --unix \"$JAVACMD\"`\n\n    # We build the pattern for arguments to be converted via cygpath\n    ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null`\n    SEP=\"\"\n    for dir in $ROOTDIRSRAW ; do\n        ROOTDIRS=\"$ROOTDIRS$SEP$dir\"\n        SEP=\"|\"\n    done\n    OURCYGPATTERN=\"(^($ROOTDIRS))\"\n    # Add a user-defined pattern to the cygpath arguments\n    if [ \"$GRADLE_CYGPATTERN\" != \"\" ] ; then\n        OURCYGPATTERN=\"$OURCYGPATTERN|($GRADLE_CYGPATTERN)\"\n    fi\n    # Now convert the arguments - kludge to limit ourselves to /bin/sh\n    i=0\n    for arg in \"$@\" ; do\n        CHECK=`echo \"$arg\"|egrep -c \"$OURCYGPATTERN\" -`\n        CHECK2=`echo \"$arg\"|egrep -c \"^-\"`                                 ### Determine if an option\n\n        if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then                    ### Added a condition\n            eval `echo args$i`=`cygpath --path --ignore --mixed \"$arg\"`\n        else\n            eval `echo args$i`=\"\\\"$arg\\\"\"\n        fi\n        i=$((i+1))\n    done\n    case $i in\n        (0) set -- ;;\n        (1) set -- \"$args0\" ;;\n        (2) set -- \"$args0\" \"$args1\" ;;\n        (3) set -- \"$args0\" \"$args1\" \"$args2\" ;;\n        (4) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" ;;\n        (5) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" ;;\n        (6) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" ;;\n        (7) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" \"$args6\" ;;\n        (8) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" \"$args6\" \"$args7\" ;;\n        (9) set -- \"$args0\" \"$args1\" \"$args2\" \"$args3\" \"$args4\" \"$args5\" \"$args6\" \"$args7\" \"$args8\" ;;\n    esac\nfi\n\n# Escape application args\nsave () {\n    for i do printf %s\\\\n \"$i\" | sed \"s/'/'\\\\\\\\''/g;1s/^/'/;\\$s/\\$/' \\\\\\\\/\" ; done\n    echo \" \"\n}\nAPP_ARGS=$(save \"$@\")\n\n# Collect all arguments for the java command, following the shell quoting and substitution rules\neval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS \"\\\"-Dorg.gradle.appname=$APP_BASE_NAME\\\"\" -classpath \"\\\"$CLASSPATH\\\"\" org.gradle.wrapper.GradleWrapperMain \"$APP_ARGS\"\n\n# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong\nif [ \"$(uname)\" = \"Darwin\" ] && [ \"$HOME\" = \"$PWD\" ]; then\n  cd \"$(dirname \"$0\")\"\nfi\n\nexec \"$JAVACMD\" \"$@\"\n"
  },
  {
    "path": "server/gradlew.bat",
    "content": "@if \"%DEBUG%\" == \"\" @echo off\n@rem ##########################################################################\n@rem\n@rem  Gradle startup script for Windows\n@rem\n@rem ##########################################################################\n\n@rem Set local scope for the variables with windows NT shell\nif \"%OS%\"==\"Windows_NT\" setlocal\n\nset DIRNAME=%~dp0\nif \"%DIRNAME%\" == \"\" set DIRNAME=.\nset APP_BASE_NAME=%~n0\nset APP_HOME=%DIRNAME%\n\n@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script.\nset DEFAULT_JVM_OPTS=\n\n@rem Find java.exe\nif defined JAVA_HOME goto findJavaFromJavaHome\n\nset JAVA_EXE=java.exe\n%JAVA_EXE% -version >NUL 2>&1\nif \"%ERRORLEVEL%\" == \"0\" goto init\n\necho.\necho ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH.\necho.\necho Please set the JAVA_HOME variable in your environment to match the\necho location of your Java installation.\n\ngoto fail\n\n:findJavaFromJavaHome\nset JAVA_HOME=%JAVA_HOME:\"=%\nset JAVA_EXE=%JAVA_HOME%/bin/java.exe\n\nif exist \"%JAVA_EXE%\" goto init\n\necho.\necho ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME%\necho.\necho Please set the JAVA_HOME variable in your environment to match the\necho location of your Java installation.\n\ngoto fail\n\n:init\n@rem Get command-line arguments, handling Windows variants\n\nif not \"%OS%\" == \"Windows_NT\" goto win9xME_args\n\n:win9xME_args\n@rem Slurp the command line arguments.\nset CMD_LINE_ARGS=\nset _SKIP=2\n\n:win9xME_args_slurp\nif \"x%~1\" == \"x\" goto execute\n\nset CMD_LINE_ARGS=%*\n\n:execute\n@rem Setup the command line\n\nset CLASSPATH=%APP_HOME%\\gradle\\wrapper\\gradle-wrapper.jar\n\n@rem Execute Gradle\n\"%JAVA_EXE%\" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% \"-Dorg.gradle.appname=%APP_BASE_NAME%\" -classpath \"%CLASSPATH%\" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS%\n\n:end\n@rem End local scope for the variables with windows NT shell\nif \"%ERRORLEVEL%\"==\"0\" goto mainEnd\n\n:fail\nrem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of\nrem the _cmd.exe /c_ return code!\nif  not \"\" == \"%GRADLE_EXIT_CONSOLE%\" exit 1\nexit /b 1\n\n:mainEnd\nif \"%OS%\"==\"Windows_NT\" endlocal\n\n:omega\n"
  },
  {
    "path": "server/resources/application.conf",
    "content": "ktor {\n    deployment {\n        port = 8080\n        port = ${?PORT}\n    }\n    application {\n        modules = [ me.amryousef.ApplicationKt.module ]\n    }\n}\n"
  },
  {
    "path": "server/resources/logback.xml",
    "content": "<configuration>\n    <appender name=\"STDOUT\" class=\"ch.qos.logback.core.ConsoleAppender\">\n        <encoder>\n            <pattern>%d{YYYY-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>\n        </encoder>\n    </appender>\n    <root level=\"trace\">\n        <appender-ref ref=\"STDOUT\"/>\n    </root>\n    <logger name=\"org.eclipse.jetty\" level=\"INFO\"/>\n    <logger name=\"io.netty\" level=\"INFO\"/>\n</configuration>\n"
  },
  {
    "path": "server/settings.gradle",
    "content": "rootProject.name = \"homedoor\"\n"
  },
  {
    "path": "server/src/me/amryousef/Application.kt",
    "content": "package me.amryousef\n\nimport io.ktor.application.Application\nimport io.ktor.application.install\nimport io.ktor.features.CallLogging\nimport io.ktor.features.ContentNegotiation\nimport io.ktor.features.DefaultHeaders\nimport io.ktor.gson.gson\nimport io.ktor.http.cio.websocket.*\nimport io.ktor.routing.routing\nimport io.ktor.websocket.WebSocketServerSession\nimport io.ktor.websocket.WebSockets\nimport io.ktor.websocket.webSocket\nimport kotlinx.coroutines.ExperimentalCoroutinesApi\nimport kotlinx.coroutines.channels.ConflatedBroadcastChannel\nimport java.time.Duration\nimport java.util.*\n\nfun main(args: Array<String>): Unit = io.ktor.server.netty.EngineMain.main(args)\n\n@ExperimentalCoroutinesApi\n@Suppress(\"unused\") // Referenced in application.conf\n@kotlin.jvm.JvmOverloads\nfun Application.module(testing: Boolean = false) {\n    install(DefaultHeaders) {\n        header(\"X-Engine\", \"Ktor\") // will send this header with each response\n    }\n\n    install(CallLogging)\n\n    install(WebSockets) {\n        pingPeriod = Duration.ofSeconds(15)\n        timeout = Duration.ofSeconds(15)\n        maxFrameSize = Long.MAX_VALUE\n        masking = false\n    }\n\n    install(ContentNegotiation) {\n        gson {\n        }\n    }\n\n    val connections = Collections.synchronizedMap(mutableMapOf<String, WebSocketServerSession>())\n\n    routing {\n        webSocket(path = \"/connect\") {\n            val id = UUID.randomUUID().toString()\n            connections[id] = this\n            println(\"Connected clients = ${connections.size}\")\n            try {\n                for (data in incoming) {\n                    if (data is Frame.Text) {\n                        val clients = connections.filter { it.key != id }\n                        val text = data.readText()\n                        clients.forEach {\n                            println(\"Sending to:${it.key}\")\n                            println(\"Sending $text\")\n                            it.value.send(text)\n                        }\n                    }\n                }\n            } finally {\n                connections.remove(id)\n            }\n        }\n    }\n}\n\n"
  }
]