Last active
March 21, 2022 18:02
-
-
Save G00fY2/f574d407f0b00311288e11cb9a062779 to your computer and use it in GitHub Desktop.
Extract link preview data from given URL
This file contains hidden or 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
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