Skip to content

Commit

Permalink
automatically add link preview card
Browse files Browse the repository at this point in the history
  • Loading branch information
JBGruber committed Jan 14, 2024
1 parent d8dffab commit 3704098
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 2 deletions.
4 changes: 4 additions & 0 deletions R/feed.r
Original file line number Diff line number Diff line change
Expand Up @@ -657,6 +657,10 @@ post <- function(text,
parsed_richtext <- parse_facets(text)
if (!any(is.na(unlist(parsed_richtext)))) {
record[["facets"]] <- parsed_richtext
if (!purrr::pluck_exists(record, "embed")) {
# preview card
record <- fetch_preview(record)
}
}

invisible(do.call(what = com_atproto_repo_create_record,
Expand Down
29 changes: 27 additions & 2 deletions R/utils.r
Original file line number Diff line number Diff line change
Expand Up @@ -173,8 +173,10 @@ com_atproto_repo_upload_blob2 <- function(image,
img <- magick::image_read(image)
image_mimetype <- paste0("image/", tolower(magick::image_info(img)$format))

# TODO: not sure how to get the magick image as raw vector
img <- readBin(image, "raw", file.info(image)$size)
# TODO: find way to do this directly
tmp <- tempfile()
magick::image_write(img, tmp)
img <- readBin(tmp, "raw", file.info(tmp)$size)

httr2::request("https://bsky.social/xrpc/com.atproto.repo.uploadBlob") |>
httr2::req_auth_bearer_token(token = .token$accessJwt) |>
Expand Down Expand Up @@ -225,3 +227,26 @@ str_locate_all_bytes <- function(string, pattern) {
}
return(spans)
}


fetch_preview <- function(record) {
uri <- purrr::pluck(record, "facets", 1, "features", 1, "uri",
.default = NA_character_)
if (!is.na(uri)) {
preview <- httr2::request("https://cardyb.bsky.app/v1/extract") |>
httr2::req_url_query(url = uri) |>
httr2::req_perform() |>
httr2::resp_body_json()

embed <- list(`$type` = "app.bsky.embed.external",
external = list(uri = preview$url,
title = preview$title,
description = preview$description))
if (purrr::pluck_exists(preview, "image")) {
embed$external$thumb <-
com_atproto_repo_upload_blob2(purrr::pluck(preview, "image"))$blob
}
record$embed <- embed
}
return(record)
}

0 comments on commit 3704098

Please sign in to comment.