/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 * All rights reserved.
 *
 * This source code is licensed under the license found in the
 * LICENSE file in the root directory of this source tree.
 */

package com.facebook.login

import android.net.Uri
import android.os.Bundle
import androidx.fragment.app.FragmentActivity
import androidx.test.core.app.ApplicationProvider
import com.facebook.AccessTokenSource
import com.facebook.FacebookException
import com.facebook.FacebookPowerMockTestCase
import com.facebook.FacebookRequestError
import com.facebook.FacebookSdk
import com.facebook.FacebookServiceException
import com.facebook.MockSharedPreference
import com.facebook.internal.ServerProtocol
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import org.mockito.kotlin.any
import org.mockito.kotlin.argumentCaptor
import org.mockito.kotlin.mock
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import org.powermock.api.mockito.PowerMockito
import org.powermock.core.classloader.annotations.PrepareForTest

@PrepareForTest(FacebookSdk::class)
class WebLoginMethodHandlerTest : FacebookPowerMockTestCase() {
  private lateinit var mockLoginClient: LoginClient
  private lateinit var testHandler: TestWebLoginMethodHandler
  private lateinit var testRequest: LoginClient.Request
  private lateinit var mockActivity: FragmentActivity
  private lateinit var mockSharedPreference: MockSharedPreference

  internal class TestWebLoginMethodHandler(loginClient: LoginClient) :
      WebLoginMethodHandler(loginClient) {
    override fun tryAuthorize(request: LoginClient.Request): Int = 0

    override fun describeContents(): Int = 0

    override val tokenSource: AccessTokenSource = AccessTokenSource.CHROME_CUSTOM_TAB

    override val nameForLogging: String = "testlogin"

    public override fun getParameters(request: LoginClient.Request): Bundle {
      return super.getParameters(request)
    }

    public override fun getRedirectUrl(): String {
      return super.getRedirectUrl()
    }

    public override fun onComplete(
        request: LoginClient.Request,
        values: Bundle?,
        error: FacebookException?
    ) {
      super.onComplete(request, values, error)
    }
  }

  override fun setup() {
    super.setup()
    mockActivity = mock()
    mockSharedPreference = MockSharedPreference()
    whenever(mockActivity.getSharedPreferences(any<String>(), any()))
        .thenReturn(mockSharedPreference)
    mockLoginClient = mock()
    whenever(mockLoginClient.activity).thenReturn(mockActivity)
    testHandler = TestWebLoginMethodHandler(mockLoginClient)
    PowerMockito.mockStatic(FacebookSdk::class.java)
    PowerMockito.`when`(FacebookSdk.isInitialized()).thenReturn(true)
    PowerMockito.`when`(FacebookSdk.getApplicationContext())
        .thenReturn(ApplicationProvider.getApplicationContext())
    PowerMockito.`when`(FacebookSdk.getApplicationId()).thenReturn("123456789")
    testRequest =
        LoginClient.Request(
            LoginBehavior.DIALOG_ONLY,
            setOf("email", "public_profile"),
            DefaultAudience.EVERYONE,
            "testAuthType",
            "123456789",
            "testAuthId")
  }

  @Test
  fun `test build parameters from request`() {
    val parameters = testHandler.getParameters(testRequest)
    assertThat(parameters.getString(ServerProtocol.DIALOG_PARAM_SCOPE))
        .isEqualTo("email,public_profile")
    assertThat(parameters.getString(ServerProtocol.DIALOG_PARAM_CBT)).isNotNull
    assertThat(parameters.getString(ServerProtocol.DIALOG_PARAM_IES)).isNotNull
    assertThat(parameters.getString(ServerProtocol.DIALOG_PARAM_STATE)).contains("testAuthId")
  }

  @Test
  fun `test onComplete will save access token and validate outcome`() {
    val values = LoginMethodHandlerTest.createValidWebLoginResultBundle()
    testHandler.onComplete(testRequest, values, null)
    assertThat(mockSharedPreference.getString("TOKEN", "")).isEqualTo("access_token")
    verify(mockLoginClient).completeAndValidate(any())
  }

  @Test
  fun `test redirect url is a valid uri`() {
    val uri = Uri.parse(testHandler.getRedirectUrl())
    assertThat(uri.scheme).isEqualTo("fb123456789")
    assertThat(uri.authority).isEqualTo("authorize")
  }

  @Test
  fun `test onComplete if a facebook service exception is received`() {
    val errorMessage = "unknown error"
    val requestError = FacebookRequestError(0xff, "test", errorMessage)
    val error = FacebookServiceException(requestError, null)
    testHandler.onComplete(testRequest, null, error)
    val outcomeCaptor = argumentCaptor<LoginClient.Result>()
    verify(mockLoginClient).completeAndValidate(outcomeCaptor.capture())
    val capturedOutcome = outcomeCaptor.firstValue
    val outcomeErrorMessage = checkNotNull(capturedOutcome.errorMessage)
    assertThat(outcomeErrorMessage).isEqualTo(requestError.toString())
  }
}


/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 * All rights reserved.
 *
 * This source code is licensed under the license found in the
 * LICENSE file in the root directory of this source tree.
 */

package com.facebook.login

import android.os.Bundle
import com.facebook.AccessToken
import com.facebook.AccessTokenSource
import com.facebook.FacebookException
import com.facebook.FacebookOperationCanceledException
import com.facebook.FacebookSdk
import com.facebook.internal.FacebookDialogFragment
import java.util.Date
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import org.mockito.kotlin.argumentCaptor
import org.mockito.kotlin.mock
import org.mockito.kotlin.times
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import org.powermock.api.mockito.PowerMockito
import org.powermock.core.classloader.annotations.PowerMockIgnore
import org.powermock.core.classloader.annotations.PrepareForTest
import org.powermock.reflect.internal.WhiteboxImpl

@PowerMockIgnore("org.mockito.*", "org.robolectric.*")
@PrepareForTest(AccessToken::class, FacebookSdk::class, LoginClient::class)
class WebViewLoginMethodHandlerTest : LoginHandlerTestCase() {
  companion object {
    private const val SIGNED_REQUEST_STR =
        "ggarbage.eyJhbGdvcml0aG0iOiJITUFDSEEyNTYiLCJ" +
            "jb2RlIjoid2h5bm90IiwiaXNzdWVkX2F0IjoxNDIyNTAyMDkyLCJ1c2VyX2lkIjoiMTIzIn0"
  }

  @Test
  fun testWebViewHandlesSuccess() {
    mockTryAuthorize()
    val bundle = Bundle()
    bundle.putString("access_token", ACCESS_TOKEN)
    bundle.putString("expires_in", String.format("%d", EXPIRES_IN_DELTA))
    bundle.putString("code", "Something else")
    bundle.putString("signed_request", SIGNED_REQUEST_STR)

    val handler = WebViewLoginMethodHandler(mockLoginClient)

    val request = createRequest()
    handler.onWebDialogComplete(request, bundle, null)

    val resultArgumentCaptor = argumentCaptor<LoginClient.Result>()
    verify(mockLoginClient, times(1)).completeAndValidate(resultArgumentCaptor.capture())

    val result = resultArgumentCaptor.firstValue
    assertThat(result).isNotNull
    assertThat(result.code).isEqualTo(LoginClient.Result.Code.SUCCESS)

    val token = checkNotNull(result.token)
    assertThat(token).isNotNull
    assertThat(token.token).isEqualTo(ACCESS_TOKEN)
    assertDateDiffersWithinDelta(Date(), token.expires, EXPIRES_IN_DELTA * 1000, 1000)
    assertThat(PERMISSIONS).isEqualTo(token.permissions)
  }

  @Test
  fun testIGWebViewHandlesSuccess() {
    mockTryAuthorize()
    val bundle = Bundle()
    bundle.putString("access_token", ACCESS_TOKEN)
    bundle.putString("graph_domain", "instagram")
    bundle.putString("signed_request", SIGNED_REQUEST_STR)

    val handler = WebViewLoginMethodHandler(mockLoginClient)

    val igRequest = createIGWebRequest()
    handler.tryAuthorize(igRequest)
    handler.onWebDialogComplete(igRequest, bundle, null)

    val resultArgumentCaptor = argumentCaptor<LoginClient.Result>()
    verify(mockLoginClient, times(1)).completeAndValidate(resultArgumentCaptor.capture())

    val result = resultArgumentCaptor.firstValue
    assertThat(result).isNotNull
    assertThat(result.code).isEqualTo(LoginClient.Result.Code.SUCCESS)

    val token = checkNotNull(result.token)
    assertThat(token).isNotNull
    assertThat(token.token).isEqualTo(ACCESS_TOKEN)
    assertThat(token.userId).isEqualTo(USER_ID)
    assertThat(token.graphDomain).isEqualTo("instagram")
    assertThat(token.source).isEqualTo(AccessTokenSource.INSTAGRAM_WEB_VIEW)
    assertThat(PERMISSIONS).isEqualTo(token.permissions)
  }

  @Test
  fun testWebViewHandlesCancel() {
    val handler = WebViewLoginMethodHandler(mockLoginClient)

    val request = createRequest()
    handler.onWebDialogComplete(request, null, FacebookOperationCanceledException())

    val resultArgumentCaptor = argumentCaptor<LoginClient.Result>()
    verify(mockLoginClient, times(1)).completeAndValidate(resultArgumentCaptor.capture())
    val result = resultArgumentCaptor.firstValue

    assertThat(result).isNotNull
    assertThat(result.code).isEqualTo(LoginClient.Result.Code.CANCEL)
    assertThat(result.token).isNull()
    assertThat(result.errorMessage).isNotNull
  }

  @Test
  fun testWebViewHandlesError() {
    val handler = WebViewLoginMethodHandler(mockLoginClient)

    val request = createRequest()
    handler.onWebDialogComplete(request, null, FacebookException(ERROR_MESSAGE))

    val resultArgumentCaptor = argumentCaptor<LoginClient.Result>()
    verify(mockLoginClient, times(1)).completeAndValidate(resultArgumentCaptor.capture())
    val result = resultArgumentCaptor.firstValue

    assertThat(result).isNotNull
    assertThat(result.code).isEqualTo(LoginClient.Result.Code.ERROR)
    assertThat(result.token).isNull()
    assertThat(result.errorMessage).isNotNull
    assertThat(result.errorMessage).isEqualTo(ERROR_MESSAGE)
  }

  @Test
  fun testFromDialog() {
    val permissions = arrayListOf("stream_publish", "go_outside_and_play")
    val token = "AnImaginaryTokenValue"

    val bundle = Bundle()
    bundle.putString("access_token", token)
    bundle.putString("expires_in", "60")
    bundle.putString("signed_request", SIGNED_REQUEST_STR)

    val accessToken =
        checkNotNull(
            LoginMethodHandler.createAccessTokenFromWebBundle(
                permissions, bundle, AccessTokenSource.WEB_VIEW, "1234"))

    assertThat(permissions.toSet()).isEqualTo(accessToken.permissions)
    assertThat(accessToken).isNotNull
    assertThat(accessToken.token).isEqualTo(token)
    assertThat(accessToken.source).isEqualTo(AccessTokenSource.WEB_VIEW)
    assertThat(accessToken.isExpired).isFalse
  }

  @Test
  fun testFromSSOWithExpiresString() {
    val permissions = arrayListOf("stream_publish", "go_outside_and_play")
    val token = "AnImaginaryTokenValue"

    val bundle = Bundle()
    bundle.putString("access_token", token)
    bundle.putString("expires_in", "60")
    bundle.putString("extra_extra", "Something unrelated")
    bundle.putString("signed_request", SIGNED_REQUEST_STR)

    val accessToken =
        checkNotNull(
            LoginMethodHandler.createAccessTokenFromWebBundle(
                permissions, bundle, AccessTokenSource.FACEBOOK_APPLICATION_WEB, "1234"))

    assertThat(permissions.toSet()).isEqualTo(accessToken.permissions)
    assertThat(accessToken).isNotNull
    assertThat(accessToken.token).isEqualTo(token)
    assertThat(accessToken.source).isEqualTo(AccessTokenSource.FACEBOOK_APPLICATION_WEB)
    assertThat(accessToken.isExpired).isFalse
  }

  @Test
  fun testFromSSOWithExpiresLong() {
    val permissions = arrayListOf("stream_publish", "go_outside_and_play")
    val token = "AnImaginaryTokenValue"

    val bundle = Bundle()
    bundle.putString("access_token", token)
    bundle.putString("expires_in", "60")
    bundle.putString("extra_extra", "Something unrelated")
    bundle.putString("signed_request", SIGNED_REQUEST_STR)

    val accessToken =
        checkNotNull(
            LoginMethodHandler.createAccessTokenFromWebBundle(
                permissions, bundle, AccessTokenSource.FACEBOOK_APPLICATION_WEB, "1234"))

    assertThat(permissions.toSet()).isEqualTo(accessToken.permissions)
    assertThat(accessToken).isNotNull
    assertThat(accessToken.token).isEqualTo(token)
    assertThat(accessToken.source).isEqualTo(AccessTokenSource.FACEBOOK_APPLICATION_WEB)
    assertThat(accessToken.isExpired).isFalse
  }

  fun mockTryAuthorize() {
    PowerMockito.mockStatic(FacebookSdk::class.java)
    whenever(FacebookSdk.isInitialized()).thenReturn(true)
    whenever(FacebookSdk.getApplicationId()).thenReturn(AuthenticationTokenTestUtil.APP_ID)

    val mockCompanion = mock<AccessToken.Companion>()
    WhiteboxImpl.setInternalState(AccessToken::class.java, "Companion", mockCompanion)
    whenever(mockCompanion.getCurrentAccessToken()).thenReturn(null)
    val dialogFragment = mock<FacebookDialogFragment>()
    PowerMockito.whenNew(FacebookDialogFragment::class.java)
        .withAnyArguments()
        .thenReturn(dialogFragment)
  }
}


/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 * All rights reserved.
 *
 * This source code is licensed under the license found in the
 * LICENSE file in the root directory of this source tree.
 */

package com.facebook.share.internal

import com.facebook.FacebookTestCase
import com.facebook.share.model.CameraEffectArguments
import java.lang.IllegalArgumentException
import org.assertj.core.api.Assertions.assertThat
import org.json.JSONArray
import org.json.JSONObject
import org.junit.Test

class CameraEffectJSONUtilityTest : FacebookTestCase() {
  @Test
  fun `test convert camera effect arguments to json`() {
    val cameraEffectArguments =
        CameraEffectArguments.Builder()
            .putArgument("name", "test")
            .putArgument("permissions", arrayOf("email", "profile"))
            .build()
    val json = checkNotNull(CameraEffectJSONUtility.convertToJSON(cameraEffectArguments))
    assertThat(json.getString("name")).isEqualTo("test")
    assertThat(json.getJSONArray("permissions")).isEqualTo(JSONArray(arrayOf("email", "profile")))
  }

  @Test
  fun `test convert json to camera effect arguments`() {
    val json =
        JSONObject(
            mapOf(
                "name" to "test",
                "permissions" to arrayOf("email", "profile"),
                "empty" to JSONObject.NULL))
    val cameraEffectArguments =
        checkNotNull(CameraEffectJSONUtility.convertToCameraEffectArguments(json))
    assertThat(cameraEffectArguments.getString("name")).isEqualTo("test")
    assertThat(cameraEffectArguments.getStringArray("permissions"))
        .containsExactlyInAnyOrder("email", "profile")
  }

  @Test(expected = IllegalArgumentException::class)
  fun `test convert json to camera effect arguments with illegal value`() {
    val json =
        JSONObject(
            mapOf(
                "name" to "test", "permissions" to arrayOf("email", "profile"), "illegal" to 1.2f))
    CameraEffectJSONUtility.convertToCameraEffectArguments(json)
  }
}


/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 * All rights reserved.
 *
 * This source code is licensed under the license found in the
 * LICENSE file in the root directory of this source tree.
 */

package com.facebook.share.internal

import android.net.Uri
import androidx.test.core.app.ApplicationProvider
import com.facebook.FacebookPowerMockTestCase
import com.facebook.FacebookSdk
import com.facebook.share.model.ShareLinkContent
import com.facebook.share.model.SharePhoto
import com.facebook.share.model.SharePhotoContent
import java.util.UUID
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import org.mockito.kotlin.whenever
import org.powermock.api.mockito.PowerMockito
import org.powermock.core.classloader.annotations.PrepareForTest

@PrepareForTest(FacebookSdk::class)
class LegacyNativeDialogParametersTest : FacebookPowerMockTestCase() {
  private lateinit var testCallId: UUID

  override fun setup() {
    super.setup()
    testCallId = UUID.randomUUID()
    PowerMockito.mockStatic(FacebookSdk::class.java)
    whenever(FacebookSdk.isInitialized()).thenReturn(true)
    whenever(FacebookSdk.getApplicationId()).thenReturn("123456789")
    whenever(FacebookSdk.getApplicationContext())
        .thenReturn(ApplicationProvider.getApplicationContext())
  }

  @Test
  fun `test creating legacy parameters for sharing a link`() {
    val url = "https://facebook.com"
    val shareLinkContent = ShareLinkContent.Builder().setContentUrl(Uri.parse(url)).build()

    val params = LegacyNativeDialogParameters.create(testCallId, shareLinkContent, true)

    checkNotNull(params)
    assertThat(params.getString(ShareConstants.LEGACY_LINK)).isEqualTo(url)
  }

  @Test
  fun `test creating legacy parameters for sharing photos`() {
    val sharePhotoUrls = listOf("https://facebook.com/1.png", "https://facebook.com/2.png")
    val sharePhotos = sharePhotoUrls.map { SharePhoto.Builder().setImageUrl(Uri.parse(it)).build() }
    val sharePhotoContent = SharePhotoContent.Builder().setPhotos(sharePhotos).build()

    val params = LegacyNativeDialogParameters.create(testCallId, sharePhotoContent, true)

    checkNotNull(params)
    assertThat(params.getStringArrayList(ShareConstants.LEGACY_PHOTOS))
        .containsExactlyInAnyOrder(*sharePhotoUrls.toTypedArray())
  }
}


/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 * All rights reserved.
 *
 * This source code is licensed under the license found in the
 * LICENSE file in the root directory of this source tree.
 */

package com.facebook.share.internal

import android.net.Uri
import android.os.Bundle
import androidx.test.core.app.ApplicationProvider
import com.facebook.FacebookPowerMockTestCase
import com.facebook.FacebookSdk
import com.facebook.share.model.ShareLinkContent
import com.facebook.share.model.ShareMediaContent
import com.facebook.share.model.SharePhoto
import com.facebook.share.model.SharePhotoContent
import com.facebook.share.model.ShareStoryContent
import com.facebook.share.model.ShareVideo
import com.facebook.share.model.ShareVideoContent
import java.util.UUID
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import org.mockito.kotlin.whenever
import org.powermock.api.mockito.PowerMockito
import org.powermock.core.classloader.annotations.PrepareForTest

@PrepareForTest(FacebookSdk::class)
class NativeDialogParametersTest : FacebookPowerMockTestCase() {
  lateinit var testCallId: UUID

  override fun setup() {
    super.setup()
    testCallId = UUID.randomUUID()
    PowerMockito.mockStatic(FacebookSdk::class.java)
    whenever(FacebookSdk.isInitialized()).thenReturn(true)
    whenever(FacebookSdk.getApplicationId()).thenReturn("123456789")
    whenever(FacebookSdk.getApplicationContext())
        .thenReturn(ApplicationProvider.getApplicationContext())
  }

  @Test
  fun `test creating parameters for sharing link content`() {
    val contentUrl = "https://facebook.com"
    val quote = "test quote"
    val linkContent =
        ShareLinkContent.Builder().setContentUrl(Uri.parse(contentUrl)).setQuote(quote).build()

    val params = NativeDialogParameters.create(testCallId, linkContent, true)

    checkNotNull(params)
    assertThat(params.getString(ShareConstants.CONTENT_URL)).isEqualTo(contentUrl)
    assertThat(params.getString(ShareConstants.MESSENGER_URL)).isEqualTo(contentUrl)
    assertThat(params.getString(ShareConstants.TARGET_DISPLAY)).isEqualTo(contentUrl)
    assertThat(params.getString(ShareConstants.QUOTE)).isEqualTo(quote)
  }

  @Test
  fun `test creating parameters for sharing photo content`() {
    val photoUrls = listOf("https://test.net/image1.png", "https://test.net/image2.png")
    val sharePhotos = photoUrls.map { SharePhoto.Builder().setImageUrl(Uri.parse(it)).build() }
    val photoContent = SharePhotoContent.Builder().setPhotos(sharePhotos).build()

    val params = NativeDialogParameters.create(testCallId, photoContent, true)

    checkNotNull(params)
    assertThat(params.getStringArrayList(ShareConstants.PHOTOS))
        .containsExactlyInAnyOrder(*photoUrls.toTypedArray())
  }

  @Test
  fun `test creating parameters for sharing video content`() {
    val videoUrl = "https://test.net/video1.avi"
    val videoTitle = "Test title"
    val shareVideo = ShareVideo.Builder().setLocalUrl(Uri.parse(videoUrl)).build()
    val videoContent =
        ShareVideoContent.Builder().setVideo(shareVideo).setContentTitle(videoTitle).build()

    val params = NativeDialogParameters.create(testCallId, videoContent, true)

    checkNotNull(params)
    assertThat(params.getString(ShareConstants.VIDEO_URL)).isEqualTo(videoUrl)
    assertThat(params.getString(ShareConstants.TITLE)).isEqualTo(videoTitle)
    assertThat(params.getString(ShareConstants.DESCRIPTION)).isNull()
  }

  @Test
  fun `test creating parameters for sharing media content`() {
    val photoUrl = "https://test.net/image1.png"
    val videoUrl = "https://test.net/video1.avi"
    val photo = SharePhoto.Builder().setImageUrl(Uri.parse(photoUrl)).build()
    val video = ShareVideo.Builder().setLocalUrl(Uri.parse(videoUrl)).build()
    val shareMediaContent = ShareMediaContent.Builder().addMedia(listOf(photo, video)).build()

    val params = NativeDialogParameters.create(testCallId, shareMediaContent, true)

    checkNotNull(params)
    val mediaInfos = checkNotNull(params.getParcelableArrayList<Bundle>(ShareConstants.MEDIA))
    val mediaInfoUrls = mediaInfos.map { it.getString("uri") }
    assertThat(mediaInfoUrls).containsExactlyInAnyOrder(photoUrl, videoUrl)
  }

  @Test
  fun `test creating parameters for sharing story content`() {
    val backgroundPhotoUrl = "https://test.net/image1.png"
    val stickerUrl = "https://test.net/image2.png"
    val attributionLink = "https://test.net"
    val backgroundColorList = listOf("color1", "color2")
    val shareStoryContent =
        ShareStoryContent.Builder()
            .setBackgroundAsset(
                SharePhoto.Builder().setImageUrl(Uri.parse(backgroundPhotoUrl)).build())
            .setBackgroundColorList(backgroundColorList)
            .setStickerAsset(SharePhoto.Builder().setImageUrl(Uri.parse(stickerUrl)).build())
            .setAttributionLink(attributionLink)
            .build()

    val params = NativeDialogParameters.create(testCallId, shareStoryContent, true)

    checkNotNull(params)
    assertThat(params.getParcelable<Bundle>(ShareConstants.STORY_BG_ASSET)?.getString("uri"))
        .isEqualTo(backgroundPhotoUrl)
    assertThat(
            params
                .getParcelable<Bundle>(ShareConstants.STORY_INTERACTIVE_ASSET_URI)
                ?.getString("uri"))
        .isEqualTo(stickerUrl)
    assertThat(params.getStringArrayList(ShareConstants.STORY_INTERACTIVE_COLOR_LIST))
        .containsExactlyInAnyOrder(*backgroundColorList.toTypedArray())
    assertThat(params.getString(ShareConstants.STORY_DEEP_LINK_URL)).isEqualTo(attributionLink)
  }
}


/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 * All rights reserved.
 *
 * This source code is licensed under the license found in the
 * LICENSE file in the root directory of this source tree.
 */

package com.facebook.share.internal

import android.os.Bundle
import com.facebook.FacebookCallback
import com.facebook.FacebookException
import com.facebook.FacebookPowerMockTestCase
import com.facebook.internal.AppCall
import org.junit.Test
import org.mockito.kotlin.mock
import org.mockito.kotlin.never
import org.mockito.kotlin.verify

class ResultProcessorTest : FacebookPowerMockTestCase() {
  private lateinit var mockCallback: FacebookCallback<Void>
  private lateinit var resultProcessor: ResultProcessor
  private lateinit var resultProcessorNullCallback: ResultProcessor
  private val appCall = AppCall(0)

  override fun setup() {
    super.setup()

    mockCallback = mock()
    resultProcessor = getResultProcessorWithCallback(mockCallback)
    resultProcessorNullCallback = getResultProcessorWithCallback(null)
  }

  private fun getResultProcessorWithCallback(callback: FacebookCallback<Void>?): ResultProcessor {
    return object : ResultProcessor(callback) {
      override fun onSuccess(appCall: AppCall, results: Bundle?) = Unit
    }
  }

  @Test
  fun `test onCancel calls callback onCancel`() {
    resultProcessor.onCancel(appCall)
    verify(mockCallback).onCancel()
  }

  @Test
  fun `test onError calls callback onError`() {
    val exception = FacebookException("error")
    resultProcessor.onError(appCall, exception)
    verify(mockCallback).onError(exception)
  }

  @Test
  fun `test onCancel with null callback`() {
    resultProcessorNullCallback.onCancel(appCall)
    verify(mockCallback, never()).onCancel()
  }

  @Test
  fun `test onError with null callback`() {
    val exception = FacebookException("error")
    resultProcessorNullCallback.onError(appCall, exception)
    verify(mockCallback, never()).onError(exception)
  }
}


/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 * All rights reserved.
 *
 * This source code is licensed under the license found in the
 * LICENSE file in the root directory of this source tree.
 */

package com.facebook.share.internal

import android.net.Uri
import com.facebook.FacebookException
import com.facebook.FacebookPowerMockTestCase
import com.facebook.internal.Validate
import com.facebook.share.internal.ShareContentValidation.validateForApiShare
import com.facebook.share.internal.ShareContentValidation.validateForMessage
import com.facebook.share.internal.ShareContentValidation.validateForNativeShare
import com.facebook.share.internal.ShareContentValidation.validateForWebShare
import com.facebook.share.model.SharePhoto
import com.facebook.share.model.SharePhotoContent
import com.facebook.share.model.ShareVideoContent
import org.junit.Test
import org.powermock.core.classloader.annotations.PrepareForTest

/** Tests for [ShareContentValidation] */
@PrepareForTest(Validate::class)
class ShareContentValidationTest : FacebookPowerMockTestCase() {
  // Share by Message
  @Test(expected = FacebookException::class)
  fun testItValidatesNullForMessage() {
    validateForMessage(null)
  }

  // -PhotoContent
  @Test(expected = FacebookException::class)
  fun testItValidatesNullImageForPhotoShareByMessage() {
    val spcBuilder = SharePhotoContent.Builder()
    val sharePhoto = SharePhoto.Builder().setImageUrl(null).setBitmap(null).build()
    val sharePhotoContent = spcBuilder.addPhoto(sharePhoto).build()
    validateForMessage(sharePhotoContent)
  }

  @Test(expected = FacebookException::class)
  fun testItValidatesEmptyListOfPhotoForPhotoShareByMessage() {
    val sharePhoto = SharePhotoContent.Builder().build()
    validateForMessage(sharePhoto)
  }

  @Test(expected = FacebookException::class)
  fun testItValidatesMaxSizeOfPhotoShareByMessage() {
    val sharePhotoContent =
        SharePhotoContent.Builder()
            .addPhoto(buildSharePhoto("https://facebook.com/awesome-1.gif"))
            .addPhoto(buildSharePhoto("https://facebook.com/awesome-2.gif"))
            .addPhoto(buildSharePhoto("https://facebook.com/awesome-3.gif"))
            .addPhoto(buildSharePhoto("https://facebook.com/awesome-4.gif"))
            .addPhoto(buildSharePhoto("https://facebook.com/awesome-5.gif"))
            .addPhoto(buildSharePhoto("https://facebook.com/awesome-6.gif"))
            .addPhoto(buildSharePhoto("https://facebook.com/awesome-7.gif"))
            .build()
    validateForMessage(sharePhotoContent)
  }

  // -ShareVideoContent
  @Test(expected = FacebookException::class)
  fun testItValidatesEmptyPreviewPhotoForShareVideoContentByMessage() {
    val sharePhoto = ShareVideoContent.Builder().setPreviewPhoto(null).build()
    validateForMessage(sharePhoto)
  }

  // Share by Native (Is the same as Message)
  @Test(expected = FacebookException::class)
  fun testItValidatesNullContentForNativeShare() {
    validateForNativeShare(null)
  }

  // Share by Web
  @Test(expected = FacebookException::class)
  fun testItValidatesNullContentForWebShare() {
    validateForWebShare(null)
  }

  @Test
  fun testItDoesAcceptSharePhotoContentByWeb() {
    val sharePhoto = buildSharePhoto("https://facebook.com/awesome.gif")
    val sharePhotoContent = SharePhotoContent.Builder().addPhoto(sharePhoto).build()
    validateForWebShare(sharePhotoContent)
  }

  @Test(expected = FacebookException::class)
  fun testItDoesNotAcceptShareVideoContentByWeb() {
    val previewPhoto = buildSharePhoto("https://facebook.com/awesome.gif")
    val shareVideoContent = ShareVideoContent.Builder().setPreviewPhoto(previewPhoto).build()
    validateForWebShare(shareVideoContent)
  }

  // Share by Api
  @Test(expected = FacebookException::class)
  fun testItValidatesNullContentForApiShare() {
    validateForApiShare(null)
  }

  @Test(expected = FacebookException::class)
  fun testItValidatesNullImageForSharePhotoContentByApi() {
    val spcBuilder = SharePhotoContent.Builder()
    val sharePhoto = SharePhoto.Builder().setImageUrl(null).build()
    val sharePhotoContent = spcBuilder.addPhoto(sharePhoto).build()
    validateForApiShare(sharePhotoContent)
  }

  private fun buildSharePhoto(url: String): SharePhoto {
    return SharePhoto.Builder().setImageUrl(Uri.parse(url)).build()
  }
}


/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 * All rights reserved.
 *
 * This source code is licensed under the license found in the
 * LICENSE file in the root directory of this source tree.
 */

package com.facebook.share.internal

import android.os.Parcel
import com.facebook.FacebookTestCase
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test

class ShareFeedContentTest : FacebookTestCase() {
  private lateinit var content: ShareFeedContent

  override fun setUp() {
    super.setUp()
    content =
        ShareFeedContent.Builder().setLink(LINK).setToId(TO_ID).setLinkCaption(LINK_CAPTION).build()
  }

  @Test
  fun `test builder`() {
    assertThat(content.link).isEqualTo(LINK)
    assertThat(content.toId).isEqualTo(TO_ID)
    assertThat(content.linkCaption).isEqualTo(LINK_CAPTION)
    assertThat(content.picture).isNull()
  }

  @Test
  fun `test build from parcel`() {
    val parcel = Parcel.obtain()
    content.writeToParcel(parcel, 0)
    parcel.setDataPosition(0)

    val recoveredContent = ShareFeedContent.CREATOR.createFromParcel(parcel)
    assertThat(recoveredContent.link).isEqualTo(LINK)
    assertThat(recoveredContent.linkCaption).isEqualTo(LINK_CAPTION)
    assertThat(recoveredContent.toId).isEqualTo(TO_ID)
    assertThat(recoveredContent.picture).isNull()
    assertThat(recoveredContent.linkName).isNull()
    assertThat(recoveredContent.linkDescription).isNull()
  }

  companion object {
    const val LINK: String = "https://www.facebook.com"
    const val LINK_CAPTION: String = "test caption"
    const val TO_ID: String = "123456789"
  }
}


/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 * All rights reserved.
 *
 * This source code is licensed under the license found in the
 * LICENSE file in the root directory of this source tree.
 */

package com.facebook.share.internal

import android.content.Intent
import android.graphics.Bitmap
import android.net.Uri
import android.os.Bundle
import androidx.test.core.app.ApplicationProvider
import com.facebook.FacebookCallback
import com.facebook.FacebookException
import com.facebook.FacebookOperationCanceledException
import com.facebook.FacebookPowerMockTestCase
import com.facebook.FacebookRequestError
import com.facebook.FacebookSdk
import com.facebook.GraphResponse
import com.facebook.HttpMethod
import com.facebook.internal.AppCall
import com.facebook.internal.CallbackManagerImpl
import com.facebook.internal.NativeProtocol
import com.facebook.share.Sharer
import com.facebook.share.model.CameraEffectTextures
import com.facebook.share.model.ShareCameraEffectContent
import com.facebook.share.model.ShareMediaContent
import com.facebook.share.model.SharePhoto
import com.facebook.share.model.SharePhotoContent
import com.facebook.share.model.ShareStoryContent
import com.facebook.share.model.ShareVideo
import com.facebook.share.model.ShareVideoContent
import java.io.File
import java.lang.Exception
import java.util.UUID
import org.assertj.core.api.Assertions.assertThat
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import org.junit.Test
import org.mockito.kotlin.any
import org.mockito.kotlin.anyOrNull
import org.mockito.kotlin.argumentCaptor
import org.mockito.kotlin.eq
import org.mockito.kotlin.mock
import org.mockito.kotlin.verify
import org.mockito.kotlin.whenever
import org.powermock.api.mockito.PowerMockito
import org.powermock.core.classloader.annotations.PrepareForTest

@PrepareForTest(FacebookSdk::class, NativeProtocol::class)
class ShareInternalUtilityTest : FacebookPowerMockTestCase() {
  private lateinit var mockCallback: FacebookCallback<Sharer.Result>
  private lateinit var mockGraphResponse: GraphResponse
  private lateinit var appCall: AppCall

  override fun setup() {
    super.setup()
    mockCallback = mock()
    mockGraphResponse = mock()
    PowerMockito.mockStatic(FacebookSdk::class.java)
    whenever(FacebookSdk.isInitialized()).thenReturn(true)
    whenever(FacebookSdk.getApplicationId()).thenReturn("123456789")
    whenever(FacebookSdk.getApplicationContext())
        .thenReturn(ApplicationProvider.getApplicationContext())
    PowerMockito.mockStatic(NativeProtocol::class.java)
    // clean pending call
    AppCall.finishPendingCall(UUID.randomUUID(), 0)
    appCall = AppCall(TEST_REQUEST_CODE)
  }

  @Test
  fun testRemoveNamespaceFromNullOGJsonObject() {
    assertThat(ShareInternalUtility.removeNamespacesFromOGJsonObject(null, false)).isNull()
  }

  @Test
  fun `test removeNamespacesFromOGJsonObject with empty JSON object`() {
    val emptyObject = JSONObject()
    assertThat(ShareInternalUtility.removeNamespacesFromOGJsonObject(emptyObject, false)).isNull()
  }

  @Test
  fun testRemoveNamespaceFromComplexOGJsonObject() {
    try {
      var testObject = jsonOGActionTestObject
      testObject =
          checkNotNull(ShareInternalUtility.removeNamespacesFromOGJsonObject(testObject, false))
      val expectedResult = jsonOGActionTestObjectWithoutNamespace
      assertThat(simpleJsonObjComparer(testObject, expectedResult)).isTrue
    } catch (ex: JSONException) {
      // Fail
      assertThat(ex).isNotNull
    }
  }

  @Test
  fun `test invokeCallbackWithException on receiving FacebookException`() {
    val exception = FacebookException("test message")
    ShareInternalUtility.invokeCallbackWithException(mockCallback, exception)
    verify(mockCallback).onError(exception)
  }

  @Test
  fun `test invokeCallbackWithException on receiving normal exception`() {
    val exception = Exception("test message")
    val exceptionCaptor = argumentCaptor<FacebookException>()
    ShareInternalUtility.invokeCallbackWithException(mockCallback, exception)
    verify(mockCallback).onError(exceptionCaptor.capture())
    assertThat(exceptionCaptor.firstValue.message).contains(exception.message)
  }

  @Test
  fun `test invokeCallbackWithException with null callback`() {
    val exception = Exception("test message")
    ShareInternalUtility.invokeCallbackWithException(null, exception)
  }

  @Test
  fun `test invokeCallbackWithError`() {
    val errorMessage = "test message"
    val exceptionCaptor = argumentCaptor<FacebookException>()
    ShareInternalUtility.invokeCallbackWithError(mockCallback, errorMessage)
    verify(mockCallback).onError(exceptionCaptor.capture())
    assertThat(exceptionCaptor.firstValue.message).contains(errorMessage)
  }

  @Test
  fun `test invokeCallbackWithError with null callback`() {
    val errorMessage = "test message"
    ShareInternalUtility.invokeCallbackWithError(null, errorMessage)
  }

  @Test
  fun `test invokeCallbackWithResults on receiving success result`() {
    val testPostId = "12345"
    whenever(mockGraphResponse.error).thenReturn(null)
    val resultCaptor = argumentCaptor<Sharer.Result>()
    ShareInternalUtility.invokeCallbackWithResults(mockCallback, testPostId, mockGraphResponse)
    verify(mockCallback).onSuccess(resultCaptor.capture())
    assertThat(resultCaptor.firstValue.postId).isEqualTo(testPostId)
  }

  @Test
  fun `test invokeCallbackWithResults on receiving error response`() {
    val error = FacebookRequestError(400, "test error type", "test error")
    whenever(mockGraphResponse.error).thenReturn(error)
    val errorCaptor = argumentCaptor<FacebookException>()
    ShareInternalUtility.invokeCallbackWithResults(mockCallback, null, mockGraphResponse)
    verify(mockCallback).onError(errorCaptor.capture())
    assertThat(errorCaptor.firstValue.message).contains(error.errorMessage)
  }

  @Test
  fun `test invokeCallbackWithResults will generate non-empty error message on receiving unknown error`() {
    val error = mock<FacebookRequestError>()
    whenever(mockGraphResponse.error).thenReturn(error)
    val errorCaptor = argumentCaptor<FacebookException>()
    ShareInternalUtility.invokeCallbackWithResults(mockCallback, null, mockGraphResponse)
    verify(mockCallback).onError(errorCaptor.capture())
    assertThat(errorCaptor.firstValue.message).isNotEmpty
  }

  @Test
  fun `test getting a native dialog completion gesture`() {
    val result = Bundle()
    val gesture = "post"
    result.putString(NativeProtocol.EXTRA_DIALOG_COMPLETION_GESTURE_KEY, gesture)
    assertThat(ShareInternalUtility.getNativeDialogCompletionGesture(result)).isEqualTo(gesture)
  }

  @Test
  fun `test getting the native dialog completion gesture in result args`() {
    val result = Bundle()
    val gesture = "post"
    result.putString(NativeProtocol.RESULT_ARGS_DIALOG_COMPLETION_GESTURE_KEY, gesture)
    assertThat(ShareInternalUtility.getNativeDialogCompletionGesture(result)).isEqualTo(gesture)
  }

  @Test
  fun `test getting a post id`() {
    val result = Bundle()
    val postId = "12345"
    result.putString(ShareConstants.RESULT_POST_ID, postId)
    assertThat(ShareInternalUtility.getShareDialogPostId(result)).isEqualTo(postId)
  }

  @Test
  fun `test handleActivityResult with success result`() {
    // prepare appCall and make it pending
    val mockIntent = mock<Intent>()
    val successResult = Bundle()
    whenever(NativeProtocol.getCallIdFromIntent(mockIntent)).thenReturn(appCall.callId)
    whenever(NativeProtocol.getSuccessResultsFromIntent(mockIntent)).thenReturn(successResult)
    appCall.setPending()

    val mockResultProcessor = mock<ResultProcessor>()
    val result =
        ShareInternalUtility.handleActivityResult(
            TEST_REQUEST_CODE, 0, mockIntent, mockResultProcessor)
    assertThat(result).isTrue
    verify(mockResultProcessor).onSuccess(appCall, successResult)
  }

  @Test
  fun `test handleActivityResult with cancel result`() {
    val mockIntent = mock<Intent>()
    val cancelException = FacebookOperationCanceledException()
    whenever(NativeProtocol.getCallIdFromIntent(mockIntent)).thenReturn(appCall.callId)
    whenever(NativeProtocol.getExceptionFromErrorData(anyOrNull())).thenReturn(cancelException)
    appCall.setPending()

    val mockResultProcessor = mock<ResultProcessor>()
    val result =
        ShareInternalUtility.handleActivityResult(
            TEST_REQUEST_CODE, 0, mockIntent, mockResultProcessor)
    assertThat(result).isTrue
    verify(mockResultProcessor).onCancel(appCall)
  }

  @Test
  fun `test handleActivityResult with error result`() {
    val mockIntent = mock<Intent>()
    whenever(NativeProtocol.getCallIdFromIntent(mockIntent)).thenReturn(appCall.callId)
    val exception = FacebookException("unknown")
    whenever(NativeProtocol.getExceptionFromErrorData(anyOrNull())).thenReturn(exception)
    appCall.setPending()

    val mockResultProcessor = mock<ResultProcessor>()
    val result =
        ShareInternalUtility.handleActivityResult(
            TEST_REQUEST_CODE, 0, mockIntent, mockResultProcessor)
    assertThat(result).isTrue
    verify(mockResultProcessor).onError(appCall, exception)
  }

  @Test
  fun `test handleActivityResult without pending app call`() {
    val mockIntent = mock<Intent>()
    val mockResultProcessor = mock<ResultProcessor>()
    val result =
        ShareInternalUtility.handleActivityResult(
            TEST_REQUEST_CODE, 0, mockIntent, mockResultProcessor)
    assertThat(result).isFalse
  }

  @Test
  fun `test sharing result processor with success result`() {
    val resultProcessor = ShareInternalUtility.getShareResultProcessor(mockCallback)
    val result = Bundle()
    val postId = "12345"
    result.putString(ShareConstants.RESULT_POST_ID, postId)
    result.putString(NativeProtocol.RESULT_ARGS_DIALOG_COMPLETION_GESTURE_KEY, "Post")
    resultProcessor.onSuccess(appCall, result)
    val resultCaptor = argumentCaptor<Sharer.Result>()
    verify(mockCallback).onSuccess(resultCaptor.capture())
    assertThat(resultCaptor.firstValue.postId).isEqualTo(postId)
  }

  @Test
  fun `test sharing result processor with cancel result`() {
    val resultProcessor = ShareInternalUtility.getShareResultProcessor(mockCallback)
    val result = Bundle()
    result.putString(NativeProtocol.RESULT_ARGS_DIALOG_COMPLETION_GESTURE_KEY, "Cancel")
    resultProcessor.onSuccess(appCall, result)
    verify(mockCallback).onCancel()
  }

  @Test
  fun `test sharing result processor with error`() {
    val resultProcessor = ShareInternalUtility.getShareResultProcessor(mockCallback)
    val result = Bundle()
    result.putString(NativeProtocol.RESULT_ARGS_DIALOG_COMPLETION_GESTURE_KEY, "Crash")
    resultProcessor.onSuccess(appCall, result)
    verify(mockCallback).onError(any())
  }

  @Test
  fun `test sharing result processor with empty bundle`() {
    val resultProcessor = ShareInternalUtility.getShareResultProcessor(mockCallback)
    val result = Bundle()
    resultProcessor.onSuccess(appCall, result)
    verify(mockCallback).onSuccess(any())
  }

  @Test
  fun `test registering callback on a callback manager`() {
    val mockCallbackManager = mock<CallbackManagerImpl>()
    val mockReturnIntern = mock<Intent>()
    // prepare the result bundle
    val successResultBundle = Bundle()
    val postId = "12345"
    successResultBundle.putString(ShareConstants.RESULT_POST_ID, postId)
    successResultBundle.putString(NativeProtocol.RESULT_ARGS_DIALOG_COMPLETION_GESTURE_KEY, "Post")
    whenever(NativeProtocol.getCallIdFromIntent(mockReturnIntern)).thenReturn(appCall.callId)
    whenever(NativeProtocol.getSuccessResultsFromIntent(mockReturnIntern))
        .thenReturn(successResultBundle)
    appCall.setPending()

    ShareInternalUtility.registerSharerCallback(
        TEST_REQUEST_CODE, mockCallbackManager, mockCallback)

    val callbackCaptor = argumentCaptor<CallbackManagerImpl.Callback>()
    verify(mockCallbackManager).registerCallback(eq(TEST_REQUEST_CODE), callbackCaptor.capture())
    callbackCaptor.firstValue.onActivityResult(0, mockReturnIntern)
    val successResultCaptor = argumentCaptor<Sharer.Result>()
    verify(mockCallback).onSuccess(successResultCaptor.capture())
    assertThat(successResultCaptor.firstValue.postId).isEqualTo("12345")
  }

  @Test
  fun `test getting the photo urls from a photo content`() {
    val testPhotoImage = Bitmap.createBitmap(1, 1, Bitmap.Config.ALPHA_8)
    val photoContent =
        SharePhotoContent.Builder()
            .addPhoto(SharePhoto.Builder().setBitmap(testPhotoImage).build())
            .build()
    val returnList = ShareInternalUtility.getPhotoUrls(photoContent, appCall.callId)
    assertThat(returnList?.size).isEqualTo(1)
  }

  @Test
  fun `test getting a video url`() {
    val tempFile = File(UUID.randomUUID().toString())
    tempFile.createNewFile()
    tempFile.deleteOnExit()
    val shareVideo = ShareVideo.Builder().setLocalUrl(Uri.fromFile(tempFile)).build()
    val shareVideoContent = ShareVideoContent.Builder().setVideo(shareVideo).build()
    val videoUrl = ShareInternalUtility.getVideoUrl(shareVideoContent, appCall.callId)
    assertThat(videoUrl).isNotEmpty()
  }

  @Test
  fun `test getting the media infos from a media content`() {
    val testPhotoImage = Bitmap.createBitmap(1, 1, Bitmap.Config.ALPHA_8)
    val sharePhoto = SharePhoto.Builder().setBitmap(testPhotoImage).build()
    val mediaContent = ShareMediaContent.Builder().addMedia(listOf(sharePhoto)).build()
    val mediaInfos = checkNotNull(ShareInternalUtility.getMediaInfos(mediaContent, appCall.callId))
    assertThat(mediaInfos.size).isEqualTo(1)
    val mediaInfo = mediaInfos[0]
    assertThat(mediaInfo.getString(ShareConstants.MEDIA_TYPE))
        .isEqualTo(sharePhoto.mediaType.toString())
    assertThat(mediaInfo.getString(ShareConstants.MEDIA_URI)).isNotEmpty
  }

  @Test
  fun `test getting the background media from a story content`() {
    val testPhotoImage = Bitmap.createBitmap(1, 1, Bitmap.Config.ALPHA_8)
    val sharePhoto = SharePhoto.Builder().setBitmap(testPhotoImage).build()
    val shareStoryContent = ShareStoryContent.Builder().setBackgroundAsset(sharePhoto).build()
    val mediaInfo =
        checkNotNull(
            ShareInternalUtility.getBackgroundAssetMediaInfo(shareStoryContent, appCall.callId))
    assertThat(mediaInfo.getString(ShareConstants.MEDIA_TYPE))
        .isEqualTo(sharePhoto.mediaType.toString())
  }

  @Test
  fun `test getting the sticker url from a story content`() {
    val testPhotoImage = Bitmap.createBitmap(1, 1, Bitmap.Config.ALPHA_8)
    val sharePhoto = SharePhoto.Builder().setBitmap(testPhotoImage).build()
    val shareStoryContent = ShareStoryContent.Builder().setStickerAsset(sharePhoto).build()
    val stickerInfo =
        checkNotNull(ShareInternalUtility.getStickerUrl(shareStoryContent, appCall.callId))
    assertThat(stickerInfo.getString(ShareConstants.MEDIA_URI)).isNotEmpty()
  }

  @Test
  fun `test getting the texture url bundle from a camera effect`() {
    val testPhotoImage = Bitmap.createBitmap(1, 1, Bitmap.Config.ALPHA_8)
    val texture = CameraEffectTextures.Builder().putTexture("test", testPhotoImage).build()
    val effect = ShareCameraEffectContent.Builder().setTextures(texture).build()
    val urlBundle = ShareInternalUtility.getTextureUrlBundle(effect, appCall.callId)
    assertThat(urlBundle?.getString("test")).isNotNull
  }

  @Test
  fun `test creating upload a bitmap as staging resource`() {
    val testPhotoImage = Bitmap.createBitmap(1, 1, Bitmap.Config.ALPHA_8)
    val request =
        ShareInternalUtility.newUploadStagingResourceWithImageRequest(null, testPhotoImage, null)
    assertThat(request.httpMethod).isEqualTo(HttpMethod.POST)
    assertThat(request.parameters.getParcelable<Bitmap>(ShareInternalUtility.STAGING_PARAM))
        .isEqualTo(testPhotoImage)
    assertThat(request.graphPath).isEqualTo(ShareInternalUtility.MY_STAGING_RESOURCES)
  }

  @Test
  fun `test creating upload a content uri as staging resource`() {
    val fileUri = Uri.parse("content://tmp/test.png")
    val request = ShareInternalUtility.newUploadStagingResourceWithImageRequest(null, fileUri, null)
    assertThat(request.httpMethod).isEqualTo(HttpMethod.POST)
    assertThat(request.graphPath).isEqualTo(ShareInternalUtility.MY_STAGING_RESOURCES)
  }

  @Test
  fun `test creating upload a file as staging resource`() {
    val tempFile = File(UUID.randomUUID().toString())
    tempFile.createNewFile()
    tempFile.deleteOnExit()

    val request =
        ShareInternalUtility.newUploadStagingResourceWithImageRequest(null, tempFile, null)
    assertThat(request.httpMethod).isEqualTo(HttpMethod.POST)
    assertThat(request.graphPath).isEqualTo(ShareInternalUtility.MY_STAGING_RESOURCES)
  }

  @Test
  fun `test getting the uri extension`() {
    assertThat(ShareInternalUtility.getUriExtension(Uri.parse("file://test.tar.gz")))
        .isEqualTo(".gz")
    assertThat(ShareInternalUtility.getUriExtension(Uri.parse("file://test-file"))).isNull()
  }

  companion object {
    const val TEST_REQUEST_CODE = 0xface

    private val jsonOGActionTestObject: JSONObject
      get() {
        val testAction = JSONObject()
        testAction.put("og:field", 1)
        testAction.put("namespaced:custom:field", 3)
        val testOGContent = jsonOGContentTestObject
        testAction.put("namespaced:content", testOGContent)
        testAction.put("array", jsonOGArrayTestObject)
        return testAction
      }

    private val jsonOGActionTestObjectWithoutNamespace: JSONObject
      get() {
        val testAction = JSONObject()
        testAction.put("field", 1)
        testAction.put("custom:field", 3)
        val testOGContent = jsonOGContentTestObjectWithoutNamespace
        testAction.put("content", testOGContent)
        testAction.put("array", jsonOGArrayTestObjectWithoutNamespace)
        return testAction
      }

    private val jsonOGArrayTestObject: JSONArray
      get() {
        val testArray = JSONArray()
        testArray.put(10)
        testArray.put(jsonOGContentTestObject)
        return testArray
      }

    private val jsonOGArrayTestObjectWithoutNamespace: JSONArray
      get() {
        val testArray = JSONArray()
        testArray.put(10)
        testArray.put(jsonOGContentTestObjectWithoutNamespace)
        return testArray
      }

    private val jsonOGContentTestObject: JSONObject
      get() {
        val testOGContent = JSONObject()
        testOGContent.put("fbsdk:create", true)
        testOGContent.put("namespaced:field", 4)
        testOGContent.put("og:field", 5)
        testOGContent.put("custom:namespaced:field", 6)
        val innerContent = JSONObject()
        innerContent.put("namespaced:field", 7)
        innerContent.put("og:field", 8)
        testOGContent.put("namespaced:innerContent", innerContent)
        return testOGContent
      }

    private val jsonOGContentTestObjectWithoutNamespace: JSONObject
      get() {
        val testOGContent = JSONObject()
        testOGContent.put("fbsdk:create", true)
        testOGContent.put("field", 5)
        val innerContent = JSONObject()
        innerContent.put("field", 8)
        val innerData = JSONObject()
        innerData.put("field", 7)
        innerContent.put("data", innerData)
        val data = JSONObject()
        data.put("field", 4)
        data.put("namespaced:field", 6)
        data.put("innerContent", innerContent)
        testOGContent.put("data", data)
        return testOGContent
      }
    private fun simpleJsonObjComparer(obj1: JSONObject, obj2: JSONObject): Boolean {
      if (obj1.length() != obj2.length()) {
        return false
      }
      val keys = obj1.keys()
      while (keys.hasNext()) {
        try {
          val key = keys.next()
          val value1 = obj1[key]
          val value2 = obj2[key]
          if (!jsonObjectValueComparer(value1, value2)) {
            return false
          }
        } catch (ex: Exception) {
          return false
        }
      }
      return true
    }

    private fun simpleJsonArrayComparer(array1: JSONArray, array2: JSONArray): Boolean {
      if (array1.length() != array2.length()) {
        return false
      }
      for (i in 0 until array1.length()) {
        if (!jsonObjectValueComparer(array1[i], array2[i])) {
          return false
        }
      }
      return true
    }

    private fun jsonObjectValueComparer(value1: Any, value2: Any): Boolean {
      if (value1 is JSONObject) {
        if (!simpleJsonObjComparer(value1, value2 as JSONObject)) {
          return false
        }
      } else if (value1 is JSONArray) {
        if (!simpleJsonArrayComparer(value1, value2 as JSONArray)) {
          return false
        }
      } else if (value1 !== value2) {
        return false
      }
      return true
    }
  }
}


/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 * All rights reserved.
 *
 * This source code is licensed under the license found in the
 * LICENSE file in the root directory of this source tree.
 */

package com.facebook.share.internal

import android.net.Uri
import com.facebook.FacebookTestCase
import com.facebook.share.model.AppGroupCreationContent
import com.facebook.share.model.GameRequestContent
import com.facebook.share.model.ShareHashtag
import com.facebook.share.model.ShareLinkContent
import com.facebook.share.model.SharePhoto
import com.facebook.share.model.SharePhotoContent
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test

class WebDialogParametersTest : FacebookTestCase() {

  @Test
  fun `test create with AppGroupCreationContent`() {
    val appGroupCreationContent =
        AppGroupCreationContent.Builder()
            .setName("name")
            .setDescription("description")
            .setAppGroupPrivacy(AppGroupCreationContent.AppGroupPrivacy.Closed)
            .build()

    val bundle = WebDialogParameters.create(appGroupCreationContent)
    assertThat(bundle.getString(ShareConstants.WEB_DIALOG_PARAM_NAME)).isEqualTo("name")
    assertThat(bundle.getString(ShareConstants.WEB_DIALOG_PARAM_DESCRIPTION))
        .isEqualTo("description")
    assertThat(bundle.getString(ShareConstants.WEB_DIALOG_PARAM_PRIVACY)).isEqualTo("closed")
  }

  @Test
  fun `test create with GameRequestContent`() {
    val gameRequestContent =
        GameRequestContent.Builder()
            .setMessage("message")
            .setRecipients(listOf("recipient1", "recipient2"))
            .setTitle("title")
            .setData("data")
            .setActionType(GameRequestContent.ActionType.INVITE)
            .setObjectId("objectId")
            .setFilters(GameRequestContent.Filters.APP_USERS)
            .setSuggestions(listOf("suggestion1", "suggestion2"))
            .build()

    val bundle = WebDialogParameters.create(gameRequestContent)
    assertThat(bundle.getString(ShareConstants.WEB_DIALOG_PARAM_MESSAGE)).isEqualTo("message")
    assertThat(bundle.getString(ShareConstants.WEB_DIALOG_PARAM_TO))
        .isEqualTo("recipient1,recipient2")
    assertThat(bundle.getString(ShareConstants.WEB_DIALOG_PARAM_TITLE)).isEqualTo("title")
    assertThat(bundle.getString(ShareConstants.WEB_DIALOG_PARAM_DATA)).isEqualTo("data")
    assertThat(bundle.getString(ShareConstants.WEB_DIALOG_PARAM_ACTION_TYPE)).isEqualTo("invite")
    assertThat(bundle.getString(ShareConstants.WEB_DIALOG_PARAM_OBJECT_ID)).isEqualTo("objectId")
    assertThat(bundle.getString(ShareConstants.WEB_DIALOG_PARAM_FILTERS)).isEqualTo("app_users")
    assertThat(bundle.getString(ShareConstants.WEB_DIALOG_PARAM_SUGGESTIONS))
        .isEqualTo("suggestion1,suggestion2")
  }

  @Test
  fun `test create with ShareLinkContent`() {
    val shareLinkContent =
        ShareLinkContent.Builder()
            .setContentUrl(Uri.parse("www.facebook.com/content_url"))
            .setQuote("quote")
            .setShareHashtag(ShareHashtag.Builder().setHashtag("#hashtag").build())
            .build()

    val bundle = WebDialogParameters.create(shareLinkContent)
    assertThat(bundle.getString(ShareConstants.WEB_DIALOG_PARAM_LINK)).isNull()
    assertThat(bundle.getString(ShareConstants.WEB_DIALOG_PARAM_HREF))
        .isEqualTo("www.facebook.com/content_url")
    assertThat(bundle.getString(ShareConstants.WEB_DIALOG_PARAM_QUOTE)).isEqualTo("quote")
    assertThat(bundle.getString(ShareConstants.WEB_DIALOG_PARAM_HASHTAG)).isEqualTo("#hashtag")
  }

  @Test
  fun `test create with SharePhotoContent`() {
    val photoUrlStrings = arrayListOf("www.facebook.com/photo1", "www.facebook.com/photo2")
    val sharePhotos =
        photoUrlStrings.map { SharePhoto.Builder().setImageUrl(Uri.parse(it)).build() }

    val sharePhotoContent =
        SharePhotoContent.Builder()
            .setPhotos(sharePhotos)
            .setShareHashtag(ShareHashtag.Builder().setHashtag("#hashtag").build())
            .build()

    val bundle = WebDialogParameters.create(sharePhotoContent)
    assertThat(bundle.getStringArray(ShareConstants.WEB_DIALOG_PARAM_MEDIA))
        .isEqualTo(photoUrlStrings.toArray())
    assertThat(bundle.getString(ShareConstants.WEB_DIALOG_PARAM_HASHTAG)).isEqualTo("#hashtag")
  }

  @Test
  fun `test createBaseParameters only sets the hashtag`() {
    val shareLinkContent =
        ShareLinkContent.Builder()
            .setContentUrl(Uri.parse("www.facebook.com/content_url"))
            .setQuote("quote")
            .setShareHashtag(ShareHashtag.Builder().setHashtag("#hashtag").build())
            .build()

    val bundle = WebDialogParameters.createBaseParameters(shareLinkContent)
    assertThat(bundle.getString(ShareConstants.WEB_DIALOG_PARAM_LINK)).isNull()
    assertThat(bundle.getString(ShareConstants.WEB_DIALOG_PARAM_QUOTE)).isNull()
    assertThat(bundle.getString(ShareConstants.WEB_DIALOG_PARAM_HASHTAG)).isEqualTo("#hashtag")
  }

  @Test
  fun `test createForFeed with ShareLinkContent`() {
    val shareLinkContent =
        ShareLinkContent.Builder()
            .setContentUrl(Uri.parse("www.facebook.com/content_url"))
            .setQuote("quote")
            .setShareHashtag(ShareHashtag.Builder().setHashtag("#hashtag").build())
            .build()

    val bundle = WebDialogParameters.createForFeed(shareLinkContent)
    assertThat(bundle.getString(ShareConstants.WEB_DIALOG_PARAM_NAME))
        .isNull() // setContentTitle is deprecated and does nothing
    assertThat(bundle.getString(ShareConstants.WEB_DIALOG_PARAM_DESCRIPTION))
        .isNull() // setContentDescription is deprecated and does nothing
    assertThat(bundle.getString(ShareConstants.WEB_DIALOG_PARAM_LINK))
        .isEqualTo("www.facebook.com/content_url")
    assertThat(bundle.getString(ShareConstants.WEB_DIALOG_PARAM_PICTURE))
        .isNull() // setImageUrl does nothing
    assertThat(bundle.getString(ShareConstants.WEB_DIALOG_PARAM_QUOTE)).isEqualTo("quote")
    assertThat(bundle.getString(ShareConstants.WEB_DIALOG_PARAM_HASHTAG)).isEqualTo("#hashtag")
  }

  @Test
  fun `test createForFeed with ShareFeedContent`() {
    val shareFeedContent =
        ShareFeedContent.Builder()
            .setToId("toId")
            .setLink("link")
            .setPicture("picture")
            .setMediaSource("mediaSource")
            .setLinkName("linkName")
            .setLinkCaption("linkCaption")
            .setLinkDescription("linkDescription")
            .build()

    val bundle = WebDialogParameters.createForFeed(shareFeedContent)
    assertThat(bundle.getString(ShareConstants.FEED_TO_PARAM)).isEqualTo("toId")
    assertThat(bundle.getString(ShareConstants.FEED_LINK_PARAM)).isEqualTo("link")
    assertThat(bundle.getString(ShareConstants.FEED_PICTURE_PARAM)).isEqualTo("picture")
    assertThat(bundle.getString(ShareConstants.FEED_SOURCE_PARAM)).isEqualTo("mediaSource")
    assertThat(bundle.getString(ShareConstants.FEED_NAME_PARAM)).isEqualTo("linkName")
    assertThat(bundle.getString(ShareConstants.FEED_CAPTION_PARAM)).isEqualTo("linkCaption")
    assertThat(bundle.getString(ShareConstants.FEED_DESCRIPTION_PARAM)).isEqualTo("linkDescription")
  }
}


/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 * All rights reserved.
 *
 * This source code is licensed under the license found in the
 * LICENSE file in the root directory of this source tree.
 */

package com.facebook.share.model

import android.os.Parcel
import com.facebook.FacebookTestCase
import com.facebook.share.model.AppGroupCreationContent.AppGroupPrivacy
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Test

class AppGroupCreationContentTest : FacebookTestCase() {
  private lateinit var appGroupCreationContent: AppGroupCreationContent

  @Before
  fun init() {
    appGroupCreationContent =
        AppGroupCreationContent.Builder()
            .setName("name")
            .setDescription("description")
            .setAppGroupPrivacy(AppGroupPrivacy.Open)
            .build()
  }

  @Test
  fun `test build AppGroupCreationContent`() {
    assertThat(appGroupCreationContent).isNotNull
  }

  @Test
  fun `test getName`() {
    assertThat(appGroupCreationContent.name).isEqualTo("name")
  }

  @Test
  fun `test getDescription`() {
    assertThat(appGroupCreationContent.description).isEqualTo("description")
  }

  @Test
  fun `test getAppGroupPrivacy`() {
    assertThat(appGroupCreationContent.appGroupPrivacy).isEqualTo(AppGroupPrivacy.Open)
  }

  @Test
  fun `test serialize with parcel`() {
    val parcel = Parcel.obtain()
    parcel.writeParcelable(appGroupCreationContent, 0)
    parcel.setDataPosition(0)

    val recoveredContent =
        parcel.readParcelable<AppGroupCreationContent>(
            AppGroupCreationContent::class.java.classLoader)
    checkNotNull(recoveredContent)
    assertThat(recoveredContent.name).isEqualTo(appGroupCreationContent.name)
    assertThat(recoveredContent.description).isEqualTo(appGroupCreationContent.description)
    assertThat(recoveredContent.appGroupPrivacy).isEqualTo(appGroupCreationContent.appGroupPrivacy)
    parcel.recycle()
  }

  @Test
  fun `test builder read from existing content`() {
    val recoveredContent =
        AppGroupCreationContent.Builder().readFrom(appGroupCreationContent).build()
    checkNotNull(recoveredContent)
    assertThat(recoveredContent.name).isEqualTo(appGroupCreationContent.name)
    assertThat(recoveredContent.description).isEqualTo(appGroupCreationContent.description)
    assertThat(recoveredContent.appGroupPrivacy).isEqualTo(appGroupCreationContent.appGroupPrivacy)
  }
}


/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 * All rights reserved.
 *
 * This source code is licensed under the license found in the
 * LICENSE file in the root directory of this source tree.
 */

package com.facebook.share.model

import android.os.Parcel
import com.facebook.FacebookTestCase
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Test

class CameraEffectArgumentsTest : FacebookTestCase() {
  private lateinit var cameraEffectArguments: CameraEffectArguments
  private val itemArray = arrayOf("item1", "item2")
  private val expectedKeySet = setOf("string_key", "string_array_key")

  @Before
  fun init() {
    cameraEffectArguments =
        CameraEffectArguments.Builder()
            .putArgument("string_key", "string_value")
            .putArgument("string_array_key", itemArray)
            .build()
  }

  @Test
  fun `test builder`() {
    assertThat(cameraEffectArguments).isNotNull
  }

  @Test
  fun `test getString`() {
    assertThat(cameraEffectArguments.getString("string_key")).isEqualTo("string_value")
    assertThat(cameraEffectArguments.getString("does_not_exist")).isNull()
  }

  @Test
  fun `test getStringArray`() {
    assertThat(cameraEffectArguments.getStringArray("string_array_key")).isEqualTo(itemArray)
    assertThat(cameraEffectArguments.getStringArray("does_not_exist")).isNull()
  }

  @Test
  fun `test get`() {
    assertThat(cameraEffectArguments.get("string_key")).isEqualTo("string_value")
    assertThat(cameraEffectArguments.get("string_array_key")).isEqualTo(itemArray)
  }

  @Test
  fun `test keySet`() {
    assertThat(cameraEffectArguments.keySet()).isEqualTo(expectedKeySet)
  }

  @Test
  fun `test serialize with parcel`() {
    val parcel = Parcel.obtain()
    parcel.writeParcelable(cameraEffectArguments, 0)
    parcel.setDataPosition(0)

    val recoveredContent =
        parcel.readParcelable<CameraEffectArguments>(CameraEffectArguments::class.java.classLoader)
    checkNotNull(recoveredContent)
    assertThat(recoveredContent.getString("string_key")).isEqualTo("string_value")
    assertThat(recoveredContent.getStringArray("string_array_key")).isEqualTo(itemArray)
    assertThat(recoveredContent.keySet()).isEqualTo(expectedKeySet)

    parcel.recycle()
  }

  @Test
  fun `test builder read from existing content`() {
    val recoveredContent = CameraEffectArguments.Builder().readFrom(cameraEffectArguments).build()
    assertThat(recoveredContent.getString("string_key")).isEqualTo("string_value")
    assertThat(recoveredContent.getStringArray("string_array_key")).isEqualTo(itemArray)
    assertThat(recoveredContent.keySet()).isEqualTo(expectedKeySet)
  }
}


/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 * All rights reserved.
 *
 * This source code is licensed under the license found in the
 * LICENSE file in the root directory of this source tree.
 */

package com.facebook.share.model

import android.graphics.Bitmap
import android.net.Uri
import android.os.Parcel
import com.facebook.FacebookTestCase
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Test

class CameraEffectTexturesTest : FacebookTestCase() {
  private val bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ALPHA_8)
  private val uri = Uri.parse("https://image.png")

  private lateinit var cameraEffectTextures: CameraEffectTextures

  @Before
  fun init() {
    cameraEffectTextures =
        CameraEffectTextures.Builder().putTexture("bitmap", bitmap).putTexture("uri", uri).build()
  }

  @Test
  fun `test builder`() {
    assertThat(cameraEffectTextures).isNotNull
  }

  @Test
  fun `test getTextureBitmap`() {
    assertThat(cameraEffectTextures.getTextureBitmap("bitmap")).isEqualTo(bitmap)
    assertThat(cameraEffectTextures.getTextureBitmap("uri")).isNull()
    assertThat(cameraEffectTextures.getTextureBitmap("key_does_not_exist")).isNull()
  }

  @Test
  fun `test getTextureUri`() {
    assertThat(cameraEffectTextures.getTextureUri("uri")).isEqualTo(uri)
    assertThat(cameraEffectTextures.getTextureUri("bitmap")).isNull()
    assertThat(cameraEffectTextures.getTextureUri("key_does_not_exist")).isNull()
  }

  @Test
  fun `test get`() {
    assertThat(cameraEffectTextures.get("uri")).isEqualTo(uri)
    assertThat(cameraEffectTextures.get("bitmap")?.javaClass).isEqualTo(Bitmap::class.java)
  }

  @Test
  fun `test keySet`() {
    assertThat(cameraEffectTextures.keySet()).isEqualTo(setOf("bitmap", "uri"))
  }

  @Test
  fun `test serialize with parcel`() {
    val parcel = Parcel.obtain()
    parcel.writeParcelable(cameraEffectTextures, 0)
    parcel.setDataPosition(0)

    val recoveredContent =
        parcel.readParcelable<CameraEffectTextures>(CameraEffectTextures::class.java.classLoader)
    checkNotNull(recoveredContent)
    assertThat(recoveredContent.getTextureBitmap("bitmap")).isNotNull
    assertThat(recoveredContent.getTextureUri("uri")).isEqualTo(uri)
    assertThat(recoveredContent.keySet()).isEqualTo(setOf("bitmap", "uri"))
    parcel.recycle()
  }

  @Test
  fun `test builder read from existing content`() {
    val recoveredContent = CameraEffectTextures.Builder().readFrom(cameraEffectTextures).build()
    assertThat(recoveredContent.getTextureBitmap("bitmap")).isNotNull
    assertThat(recoveredContent.getTextureUri("uri")).isEqualTo(uri)
    assertThat(recoveredContent.keySet()).isEqualTo(setOf("bitmap", "uri"))
  }
}


/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 * All rights reserved.
 *
 * This source code is licensed under the license found in the
 * LICENSE file in the root directory of this source tree.
 */

package com.facebook.share.model

import android.os.Parcel
import com.facebook.FacebookTestCase
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test

class GameRequestContentTest : FacebookTestCase() {
  private lateinit var gameRequestContent: GameRequestContent

  override fun setUp() {
    super.setUp()

    gameRequestContent =
        GameRequestContent.Builder()
            .setMessage("message")
            .setCta("cta")
            .setRecipients(listOf("recipient1", "recipient2"))
            .setTitle("title")
            .setData("data")
            .setActionType(GameRequestContent.ActionType.INVITE)
            .setObjectId("objectId")
            .setFilters(GameRequestContent.Filters.APP_USERS)
            .setSuggestions(listOf("suggestion1", "suggestion2"))
            .build()
  }

  @Test
  fun `test build GameRequestContent`() {
    assertThat(gameRequestContent).isNotNull
  }

  @Test
  fun `test getMessage`() {
    assertThat(gameRequestContent.message).isEqualTo("message")
  }

  @Test
  fun `test getCta`() {
    assertThat(gameRequestContent.cta).isEqualTo("cta")
  }

  @Test
  fun `test getRecipients`() {
    assertThat(gameRequestContent.recipients).isEqualTo(listOf("recipient1", "recipient2"))
  }

  @Test
  fun `test getTitle`() {
    assertThat(gameRequestContent.title).isEqualTo("title")
  }

  @Test
  fun `test getData`() {
    assertThat(gameRequestContent.data).isEqualTo("data")
  }

  @Test
  fun `test getActionType`() {
    assertThat(gameRequestContent.actionType).isEqualTo(GameRequestContent.ActionType.INVITE)
  }

  @Test
  fun `test getObjectId`() {
    assertThat(gameRequestContent.objectId).isEqualTo("objectId")
  }

  @Test
  fun `test getFilters`() {
    assertThat(gameRequestContent.filters).isEqualTo(GameRequestContent.Filters.APP_USERS)
  }

  @Test
  fun `test getSuggestions`() {
    assertThat(gameRequestContent.suggestions).isEqualTo(listOf("suggestion1", "suggestion2"))
  }

  @Test
  fun `test serialize with parcel`() {
    val parcel = Parcel.obtain()
    parcel.writeParcelable(gameRequestContent, 0)
    parcel.setDataPosition(0)

    val recoveredContent =
        parcel.readParcelable<GameRequestContent>(GameRequestContent::class.java.classLoader)
    checkNotNull(recoveredContent)
    assertThat(recoveredContent.message).isEqualTo(gameRequestContent.message)
    assertThat(recoveredContent.cta).isEqualTo(gameRequestContent.cta)
    assertThat(recoveredContent.recipients).isEqualTo(gameRequestContent.recipients)
    assertThat(recoveredContent.title).isEqualTo(gameRequestContent.title)
    assertThat(recoveredContent.data).isEqualTo(gameRequestContent.data)
    assertThat(recoveredContent.actionType).isEqualTo(gameRequestContent.actionType)
    assertThat(recoveredContent.objectId).isEqualTo(gameRequestContent.objectId)
    assertThat(recoveredContent.filters).isEqualTo(gameRequestContent.filters)
    assertThat(recoveredContent.suggestions).isEqualTo(gameRequestContent.suggestions)
    parcel.recycle()
  }

  @Test
  fun `test builder read from existing content`() {
    val recoveredContent = GameRequestContent.Builder().readFrom(gameRequestContent).build()
    checkNotNull(recoveredContent)
    assertThat(recoveredContent.message).isEqualTo(gameRequestContent.message)
    assertThat(recoveredContent.cta).isEqualTo(gameRequestContent.cta)
    assertThat(recoveredContent.recipients).isEqualTo(gameRequestContent.recipients)
    assertThat(recoveredContent.title).isEqualTo(gameRequestContent.title)
    assertThat(recoveredContent.data).isEqualTo(gameRequestContent.data)
    assertThat(recoveredContent.actionType).isEqualTo(gameRequestContent.actionType)
    assertThat(recoveredContent.objectId).isEqualTo(gameRequestContent.objectId)
    assertThat(recoveredContent.filters).isEqualTo(gameRequestContent.filters)
    assertThat(recoveredContent.suggestions).isEqualTo(gameRequestContent.suggestions)
  }
}


/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 * All rights reserved.
 *
 * This source code is licensed under the license found in the
 * LICENSE file in the root directory of this source tree.
 */

package com.facebook.share.model

import android.graphics.Bitmap
import android.net.Uri
import android.os.Parcel
import com.facebook.FacebookTestCase
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test

class ShareCameraEffectContentTest : FacebookTestCase() {
  private val bitmap = Bitmap.createBitmap(1, 1, Bitmap.Config.ALPHA_8)
  private val uri = Uri.parse("https://image.png")

  private val effectId = "effectId"
  private lateinit var cameraEffectArguments: CameraEffectArguments
  private lateinit var cameraEffectTextures: CameraEffectTextures
  private lateinit var shareCameraEffectContent: ShareCameraEffectContent

  override fun setUp() {
    super.setUp()

    cameraEffectArguments =
        CameraEffectArguments.Builder()
            .putArgument("string_key", "string_value")
            .putArgument("string_array_key", arrayOf("item1", "item2"))
            .build()

    cameraEffectTextures =
        CameraEffectTextures.Builder().putTexture("bitmap", bitmap).putTexture("uri", uri).build()

    shareCameraEffectContent =
        ShareCameraEffectContent.Builder()
            .setEffectId(effectId)
            .setArguments(cameraEffectArguments)
            .setTextures(cameraEffectTextures)
            .build()
  }

  @Test
  fun `test builder`() {
    assertThat(shareCameraEffectContent).isNotNull
  }

  @Test
  fun `test getEffectId`() {
    assertThat(shareCameraEffectContent.effectId).isEqualTo(effectId)
  }

  @Test
  fun `test getArguments`() {
    assertThat(shareCameraEffectContent.arguments).isEqualTo(cameraEffectArguments)
  }

  @Test
  fun `test getTextures`() {
    assertThat(shareCameraEffectContent.textures).isEqualTo(cameraEffectTextures)
  }

  @Test
  fun `test serialize with parcel`() {
    val parcel = Parcel.obtain()
    parcel.writeParcelable(shareCameraEffectContent, 0)
    parcel.setDataPosition(0)

    val recoveredContent: ShareCameraEffectContent? =
        parcel.readParcelable(ShareCameraEffectContent::class.java.classLoader)
    checkNotNull(recoveredContent)
    assertThat(recoveredContent.effectId).isEqualTo(effectId)
    assertThat(recoveredContent.arguments?.keySet()).isEqualTo(cameraEffectArguments.keySet())
    assertThat(recoveredContent.textures?.keySet()).isEqualTo(cameraEffectTextures.keySet())
    parcel.recycle()
  }

  @Test
  fun `test builder read from existing content`() {
    val recoveredContent =
        ShareCameraEffectContent.Builder().readFrom(shareCameraEffectContent).build()
    assertThat(recoveredContent.effectId).isEqualTo(effectId)
    assertThat(recoveredContent.arguments).isEqualTo(cameraEffectArguments)
    assertThat(recoveredContent.textures).isEqualTo(cameraEffectTextures)
  }
}


/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 * All rights reserved.
 *
 * This source code is licensed under the license found in the
 * LICENSE file in the root directory of this source tree.
 */

package com.facebook.share.model

import android.net.Uri
import android.os.Parcel
import com.facebook.FacebookTestCase
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Test

class ShareContentTest : FacebookTestCase() {
  private lateinit var shareContent: ShareLinkContent
  private lateinit var contentUri: Uri
  private lateinit var shareHashtag: ShareHashtag
  @Before
  fun init() {
    contentUri = Uri.parse("www.facebook.com/test")
    shareHashtag = ShareHashtag.Builder().setHashtag("test").build()
    shareContent =
        ShareLinkContent.Builder()
            .setQuote(quote)
            .setContentUrl(contentUri)
            .setPageId(pageID)
            .setPeopleIds(friendIds)
            .setRef(ref)
            .setShareHashtag(shareHashtag)
            .build()
  }
  @Test
  fun `test share content properties`() {
    assertThat(shareContent.quote).isEqualTo(quote)
    assertThat(shareContent.contentUrl).isEqualTo(contentUri)
    assertThat(shareContent.pageId).isEqualTo(pageID)
    assertThat(shareContent.peopleIds).isEqualTo(friendIds)
    assertThat(shareContent.ref).isEqualTo(ref)
    assertThat(shareContent.shareHashtag).isEqualTo(shareHashtag)
  }

  @Test
  fun `test write to parcel`() {
    val parcel = Parcel.obtain()
    shareContent.writeToParcel(parcel, 0)
    parcel.setDataPosition(0)

    assertThat(parcel.readParcelable<Uri>(Uri::class.java.classLoader)).isEqualTo(contentUri)
    val list = mutableListOf<String>()
    parcel.readStringList(list)
    assertThat(list).isEqualTo(friendIds)
    assertThat(parcel.readString()).isEqualTo(null) // place id
    assertThat(parcel.readString()).isEqualTo(pageID)
    assertThat(parcel.readString()).isEqualTo(ref)
    val ht = ShareHashtag.Builder().readFrom(parcel).build()
    assertThat(ht.hashtag).isEqualTo(shareHashtag.hashtag)
  }

  companion object {
    val friendIds = listOf("111", "222", "333")
    const val quote = "quoteText"
    const val pageID = "123"
    const val ref = "ref"
  }
}


/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 * All rights reserved.
 *
 * This source code is licensed under the license found in the
 * LICENSE file in the root directory of this source tree.
 */

package com.facebook.share.model

import android.os.Parcel
import com.facebook.FacebookTestCase
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Test

class ShareHashtagTest : FacebookTestCase() {
  private lateinit var shareHashtag: ShareHashtag
  @Before
  fun init() {
    shareHashtag = ShareHashtag.Builder().setHashtag("test").build()
  }

  @Test
  fun `test build hashtag`() {
    assertThat(shareHashtag).isNotNull
  }

  @Test
  fun `test get hashtag`() {
    assertThat(shareHashtag.hashtag).isEqualTo("test")
  }

  @Test
  fun `test serialize with parcel`() {
    val parcel = Parcel.obtain()
    parcel.writeParcelable(shareHashtag, 0)
    parcel.setDataPosition(0)

    val recoveredContent = parcel.readParcelable<ShareHashtag>(ShareHashtag::class.java.classLoader)
    checkNotNull(recoveredContent)
    assertThat(recoveredContent.hashtag).isEqualTo(shareHashtag.hashtag)
    parcel.recycle()
  }

  @Test
  fun `test builder read from existing content`() {
    val recoveredContent = ShareHashtag.Builder().readFrom(shareHashtag).build()
    assertThat(recoveredContent.hashtag).isEqualTo(shareHashtag.hashtag)
  }
}


/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 * All rights reserved.
 *
 * This source code is licensed under the license found in the
 * LICENSE file in the root directory of this source tree.
 */

package com.facebook.share.model

import android.net.Uri
import android.os.Parcel
import com.facebook.FacebookTestCase
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test

class ShareLinkContentTest : FacebookTestCase() {
  @Test
  fun `test create link content`() {
    val url = "https://facebook.com"
    val quote = "test quote"

    val linkContent =
        ShareLinkContent.Builder().setContentUrl(Uri.parse(url)).setQuote(quote).build()

    assertThat(linkContent.quote).isEqualTo(quote)
    assertThat(linkContent.contentUrl).isEqualTo(Uri.parse(url))
  }

  @Test
  fun `test read link content from parcel`() {
    val url = "https://facebook.com"
    val quote = "test quote"

    val linkContent =
        ShareLinkContent.Builder().setContentUrl(Uri.parse(url)).setQuote(quote).build()
    val parcel = Parcel.obtain()
    linkContent.writeToParcel(parcel, 0)
    parcel.setDataPosition(0)
    val restoredLinkContent = ShareLinkContent.CREATOR.createFromParcel(parcel)

    assertThat(restoredLinkContent.quote).isEqualTo(quote)
    assertThat(restoredLinkContent.contentUrl).isEqualTo(Uri.parse(url))
  }
}


/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 * All rights reserved.
 *
 * This source code is licensed under the license found in the
 * LICENSE file in the root directory of this source tree.
 */

package com.facebook.share.model

import android.net.Uri
import android.os.Parcel
import com.facebook.FacebookTestCase
import java.lang.IllegalArgumentException
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
import org.mockito.kotlin.mock

class ShareMediaContentTest : FacebookTestCase() {
  private lateinit var testPhoto: SharePhoto
  private lateinit var testVideo: ShareVideo
  private lateinit var mockUnknownMedium: ShareMedia<*, *>

  override fun setUp() {
    super.setUp()
    testPhoto = SharePhoto.Builder().setImageUrl(Uri.parse("https://test.net/image1.png")).build()
    testVideo = ShareVideo.Builder().setLocalUrl(Uri.parse("https://test.net/video1.mp4")).build()
    mockUnknownMedium = mock()
  }

  @Test
  fun `test building media content with photo`() {
    val content = ShareMediaContent.Builder().addMedium(testPhoto).build()

    val contentUrl = (content.media.first() as SharePhoto?)?.imageUrl
    assertThat(contentUrl).isEqualTo(testPhoto.imageUrl)
  }

  @Test
  fun `test building media content with video`() {
    val content = ShareMediaContent.Builder().addMedium(testVideo).build()

    val contentUrl = (content.media.first() as ShareVideo?)?.localUrl
    assertThat(contentUrl).isEqualTo(testVideo.localUrl)
  }

  @Test(expected = IllegalArgumentException::class)
  fun `test adding unknown medium`() {
    ShareMediaContent.Builder().addMedium(mockUnknownMedium).build()
  }

  @Test
  fun `test building media content with a list of media`() {
    val content = ShareMediaContent.Builder().addMedia(listOf(testPhoto, testVideo)).build()
    assertThat(content.media.size).isEqualTo(2)
  }

  @Test
  fun `test restoring media content from a parcel`() {
    val parcel = Parcel.obtain()
    val content = ShareMediaContent.Builder().addMedia(listOf(testPhoto, testVideo)).build()
    parcel.writeParcelable(content, 0)
    parcel.setDataPosition(0)

    val restoredContent =
        parcel.readParcelable<ShareMediaContent>(ShareMediaContent::class.java.classLoader)

    assertThat(restoredContent?.media?.size).isEqualTo(2)
    parcel.recycle()
  }

  @Test
  fun `test read from an existing share media content`() {
    val content = ShareMediaContent.Builder().addMedia(listOf(testPhoto)).build()
    val newContent = ShareMediaContent.Builder().readFrom(content).build()

    assertThat((newContent.media.first() as SharePhoto?)?.imageUrl).isEqualTo(testPhoto.imageUrl)
  }

  @Test
  fun `test builder setting media will clear existing media`() {
    val content =
        ShareMediaContent.Builder().addMedium(testPhoto).setMedia(listOf(testVideo)).build()

    assertThat(content.media.first() is ShareVideo).isTrue
    assertThat(content.media.size).isEqualTo(1)
  }
}


/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 * All rights reserved.
 *
 * This source code is licensed under the license found in the
 * LICENSE file in the root directory of this source tree.
 */

package com.facebook.share.model

import android.os.Parcel
import android.os.Parcelable
import com.facebook.FacebookTestCase
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test

class ShareMediaTest : FacebookTestCase() {
  class TestShareMedia : ShareMedia<TestShareMedia, TestShareMedia.Builder> {
    constructor(builder: Builder) : super(builder)
    constructor(parcel: Parcel) : super(parcel)

    override val mediaType: Type = Type.PHOTO

    class Builder : ShareMedia.Builder<TestShareMedia, Builder>() {
      override fun build(): TestShareMedia {
        return TestShareMedia(this)
      }
    }

    companion object {
      @JvmField
      val CREATOR: Parcelable.Creator<TestShareMedia> =
          object : Parcelable.Creator<TestShareMedia> {
            override fun createFromParcel(source: Parcel): TestShareMedia = TestShareMedia(source)
            override fun newArray(size: Int): Array<TestShareMedia?> = arrayOfNulls(size)
          }
    }
  }

  @Test
  fun `test parcelize share media`() {
    val shareMedia = TestShareMedia.Builder().setParameter("key", "value").build()
    val parcel = Parcel.obtain()

    parcel.writeParcelable(shareMedia, 0)
    parcel.setDataPosition(0)
    val restoredShareMedia =
        parcel.readParcelable<TestShareMedia>(TestShareMedia::class.java.classLoader)
    checkNotNull(restoredShareMedia)
    assertThat(restoredShareMedia.getParameters().get("key")).isEqualTo("value")

    parcel.recycle()
  }

  @Test
  fun `test write and read share media list`() {
    val medias =
        listOf(
            TestShareMedia.Builder().setParameter("k1", "v1").build(),
            TestShareMedia.Builder().setParameter("k2", "v2").build())
    val parcel = Parcel.obtain()

    ShareMedia.Builder.writeListTo(parcel, 0, medias)
    parcel.setDataPosition(0)
    val restoredMedias = ShareMedia.Builder.readListFrom(parcel)

    assertThat(restoredMedias.size).isEqualTo(2)
    assertThat(restoredMedias[0].getParameters().get("k1")).isEqualTo("v1")
    assertThat(restoredMedias[1].getParameters().get("k2")).isEqualTo("v2")
  }
}


/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 * All rights reserved.
 *
 * This source code is licensed under the license found in the
 * LICENSE file in the root directory of this source tree.
 */

package com.facebook.share.model

import android.os.Parcel
import android.os.Parcelable
import com.facebook.FacebookTestCase
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Test

class ShareMessengerActionButtonTest : FacebookTestCase() {
  class TestShareMessengerActionButton : ShareMessengerActionButton {
    private constructor(builder: Builder) : super(builder)

    internal constructor(parcel: Parcel) : super(parcel)

    class Builder : ShareMessengerActionButton.Builder<TestShareMessengerActionButton, Builder>() {
      override fun build(): TestShareMessengerActionButton {
        return TestShareMessengerActionButton(this)
      }
    }

    companion object {
      @JvmField
      val CREATOR: Parcelable.Creator<TestShareMessengerActionButton> =
          object : Parcelable.Creator<TestShareMessengerActionButton> {
            override fun createFromParcel(parcel: Parcel): TestShareMessengerActionButton {
              return TestShareMessengerActionButton(parcel)
            }

            override fun newArray(size: Int): Array<TestShareMessengerActionButton?> {
              return arrayOfNulls(size)
            }
          }
    }
  }

  private val title = "title"
  private lateinit var shareMessengerActionButton: TestShareMessengerActionButton

  @Before
  fun init() {
    shareMessengerActionButton = TestShareMessengerActionButton.Builder().setTitle(title).build()
  }

  @Test
  fun `test builder`() {
    assertThat(shareMessengerActionButton).isNotNull
  }

  @Test
  fun `test title`() {
    assertThat(shareMessengerActionButton.title).isEqualTo(title)
  }

  @Test
  fun `test serialize with parcel`() {
    val parcel = Parcel.obtain()
    parcel.writeParcelable(shareMessengerActionButton, 0)
    parcel.setDataPosition(0)

    val recoveredContent =
        parcel.readParcelable<TestShareMessengerActionButton>(
            TestShareMessengerActionButton::class.java.classLoader)

    checkNotNull(recoveredContent)
    assertThat(recoveredContent.title).isEqualTo(title)

    parcel.recycle()
  }

  @Test
  fun `test builder read from existing content`() {
    val recoveredContent =
        TestShareMessengerActionButton.Builder().readFrom(shareMessengerActionButton).build()
    assertThat(recoveredContent.title).isEqualTo(title)
  }
}


/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 * All rights reserved.
 *
 * This source code is licensed under the license found in the
 * LICENSE file in the root directory of this source tree.
 */

package com.facebook.share.model

import android.net.Uri
import android.os.Parcel
import com.facebook.FacebookTestCase
import com.facebook.share.model.ShareMessengerURLActionButton.WebviewHeightRatio
import org.assertj.core.api.Assertions.assertThat
import org.junit.Before
import org.junit.Test

class ShareMessengerURLActionButtonTest : FacebookTestCase() {
  private val url = Uri.parse("https://facebook.com")
  private val fallbackUrl = Uri.parse("https://facebook.com/fallback")
  private val webviewHeightRatio = WebviewHeightRatio.WebviewHeightRatioTall
  private lateinit var shareMessengerURLActionButton: ShareMessengerURLActionButton

  @Before
  fun init() {
    shareMessengerURLActionButton =
        ShareMessengerURLActionButton.Builder()
            .setUrl(url)
            .setFallbackUrl(fallbackUrl)
            .setIsMessengerExtensionURL(true)
            .setShouldHideWebviewShareButton(true)
            .setWebviewHeightRatio(webviewHeightRatio)
            .build()
  }

  @Test
  fun `test builder`() {
    assertThat(shareMessengerURLActionButton).isNotNull
  }

  @Test
  fun `test url`() {
    assertThat(shareMessengerURLActionButton.url).isEqualTo(url)
  }

  @Test
  fun `test fallbackUrl`() {
    assertThat(shareMessengerURLActionButton.fallbackUrl).isEqualTo(fallbackUrl)
  }

  @Test
  fun `test isMessengerExtensionURL`() {
    assertThat(shareMessengerURLActionButton.isMessengerExtensionURL).isTrue
  }

  @Test
  fun `test shouldHideWebviewShareButton`() {
    assertThat(shareMessengerURLActionButton.shouldHideWebviewShareButton).isTrue
  }

  @Test
  fun `test serialize with parcel`() {
    val parcel = Parcel.obtain()
    parcel.writeParcelable(shareMessengerURLActionButton, 0)
    parcel.setDataPosition(0)

    val recoveredContent =
        parcel.readParcelable<ShareMessengerURLActionButton>(
            ShareMessengerURLActionButton::class.java.classLoader)

    checkNotNull(recoveredContent)
    assertThat(recoveredContent.url).isEqualTo(url)
    assertThat(recoveredContent.fallbackUrl).isEqualTo(fallbackUrl)
    assertThat(recoveredContent.isMessengerExtensionURL).isTrue
    assertThat(recoveredContent.shouldHideWebviewShareButton).isTrue
    assertThat(recoveredContent.webviewHeightRatio)
        .isEqualTo(WebviewHeightRatio.WebviewHeightRatioTall)

    parcel.recycle()
  }

  @Test
  fun `test builder read from existing content`() {
    val recoveredContent =
        ShareMessengerURLActionButton.Builder().readFrom(shareMessengerURLActionButton).build()
    assertThat(recoveredContent.url).isEqualTo(url)
    assertThat(recoveredContent.fallbackUrl).isEqualTo(fallbackUrl)
    assertThat(recoveredContent.isMessengerExtensionURL).isTrue
    assertThat(recoveredContent.shouldHideWebviewShareButton).isTrue
    assertThat(recoveredContent.webviewHeightRatio)
        .isEqualTo(WebviewHeightRatio.WebviewHeightRatioTall)
  }
}


/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 * All rights reserved.
 *
 * This source code is licensed under the license found in the
 * LICENSE file in the root directory of this source tree.
 */

package com.facebook.share.model

import android.net.Uri
import android.os.Parcel
import com.facebook.FacebookTestCase
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test

class SharePhotoContentTest : FacebookTestCase() {
  private lateinit var photos: List<SharePhoto>
  override fun setUp() {
    super.setUp()
    photos =
        listOf(
            SharePhoto.Builder()
                .setImageUrl(Uri.parse("file://tmp/photo1.jpg"))
                .setCaption("photo 1")
                .build(),
            SharePhoto.Builder()
                .setImageUrl(Uri.parse("file://tmp/photo2.jpg"))
                .setCaption("photo 2")
                .build(),
        )
  }

  @Test
  fun `test add photo`() {
    val photoContent = SharePhotoContent.Builder().addPhoto(photos[0]).addPhoto(null).build()
    assertThat(photoContent.photos.size).isEqualTo(1)
    assertThat(photoContent.photos[0].imageUrl).isEqualTo(photos[0].imageUrl)
    assertThat(photoContent.photos[0].caption).isEqualTo(photos[0].caption)
  }

  @Test
  fun `test add photos`() {
    val photoContent = SharePhotoContent.Builder().addPhotos(photos).build()
    assertThat(photoContent.photos.size).isEqualTo(2)
    assertThat(photoContent.photos[0].imageUrl).isEqualTo(photos[0].imageUrl)
    assertThat(photoContent.photos[0].caption).isEqualTo(photos[0].caption)
    assertThat(photoContent.photos[1].imageUrl).isEqualTo(photos[1].imageUrl)
    assertThat(photoContent.photos[1].caption).isEqualTo(photos[1].caption)
  }

  @Test
  fun `test set photos`() {
    val photoContent =
        SharePhotoContent.Builder()
            .addPhotos(photos)
            .setPhotos(listOf(photos[1], photos[0]))
            .build()
    assertThat(photoContent.photos.size).isEqualTo(2)
    assertThat(photoContent.photos[1].imageUrl).isEqualTo(photos[0].imageUrl)
    assertThat(photoContent.photos[1].caption).isEqualTo(photos[0].caption)
    assertThat(photoContent.photos[0].imageUrl).isEqualTo(photos[1].imageUrl)
    assertThat(photoContent.photos[0].caption).isEqualTo(photos[1].caption)
  }

  @Test
  fun `test read from existing photo content`() {
    val photoContent = SharePhotoContent.Builder().addPhotos(photos).build()
    val recoveredPhotoContent = SharePhotoContent.Builder().readFrom(photoContent).build()
    assertThat(recoveredPhotoContent.photos).isNotEqualTo(photoContent.photos)
    assertThat(recoveredPhotoContent.photos[0].imageUrl).isEqualTo(photos[0].imageUrl)
    assertThat(recoveredPhotoContent.photos[0].caption).isEqualTo(photos[0].caption)
    assertThat(recoveredPhotoContent.photos[1].imageUrl).isEqualTo(photos[1].imageUrl)
    assertThat(recoveredPhotoContent.photos[1].caption).isEqualTo(photos[1].caption)
  }

  @Test
  fun `test serialize with parcel`() {
    val parcel = Parcel.obtain()
    val photoContent = SharePhotoContent.Builder().addPhotos(photos).build()
    photoContent.writeToParcel(parcel, 0)
    parcel.setDataPosition(0)
    val recoveredPhotoContent = SharePhotoContent.CREATOR.createFromParcel(parcel)
    assertThat(recoveredPhotoContent.photos[0].imageUrl).isEqualTo(photos[0].imageUrl)
    assertThat(recoveredPhotoContent.photos[0].caption).isEqualTo(photos[0].caption)
    assertThat(recoveredPhotoContent.photos[1].imageUrl).isEqualTo(photos[1].imageUrl)
    assertThat(recoveredPhotoContent.photos[1].caption).isEqualTo(photos[1].caption)
  }
}


/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 * All rights reserved.
 *
 * This source code is licensed under the license found in the
 * LICENSE file in the root directory of this source tree.
 */

package com.facebook.share.model

import android.graphics.Bitmap
import android.net.Uri
import android.os.Parcel
import com.facebook.FacebookTestCase
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test

class SharePhotoTest : FacebookTestCase() {
  private lateinit var testBitmap: Bitmap
  private lateinit var testImageUri: Uri
  private lateinit var testSharePhoto: SharePhoto
  private val testCaption = "test caption"

  override fun setUp() {
    super.setUp()
    testBitmap = Bitmap.createBitmap(1, 2, Bitmap.Config.ALPHA_8)
    testImageUri = Uri.parse("https://facebook.com/1.png")
    testSharePhoto =
        SharePhoto.Builder()
            .setBitmap(testBitmap)
            .setImageUrl(testImageUri)
            .setCaption(testCaption)
            .setUserGenerated(true)
            .build()
  }

  @Test
  fun `test creating a photo with bitmap`() {
    val sharePhoto =
        SharePhoto.Builder()
            .setBitmap(testBitmap)
            .setCaption(testCaption)
            .setUserGenerated(true)
            .build()

    assertThat(sharePhoto.imageUrl).isNull()
    val bitmap = checkNotNull(sharePhoto.bitmap)
    assertThat(bitmap.width).isEqualTo(1)
    assertThat(bitmap.height).isEqualTo(2)
    assertThat(bitmap.config).isEqualTo(Bitmap.Config.ALPHA_8)
    assertThat(sharePhoto.caption).isEqualTo(testCaption)
    assertThat(sharePhoto.userGenerated).isTrue
  }

  @Test
  fun `test creating a photo with uri`() {
    val sharePhoto =
        SharePhoto.Builder()
            .setImageUrl(testImageUri)
            .setCaption(testCaption)
            .setUserGenerated(false)
            .build()

    assertThat(sharePhoto.imageUrl?.toString()).isEqualTo(testImageUri.toString())
    assertThat(sharePhoto.bitmap).isNull()
    assertThat(sharePhoto.caption).isEqualTo(testCaption)
    assertThat(sharePhoto.userGenerated).isFalse
  }

  @Test
  fun `test creating share photo from an existing share photo`() {
    val sharePhoto = SharePhoto.Builder().readFrom(testSharePhoto).build()

    assertThat(sharePhoto.imageUrl.toString()).isEqualTo(testImageUri.toString())
    val bitmap = checkNotNull(sharePhoto.bitmap)
    assertThat(bitmap.width).isEqualTo(1)
    assertThat(bitmap.height).isEqualTo(2)
    assertThat(bitmap.config).isEqualTo(Bitmap.Config.ALPHA_8)
    assertThat(sharePhoto.caption).isEqualTo(testCaption)
    assertThat(sharePhoto.userGenerated).isTrue
  }

  @Test
  fun `test recovering share photo from parcel`() {
    val parcel = Parcel.obtain()
    parcel.writeParcelable(testSharePhoto, 0)
    parcel.setDataPosition(0)

    val sharePhoto = parcel.readParcelable<SharePhoto>(SharePhoto::class.java.classLoader)

    checkNotNull(sharePhoto)
    assertThat(sharePhoto.imageUrl.toString()).isEqualTo(testImageUri.toString())
    val bitmap = checkNotNull(sharePhoto.bitmap)
    assertThat(bitmap.width).isEqualTo(1)
    assertThat(bitmap.height).isEqualTo(2)
    assertThat(bitmap.config).isEqualTo(Bitmap.Config.ALPHA_8)
    assertThat(sharePhoto.caption).isEqualTo(testCaption)
    assertThat(sharePhoto.userGenerated).isTrue

    parcel.recycle()
  }
}


/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 * All rights reserved.
 *
 * This source code is licensed under the license found in the
 * LICENSE file in the root directory of this source tree.
 */

package com.facebook.share.model

import android.graphics.Bitmap
import android.os.Parcel
import com.facebook.FacebookTestCase
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test

class ShareStoryContentTest : FacebookTestCase() {
  private lateinit var background: SharePhoto
  private lateinit var sticker: SharePhoto
  private lateinit var attributionLink: String
  private lateinit var backgroundColorList: List<String>
  private lateinit var storyContent: ShareStoryContent

  override fun setUp() {
    super.setUp()
    sticker =
        SharePhoto.Builder().setBitmap(Bitmap.createBitmap(2, 3, Bitmap.Config.ALPHA_8)).build()
    background =
        SharePhoto.Builder().setBitmap(Bitmap.createBitmap(5, 7, Bitmap.Config.ALPHA_8)).build()
    attributionLink = "https://facebook.com"
    backgroundColorList = listOf("red", "blue")

    storyContent =
        ShareStoryContent.Builder()
            .setBackgroundAsset(background)
            .setStickerAsset(sticker)
            .setAttributionLink(attributionLink)
            .setBackgroundColorList(backgroundColorList)
            .build()
  }

  @Test
  fun `test builder creates the correct content`() {
    validateContentIsExpected(storyContent)
  }

  @Test
  fun `test parcelizing story content`() {
    val parcel = Parcel.obtain()
    parcel.writeParcelable(storyContent, 0)
    parcel.setDataPosition(0)
    val recoveredStoryContent =
        parcel.readParcelable<ShareStoryContent>(ShareStoryContent::class.java.classLoader)
    checkNotNull(recoveredStoryContent)
    validateContentIsExpected(recoveredStoryContent)
    parcel.recycle()
  }

  @Test
  fun `test building from an existing story content`() {
    val recoveredStoryContent = ShareStoryContent.Builder().readFrom(storyContent).build()
    validateContentIsExpected(recoveredStoryContent)
  }

  private fun validateContentIsExpected(content: ShareStoryContent) {
    assertThat(content.attributionLink).isEqualTo(attributionLink)
    assertThat(content.backgroundColorList)
        .containsExactlyInAnyOrder(*backgroundColorList.toTypedArray())
    val stickBitmap = checkNotNull(sticker.bitmap)
    assertThat(content.stickerAsset?.bitmap?.width).isEqualTo(stickBitmap.width)
    assertThat(content.stickerAsset?.bitmap?.height).isEqualTo(stickBitmap.height)
    val contentBackgroundAssert = content.backgroundAsset as SharePhoto?
    assertThat(contentBackgroundAssert?.bitmap?.width).isEqualTo(background.bitmap?.width)
    assertThat(contentBackgroundAssert?.bitmap?.height).isEqualTo(background.bitmap?.height)
  }
}