Last active
August 11, 2022 22:13
-
-
Save dmitriy-chernysh/c30450d56de97eff0ef19afecb8986fb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object FacebookGraphUtil { | |
@Throws(RuntimeException::class) | |
fun getFacebookPageList(accessToken: AccessToken, doOnSuccess: (List<FacebookPage>) -> Unit) { | |
GraphRequest.newGraphPathRequest( | |
accessToken, | |
"/me/accounts" | |
) { response: GraphResponse -> | |
parsePageListJson(response.jsonObject) | |
.also(doOnSuccess) | |
}.executeAsync() | |
} | |
@Throws(RuntimeException::class) | |
private fun parsePageListJson(jsonObject: JSONObject?): List<FacebookPage> { | |
jsonObject | |
?: throw RuntimeException("Failed to get Facebook business pages you have access to. Please check you have access to a business page.") | |
val pagesList = ArrayList<FacebookPage>() | |
try { | |
jsonObject.getJSONArray(KEY_DATA) | |
.also { jsonArray -> | |
for (i in 0 until jsonArray.length()) | |
jsonArray.getJSONObject(i).let { page -> | |
FacebookPage( | |
page.getString(KEY_PAGE_ID), | |
page.getString(KEY_PAGE_NAME), | |
page.getString(KEY_ACCESS_TOKEN) | |
) | |
}.also(pagesList::add) | |
} | |
} catch (e: JSONException) { | |
throw RuntimeException("Failed to parse Facebook pages list: ${e.localizedMessage}") | |
} | |
return pagesList | |
} | |
private const val KEY_DATA = "data" | |
private const val KEY_PAGE_ID = "id" | |
private const val KEY_PAGE_NAME = "name" | |
private const val KEY_ACCESS_TOKEN = "access_token" | |
} | |
data class FacebookPage( | |
val id: String, | |
val name: String, | |
val accessToken: String | |
) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment