Skip to content

Commit

Permalink
Remove the ArticleExtractor, all dependent classes, tests, & plugin…
Browse files Browse the repository at this point in the history
…s. Updated README to indicate how to use `dankito/Readability4J` for article parsing.
  • Loading branch information
chimbori committed Jul 16, 2023
1 parent 4aa31ad commit 365b896
Show file tree
Hide file tree
Showing 112 changed files with 118 additions and 135,803 deletions.
298 changes: 118 additions & 180 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,11 +1,52 @@
# Crux

Crux offers a flexible plugin-based API & implementation to extract interesting information from
Web pages.
Crux offers a flexible plugin-based API & implementation to extract metadata from Web pages.
As of v5.0, Crux no longer extracts article information from web page text; read on for recommended alternatives.

## Sample Code
## Usage

Crux uses semantic versioning. If the API changes, then the major version will be incremented.
Upgrading from one minor version to the next minor version within the same major version should
not require any client code to be modified.

The latest release is available via
[Maven Central](https://search.maven.org/artifact/com.chimbori.crux/crux)
or
[GitHub Releases](https://github.com/chimbori/crux/releases).

[![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.chimbori.crux/crux/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.chimbori.crux/crux)

### Get Crux via Maven

```xml
<dependency>
<groupId>com.chimbori.crux</groupId>
<artifactId>crux</artifactId>
<version>0.0.0</version> <!-- See the latest version number above. -->
</dependency>
```

### Get Crux via Gradle

Project/`build.gradle.kts`

```kotlin
allprojects {
repositories {
mavenCentral()
}
}
```

Module/`build.gradle.kts`

```kotlin
dependencies {
implementation("com.chimbori.crux:crux:0.0.0") // See the latest version number above.
}
```

### Kotlin
## Sample Code

```kotlin
// Create a reusable object configured with the default set of plugins.
Expand Down Expand Up @@ -48,140 +89,114 @@ assertEquals("https://chimbori.com/media/favicon.png".toHttpUrl(),
assertEquals("https://chimbori.com/media/cover-photo.png", extractedMetadata[BANNER_IMAGE_URL])
```

### Java
## Design & Features

```java
import com.chimbori.crux.Crux;
import com.chimbori.crux.api.Resource;
import kotlin.coroutines.Continuation;
import kotlin.coroutines.CoroutineContext;
import kotlin.coroutines.EmptyCoroutineContext;
import okhttp3.HttpUrl;
import java.util.concurrent.CompletableFuture;
// Other imports here...
Crux is designed as a chain of plugins; each one performs a small specific task.

// Create a reusable object configured with the default set of plugins.
var crux = Crux();

var httpURL = HttpUrl.get("https://chimbori.com/");

var htmlContent = """
<html>
<head>
<title>Chimbori</title>
<meta name="twitter:image" property="og:image"
content="https://chimbori.com/media/cover-photo.png">
<meta name="twitter:site" content="ChimboriApps">
<link rel="apple-touch-icon-precomposed" sizes="192x192"
href="https://chimbori.com/media/favicon.png">
</head>
</html>""";
// Scrape page text, if you please
final CompletableFuture<Resource> extractedMetadataFuture = new CompletableFuture<>();
crux.extractFrom(httpURL, Jsoup.parse(htmlContent, httpURL.toString()), new Continuation<Resource>() {
@Override
public CoroutineContext getContext() {
return EmptyCoroutineContext.INSTANCE;
}
Each plugin receives as input a `Resource` object, which includes a URL and all the fields
populated by previous plugins in the chain. Each plugin can

@Override
public void resumeWith(Object value) {
Resource extractedMetadata = (Resource) value;
extractedMetadataFuture.complete(extractedMetadata);
}
});
- extract new pieces of metadata and add them to the output, or
- overwrite existing fields by setting a new value for the same key, or
- remove existing fields by setting a `null` value for that key.

Resource extractedMetadata = extractedMetadataFuture.get();
A small set of well-known key names are defined in the API as `Fields`, but plugins and clients are
not restricted to this set. You can extend Crux for your own applications by defining and using
your own string keys for extracted metadata.

// Metadata fields such as the Title and Description are available from the
// returned [Resource] object as an indexed collection.
assertEquals("Chimbori", extractedMetadata.get(Fields.TITLE).toString());
Plugins can rewrite URLs, which are then passed on down the chain. This is how HTTP redirects
(301 and 302) as well as static redirectors (such as those from Google and Facebook) are handled.

// Well-known URLs related to this page are available either as strings.
assertEquals("https://chimbori.com/media/favicon.png", extractedMetadata.get(Fields.FAVICON_URL).toString());
Each plugin is independent of others. You can pick and choose the ones you want to use. If you use
Crux in an Android app, Proguard or other minification tools can strip out the plugins you don’t
use.

// Extra markup fields like Twitter Cards metadata or Open Graph metadata are
// available as metadata fields as well.
assertEquals("https://chimbori.com/media/cover-photo.png", extractedMetadata.get(Fields.BANNER_IMAGE_URL).toString())
```
Crux’s API includes fewer setters/getters (compared to other such libraries), to keep the method
count low (this is important for Android). Its plugin-based architecture makes it cleaner &
leaner, compared to other libraries not explicitly optimized for Android.

# Default Plugins
## Default Plugins

## HtmlMetadataPlugin
### HtmlMetadataPlugin

Extracts titles, banner images, & other metadata from any web page.

- Support for more metadata formats: OpenGraph, Twitter Cards, Schema.org.

## ArticleExtractorPlugin

Strips out sidebars, navigation bars, and other unimportant parts of a page, and extracts
the core article content.

- Rich formatted content available, not just plain text.
- Support for more sites & better parsing overall.
- Small footprint and code size: JSoup & OkHttp are the only required dependencies.

### Retaining specific nodes via `crux-keep`

If you control the HTML that is fed into Crux, and would like to instruct Crux to keep certain DOM
nodes, irrespective of what Crux’s algorithm recommends, add the special attribute `crux-keep` to
each such DOM node.

```html
<p crux-keep="true">
Content that should not be removed.
</p>
```

## AmpPlugin
### AmpPlugin

Rewrites the URL of an AMP page to its canonical (original) URL.

## GoogleStaticRedirectorPlugin
### GoogleStaticRedirectorPlugin

Rewrites URLs generated by the Google Redirector Service to their canonical (original) URLs.

## FacebookStaticRedirectorPlugin
### FacebookStaticRedirectorPlugin

Rewrites URLs generated by the Facebook Redirector Service to their canonical (original) URLs.

# Optional Plugins
## Optional Plugins

## TrackingParameterRemover
### TrackingParameterRemover

Removes URL parameters typically used by analytics providers to track users’ behavior across the
Web. This plugin is optional because it may break some misconfigured URLs and cause them to
return the wrong content.

# Design & Features
## Writing a Custom Plugin

Crux is designed as a chain of plugins; each one performs a small specific task.
### ArticleExtractorPlugin

Each plugin receives as input a `Resource` object, which includes a URL and all the fields
populated by previous plugins in the chain. Each plugin can
As of v5.0, Crux no longer contains its own article extraction plugin.
We recommend [dankito/Readability4J](https://github.com/dankito/Readability4J), a fork of Mozilla’s Readability.js,
which is higher-quality and newer than Crux’s origin, Snacktory.
We recommend that you use it instead of relying on Crux’s parser (which has now been removed).

- extract new pieces of metadata and add them to the output, or
- overwrite existing fields by setting a new value for the same key, or
- remove existing fields by setting a `null` value for that key.
Readability4J strips out sidebars, navigation bars, and other unimportant parts of a page, and extracts the core
article content.

A small set of well-known key names are defined in the API as `Fields`, but plugins and clients are
not restricted to this set. You can extend Crux for your own applications by defining and using
your own string keys for extracted metadata.
build.gradle.kts:
```kotlinscript
dependencies {
implementation("net.dankito.readability4j:readability4j:1.0.8")
}
```

Plugins can rewrite URLs, which are then passed on down the chain. This is how HTTP redirects
(301 and 302) as well as static redirectors (such as those from Google and Facebook) are handled.
Readability4JPlugin.kt:
```kotlin
import com.chimbori.crux.api.Extractor
import com.chimbori.crux.api.Fields.DURATION_MS
import com.chimbori.crux.api.Fields.TITLE
import com.chimbori.crux.api.Resource
import com.chimbori.crux.common.estimatedReadingTimeMs
import com.chimbori.crux.common.isLikelyArticle
import net.dankito.readability4j.extended.Readability4JExtended
import okhttp3.HttpUrl

class Readability4JPlugin : Extractor {
override fun canExtract(url: HttpUrl) = url.isLikelyArticle()

override suspend fun extract(request: Resource): Resource? = if (request.url != null && request.document != null) {
val readability4J = Readability4JExtended(request.url.toString(), request.document!!)
val article = readability4J.parse()
Resource(
article = article.articleContent,
metadata = mapOf(
TITLE to article.title,
DURATION_MS to article.articleContent?.text()?.estimatedReadingTimeMs()
),
)
} else {
null
}
}
```

Each plugin is independent of others. You can pick and choose the ones you want to use. If you use
Crux in an Android app, Proguard or other minification tools can strip out the plugins you don’t
use.
Then add `Readability4JPlugin` to the list of Crux plugins to use it along with Crux’s default plugins.

Crux’s API includes fewer setters/getters (compared to other such libraries), to keep the method
count low (this is important for Android). Its plugin-based architecture makes it cleaner &
leaner, compared to other libraries not explicitly optimized for Android.
### CustomerNumberExtractorPlugin

## Writing a Custom Plugin
As an example, one can write a custom plugin to extract specific fields from a URL as follows:

```kotlin
// If you write a new plugin yourself, you can add any custom fields to the `Resource` object
Expand All @@ -206,6 +221,7 @@ val orderDetailsUrl = "https://www.your-website.com/orders?customer-number=42".t
val metadata = runBlocking {
cruxWithCustomPlugin.extractFrom(orderDetailsUrl, Document(orderDetailsUrl.toString()))
}

// Input URL was unchanged and is available in the output metadata.
assertEquals(orderDetailsUrl, metadata.url)
// Data extracted by the custom plugin is available as a custom field.
Expand Down Expand Up @@ -254,85 +270,7 @@ assertTrue(url.isLikelyArticle())
assertFalse(url.isLikelyImage())
```

# Usage

Include Crux in your project, then see sample code for each API provided above.

Crux uses semantic versioning. If the API changes, then the major version will be incremented.
Upgrading from one minor version to the next minor version within the same major version should
not require any client code to be modified.

The latest release is available via
[Maven Central](https://search.maven.org/artifact/com.chimbori.crux/crux)
or
[GitHub Releases](https://github.com/chimbori/crux/releases).

[![Maven Central](https://maven-badges.herokuapp.com/maven-central/com.chimbori.crux/crux/badge.svg)](https://maven-badges.herokuapp.com/maven-central/com.chimbori.crux/crux)

## Get Crux via Maven

```xml

<dependency>
<groupId>com.chimbori.crux</groupId>
<artifactId>crux</artifactId>
<version>0.0.0</version> <!-- See the latest version number above. -->
</dependency>
```

## Get Crux via Gradle

### Gradle Groovy DSL

Project/`build.gradle`

```groovy
allprojects {
repositories {
mavenCentral()
}
}
```

Module/`build.gradle`:

```groovy
dependencies {
implementation 'com.chimbori.crux:crux:0.0.0' // See the latest version number above.
}
```

### Gradle Kotlin DSL

Project/`build.gradle.kts`

```groovy
allprojects {
repositories {
mavenCentral()
}
}
```

Module/`build.gradle.kts`:

```kotlin
dependencies {
implementation("com.chimbori.crux:crux:0.0.0") // See the latest version number above.
}
```

# History

Crux began as a fork of [Snacktory](http:https://github.com/karussell/snacktory) with the goal of making
it more performant on Android devices, but it has quickly gained several new features that are not
available in Snacktory.

Snacktory (and thus Crux) borrow ideas and test cases from
[Goose](https://github.com/GravityLabs/goose) and
[JReadability](https://github.com/ifesdjeen/jReadability).

# License
## License

Copyright 2016, Chimbori, makers of Hermit, the Lite Apps Browser.

Expand Down
3 changes: 0 additions & 3 deletions src/main/kotlin/com/chimbori/crux/Crux.kt
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import com.chimbori.crux.api.Resource
import com.chimbori.crux.api.Rewriter
import com.chimbori.crux.common.CHROME_USER_AGENT
import com.chimbori.crux.plugins.AmpRedirector
import com.chimbori.crux.plugins.ArticleExtractor
import com.chimbori.crux.plugins.FacebookUrlRewriter
import com.chimbori.crux.plugins.FaviconExtractor
import com.chimbori.crux.plugins.GoogleUrlRewriter
Expand Down Expand Up @@ -42,8 +41,6 @@ public fun createDefaultPlugins(okHttpClient: OkHttpClient): List<Plugin> = list
WebAppManifestParser(okHttpClient),
// Extracts the best possible favicon from all the markup available on the page itself.
FaviconExtractor(),
// Parses the content of the page to remove ads, navigation, and all the other fluff.
ArticleExtractor(okHttpClient),
)

/**
Expand Down
Loading

0 comments on commit 365b896

Please sign in to comment.