Skip to content

Instantly share code, notes, and snippets.

@G00fY2
Last active March 21, 2022 18:02
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save G00fY2/f574d407f0b00311288e11cb9a062779 to your computer and use it in GitHub Desktop.
Save G00fY2/f574d407f0b00311288e11cb9a062779 to your computer and use it in GitHub Desktop.
Extract link preview data from given URL
class GetLinkPreviewDataInteractorImpl @Inject constructor(
private val okHttpClient: OkHttpClient
) : GetLinkPreviewDataInteractor {
override fun execute(url: String): Single<LinkPreviewData> {
return Single.fromCallable {
okHttpClient.newCall(Builder().url(url).build()).execute().use { response ->
val requestedUrl = response.request.url.toString()
Jsoup.parse(response.body!!.string()).let {
val title = it.select("meta[property=og:title]").firstOrNull()?.attr("content")
val description = it.select("meta[property=og:description]").firstOrNull()?.attr("content")
var imageUrl = it.select("meta[property=og:image]").firstOrNull()?.attr("content")
if (!imageUrl.isNullOrEmpty() && Uri.parse(imageUrl).scheme.isNullOrEmpty()) {
imageUrl = Uri.parse(imageUrl)
.buildUpon()
.apply { scheme(Uri.parse(requestedUrl).scheme) }
.build()
.toString()
}
LinkPreviewData(title, description, imageUrl, requestedUrl)
}
}
}
}
data class LinkPreviewData(
val title: String? = null,
val description: String? = null,
val imageUrl: String? = null,
val url: String
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment