summaryrefslogtreecommitdiff
path: root/app/src/main/java/org/terst/feedreader/data/ArticleSaving.kt
blob: f2bcb7224f095aa6054b157b57192c3e3cc64b61 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package org.terst.feedreader.data

import android.content.Context
import org.terst.feedreader.readability.ReaderExtractor
import java.security.MessageDigest

fun urlToArticleId(url: String): String =
    MessageDigest.getInstance("SHA-256").digest(url.toByteArray()).joinToString("") { "%02x".format(it) }

/**
 * Creates (or returns the existing) standalone ArticleEntity for a bare URL not tied to any
 * feed, extracting it fresh via Readability if it's not already on-device. Shared by every
 * "save something without opening it in the reader first" entry point: the share-sheet
 * target, and long-pressing a link inside an article to save/stash it directly.
 */
suspend fun ensureStandaloneArticle(context: Context, db: AppDatabase, url: String): ArticleEntity {
    val id = urlToArticleId(url)
    db.articleDao().getById(id)?.let { return it }
    val extracted = ReaderExtractor.extract(context, url)
    val entity = ArticleEntity(
        id = id,
        feedId = null,
        title = extracted?.title ?: url,
        link = url,
        extractedContent = extracted?.content,
        createdAt = System.currentTimeMillis()
    )
    db.articleDao().upsert(entity)
    return entity
}