├── .github └── ISSUE_TEMPLATE │ ├── bug_report.md │ └── feature_request.md ├── .gitignore ├── LICENSE ├── OGParser ├── .gitignore ├── build.gradle ├── consumer-rules.pro ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── kedia │ │ └── ogparser │ │ └── ExampleInstrumentedTest.kt │ ├── main │ ├── AndroidManifest.xml │ └── java │ │ └── com │ │ └── kedia │ │ └── ogparser │ │ ├── CacheProvider.kt │ │ ├── JsoupNetworkCall.kt │ │ ├── JsoupProxy.kt │ │ ├── OpenGraphCacheProvider.kt │ │ ├── OpenGraphCallback.kt │ │ ├── OpenGraphParser.kt │ │ ├── OpenGraphResult.kt │ │ └── UtilityFunctions.kt │ └── test │ └── java │ └── com │ └── kedia │ └── ogparser │ └── ExampleUnitTest.kt ├── README.md ├── app ├── .gitignore ├── build.gradle ├── proguard-rules.pro └── src │ ├── androidTest │ └── java │ │ └── com │ │ └── kedia │ │ └── opengraphpreview │ │ └── ExampleInstrumentedTest.kt │ ├── main │ ├── AndroidManifest.xml │ ├── java │ │ └── com │ │ │ └── kedia │ │ │ └── opengraphpreview │ │ │ └── MainActivity.kt │ └── res │ │ ├── drawable-v24 │ │ └── ic_launcher_foreground.xml │ │ ├── drawable │ │ └── ic_launcher_background.xml │ │ ├── layout │ │ └── activity_main.xml │ │ ├── mipmap-anydpi-v26 │ │ ├── ic_launcher.xml │ │ └── ic_launcher_round.xml │ │ ├── mipmap-hdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-mdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── mipmap-xxxhdpi │ │ ├── ic_launcher.png │ │ └── ic_launcher_round.png │ │ ├── values-night │ │ └── themes.xml │ │ └── values │ │ ├── colors.xml │ │ ├── strings.xml │ │ └── themes.xml │ └── test │ └── java │ └── com │ └── kedia │ └── opengraphpreview │ └── ExampleUnitTest.kt ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── images ├── Story-Medium.png ├── Story-Medium.svg └── google-devlib.svg ├── jitpack.yml └── settings.gradle /.github/ISSUE_TEMPLATE/bug_report.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Bug report 3 | about: Create a report to help us improve 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Describe the bug** 11 | A clear and concise description of what the bug is. 12 | 13 | **To Reproduce** 14 | Steps to reproduce the behavior: 15 | 1. Go to '...' 16 | 2. Click on '....' 17 | 3. Scroll down to '....' 18 | 4. See error 19 | 20 | **Expected behavior** 21 | A clear and concise description of what you expected to happen. 22 | 23 | **Screenshots** 24 | If applicable, add screenshots to help explain your problem. 25 | 26 | **Desktop (please complete the following information):** 27 | - OS: [e.g. iOS] 28 | - Browser [e.g. chrome, safari] 29 | - Version [e.g. 22] 30 | 31 | **Smartphone (please complete the following information):** 32 | - Device: [e.g. iPhone6] 33 | - OS: [e.g. iOS8.1] 34 | - Browser [e.g. stock browser, safari] 35 | - Version [e.g. 22] 36 | 37 | **Additional context** 38 | Add any other context about the problem here. 39 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE/feature_request.md: -------------------------------------------------------------------------------- 1 | --- 2 | name: Feature request 3 | about: Suggest an idea for this project 4 | title: '' 5 | labels: '' 6 | assignees: '' 7 | 8 | --- 9 | 10 | **Is your feature request related to a problem? Please describe.** 11 | A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] 12 | 13 | **Describe the solution you'd like** 14 | A clear and concise description of what you want to happen. 15 | 16 | **Describe alternatives you've considered** 17 | A clear and concise description of any alternative solutions or features you've considered. 18 | 19 | **Additional context** 20 | Add any other context or screenshots about the feature request here. 21 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Built application files 2 | *.apk 3 | *.aar 4 | *.ap_ 5 | *.aab 6 | 7 | # Files for the ART/Dalvik VM 8 | *.dex 9 | 10 | # Java class files 11 | *.class 12 | 13 | # Generated files 14 | bin/ 15 | gen/ 16 | out/ 17 | 18 | release/ 19 | 20 | # Gradle files 21 | .gradle/ 22 | build/ 23 | 24 | # Local configuration file (sdk path, etc) 25 | local.properties 26 | 27 | # Proguard folder generated by Eclipse 28 | proguard/ 29 | 30 | # Log Files 31 | *.log 32 | 33 | # Android Studio Navigation editor temp files 34 | .navigation/ 35 | 36 | # Android Studio captures folder 37 | captures/ 38 | 39 | # IntelliJ 40 | *.iml 41 | .idea/ 42 | .idea/workspace.xml 43 | .idea/tasks.xml 44 | .idea/gradle.xml 45 | .idea/assetWizardSettings.xml 46 | .idea/dictionaries 47 | .idea/libraries 48 | # Android Studio 3 in .gitignore file. 49 | .idea/caches 50 | .idea/modules.xml 51 | # Comment next line if keeping position of elements in Navigation Editor is relevant for you 52 | .idea/navEditor.xml 53 | 54 | # Keystore files 55 | # Uncomment the following lines if you do not want to check your keystore files in. 56 | *.jks 57 | *.keystore 58 | 59 | # External native build folder generated in Android Studio 2.2 and later 60 | .externalNativeBuild 61 | .cxx/ 62 | 63 | # Google Services (e.g. APIs or Firebase) 64 | # google-services.json 65 | 66 | # Freeline 67 | freeline.py 68 | freeline/ 69 | freeline_project_description.json 70 | 71 | # fastlane 72 | fastlane/report.xml 73 | fastlane/Preview.html 74 | fastlane/screenshots 75 | fastlane/test_output 76 | fastlane/readme.md 77 | 78 | # Version control 79 | vcs.xml 80 | 81 | # lint 82 | lint/intermediates/ 83 | lint/generated/ 84 | lint/outputs/ 85 | lint/tmp/ 86 | # lint/reports/ -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 Priyansh Kedia 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /OGParser/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /OGParser/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'com.android.library' 3 | id 'kotlin-android' 4 | id 'maven-publish' 5 | } 6 | 7 | 8 | android { 9 | compileSdkVersion 30 10 | buildToolsVersion "30.0.3" 11 | 12 | defaultConfig { 13 | minSdkVersion 16 14 | targetSdkVersion 30 15 | versionCode 1 16 | versionName "1.0" 17 | 18 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 19 | consumerProguardFiles "consumer-rules.pro" 20 | } 21 | 22 | buildTypes { 23 | release { 24 | minifyEnabled false 25 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 26 | } 27 | } 28 | compileOptions { 29 | sourceCompatibility JavaVersion.VERSION_1_8 30 | targetCompatibility JavaVersion.VERSION_1_8 31 | } 32 | kotlinOptions { 33 | jvmTarget = '1.8' 34 | } 35 | } 36 | 37 | dependencies { 38 | 39 | implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" 40 | implementation 'androidx.core:core-ktx:1.6.0' 41 | implementation 'androidx.appcompat:appcompat:1.3.1' 42 | implementation 'com.google.android.material:material:1.4.0' 43 | testImplementation 'junit:junit:4.+' 44 | androidTestImplementation 'androidx.test.ext:junit:1.1.3' 45 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0' 46 | 47 | // OpenGraph 48 | implementation 'org.jsoup:jsoup:1.10.3' 49 | 50 | // Preference AndroidX 51 | def preference_version = "1.1.1" 52 | implementation "androidx.preference:preference-ktx:$preference_version" 53 | 54 | //ktx 55 | implementation 'androidx.core:core-ktx:1.6.0' 56 | 57 | //Architecture 58 | def lifecycle_version = '2.2.0' 59 | 60 | implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.3.9' 61 | // implementation "androidx.lifecycle:lifecycle-extensions:${lifecycle_version}" 62 | // implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:${lifecycle_version}" 63 | } 64 | 65 | afterEvaluate { 66 | publishing { 67 | publications { 68 | release(MavenPublication) { 69 | from components.release 70 | 71 | groupId = 'com.github.Priyansh-Kedia' 72 | artifactId = 'OpenGraphParser' 73 | version = '2.5.6' 74 | } 75 | } 76 | } 77 | } -------------------------------------------------------------------------------- /OGParser/consumer-rules.pro: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/pknotfound/OpenGraphParser/9e421c804ec2d986f0f3dbe36284ec374ad0c435/OGParser/consumer-rules.pro -------------------------------------------------------------------------------- /OGParser/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile -------------------------------------------------------------------------------- /OGParser/src/androidTest/java/com/kedia/ogparser/ExampleInstrumentedTest.kt: -------------------------------------------------------------------------------- 1 | package com.kedia.ogparser 2 | 3 | import androidx.test.platform.app.InstrumentationRegistry 4 | import androidx.test.ext.junit.runners.AndroidJUnit4 5 | 6 | import org.junit.Test 7 | import org.junit.runner.RunWith 8 | 9 | import org.junit.Assert.* 10 | 11 | /** 12 | * Instrumented test, which will execute on an Android device. 13 | * 14 | * See [testing documentation](http://d.android.com/tools/testing). 15 | */ 16 | @RunWith(AndroidJUnit4::class) 17 | class ExampleInstrumentedTest { 18 | @Test 19 | fun useAppContext() { 20 | // Context of the app under test. 21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext 22 | assertEquals("com.kedia.ogparser.test", appContext.packageName) 23 | } 24 | } -------------------------------------------------------------------------------- /OGParser/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | -------------------------------------------------------------------------------- /OGParser/src/main/java/com/kedia/ogparser/CacheProvider.kt: -------------------------------------------------------------------------------- 1 | package com.kedia.ogparser 2 | 3 | interface CacheProvider { 4 | suspend fun getOpenGraphResult(url: String): OpenGraphResult? 5 | suspend fun setOpenGraphResult(openGraphResult: OpenGraphResult, url: String) 6 | } 7 | -------------------------------------------------------------------------------- /OGParser/src/main/java/com/kedia/ogparser/JsoupNetworkCall.kt: -------------------------------------------------------------------------------- 1 | package com.kedia.ogparser 2 | 3 | import android.util.Log 4 | import org.jsoup.Jsoup 5 | 6 | /** 7 | * @param timeout - Timeout for requests, specified in milliseconds (default - 60000) 8 | * @param jsoupProxy - Specify proxy for requests (host, port) 9 | * @param maxBodySize - The maximum size to fetch for body 10 | */ 11 | 12 | class JsoupNetworkCall( 13 | private val timeout: Int? = DEFAULT_TIMEOUT, 14 | private val jsoupProxy: JsoupProxy? = null, 15 | private val maxBodySize: Int? = null 16 | ) { 17 | 18 | fun callUrl(url: String, agent: String): OpenGraphResult? { 19 | val openGraphResult = OpenGraphResult() 20 | try { 21 | val connection = Jsoup.connect(url) 22 | .ignoreContentType(true) 23 | .userAgent(agent) 24 | .referrer(REFERRER) 25 | .timeout(timeout ?: DEFAULT_TIMEOUT) 26 | .followRedirects(true) 27 | 28 | jsoupProxy?.let { connection.proxy(it.host, it.port) } 29 | maxBodySize?.let { connection.maxBodySize(it) } 30 | 31 | val response = connection.execute() 32 | 33 | val doc = response.parse() 34 | val ogTags = doc.select(DOC_SELECT_OGTAGS) 35 | 36 | ogTags.forEach { tag -> 37 | val text = tag.attr(PROPERTY) 38 | 39 | when (text) { 40 | OG_IMAGE -> { 41 | openGraphResult.image = tag.attr(OPEN_GRAPH_KEY) 42 | } 43 | OG_DESCRIPTION -> { 44 | openGraphResult.description = tag.attr(OPEN_GRAPH_KEY) 45 | } 46 | OG_URL -> { 47 | openGraphResult.url = tag.attr(OPEN_GRAPH_KEY) 48 | } 49 | OG_TITLE -> { 50 | openGraphResult.title = tag.attr(OPEN_GRAPH_KEY) 51 | } 52 | OG_SITE_NAME -> { 53 | openGraphResult.siteName = tag.attr(OPEN_GRAPH_KEY) 54 | } 55 | OG_TYPE -> { 56 | openGraphResult.type = tag.attr(OPEN_GRAPH_KEY) 57 | } 58 | } 59 | } 60 | 61 | if (openGraphResult.title.isNullOrEmpty()) { 62 | openGraphResult.title = doc.title() 63 | } 64 | if (openGraphResult.description.isNullOrEmpty()) { 65 | val docSelection = doc.select(DOC_SELECT_DESCRIPTION) 66 | openGraphResult.description = docSelection.firstOrNull()?.attr("content") ?: "" 67 | } 68 | if (openGraphResult.url.isNullOrEmpty()) { 69 | openGraphResult.url = getBaseUrl(url) 70 | } 71 | } catch (e: Exception) { 72 | e.printStackTrace() 73 | return null 74 | } 75 | 76 | return openGraphResult 77 | } 78 | 79 | companion object { 80 | private const val REFERRER = "http://www.google.com" 81 | private const val DEFAULT_TIMEOUT = 60000 82 | 83 | private const val DOC_SELECT_OGTAGS = "meta[property^=og:]" 84 | private const val DOC_SELECT_DESCRIPTION = "meta[name=description]" 85 | 86 | private const val OPEN_GRAPH_KEY = "content" 87 | private const val PROPERTY = "property" 88 | 89 | private const val OG_IMAGE = "og:image" 90 | private const val OG_DESCRIPTION = "og:description" 91 | private const val OG_URL = "og:url" 92 | private const val OG_TITLE = "og:title" 93 | private const val OG_SITE_NAME = "og:site_name" 94 | private const val OG_TYPE = "og:type" 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /OGParser/src/main/java/com/kedia/ogparser/JsoupProxy.kt: -------------------------------------------------------------------------------- 1 | package com.kedia.ogparser 2 | 3 | data class JsoupProxy( 4 | val host: String, 5 | val port: Int 6 | ) -------------------------------------------------------------------------------- /OGParser/src/main/java/com/kedia/ogparser/OpenGraphCacheProvider.kt: -------------------------------------------------------------------------------- 1 | package com.kedia.ogparser 2 | 3 | import android.content.Context 4 | import android.content.SharedPreferences 5 | import android.util.Log 6 | import androidx.preference.PreferenceManager 7 | 8 | class OpenGraphCacheProvider(context: Context) : CacheProvider { 9 | 10 | private val pm: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(context) 11 | 12 | 13 | private fun setTitle(link: String, title: String) { 14 | pm.edit().putString(TITLE + "_$link", title).apply() 15 | } 16 | 17 | private fun getTitle(link: String): String { 18 | return pm.getString(TITLE + "_$link", "") ?: "" 19 | } 20 | 21 | private fun setDescription(link: String, description: String) { 22 | pm.edit().putString(DESCRIPTION + "_$link", description).apply() 23 | } 24 | 25 | private fun getDescription(link: String): String { 26 | return pm.getString(DESCRIPTION + "_$link", "") ?: "" 27 | } 28 | 29 | private fun setUrl(link: String, url: String) { 30 | pm.edit().putString(URL + "_$link", url).apply() 31 | } 32 | 33 | private fun getUrl(link: String): String { 34 | return pm.getString(URL + "_$link", "") ?: "" 35 | } 36 | 37 | private fun setImage(link: String, image: String) { 38 | pm.edit().putString(IMAGE + "_$link", image).apply() 39 | } 40 | 41 | private fun getImage(link: String): String { 42 | return pm.getString(IMAGE + "_$link", "") ?: "" 43 | } 44 | 45 | private fun setSiteName(link: String, siteName: String) { 46 | pm.edit().putString(SITE_NAME + "_$link", siteName).apply() 47 | } 48 | 49 | private fun getSiteName(link: String): String { 50 | return pm.getString(SITE_NAME + "_$link", "") ?: "" 51 | } 52 | 53 | private fun setType(link: String, type: String) { 54 | pm.edit().putString(TYPE + "_$link", type).apply() 55 | } 56 | 57 | private fun getType(link: String): String { 58 | return pm.getString(TYPE + "_$link", "") ?: "" 59 | } 60 | 61 | private fun urlExists(title: String, description: String, image: String): Boolean { 62 | return title.isNotEmpty() && 63 | title != "null" && 64 | description.isNotEmpty() && 65 | title != "null" && 66 | image.isNotEmpty() && 67 | title != "null" 68 | } 69 | 70 | override suspend fun setOpenGraphResult(openGraphResult: OpenGraphResult, url: String) { 71 | setTitle(url, openGraphResult.title.toString()) 72 | setDescription(url, openGraphResult.description.toString()) 73 | setImage(url, openGraphResult.image.toString()) 74 | setSiteName(url, openGraphResult.siteName.toString()) 75 | setType(url, openGraphResult.type.toString()) 76 | setUrl(url, openGraphResult.url.toString()) 77 | } 78 | 79 | override suspend fun getOpenGraphResult(url: String): OpenGraphResult? { 80 | val title = getTitle(url) 81 | val description = getDescription(url) 82 | val image = getImage(url) 83 | 84 | if (!urlExists(title, description, image)) { 85 | return null 86 | } 87 | 88 | val siteName = getSiteName(url) 89 | val type = getType(url) 90 | val url = getUrl(url) 91 | return OpenGraphResult(title, description, url, image, siteName, type) 92 | } 93 | 94 | companion object { 95 | private const val OG_PARSER = "Og_Parser" 96 | private const val TITLE = OG_PARSER + "_title" 97 | private const val DESCRIPTION = OG_PARSER + "_description" 98 | private const val URL = OG_PARSER + "_url" 99 | private const val IMAGE = OG_PARSER + "_image" 100 | private const val SITE_NAME = OG_PARSER + "_site_name" 101 | private const val TYPE = OG_PARSER + "_type" 102 | } 103 | } 104 | -------------------------------------------------------------------------------- /OGParser/src/main/java/com/kedia/ogparser/OpenGraphCallback.kt: -------------------------------------------------------------------------------- 1 | package com.kedia.ogparser 2 | 3 | interface OpenGraphCallback { 4 | fun onPostResponse(openGraphResult: OpenGraphResult) 5 | fun onError(error: String) 6 | } -------------------------------------------------------------------------------- /OGParser/src/main/java/com/kedia/ogparser/OpenGraphParser.kt: -------------------------------------------------------------------------------- 1 | package com.kedia.ogparser 2 | 3 | import kotlinx.coroutines.* 4 | import kotlin.coroutines.CoroutineContext 5 | 6 | class OpenGraphParser @JvmOverloads constructor( 7 | private val listener: OpenGraphCallback, 8 | private var showNullOnEmpty: Boolean = false, 9 | private val cacheProvider: CacheProvider? = null, 10 | timeout: Int? = null, 11 | jsoupProxy: JsoupProxy? = null, 12 | maxBodySize: Int? = null) { 13 | 14 | private val jsoupNetworkCall = JsoupNetworkCall( 15 | timeout, jsoupProxy, maxBodySize 16 | ) 17 | 18 | private constructor(builder: Builder): this( 19 | builder.listener, 20 | builder.showNullOnEmpty, 21 | builder.cacheProvider, 22 | builder.timeout, 23 | builder.jsoupProxy, 24 | builder.maxBodySize 25 | ) 26 | 27 | class Builder( 28 | val listener: OpenGraphCallback 29 | ) { 30 | var showNullOnEmpty: Boolean = false 31 | private set 32 | 33 | var cacheProvider: CacheProvider? = null 34 | private set 35 | 36 | var timeout: Int? = null 37 | private set 38 | 39 | var jsoupProxy: JsoupProxy? = null 40 | private set 41 | 42 | var maxBodySize: Int? = null 43 | private set 44 | 45 | // Setter methods for the vars 46 | fun showNullOnEmpty(showNullOnEmpty: Boolean) = apply { this.showNullOnEmpty = showNullOnEmpty } 47 | fun cacheProvider(cacheProvider: CacheProvider) = apply { this.cacheProvider = cacheProvider } 48 | fun timeout(timeout: Int) = apply { this.timeout = timeout } 49 | fun jsoupProxy(jsoupProxy: JsoupProxy) = apply { this.jsoupProxy = jsoupProxy } 50 | fun maxBodySize(maxBodySize: Int) = apply { this.maxBodySize = maxBodySize } 51 | 52 | fun build() = OpenGraphParser(this) 53 | } 54 | 55 | fun parse(url: String) { 56 | ParseLink(url).parse() 57 | } 58 | 59 | inner class ParseLink(private val url: String) : CoroutineScope { 60 | private val job: Job = Job() 61 | override val coroutineContext: CoroutineContext 62 | get() = Dispatchers.Main + job 63 | 64 | fun parse() = launch { 65 | val result = fetchContent(url) 66 | result?.let { 67 | listener.onPostResponse(it) 68 | } 69 | } 70 | } 71 | 72 | private suspend fun fetchContent(url: String) = withContext(Dispatchers.IO) { 73 | var validatedUrl = url 74 | if (!validatedUrl.contains("http")) { 75 | validatedUrl = "http://$validatedUrl" 76 | } 77 | 78 | cacheProvider?.getOpenGraphResult(url)?.let { 79 | return@withContext it 80 | } 81 | 82 | var openGraphResult: OpenGraphResult? = null 83 | AGENTS.forEach { 84 | openGraphResult = jsoupNetworkCall.callUrl(validatedUrl, it) 85 | val isResultNull = checkNullParserResult(openGraphResult) 86 | if (!isResultNull) { 87 | openGraphResult?.let { cacheProvider?.setOpenGraphResult(it, url) } 88 | return@withContext openGraphResult 89 | } 90 | } 91 | 92 | if (checkNullParserResult(openGraphResult) && showNullOnEmpty) { 93 | launch(Dispatchers.Main) { 94 | listener.onError("Null or empty response from the server") 95 | } 96 | return@withContext null 97 | } 98 | 99 | openGraphResult?.let { cacheProvider?.setOpenGraphResult(it, url) } 100 | 101 | return@withContext openGraphResult 102 | } 103 | 104 | companion object { 105 | private val AGENTS = arrayOf( 106 | "facebookexternalhit/1.1 (+http://www.facebook.com/externalhit_uatext.php)", 107 | "Mozilla", 108 | "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.45 Safari/537.36", 109 | "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36", 110 | "WhatsApp/2.19.81 A", 111 | "facebookexternalhit/1.1", 112 | "facebookcatalog/1.0" 113 | ) 114 | } 115 | } 116 | -------------------------------------------------------------------------------- /OGParser/src/main/java/com/kedia/ogparser/OpenGraphResult.kt: -------------------------------------------------------------------------------- 1 | package com.kedia.ogparser 2 | 3 | data class OpenGraphResult( 4 | var title: String? = null, 5 | var description: String? = null, 6 | var url: String? = null, 7 | var image: String? = null, 8 | var siteName: String? = null, 9 | var type: String? = null 10 | ) -------------------------------------------------------------------------------- /OGParser/src/main/java/com/kedia/ogparser/UtilityFunctions.kt: -------------------------------------------------------------------------------- 1 | package com.kedia.ogparser 2 | 3 | import java.net.URI 4 | import java.net.URL 5 | 6 | fun checkNullParserResult(openGraphResult: OpenGraphResult?): Boolean { 7 | return (openGraphResult?.title.isNullOrEmpty() || openGraphResult?.title == "null") && 8 | (openGraphResult?.description.isNullOrEmpty() || openGraphResult?.description == "null") 9 | } 10 | 11 | fun getBaseUrl(urlString: String): String { 12 | val url: URL = URI.create(urlString).toURL() 13 | return url.protocol.toString() + "://" + url.authority + "/" 14 | } 15 | -------------------------------------------------------------------------------- /OGParser/src/test/java/com/kedia/ogparser/ExampleUnitTest.kt: -------------------------------------------------------------------------------- 1 | package com.kedia.ogparser 2 | 3 | import org.junit.Test 4 | 5 | import org.junit.Assert.* 6 | 7 | /** 8 | * Example local unit test, which will execute on the development machine (host). 9 | * 10 | * See [testing documentation](http://d.android.com/tools/testing). 11 | */ 12 | class ExampleUnitTest { 13 | @Test 14 | fun addition_isCorrect() { 15 | assertEquals(4, 2 + 2) 16 | } 17 | } -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | # OpenGraphParser 4 | [![](https://jitpack.io/v/Priyansh-Kedia/OpenGraphParser.svg)](https://jitpack.io/#Priyansh-Kedia/OpenGraphParser) 5 | Google 6 | [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) 7 | ProAndroidDev 9 | 10 | A small and easy to use library which provides the convenience of using [Open Graph Protocol](https://ogp.me/) in Android very easily. 11 | Create previews for links to share in Android very easily. 12 | 13 | 14 | 15 | 16 | ### Star this repo to show your support [stargazers](https://github.com/Priyansh-Kedia/OpenGraphParser/stargazers) for this repository. :star2: 17 | 18 | 19 | https://user-images.githubusercontent.com/52661249/127740097-51535912-6623-48ac-8a3f-7709ac9b968e.mp4 20 | 21 | 22 | 23 | Add this in your root build.gradle at the end of repositories: 24 | 25 | allprojects { 26 | repositories { 27 | ... 28 | maven { url 'https://jitpack.io' } 29 | } 30 | } 31 | 32 | Add the dependency 33 | 34 | dependencies { 35 | implementation 'com.github.Priyansh-Kedia:OpenGraphParser:' 36 | } 37 | 38 | 39 | ### If using ProGuard add this line to your proguard-rules.pro: 40 | 41 | -keep public class org.jsoup.** { 42 | public *; 43 | } 44 | 45 | 46 | # Implementation 47 | 48 | private val openGraphParser = OpenGraphParser(this, showNullOnEmpty = true, cacheProvider = OpenGraphCacheProvider(this)) 49 | 50 | openGraphParser.parse(linkUrl) // To parse the link provided 51 | 52 | or you can use the Builder to create the instance of the class if you need to specify additional values. You can do so like this 53 | 54 | OpenGraphParser.Builder(listener = this) 55 | .cacheProvider(OpenGraphCacheProvider(this)) 56 | .showNullOnEmpty(true) 57 | .maxBodySize(1000000) 58 | .timeout(1000000) 59 | .jsoupProxy(JsoupProxy("", 8000)) 60 | .build() 61 | 62 | > Note: All values can be specified using the default constructor also 63 | 64 | Values that can be specified using the Builder pattern are 65 | 66 | > listener:- Specified [here](#listener-opengraphcallback) 67 | 68 | > showNullOnEmpty:- Specified [here](#shownullonempty) 69 | 70 | > cacheProvider:- Specified [here](#cacheprovider) 71 | 72 | > maxBodySize:- max body size to fetch from internet (default 1000000 bytes) 73 | 74 | > timeout:- timeout for network request (default 60000 ms) 75 | 76 | > jsoupProxy:- Specify proxy while fetching from internet. This will be an instance of JsoupProxy to specify host and port. See: [JsoupProxy](#jsoupproxy-class) 77 | 78 | 79 | ##### Listener (OpenGraphCallback) 80 | The class requires you to implement two callback functions,`onError(error: String)` and `onPostResponse(openGraphResult: OpenGraphResult)`. The former is invoked in case of error (incorrect url), and the latter is invoked on successful response. 81 | 82 | ##### showNullOnEmpty 83 | The `showNullOnEmpty` is an optional parameter, with a default value of `false`. If set to `true`, the parser would invoke `onError` if the `title` and `description` are empty for the link provided. 84 | 85 | ##### CacheProvider 86 | The `cacheProvider` is also an optional parameter. It can be passed in two ways :- 87 | 1. The default `OpenGraphCacheProvider`, which implements `SharedPreferences` from the library itself. 88 | 2. A custom Shared Preferences class which should implement the interface `CacheProvider`. The `CacheProvider` interface provides two callback functions `getOpenGraphResult` and `setOpenGraphResult`, where `getOpenGraphResult` is used to write to the cache, and `setOpenGraphResult` is used to read from the cache. 89 | 90 | --------- 91 | 92 | Inside `onPostResponse(openGraphResult: OpenGraphResult)` you can use the data to show on your UI like this. 93 | 94 | override fun onPostResponse(openGraphResult: OpenGraphResult) { 95 | linkPreviewLayout.apply { 96 | Glide.with(this@ChannelActivity).load(openGraphResult.image).into(linkImage) 97 | linkTitle.text = openGraphResult.title 98 | linkDescription.text = openGraphResult.description 99 | website.text = openGraphResult.siteName 100 | }} 101 | 102 | ## OpenGraphResult class 103 | The data class ***OpenGraphResult*** contains: 104 | 105 | - title -> The title of the page the link points to 106 | - description -> The description metadata of the page 107 | - url -> The url of the page 108 | - image -> The image metadata for the page 109 | - siteName -> The name of the website (BASE URL). 110 | - type -> The type of the object e.g., "video.movie". 111 | 112 | ## JsoupProxy class 113 | The data class ***JsoupProxy*** contains: 114 | - host -> The host for the proxy 115 | - port -> The port for the proxy 116 | 117 | 118 | # Contributions 119 | - Fork the repo 120 | - Create a new branch and make changes 121 | - Push the code to the branch and make a PR! :+1: 122 | 123 | # License 124 | MIT License 125 | 126 | Copyright (c) 2021 Priyansh Kedia 127 | 128 | Permission is hereby granted, free of charge, to any person obtaining a copy 129 | of this software and associated documentation files (the "Software"), to deal 130 | in the Software without restriction, including without limitation the rights 131 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 132 | copies of the Software, and to permit persons to whom the Software is 133 | furnished to do so, subject to the following conditions: 134 | 135 | The above copyright notice and this permission notice shall be included in all 136 | copies or substantial portions of the Software. 137 | 138 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 139 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 140 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 141 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 142 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 143 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 144 | SOFTWARE. 145 | 146 | 147 | 148 | ### Found this library useful? :heart: 149 | 150 | Support it by joining [stargazers](https://github.com/Priyansh-Kedia/OpenGraphParser/stargazers) for this repository. :star2: 151 | -------------------------------------------------------------------------------- /app/.gitignore: -------------------------------------------------------------------------------- 1 | /build -------------------------------------------------------------------------------- /app/build.gradle: -------------------------------------------------------------------------------- 1 | plugins { 2 | id 'com.android.application' 3 | id 'kotlin-android' 4 | id 'kotlin-android-extensions' 5 | } 6 | 7 | android { 8 | compileSdkVersion 30 9 | buildToolsVersion "30.0.3" 10 | 11 | defaultConfig { 12 | applicationId "com.kedia.opengraphpreview" 13 | minSdkVersion 16 14 | targetSdkVersion 30 15 | versionCode 1 16 | versionName "1.0" 17 | 18 | testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" 19 | } 20 | 21 | buildTypes { 22 | release { 23 | minifyEnabled false 24 | proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' 25 | } 26 | } 27 | compileOptions { 28 | sourceCompatibility JavaVersion.VERSION_1_8 29 | targetCompatibility JavaVersion.VERSION_1_8 30 | } 31 | kotlinOptions { 32 | jvmTarget = '1.8' 33 | } 34 | } 35 | 36 | dependencies { 37 | 38 | implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" 39 | implementation 'androidx.core:core-ktx:1.6.0' 40 | implementation 'androidx.appcompat:appcompat:1.3.1' 41 | implementation 'com.google.android.material:material:1.4.0' 42 | implementation 'androidx.constraintlayout:constraintlayout:2.0.4' 43 | // implementation project(path: ':OGParser') 44 | testImplementation 'junit:junit:4.+' 45 | androidTestImplementation 'androidx.test.ext:junit:1.1.3' 46 | androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0' 47 | implementation 'com.github.Priyansh-Kedia:OpenGraphParser:2.5.6' 48 | 49 | } -------------------------------------------------------------------------------- /app/proguard-rules.pro: -------------------------------------------------------------------------------- 1 | # Add project specific ProGuard rules here. 2 | # You can control the set of applied configuration files using the 3 | # proguardFiles setting in build.gradle. 4 | # 5 | # For more details, see 6 | # http://developer.android.com/guide/developing/tools/proguard.html 7 | 8 | # If your project uses WebView with JS, uncomment the following 9 | # and specify the fully qualified class name to the JavaScript interface 10 | # class: 11 | #-keepclassmembers class fqcn.of.javascript.interface.for.webview { 12 | # public *; 13 | #} 14 | 15 | # Uncomment this to preserve the line number information for 16 | # debugging stack traces. 17 | #-keepattributes SourceFile,LineNumberTable 18 | 19 | # If you keep the line number information, uncomment this to 20 | # hide the original source file name. 21 | #-renamesourcefileattribute SourceFile -------------------------------------------------------------------------------- /app/src/androidTest/java/com/kedia/opengraphpreview/ExampleInstrumentedTest.kt: -------------------------------------------------------------------------------- 1 | package com.kedia.opengraphpreview 2 | 3 | import androidx.test.platform.app.InstrumentationRegistry 4 | import androidx.test.ext.junit.runners.AndroidJUnit4 5 | 6 | import org.junit.Test 7 | import org.junit.runner.RunWith 8 | 9 | import org.junit.Assert.* 10 | 11 | /** 12 | * Instrumented test, which will execute on an Android device. 13 | * 14 | * See [testing documentation](http://d.android.com/tools/testing). 15 | */ 16 | @RunWith(AndroidJUnit4::class) 17 | class ExampleInstrumentedTest { 18 | @Test 19 | fun useAppContext() { 20 | // Context of the app under test. 21 | val appContext = InstrumentationRegistry.getInstrumentation().targetContext 22 | assertEquals("com.kedia.opengraphpreview", appContext.packageName) 23 | } 24 | } -------------------------------------------------------------------------------- /app/src/main/AndroidManifest.xml: -------------------------------------------------------------------------------- 1 | 2 | 4 | 5 | 6 | 7 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /app/src/main/java/com/kedia/opengraphpreview/MainActivity.kt: -------------------------------------------------------------------------------- 1 | package com.kedia.opengraphpreview 2 | 3 | import android.os.Bundle 4 | import android.util.Log 5 | import androidx.appcompat.app.AppCompatActivity 6 | import com.kedia.ogparser.OpenGraphCallback 7 | import com.kedia.ogparser.OpenGraphParser 8 | import com.kedia.ogparser.OpenGraphResult 9 | import com.kedia.ogparser.OpenGraphCacheProvider 10 | import kotlinx.android.synthetic.main.activity_main.* 11 | 12 | class MainActivity : AppCompatActivity(), OpenGraphCallback { 13 | 14 | private val openGraphParser by lazy { 15 | OpenGraphParser( 16 | listener = this, 17 | showNullOnEmpty = true, 18 | cacheProvider = OpenGraphCacheProvider(this) 19 | ) 20 | } 21 | 22 | private val LINKS_TO_TEST = mutableListOf( 23 | "https://www.linkedin.com/posts/madhusmita-padhy_machinelearning-datascience-activity-6886390508722163712-yhQ0", 24 | "https://www.youtube.com/watch?v=n3zsoX7bRlc", 25 | "https://twitter.com/levelsio/status/1481942293108359168", 26 | "https://stackoverflow.com/questions/44515769/conda-is-not-recognized-as-internal-or-external-command", 27 | "https://github.com/Priyansh-Kedia/OpenGraphParser", 28 | "https://chat.whatsapp.com/DdWAKRkt2VfAmd4OS47y7P", 29 | "https://www.reddit.com/r/MachineLearning/comments/s3mjqf/deep_learning_interviews_hundreds_of_fully_solved/?utm_medium=android_app&utm_source=share", 30 | "https://instagram.com/fcbarcelona?utm_medium=copy_link", 31 | "https://www.facebook.com/groups/777946865955982/permalink/1385110621906267/", 32 | "https://www.youtube.com/", 33 | "https://www.instagram.com/", 34 | "https://klusterapp.io/kluster/message?message_id=7244&channel_id=2247&Channel_name=new-channel-with-spa&kluster_id=64" 35 | ) 36 | 37 | override fun onCreate(savedInstanceState: Bundle?) { 38 | super.onCreate(savedInstanceState) 39 | setContentView(R.layout.activity_main) 40 | 41 | openGraphParser.parse(LINKS_TO_TEST.first()) 42 | LINKS_TO_TEST.removeFirstOrNull() 43 | 44 | // for (link in LINKS_TO_TEST) { 45 | // Handler().postDelayed({ 46 | // openGraphParser.parse(link) 47 | // }, 2000) 48 | // Log.e("TAG!!!!", "called parse") 49 | // } 50 | 51 | button.setOnClickListener { 52 | openGraphParser.parse(tview.text.toString()) 53 | } 54 | } 55 | 56 | override fun onPostResponse(openGraphResult: OpenGraphResult) { 57 | Log.e("TAG!!!!", "response $openGraphResult") 58 | tview.setText(openGraphResult.toString()) 59 | if (LINKS_TO_TEST.isNotEmpty()) { 60 | openGraphParser.parse(LINKS_TO_TEST.first()) 61 | LINKS_TO_TEST.removeFirstOrNull() 62 | } 63 | } 64 | 65 | override fun onError(error: String) { 66 | Log.e("TAG!!!!", "$error") 67 | // tview.text = error 68 | if (LINKS_TO_TEST.isNotEmpty()) { 69 | openGraphParser.parse(LINKS_TO_TEST.first()) 70 | LINKS_TO_TEST.removeFirstOrNull() 71 | } 72 | } 73 | } 74 | -------------------------------------------------------------------------------- /app/src/main/res/drawable-v24/ic_launcher_foreground.xml: -------------------------------------------------------------------------------- 1 | 7 | 8 | 9 | 15 | 18 | 21 | 22 | 23 | 24 | 30 | -------------------------------------------------------------------------------- /app/src/main/res/drawable/ic_launcher_background.xml: -------------------------------------------------------------------------------- 1 | 2 | 7 | 10 | 15 | 20 | 25 | 30 | 35 | 40 | 45 | 50 | 55 | 60 | 65 | 70 | 75 | 80 | 85 | 90 | 95 | 100 | 105 | 110 | 115 | 120 | 125 | 130 | 135 | 140 | 145 | 150 | 155 | 160 | 165 | 170 | 171 | -------------------------------------------------------------------------------- /app/src/main/res/layout/activity_main.xml: -------------------------------------------------------------------------------- 1 | 2 | 8 | 9 | 18 | 19 |