mirror of
https://framagit.org/veretcle/oolatoocs.git
synced 2025-07-20 12:31:18 +02:00
Compare commits
41 Commits
Author | SHA1 | Date | |
---|---|---|---|
![]() |
402fcffc75 | ||
![]() |
b295cc5b94 | ||
![]() |
a882aaa59d | ||
![]() |
259032a7b9 | ||
![]() |
e7f0c9c6f5 | ||
![]() |
83c8da46e8 | ||
![]() |
823f80729f | ||
![]() |
5969e3a56a | ||
![]() |
3ea2478512 | ||
![]() |
5606d00da2 | ||
![]() |
4cb80b0607 | ||
![]() |
bbe14f1f30 | ||
![]() |
6fbc011914 | ||
![]() |
8f23c2459b | ||
![]() |
26805feadb | ||
![]() |
3a8fd538fc | ||
![]() |
891f46ec2f | ||
![]() |
cad7840f98 | ||
![]() |
6e7299585a | ||
![]() |
62efcb8112 | ||
![]() |
49279e7f1f | ||
![]() |
f05669923f | ||
![]() |
9da43beb34 | ||
![]() |
e99a666b18 | ||
![]() |
3b18dac2fb | ||
![]() |
af977a1ee0 | ||
![]() |
b90b727783 | ||
![]() |
f8227f99c1 | ||
![]() |
9f2ff119ff | ||
![]() |
c0244c8c30 | ||
![]() |
89aec3e0ed | ||
![]() |
6a7eef757a | ||
![]() |
f46f90ad34 | ||
![]() |
4b4f9abe2f | ||
![]() |
9f9cf52722 | ||
![]() |
e0d3667fb9 | ||
![]() |
ac8af5ce95 | ||
![]() |
f7e2aafa7b | ||
![]() |
6e9bb6b42c | ||
![]() |
88edb1b2e1 | ||
![]() |
bf9d27df61 |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -1,3 +1,4 @@
|
||||
/target
|
||||
.last_tweet
|
||||
.config.toml
|
||||
.config.json
|
||||
|
3208
Cargo.lock
generated
3208
Cargo.lock
generated
File diff suppressed because it is too large
Load Diff
18
Cargo.toml
18
Cargo.toml
@@ -1,25 +1,29 @@
|
||||
[package]
|
||||
name = "oolatoocs"
|
||||
version = "2.0.2"
|
||||
version = "4.3.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
||||
chrono = "0.4.31"
|
||||
chrono = "^0.4"
|
||||
clap = "^4"
|
||||
env_logger = "^0.10"
|
||||
env_logger = "^0.11"
|
||||
futures = "^0.3"
|
||||
html-escape = "^0.2"
|
||||
log = "^0.4"
|
||||
megalodon = "^0.11"
|
||||
megalodon = "^1.0"
|
||||
oauth1-request = "^0.6"
|
||||
regex = "^1.10"
|
||||
reqwest = { version = "^0.11", features = ["json", "stream", "multipart"] }
|
||||
rusqlite = { version = "^0.30", features = ["chrono"] }
|
||||
reqwest = { version = "^0.12", features = ["json", "stream", "multipart"] }
|
||||
rusqlite = { version = "^0.33", features = ["chrono"] }
|
||||
serde = { version = "^1.0", features = ["derive"] }
|
||||
tokio = { version = "^1.33", features = ["rt-multi-thread", "macros", "time"] }
|
||||
tokio = { version = "^1.33", features = ["rt-multi-thread", "macros"] }
|
||||
toml = "^0.8"
|
||||
bsky-sdk = "^0.1"
|
||||
atrium-api = { version = "^0.25", features = ["namespace-appbsky"] }
|
||||
image = "^0.25"
|
||||
webp = "^0.3"
|
||||
|
||||
[profile.release]
|
||||
strip = true
|
||||
|
43
README.md
43
README.md
@@ -1,20 +1,27 @@
|
||||
# oolatoocs, a Mastodon to Twitter bot
|
||||
# oolatoocs, a Mastodon to Bluesky bot
|
||||
## A little bit of history
|
||||
|
||||
So what is it? Originally, I wrote, with some help, [Scootaloo](https://framagit.org/veretcle/scootaloo/) which was a Twitter to Mastodon Bot to help the [writers at NintendojoFR](https://www.nintendojo.fr) not to worry about Mastodon: the vast majority of writers were posting to Twitter, the bot scooped everything and arranged it properly for Mastodon and everything was fine and dandy. It was also used, in an altered beefed-up version, for [Nupes.social](https://nupes.social) to make the tweets from the NUPES political alliance on Twitter, more easily accessible in Mastodon.
|
||||
So what is it? Originally, I wrote, with some help, [Scootaloo](https://framagit.org/veretcle/scootaloo/) which was a Twitter to Mastodon Bot to help the [writers at NintendojoFR](https://www.nintendojo.fr) not to worry about Mastodon: the vast majority of writers were posting to Twitter, the bot scooped everything and arranged it properly for Mastodon and everything was fine and dandy. It was also used, in an altered beefed-up version, for the (now defunct) Mastodon Instance [Nupes.social](https://nupes.social) to make the tweets from the NUPES political alliance on Twitter, more easily accessible for Mastodon users.
|
||||
|
||||
But then Elon came, and we couldn’t read data from Twitter anymore. So we had to rely on copy/pasting things from one to another, which is not fun nor efficient.
|
||||
|
||||
Hence `oolatoocs`, which takes a Mastodon Timeline and reposts it to Twitter as properly as possible.
|
||||
## And now…
|
||||
|
||||
Hence `oolatoocs`, which takes a Mastodon Timeline and reposts it to Bluesky as properly as possible.
|
||||
|
||||
Since 2025-01-20, Twitter is now longer supported.
|
||||
|
||||
# Remarkable features
|
||||
|
||||
What it can do:
|
||||
* Reproduces the Toot content into the Tweet;
|
||||
* Cuts (poorly) the Toot in half in it’s too long for Twitter and thread it (this is cut using a word count, not the best method, but it gets the job done);
|
||||
* Reuploads images/gifs/videos from Mastodon to Twitter
|
||||
* Can reproduce threads from Mastodon to Twitter
|
||||
* Can reproduce poll from Mastodon to Twitter
|
||||
* Can prevent a Toot from being tweeted by using the #NoTweet (case-insensitive) hashtag in Mastodon
|
||||
* Reproduces the Toot content into the Record;
|
||||
* Cuts (poorly) the Toot in half in it’s too long for Bluesky and thread it (this is cut using a word count, not the best method, but it gets the job done);
|
||||
* Reuploads images/gifs/videos from Mastodon to Bluesky
|
||||
* ⚠️ Bluesky does not support mixing images and videos. You can have up to 4 images on a Bsky record **or** 1 video but not mix around. If you do so, only the video will be posted on Bluesky.
|
||||
* ⚠️ Bluesky does not support images greater than 1Mb (that is 1,000,000 bytes or 976.6 KiB), so Oolatoocs converts the image to WebP and progressively reduces the quality to fit that limitation.
|
||||
* Can reproduce threads from Mastodon to Bluesky
|
||||
* ⚠️ Bluesky does support polls for now. So the poll itself is just presented as text from Mastodon instead which is not the most elegant.
|
||||
* Can prevent a Toot from being recorded to Bluesky by using the #NoTweet (case-insensitive) hashtag in Mastodon
|
||||
|
||||
# Configuration file
|
||||
|
||||
@@ -22,7 +29,8 @@ The configuration is relatively easy to follow:
|
||||
|
||||
```toml
|
||||
[oolatoocs]
|
||||
db_path = "/var/lib/oolatoocs/db.sqlite3" # the path to the DB where toot/tweet are stored
|
||||
db_path = "/var/lib/oolatoocs/db.sqlite3" # the path to the DB where toots/tweets/records are stored
|
||||
remove_hashtags = false # optional, default to false
|
||||
|
||||
[mastodon] # This part can be generated, see below
|
||||
base = "https://m.nintendojo.fr"
|
||||
@@ -31,11 +39,10 @@ client_secret = "<REDACTED>"
|
||||
redirect = "urn:ietf:wg:oauth:2.0:oob"
|
||||
token = "<REDACTED>"
|
||||
|
||||
[twitter] # you’ll have to get this part from Twitter, this can be done via https://developer.twitter.com/en
|
||||
consumer_key = "<REDACTED>"
|
||||
consumer_secret = "<REDACTED>"
|
||||
oauth_token = "<REDACTED>"
|
||||
oauth_token_secret = "<REDACTED>"
|
||||
[bluesky] # this is your Bsky handle and password + a writable path for the session handling
|
||||
handle = "nintendojofr.bsky.social"
|
||||
password = "<REDACTED>"
|
||||
config_path = "/var/lib/oolatoocs/bsky.json"
|
||||
```
|
||||
|
||||
## How to generate the Mastodon keys?
|
||||
@@ -48,11 +55,9 @@ oolatoocs register --host https://<your-instance>
|
||||
|
||||
And follow the instructions.
|
||||
|
||||
## How to generate the Twitter part?
|
||||
## How to generate the Bluesky part?
|
||||
|
||||
You’ll need to generate a key. This is a real pain in the ass, but you can use [this script](https://github.com/twitterdev/Twitter-API-v2-sample-code/blob/main/Manage-Tweets/create_tweet.py), modify it and run it to recover you key.
|
||||
|
||||
Will I some day make a subcommand to generate it? Maybe…
|
||||
You’ll need your handle and password. I strongly recommend a dedicated application password. You’ll also need a writable path to store the Bsky session.
|
||||
|
||||
# How to run
|
||||
|
||||
|
328
src/bsky.rs
Normal file
328
src/bsky.rs
Normal file
@@ -0,0 +1,328 @@
|
||||
use crate::config::BlueskyConfig;
|
||||
use atrium_api::{
|
||||
app::bsky::feed::post::RecordData, com::atproto::repo::upload_blob::Output,
|
||||
types::string::Datetime, types::string::Language, types::string::RecordKey,
|
||||
};
|
||||
use bsky_sdk::{
|
||||
agent::config::{Config, FileStore},
|
||||
rich_text::RichText,
|
||||
BskyAgent,
|
||||
};
|
||||
use futures::{stream, StreamExt};
|
||||
use image::ImageReader;
|
||||
use log::{debug, error, warn};
|
||||
use megalodon::entities::{
|
||||
attachment::{Attachment, AttachmentType},
|
||||
card::Card,
|
||||
};
|
||||
use regex::Regex;
|
||||
use std::{error::Error, fs::exists, io::Cursor};
|
||||
use webp::*;
|
||||
|
||||
/// Intermediary struct to deal with replies more easily
|
||||
#[derive(Debug)]
|
||||
pub struct BskyReply {
|
||||
pub record_uri: String,
|
||||
pub root_record_uri: String,
|
||||
}
|
||||
|
||||
pub async fn get_session(config: &BlueskyConfig) -> Result<BskyAgent, Box<dyn Error>> {
|
||||
if exists(&config.config_path)? {
|
||||
let bluesky = BskyAgent::builder()
|
||||
.config(Config::load(&FileStore::new(&config.config_path)).await?)
|
||||
.build()
|
||||
.await?;
|
||||
|
||||
if bluesky.api.com.atproto.server.get_session().await.is_ok() {
|
||||
bluesky
|
||||
.to_config()
|
||||
.await
|
||||
.save(&FileStore::new(&config.config_path))
|
||||
.await?;
|
||||
return Ok(bluesky);
|
||||
}
|
||||
}
|
||||
|
||||
let bluesky = BskyAgent::builder().build().await?;
|
||||
bluesky.login(&config.handle, &config.password).await?;
|
||||
bluesky
|
||||
.to_config()
|
||||
.await
|
||||
.save(&FileStore::new(&config.config_path))
|
||||
.await?;
|
||||
|
||||
Ok(bluesky)
|
||||
}
|
||||
|
||||
pub async fn build_post_record(
|
||||
config: &BlueskyConfig,
|
||||
text: &str,
|
||||
language: &Option<String>,
|
||||
embed: Option<atrium_api::types::Union<atrium_api::app::bsky::feed::post::RecordEmbedRefs>>,
|
||||
reply_to: &Option<BskyReply>,
|
||||
) -> Result<RecordData, Box<dyn Error>> {
|
||||
let mut rt = RichText::new_with_detect_facets(text).await?;
|
||||
|
||||
let insert_chars = "…";
|
||||
|
||||
let re = Regex::new(r#"(https?://)(www\.)?(\S{1,26})(\S*)"#).unwrap();
|
||||
|
||||
while let Some(found) = re.captures(&rt.text.clone()) {
|
||||
if let Some(group) = found.get(4) {
|
||||
if !group.is_empty() {
|
||||
rt.insert(group.start(), insert_chars);
|
||||
rt.delete(
|
||||
group.start() + insert_chars.len(),
|
||||
group.start() + insert_chars.len() + group.len(),
|
||||
);
|
||||
}
|
||||
}
|
||||
if let Some(group) = found.get(1) {
|
||||
let www: usize = found.get(2).map_or(0, |x| x.len());
|
||||
rt.delete(group.start(), group.start() + www + group.len());
|
||||
}
|
||||
}
|
||||
|
||||
let langs = language.clone().map(|s| vec![Language::new(s).unwrap()]);
|
||||
|
||||
let reply = if let Some(x) = reply_to {
|
||||
let root_record = get_record(&config.handle, &rkey(&x.root_record_uri)).await?;
|
||||
let parent_record = get_record(&config.handle, &rkey(&x.record_uri)).await?;
|
||||
|
||||
Some(
|
||||
atrium_api::app::bsky::feed::post::ReplyRefData {
|
||||
parent: atrium_api::com::atproto::repo::strong_ref::MainData {
|
||||
cid: parent_record.data.cid.unwrap(),
|
||||
uri: parent_record.data.uri.to_owned(),
|
||||
}
|
||||
.into(),
|
||||
root: atrium_api::com::atproto::repo::strong_ref::MainData {
|
||||
cid: root_record.data.cid.unwrap(),
|
||||
uri: root_record.data.uri.to_owned(),
|
||||
}
|
||||
.into(),
|
||||
}
|
||||
.into(),
|
||||
)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
Ok(RecordData {
|
||||
created_at: Datetime::now(),
|
||||
embed,
|
||||
entities: None,
|
||||
facets: rt.facets,
|
||||
labels: None,
|
||||
langs,
|
||||
reply,
|
||||
tags: None,
|
||||
text: rt.text,
|
||||
})
|
||||
}
|
||||
|
||||
async fn get_record(
|
||||
config: &str,
|
||||
rkey: &str,
|
||||
) -> Result<
|
||||
atrium_api::types::Object<atrium_api::com::atproto::repo::get_record::OutputData>,
|
||||
Box<dyn Error>,
|
||||
> {
|
||||
let bsky = BskyAgent::builder().build().await?;
|
||||
let record = bsky
|
||||
.api
|
||||
.com
|
||||
.atproto
|
||||
.repo
|
||||
.get_record(
|
||||
atrium_api::com::atproto::repo::get_record::ParametersData {
|
||||
cid: None,
|
||||
collection: atrium_api::types::string::Nsid::new("app.bsky.feed.post".to_string())?,
|
||||
repo: atrium_api::types::string::Handle::new(config.to_string())?.into(),
|
||||
rkey: RecordKey::new(rkey.to_string())?,
|
||||
}
|
||||
.into(),
|
||||
)
|
||||
.await?;
|
||||
|
||||
Ok(record)
|
||||
}
|
||||
|
||||
/// Generate an embed card record into Bsky
|
||||
/// If the preview image does not exist or fails to upload, it is simply ignored
|
||||
pub async fn generate_embed_records(
|
||||
bsky: &BskyAgent,
|
||||
card: &Card,
|
||||
) -> Option<atrium_api::types::Union<atrium_api::app::bsky::feed::post::RecordEmbedRefs>> {
|
||||
// uploads the image card, if it fails, simply ignore everything
|
||||
let blob = if let Some(url) = &card.image {
|
||||
if let Ok(image_blob) = upload_media(true, bsky, url).await {
|
||||
Some(image_blob.blob.clone())
|
||||
} else {
|
||||
None
|
||||
}
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let record_card = atrium_api::app::bsky::embed::external::ExternalData {
|
||||
description: card.description.clone(),
|
||||
thumb: blob,
|
||||
title: card.title.clone(),
|
||||
uri: card.url.clone(),
|
||||
};
|
||||
|
||||
Some(atrium_api::types::Union::Refs(
|
||||
atrium_api::app::bsky::feed::post::RecordEmbedRefs::AppBskyEmbedExternalMain(Box::new(
|
||||
atrium_api::app::bsky::embed::external::MainData {
|
||||
external: record_card.into(),
|
||||
}
|
||||
.into(),
|
||||
)),
|
||||
))
|
||||
}
|
||||
|
||||
/// Generate an array of Bsky media records
|
||||
/// As Bsky does not support multiple video in a record or mix of video and images, video has the
|
||||
/// highest priority
|
||||
pub async fn generate_media_records(
|
||||
bsky: &BskyAgent,
|
||||
media_attach: &[Attachment],
|
||||
) -> Option<atrium_api::types::Union<atrium_api::app::bsky::feed::post::RecordEmbedRefs>> {
|
||||
let mut embed: Option<
|
||||
atrium_api::types::Union<atrium_api::app::bsky::feed::post::RecordEmbedRefs>,
|
||||
> = None;
|
||||
|
||||
let image_media_attach: Vec<_> = media_attach
|
||||
.iter()
|
||||
.filter(|x| x.r#type == AttachmentType::Image)
|
||||
.cloned()
|
||||
.collect();
|
||||
let video_media_attach: Vec<_> = media_attach
|
||||
.iter()
|
||||
.filter(|x| (x.r#type == AttachmentType::Video || x.r#type == AttachmentType::Gifv))
|
||||
.cloned()
|
||||
.collect();
|
||||
|
||||
// Bsky only tasks 1 video per post, so we’ll try to treat that first and exit
|
||||
if !video_media_attach.is_empty() {
|
||||
// treat only the very first video, ignore the rest
|
||||
let media = &video_media_attach[0];
|
||||
let blob = upload_media(false, bsky, &media.url).await.unwrap();
|
||||
|
||||
embed = Some(atrium_api::types::Union::Refs(
|
||||
atrium_api::app::bsky::feed::post::RecordEmbedRefs::AppBskyEmbedVideoMain(Box::new(
|
||||
atrium_api::app::bsky::embed::video::MainData {
|
||||
alt: media.description.clone(),
|
||||
aspect_ratio: None,
|
||||
captions: None,
|
||||
video: blob.data.blob,
|
||||
}
|
||||
.into(),
|
||||
)),
|
||||
));
|
||||
|
||||
// returns immediately, we don’t want to treat the other medias
|
||||
return embed;
|
||||
}
|
||||
|
||||
let mut stream = stream::iter(image_media_attach)
|
||||
.map(|media| {
|
||||
let bsky = bsky.clone();
|
||||
tokio::task::spawn(async move {
|
||||
debug!("Treating media {}", &media.url);
|
||||
upload_media(true, &bsky, &media.url).await.map(|i| {
|
||||
atrium_api::app::bsky::embed::images::ImageData {
|
||||
alt: media
|
||||
.description
|
||||
.clone()
|
||||
.map_or("".to_string(), |v| v.to_owned()),
|
||||
aspect_ratio: None,
|
||||
image: i.data.blob,
|
||||
}
|
||||
})
|
||||
})
|
||||
})
|
||||
.buffered(4);
|
||||
|
||||
let mut images = Vec::new();
|
||||
|
||||
while let Some(result) = stream.next().await {
|
||||
match result {
|
||||
Ok(Ok(v)) => images.push(v.into()),
|
||||
Ok(Err(e)) => warn!("Cannot treat a specific media: {}", e),
|
||||
Err(e) => error!("Something went wrong when joining main thread: {}", e),
|
||||
}
|
||||
}
|
||||
|
||||
if !images.is_empty() {
|
||||
embed = Some(atrium_api::types::Union::Refs(
|
||||
atrium_api::app::bsky::feed::post::RecordEmbedRefs::AppBskyEmbedImagesMain(Box::new(
|
||||
atrium_api::app::bsky::embed::images::MainData { images }.into(),
|
||||
)),
|
||||
));
|
||||
}
|
||||
|
||||
embed
|
||||
}
|
||||
|
||||
async fn upload_media(
|
||||
is_image: bool,
|
||||
bsky: &BskyAgent,
|
||||
u: &str,
|
||||
) -> Result<Output, Box<dyn Error + Send + Sync>> {
|
||||
let dl = reqwest::get(u).await?;
|
||||
let content_length = dl.content_length().ok_or("Content length unavailable")?;
|
||||
let bytes = if content_length <= 1_000_000 || !is_image {
|
||||
dl.bytes().await?.as_ref().to_vec()
|
||||
} else {
|
||||
// this is an image and it’s over 1Mb long
|
||||
debug!("Img file too large: {}", content_length);
|
||||
// defaults to 95% quality for WebP compression
|
||||
let mut default_quality = 95f32;
|
||||
let img = ImageReader::new(Cursor::new(dl.bytes().await?))
|
||||
.with_guessed_format()?
|
||||
.decode()?;
|
||||
let encoder: Encoder = Encoder::from_image(&img)?;
|
||||
let mut webp: WebPMemory = encoder.encode(default_quality);
|
||||
|
||||
while webp.len() > 1_000_000 {
|
||||
debug!("Img file too large at {}%, reducing…", default_quality);
|
||||
default_quality -= 5.0;
|
||||
webp = encoder.encode(default_quality);
|
||||
}
|
||||
|
||||
webp.to_vec()
|
||||
};
|
||||
|
||||
let record = bsky.api.com.atproto.repo.upload_blob(bytes).await?;
|
||||
|
||||
Ok(record)
|
||||
}
|
||||
|
||||
fn rkey(record_id: &str) -> String {
|
||||
record_id.split('/').nth(4).unwrap().to_string()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_build_post_record() {
|
||||
let text = "@factornews@piaille.fr Retrouvez-nous ici https://www.nintendojo.fr/articles/editos/le-mod-renovation-de-8bitdo-pour-manette-n64 et là https://www.nintendojo.fr/articles/analyses/vite-vu/vite-vu-morbid-the-lords-of-ire et un lien très court http://vsl.ie/TaMere et un autre https://p.nintendojo.fr/w/kV3CBbKKt1nPEChHhZiNve + http://www.xxx.com + https://www.youtube.com/watch?v=dQw4w9WgXcQ&pp=ygUJcmljayByb2xs";
|
||||
let expected_text = "@factornews@piaille.fr Retrouvez-nous ici nintendojo.fr/articles/edi… et là nintendojo.fr/articles/ana… et un lien très court vsl.ie/TaMere et un autre p.nintendojo.fr/w/kV3CBbKK… + xxx.com + youtube.com/watch?v=dQw4w9…";
|
||||
|
||||
let bsky_conf = BlueskyConfig {
|
||||
handle: "tamerelol.bsky.social".to_string(),
|
||||
password: "dtc".to_string(),
|
||||
config_path: "nope".to_string(),
|
||||
};
|
||||
|
||||
let created_record_data = build_post_record(&bsky_conf, text, &None, None, &None)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(expected_text, &created_record_data.text);
|
||||
}
|
||||
}
|
@@ -5,20 +5,23 @@ use std::fs::read_to_string;
|
||||
pub struct Config {
|
||||
pub oolatoocs: OolatoocsConfig,
|
||||
pub mastodon: MastodonConfig,
|
||||
pub twitter: TwitterConfig,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize, Clone)]
|
||||
pub struct TwitterConfig {
|
||||
pub consumer_key: String,
|
||||
pub consumer_secret: String,
|
||||
pub oauth_token: String,
|
||||
pub oauth_token_secret: String,
|
||||
pub bluesky: BlueskyConfig,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct OolatoocsConfig {
|
||||
pub db_path: String,
|
||||
#[serde(default)]
|
||||
pub remove_hashtags: bool,
|
||||
}
|
||||
|
||||
impl Default for OolatoocsConfig {
|
||||
fn default() -> Self {
|
||||
OolatoocsConfig {
|
||||
db_path: "/var/lib/oolatoocs/db".to_string(),
|
||||
remove_hashtags: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
@@ -30,6 +33,13 @@ pub struct MastodonConfig {
|
||||
pub token: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Deserialize)]
|
||||
pub struct BlueskyConfig {
|
||||
pub handle: String,
|
||||
pub password: String,
|
||||
pub config_path: String,
|
||||
}
|
||||
|
||||
/// parses TOML file into Config struct
|
||||
pub fn parse_toml(toml_file: &str) -> Config {
|
||||
let toml_config =
|
||||
|
132
src/lib.rs
132
src/lib.rs
@@ -1,3 +1,5 @@
|
||||
use log::debug;
|
||||
|
||||
mod error;
|
||||
pub use error::OolatoocsError;
|
||||
|
||||
@@ -5,8 +7,7 @@ mod config;
|
||||
pub use config::{parse_toml, Config};
|
||||
|
||||
mod state;
|
||||
#[allow(unused_imports)]
|
||||
use state::{delete_state, read_all_tweet_state, read_state, write_state, TweetToToot};
|
||||
use state::{delete_state, read_all_state, read_state, write_state, TootRecord};
|
||||
pub use state::{init_db, migrate_db};
|
||||
|
||||
mod mastodon;
|
||||
@@ -16,9 +17,10 @@ use mastodon::{get_mastodon_instance, get_mastodon_timeline_since, get_status_ed
|
||||
mod utils;
|
||||
use utils::{generate_multi_tweets, strip_everything};
|
||||
|
||||
mod twitter;
|
||||
#[allow(unused_imports)]
|
||||
use twitter::{delete_tweet, generate_media_ids, post_tweet, transform_poll};
|
||||
mod bsky;
|
||||
use bsky::{
|
||||
build_post_record, generate_embed_records, generate_media_records, get_session, BskyReply,
|
||||
};
|
||||
|
||||
use rusqlite::Connection;
|
||||
|
||||
@@ -27,7 +29,12 @@ pub async fn run(config: &Config) {
|
||||
let conn = Connection::open(&config.oolatoocs.db_path)
|
||||
.unwrap_or_else(|e| panic!("Cannot open DB: {}", e));
|
||||
|
||||
let mastodon = get_mastodon_instance(&config.mastodon);
|
||||
let mastodon = get_mastodon_instance(&config.mastodon)
|
||||
.unwrap_or_else(|e| panic!("Cannot instantiate Mastodon: {}", e));
|
||||
|
||||
let bluesky = get_session(&config.bluesky)
|
||||
.await
|
||||
.unwrap_or_else(|e| panic!("Cannot get Bsky session: {}", e));
|
||||
|
||||
let last_entry =
|
||||
read_state(&conn, None).unwrap_or_else(|e| panic!("Cannot get last toot id: {}", e));
|
||||
@@ -40,21 +47,20 @@ pub async fn run(config: &Config) {
|
||||
Some(d) => {
|
||||
// a date has been found
|
||||
if d > t.datetime.unwrap() {
|
||||
// said date is posterior to the previously
|
||||
// written tweet, we need to delete/rewrite
|
||||
for local_tweet_id in read_all_tweet_state(&conn, t.toot_id)
|
||||
.unwrap_or_else(|e| {
|
||||
debug!("Last toot date is posterior to the previously written tweet, deleting…");
|
||||
let local_record_uris =
|
||||
read_all_state(&conn, t.toot_id).unwrap_or_else(|e| {
|
||||
panic!(
|
||||
"Cannot fetch all tweets associated with Toot ID {}: {}",
|
||||
"Cannot fetch all records associated with Toot ID {}: {}",
|
||||
t.toot_id, e
|
||||
)
|
||||
})
|
||||
.into_iter()
|
||||
{
|
||||
delete_tweet(&config.twitter, local_tweet_id)
|
||||
});
|
||||
for local_record_uri in local_record_uris.into_iter() {
|
||||
bluesky
|
||||
.delete_record(&local_record_uri)
|
||||
.await
|
||||
.unwrap_or_else(|e| {
|
||||
panic!("Cannot delete Tweet ID ({}): {}", t.tweet_id, e)
|
||||
panic!("Cannot delete record ID ({}): {}", &t.record_uri, e)
|
||||
});
|
||||
}
|
||||
delete_state(&conn, t.toot_id).unwrap_or_else(|e| {
|
||||
@@ -82,60 +88,116 @@ pub async fn run(config: &Config) {
|
||||
}
|
||||
|
||||
// form tweet_content and strip everything useless in it
|
||||
let Ok(mut tweet_content) = strip_everything(&toot.content, &toot.tags) else {
|
||||
let toot_tags: Vec<megalodon::entities::status::Tag> =
|
||||
match &config.oolatoocs.remove_hashtags {
|
||||
true => toot.tags.clone(),
|
||||
false => vec![],
|
||||
};
|
||||
let Ok(mut tweet_content) = strip_everything(&toot.content, &toot_tags) else {
|
||||
continue; // skip in case we can’t strip something
|
||||
};
|
||||
|
||||
// threads if necessary
|
||||
let mut reply_to = toot.in_reply_to_id.and_then(|t| {
|
||||
let mut record_reply_to = toot.in_reply_to_id.and_then(|t| {
|
||||
read_state(&conn, Some(t.parse::<u64>().unwrap()))
|
||||
.ok()
|
||||
.flatten()
|
||||
.map(|s| s.tweet_id)
|
||||
.map(|s| BskyReply {
|
||||
record_uri: s.record_uri.to_owned(),
|
||||
root_record_uri: s.root_record_uri.to_owned(),
|
||||
})
|
||||
});
|
||||
|
||||
// if the toot is too long, we cut it in half here
|
||||
if let Some((first_half, second_half)) = generate_multi_tweets(&tweet_content) {
|
||||
tweet_content = second_half;
|
||||
// post the first half
|
||||
let reply_id = post_tweet(&config.twitter, first_half, vec![], reply_to, None)
|
||||
.await
|
||||
.unwrap_or_else(|e| panic!("Cannot post the first half of {}: {}", &toot.id, e));
|
||||
let record = build_post_record(
|
||||
&config.bluesky,
|
||||
&first_half,
|
||||
&toot.language,
|
||||
None,
|
||||
&record_reply_to,
|
||||
)
|
||||
.await
|
||||
.unwrap_or_else(|e| panic!("Cannot create valid record for {}: {}", &toot.id, e));
|
||||
let record_reply_id = bluesky.create_record(record).await.unwrap_or_else(|e| {
|
||||
panic!(
|
||||
"Cannot post the first half of {} for Bluesky: {}",
|
||||
&toot.id, e
|
||||
)
|
||||
});
|
||||
// write it to db
|
||||
write_state(
|
||||
&conn,
|
||||
TweetToToot {
|
||||
tweet_id: reply_id,
|
||||
TootRecord {
|
||||
toot_id: toot.id.parse::<u64>().unwrap(),
|
||||
record_uri: record_reply_id.data.uri.to_owned(),
|
||||
root_record_uri: record_reply_to
|
||||
.as_ref()
|
||||
.map_or(record_reply_id.data.uri.to_owned(), |v| {
|
||||
v.root_record_uri.to_owned()
|
||||
}),
|
||||
datetime: None,
|
||||
},
|
||||
)
|
||||
.unwrap_or_else(|e| {
|
||||
panic!("Cannot store Toot/Tweet ({}/{}): {}", &toot.id, reply_id, e)
|
||||
panic!(
|
||||
"Cannot store Toot/Tweet/Record ({}/{}): {}",
|
||||
&toot.id, &record_reply_id.data.uri, e
|
||||
)
|
||||
});
|
||||
|
||||
record_reply_to = Some(BskyReply {
|
||||
record_uri: record_reply_id.data.uri.to_owned(),
|
||||
root_record_uri: record_reply_to
|
||||
.as_ref()
|
||||
.map_or(record_reply_id.data.uri.clone(), |v| {
|
||||
v.root_record_uri.clone()
|
||||
}),
|
||||
});
|
||||
reply_to = Some(reply_id);
|
||||
};
|
||||
|
||||
// treats poll if any
|
||||
let in_poll = toot.poll.map(|p| transform_poll(&p));
|
||||
|
||||
// treats medias
|
||||
let medias = generate_media_ids(&config.twitter, &toot.media_attachments).await;
|
||||
let mut record_embed = generate_media_records(&bluesky, &toot.media_attachments).await;
|
||||
|
||||
// treats embed cards if any
|
||||
if let Some(card) = &toot.card {
|
||||
if record_embed.is_none() {
|
||||
record_embed = generate_embed_records(&bluesky, card).await;
|
||||
}
|
||||
}
|
||||
|
||||
// posts corresponding tweet
|
||||
let tweet_id = post_tweet(&config.twitter, tweet_content, medias, reply_to, in_poll)
|
||||
let record = build_post_record(
|
||||
&config.bluesky,
|
||||
&tweet_content,
|
||||
&toot.language,
|
||||
record_embed,
|
||||
&record_reply_to,
|
||||
)
|
||||
.await
|
||||
.unwrap_or_else(|e| panic!("Cannot build record for {}: {}", &toot.id, e));
|
||||
|
||||
let created_record = bluesky
|
||||
.create_record(record)
|
||||
.await
|
||||
.unwrap_or_else(|e| panic!("Cannot Tweet {}: {}", toot.id, e));
|
||||
.unwrap_or_else(|e| panic!("Cannot put record {}: {}", &toot.id, e));
|
||||
|
||||
// writes the current state of the tweet
|
||||
write_state(
|
||||
&conn,
|
||||
TweetToToot {
|
||||
tweet_id,
|
||||
TootRecord {
|
||||
toot_id: toot.id.parse::<u64>().unwrap(),
|
||||
record_uri: created_record.data.uri.clone(),
|
||||
root_record_uri: record_reply_to
|
||||
.as_ref()
|
||||
.map_or(created_record.data.uri.clone(), |v| {
|
||||
v.root_record_uri.clone()
|
||||
}),
|
||||
datetime: None,
|
||||
},
|
||||
)
|
||||
.unwrap_or_else(|e| panic!("Cannot store Toot/Tweet ({}/{}): {}", &toot.id, tweet_id, e));
|
||||
.unwrap_or_else(|e| panic!("Cannot store Toot/Tweet ({}): {}", &toot.id, e));
|
||||
}
|
||||
}
|
||||
|
@@ -12,12 +12,12 @@ use std::error::Error;
|
||||
use std::io::stdin;
|
||||
|
||||
/// Get Mastodon Object instance
|
||||
pub fn get_mastodon_instance(config: &MastodonConfig) -> Mastodon {
|
||||
Mastodon::new(
|
||||
pub fn get_mastodon_instance(config: &MastodonConfig) -> Result<Mastodon, Box<dyn Error>> {
|
||||
Ok(Mastodon::new(
|
||||
config.base.to_string(),
|
||||
Some(config.token.to_string()),
|
||||
None,
|
||||
)
|
||||
)?)
|
||||
}
|
||||
|
||||
/// Get the edited_at field from the specified toot
|
||||
@@ -71,7 +71,8 @@ pub async fn get_mastodon_timeline_since(
|
||||
/// Most of this function is a direct copy/paste of the official `elefren` crate
|
||||
#[tokio::main]
|
||||
pub async fn register(host: &str) {
|
||||
let mastodon = generator(megalodon::SNS::Mastodon, host.to_string(), None, None);
|
||||
let mastodon = generator(megalodon::SNS::Mastodon, host.to_string(), None, None)
|
||||
.expect("Cannot build Mastodon generator object");
|
||||
|
||||
let options = AppInputOptions {
|
||||
redirect_uris: None,
|
||||
|
236
src/state.rs
236
src/state.rs
@@ -5,9 +5,12 @@ use std::error::Error;
|
||||
|
||||
/// Struct for each query line
|
||||
#[derive(Debug)]
|
||||
pub struct TweetToToot {
|
||||
pub tweet_id: u64,
|
||||
pub struct TootRecord {
|
||||
// Mastodon part
|
||||
pub toot_id: u64,
|
||||
// Bluesky part
|
||||
pub record_uri: String,
|
||||
pub root_record_uri: String,
|
||||
pub datetime: Option<DateTime<Utc>>,
|
||||
}
|
||||
|
||||
@@ -15,51 +18,50 @@ pub struct TweetToToot {
|
||||
pub fn delete_state(conn: &Connection, toot_id: u64) -> Result<(), Box<dyn Error>> {
|
||||
debug!("Deleting Toot ID {}", toot_id);
|
||||
conn.execute(
|
||||
&format!("DELETE FROM tweet_to_toot WHERE toot_id = {}", toot_id),
|
||||
&format!("DELETE FROM toot_record WHERE toot_id = {}", toot_id),
|
||||
[],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Retrieves all tweets associated to a toot in the form of a vector
|
||||
pub fn read_all_tweet_state(conn: &Connection, toot_id: u64) -> Result<Vec<u64>, Box<dyn Error>> {
|
||||
pub fn read_all_state(conn: &Connection, toot_id: u64) -> Result<Vec<String>, Box<dyn Error>> {
|
||||
let query = format!(
|
||||
"SELECT tweet_id FROM tweet_to_toot WHERE toot_id = {};",
|
||||
"SELECT record_uri FROM toot_record WHERE toot_id = {};",
|
||||
toot_id
|
||||
);
|
||||
let mut stmt = conn.prepare(&query)?;
|
||||
let mut rows = stmt.query([])?;
|
||||
|
||||
let mut v = Vec::new();
|
||||
let mut record_v: Vec<String> = Vec::new();
|
||||
while let Some(row) = rows.next()? {
|
||||
v.push(row.get(0)?);
|
||||
record_v.push(row.get(0)?);
|
||||
}
|
||||
|
||||
Ok(v)
|
||||
Ok(record_v)
|
||||
}
|
||||
|
||||
/// if None is passed, read the last tweet from DB
|
||||
/// if a tweet_id is passed, read this particular tweet from DB
|
||||
pub fn read_state(
|
||||
conn: &Connection,
|
||||
s: Option<u64>,
|
||||
) -> Result<Option<TweetToToot>, Box<dyn Error>> {
|
||||
pub fn read_state(conn: &Connection, s: Option<u64>) -> Result<Option<TootRecord>, Box<dyn Error>> {
|
||||
debug!("Reading toot_id {:?}", s);
|
||||
let begin_query = "SELECT *, UNIXEPOCH(datetime) AS unix_datetime FROM toot_record";
|
||||
let query: String = match s {
|
||||
Some(i) => format!(
|
||||
"SELECT tweet_id, toot_id, UNIXEPOCH(datetime) AS datetime FROM tweet_to_toot WHERE toot_id = {i} ORDER BY tweet_id DESC LIMIT 1"
|
||||
),
|
||||
None => "SELECT tweet_id, toot_id, UNIXEPOCH(datetime) AS datetime FROM tweet_to_toot ORDER BY toot_id DESC LIMIT 1".to_string(),
|
||||
Some(i) => format!("{begin_query} WHERE toot_id = {i} ORDER BY record_uri DESC LIMIT 1"),
|
||||
None => format!("{begin_query} ORDER BY toot_id DESC LIMIT 1"),
|
||||
};
|
||||
|
||||
let mut stmt = conn.prepare(&query)?;
|
||||
|
||||
let t = stmt
|
||||
.query_row([], |row| {
|
||||
Ok(TweetToToot {
|
||||
tweet_id: row.get("tweet_id")?,
|
||||
Ok(TootRecord {
|
||||
toot_id: row.get("toot_id")?,
|
||||
datetime: Some(DateTime::from_timestamp(row.get("datetime").unwrap(), 0).unwrap()),
|
||||
record_uri: row.get("record_uri")?,
|
||||
root_record_uri: row.get("root_record_uri")?,
|
||||
datetime: Some(
|
||||
DateTime::from_timestamp(row.get("unix_datetime").unwrap(), 0).unwrap(),
|
||||
),
|
||||
})
|
||||
})
|
||||
.optional()?;
|
||||
@@ -68,11 +70,11 @@ pub fn read_state(
|
||||
}
|
||||
|
||||
/// Writes last treated tweet id and toot id to the db
|
||||
pub fn write_state(conn: &Connection, t: TweetToToot) -> Result<(), Box<dyn Error>> {
|
||||
pub fn write_state(conn: &Connection, t: TootRecord) -> Result<(), Box<dyn Error>> {
|
||||
debug!("Write struct {:?}", t);
|
||||
conn.execute(
|
||||
"INSERT INTO tweet_to_toot (tweet_id, toot_id) VALUES (?1, ?2)",
|
||||
params![t.tweet_id, t.toot_id],
|
||||
"INSERT INTO toot_record (toot_id, record_uri, root_record_uri) VALUES (?1, ?2, ?3)",
|
||||
params![t.toot_id, t.record_uri, t.root_record_uri],
|
||||
)?;
|
||||
|
||||
Ok(())
|
||||
@@ -80,16 +82,14 @@ pub fn write_state(conn: &Connection, t: TweetToToot) -> Result<(), Box<dyn Erro
|
||||
|
||||
/// Initiates the DB from path
|
||||
pub fn init_db(d: &str) -> Result<(), Box<dyn Error>> {
|
||||
debug!(
|
||||
"{}",
|
||||
format!("Initializing DB for {}", env!("CARGO_PKG_NAME"))
|
||||
);
|
||||
debug!("Initializing DB for {}", env!("CARGO_PKG_NAME"));
|
||||
let conn = Connection::open(d)?;
|
||||
|
||||
conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS tweet_to_toot (
|
||||
tweet_id INTEGER PRIMARY KEY,
|
||||
"CREATE TABLE IF NOT EXISTS toot_record (
|
||||
toot_id INTEGER,
|
||||
record_uri VARCHAR(128) PRIMARY KEY,
|
||||
root_record_uri VARCHAR(128) DEFAULT '',
|
||||
datetime INTEGER DEFAULT CURRENT_TIMESTAMP
|
||||
)",
|
||||
[],
|
||||
@@ -98,19 +98,19 @@ pub fn init_db(d: &str) -> Result<(), Box<dyn Error>> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Migrate DB from 1.5.x to 1.6.x
|
||||
/// Migrate DB from 3+ to 4+
|
||||
pub fn migrate_db(d: &str) -> Result<(), Box<dyn Error>> {
|
||||
debug!("Migration DB for Oolatoocs");
|
||||
|
||||
let conn = Connection::open(d)?;
|
||||
|
||||
let res = conn.execute("SELECT datetime from tweet_to_toot;", []);
|
||||
let res = conn.execute("SELECT datetime FROM toot_record;", []);
|
||||
|
||||
// If the column can be selected then, it’s OK
|
||||
// if not, see if the error is a missing column and add it
|
||||
match res {
|
||||
Err(e) => match e.to_string().as_str() {
|
||||
"no such column: datetime" => migrate_db_alter_table(&conn), //column does not exist
|
||||
"no such table: toot_record" => migrate_db_alter_table(&conn), // table does not exist
|
||||
"Execute returned results - did you mean to call query?" => Ok(()), // return results,
|
||||
// column does
|
||||
// exist
|
||||
@@ -124,9 +124,10 @@ pub fn migrate_db(d: &str) -> Result<(), Box<dyn Error>> {
|
||||
fn migrate_db_alter_table(c: &Connection) -> Result<(), Box<dyn Error>> {
|
||||
// create the new table
|
||||
c.execute(
|
||||
"CREATE TABLE IF NOT EXISTS tweet_to_toot_new (
|
||||
tweet_id INTEGER PRIMARY KEY,
|
||||
"CREATE TABLE IF NOT EXISTS toot_record (
|
||||
toot_id INTEGER,
|
||||
record_uri VARCHAR(128) PRIMARY KEY,
|
||||
root_record_uri VARCHAR(128) DEFAULT '',
|
||||
datetime INTEGER DEFAULT CURRENT_TIMESTAMP
|
||||
)",
|
||||
[],
|
||||
@@ -134,16 +135,14 @@ fn migrate_db_alter_table(c: &Connection) -> Result<(), Box<dyn Error>> {
|
||||
|
||||
// copy data from the old table
|
||||
c.execute(
|
||||
"INSERT INTO tweet_to_toot_new (tweet_id, toot_id)
|
||||
SELECT tweet_id, toot_id FROM tweet_to_toot;",
|
||||
"INSERT INTO toot_record (toot_id, record_uri, root_record_uri, datetime)
|
||||
SELECT toot_id, record_uri, root_record_uri, datetime FROM toot_tweet_record
|
||||
WHERE record_uri != '';",
|
||||
[],
|
||||
)?;
|
||||
|
||||
// drop the old table
|
||||
c.execute("DROP TABLE tweet_to_toot;", [])?;
|
||||
|
||||
// rename the new table
|
||||
c.execute("ALTER TABLE tweet_to_toot_new RENAME TO tweet_to_toot;", [])?;
|
||||
c.execute("DROP TABLE IF EXISTS toot_tweet_record;", [])?;
|
||||
|
||||
Ok(())
|
||||
}
|
||||
@@ -164,7 +163,7 @@ mod tests {
|
||||
|
||||
// open said file
|
||||
let conn = Connection::open(d).unwrap();
|
||||
conn.execute("SELECT * from tweet_to_toot;", []).unwrap();
|
||||
conn.execute("SELECT * from toot_record;", []).unwrap();
|
||||
|
||||
remove_file(d).unwrap();
|
||||
}
|
||||
@@ -179,9 +178,9 @@ mod tests {
|
||||
let conn = Connection::open(d).unwrap();
|
||||
|
||||
conn.execute(
|
||||
"INSERT INTO tweet_to_toot (tweet_id, toot_id)
|
||||
"INSERT INTO toot_record (record_uri, toot_id)
|
||||
VALUES
|
||||
(100, 1001);",
|
||||
('a', 1001);",
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
@@ -199,34 +198,35 @@ mod tests {
|
||||
|
||||
let conn = Connection::open(d).unwrap();
|
||||
|
||||
let t_in = TweetToToot {
|
||||
tweet_id: 123456789,
|
||||
let t_in = TootRecord {
|
||||
toot_id: 987654321,
|
||||
record_uri: "a".to_string(),
|
||||
root_record_uri: "c".to_string(),
|
||||
datetime: None,
|
||||
};
|
||||
|
||||
write_state(&conn, t_in).unwrap();
|
||||
|
||||
let mut stmt = conn
|
||||
.prepare(
|
||||
"SELECT tweet_id, toot_id, UNIXEPOCH(datetime) AS datetime FROM tweet_to_toot;",
|
||||
)
|
||||
.prepare("SELECT *, UNIXEPOCH(datetime) AS unix_datetime FROM toot_record;")
|
||||
.unwrap();
|
||||
|
||||
let t_out = stmt
|
||||
.query_row([], |row| {
|
||||
Ok(TweetToToot {
|
||||
tweet_id: row.get("tweet_id").unwrap(),
|
||||
Ok(TootRecord {
|
||||
toot_id: row.get("toot_id").unwrap(),
|
||||
record_uri: row.get("record_uri").unwrap(),
|
||||
root_record_uri: row.get("root_record_uri").unwrap(),
|
||||
datetime: Some(
|
||||
DateTime::from_timestamp(row.get("datetime").unwrap(), 0).unwrap(),
|
||||
DateTime::from_timestamp(row.get("unix_datetime").unwrap(), 0).unwrap(),
|
||||
),
|
||||
})
|
||||
})
|
||||
.unwrap();
|
||||
|
||||
assert_eq!(t_out.tweet_id, 123456789);
|
||||
assert_eq!(t_out.toot_id, 987654321);
|
||||
assert_eq!(t_out.record_uri, "a".to_string());
|
||||
assert_eq!(t_out.root_record_uri, "c".to_string());
|
||||
|
||||
remove_file(d).unwrap();
|
||||
}
|
||||
@@ -240,10 +240,10 @@ mod tests {
|
||||
let conn = Connection::open(d).unwrap();
|
||||
|
||||
conn.execute(
|
||||
"INSERT INTO tweet_to_toot (tweet_id, toot_id)
|
||||
"INSERT INTO toot_record (toot_id, record_uri)
|
||||
VALUES
|
||||
(101, 1001),
|
||||
(102, 1002);",
|
||||
(101, 'abc'),
|
||||
(102, 'def');",
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
@@ -252,8 +252,8 @@ mod tests {
|
||||
|
||||
remove_file(d).unwrap();
|
||||
|
||||
assert_eq!(t_out.tweet_id, 102);
|
||||
assert_eq!(t_out.toot_id, 1002);
|
||||
assert_eq!(t_out.toot_id, 102);
|
||||
assert_eq!(t_out.record_uri, "def".to_string());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -280,9 +280,9 @@ mod tests {
|
||||
let conn = Connection::open(d).unwrap();
|
||||
|
||||
conn.execute(
|
||||
"INSERT INTO tweet_to_toot (tweet_id, toot_id)
|
||||
"INSERT INTO toot_record (toot_id, record_uri)
|
||||
VALUES
|
||||
(100, 1000);",
|
||||
(100, 'abc');",
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
@@ -303,19 +303,19 @@ mod tests {
|
||||
let conn = Connection::open(d).unwrap();
|
||||
|
||||
conn.execute(
|
||||
"INSERT INTO tweet_to_toot (tweet_id, toot_id)
|
||||
"INSERT INTO toot_record (toot_id, record_uri)
|
||||
VALUES
|
||||
(100, 1000);",
|
||||
(100, 'abc');",
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let t_out = read_state(&conn, Some(1000)).unwrap().unwrap();
|
||||
let t_out = read_state(&conn, Some(100)).unwrap().unwrap();
|
||||
|
||||
remove_file(d).unwrap();
|
||||
|
||||
assert_eq!(t_out.tweet_id, 100);
|
||||
assert_eq!(t_out.toot_id, 1000);
|
||||
assert_eq!(t_out.toot_id, 100);
|
||||
assert_eq!(t_out.record_uri, "abc".to_string());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -327,8 +327,10 @@ mod tests {
|
||||
let conn = Connection::open(d).unwrap();
|
||||
|
||||
conn.execute(
|
||||
"INSERT INTO tweet_to_toot(tweet_id, toot_id)
|
||||
VALUES (100, 1000), (101, 1000);",
|
||||
"INSERT INTO toot_record (toot_id, record_uri)
|
||||
VALUES
|
||||
(1000, 'abc'),
|
||||
(1000, 'def');",
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
@@ -337,49 +339,8 @@ mod tests {
|
||||
|
||||
remove_file(d).unwrap();
|
||||
|
||||
assert_eq!(t_out.tweet_id, 101);
|
||||
assert_eq!(t_out.toot_id, 1000);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_migrate_db_alter_table() {
|
||||
let d = "/tmp/test_migrate_db_alter_table.sqlite";
|
||||
|
||||
let conn = Connection::open(d).unwrap();
|
||||
|
||||
init_db(d).unwrap();
|
||||
|
||||
write_state(
|
||||
&conn,
|
||||
TweetToToot {
|
||||
tweet_id: 0,
|
||||
toot_id: 0,
|
||||
datetime: None,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
write_state(
|
||||
&conn,
|
||||
TweetToToot {
|
||||
tweet_id: 1,
|
||||
toot_id: 1,
|
||||
datetime: None,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
migrate_db_alter_table(&conn).unwrap();
|
||||
|
||||
let mut stmt = conn.prepare("PRAGMA table_info(tweet_to_toot);").unwrap();
|
||||
let mut t = stmt.query([]).unwrap();
|
||||
|
||||
while let Some(row) = t.next().unwrap() {
|
||||
if row.get::<usize, u8>(0).unwrap() == 2 {
|
||||
assert_eq!(row.get::<usize, String>(1).unwrap(), "datetime".to_string());
|
||||
}
|
||||
}
|
||||
|
||||
remove_file(d).unwrap();
|
||||
assert_eq!(t_out.record_uri, "def".to_string());
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -389,22 +350,27 @@ mod tests {
|
||||
|
||||
let conn = Connection::open(d).unwrap();
|
||||
conn.execute(
|
||||
"CREATE TABLE IF NOT EXISTS tweet_to_toot (
|
||||
tweet_id INTEGER,
|
||||
toot_id INTEGER PRIMARY KEY
|
||||
"CREATE TABLE IF NOT EXISTS toot_tweet_record (
|
||||
toot_id INTEGER,
|
||||
tweet_id INTEGER PRIMARY KEY,
|
||||
record_uri VARCHAR(128) DEFAULT '',
|
||||
root_record_uri VARCHAR(128) DEFAULT '',
|
||||
datetime INTEGER DEFAULT CURRENT_TIMESTAMP
|
||||
)",
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
conn.execute("INSERT INTO tweet_to_toot VALUES (0, 0), (1, 1);", [])
|
||||
.unwrap();
|
||||
conn.execute(
|
||||
"INSERT INTO toot_tweet_record (tweet_id, toot_id, record_uri) VALUES (0, 0, ''), (1, 1, 'abc');",
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
migrate_db(d).unwrap();
|
||||
|
||||
let last_state = read_state(&conn, None).unwrap().unwrap();
|
||||
|
||||
assert_eq!(last_state.tweet_id, 1);
|
||||
assert_eq!(last_state.toot_id, 1);
|
||||
|
||||
migrate_db(d).unwrap(); // shouldn’t do anything
|
||||
@@ -421,7 +387,7 @@ mod tests {
|
||||
let conn = Connection::open(d).unwrap();
|
||||
|
||||
conn.execute(
|
||||
"INSERT INTO tweet_to_toot(tweet_id, toot_id) VALUES (0, 0);",
|
||||
"INSERT INTO toot_record(toot_id, record_uri) VALUES (0, 'abc');",
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
@@ -429,23 +395,24 @@ mod tests {
|
||||
delete_state(&conn, 0).unwrap();
|
||||
|
||||
let mut stmt = conn
|
||||
.prepare(
|
||||
"SELECT tweet_id, toot_id, UNIXEPOCH(datetime) AS datetime FROM tweet_to_toot;",
|
||||
)
|
||||
.prepare("SELECT *, UNIXEPOCH(datetime) AS unix_datetime FROM toot_record;")
|
||||
.unwrap();
|
||||
|
||||
let t_out = stmt.query_row([], |row| {
|
||||
Ok(TweetToToot {
|
||||
tweet_id: row.get("tweet_id").unwrap(),
|
||||
Ok(TootRecord {
|
||||
toot_id: row.get("toot_id").unwrap(),
|
||||
datetime: Some(DateTime::from_timestamp(row.get("datetime").unwrap(), 0).unwrap()),
|
||||
record_uri: row.get("record_uri").unwrap(),
|
||||
root_record_uri: row.get("root_record_uri").unwrap(),
|
||||
datetime: Some(
|
||||
DateTime::from_timestamp(row.get("unix_datetime").unwrap(), 0).unwrap(),
|
||||
),
|
||||
})
|
||||
});
|
||||
|
||||
assert!(t_out.is_err_and(|x| x == rusqlite::Error::QueryReturnedNoRows));
|
||||
|
||||
conn.execute(
|
||||
"INSERT INTO tweet_to_toot(tweet_id, toot_id) VALUES(102,42), (103,42);",
|
||||
"INSERT INTO toot_record(toot_id, record_uri) VALUES(42, 'abc'), (42, 'def');",
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
@@ -453,16 +420,17 @@ mod tests {
|
||||
delete_state(&conn, 42).unwrap();
|
||||
|
||||
let mut stmt = conn
|
||||
.prepare(
|
||||
"SELECT tweet_id, toot_id, UNIXEPOCH(datetime) AS datetime FROM tweet_to_toot;",
|
||||
)
|
||||
.prepare("SELECT *, UNIXEPOCH(datetime) AS unix_datetime FROM toot_record;")
|
||||
.unwrap();
|
||||
|
||||
let t_out = stmt.query_row([], |row| {
|
||||
Ok(TweetToToot {
|
||||
tweet_id: row.get("tweet_id").unwrap(),
|
||||
Ok(TootRecord {
|
||||
toot_id: row.get("toot_id").unwrap(),
|
||||
datetime: Some(DateTime::from_timestamp(row.get("datetime").unwrap(), 0).unwrap()),
|
||||
record_uri: row.get("record_uri").unwrap(),
|
||||
root_record_uri: row.get("root_record_uri").unwrap(),
|
||||
datetime: Some(
|
||||
DateTime::from_timestamp(row.get("unix_datetime").unwrap(), 0).unwrap(),
|
||||
),
|
||||
})
|
||||
});
|
||||
|
||||
@@ -472,24 +440,24 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_read_all_tweet_state() {
|
||||
let d = "/tmp/read_all_tweet_state.sqlite";
|
||||
fn test_read_all_state() {
|
||||
let d = "/tmp/read_all_state.sqlite";
|
||||
|
||||
init_db(d).unwrap();
|
||||
|
||||
let conn = Connection::open(d).unwrap();
|
||||
|
||||
conn.execute(
|
||||
"INSERT INTO tweet_to_toot(tweet_id, toot_id) VALUES (102, 42), (103, 42), (105, 43);",
|
||||
"INSERT INTO toot_record (toot_id, record_uri) VALUES (42, 'abc'), (42, 'def'), (43, 'ghi');",
|
||||
[],
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let v1 = read_all_tweet_state(&conn, 43).unwrap();
|
||||
let v2 = read_all_tweet_state(&conn, 42).unwrap();
|
||||
let record_v1 = read_all_state(&conn, 43).unwrap();
|
||||
let record_v2 = read_all_state(&conn, 42).unwrap();
|
||||
|
||||
assert_eq!(v1, vec![105]);
|
||||
assert_eq!(v2, vec![102, 103]);
|
||||
assert_eq!(record_v1, vec!["ghi".to_string()]);
|
||||
assert_eq!(record_v2, vec!["abc".to_string(), "def".to_string()]);
|
||||
|
||||
remove_file(d).unwrap();
|
||||
}
|
||||
|
556
src/twitter.rs
556
src/twitter.rs
@@ -1,556 +0,0 @@
|
||||
use crate::config::TwitterConfig;
|
||||
use crate::error::OolatoocsError;
|
||||
use chrono::Utc;
|
||||
use futures::{stream, StreamExt};
|
||||
use log::{debug, error, warn};
|
||||
use megalodon::entities::{
|
||||
attachment::{Attachment, AttachmentType},
|
||||
Poll,
|
||||
};
|
||||
use oauth1_request::Token;
|
||||
use reqwest::{
|
||||
multipart::{Form, Part},
|
||||
Body, Client,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{error::Error, ops::Not};
|
||||
use tokio::time::{sleep, Duration};
|
||||
|
||||
const TWITTER_API_TWEET_URL: &str = "https://api.twitter.com/2/tweets";
|
||||
const TWITTER_UPLOAD_MEDIA_URL: &str = "https://upload.twitter.com/1.1/media/upload.json";
|
||||
const TWITTER_METADATA_MEDIA_URL: &str =
|
||||
"https://upload.twitter.com/1.1/media/metadata/create.json";
|
||||
|
||||
// I don’t know, don’t ask me
|
||||
#[derive(oauth1_request::Request)]
|
||||
struct EmptyRequest {}
|
||||
|
||||
#[derive(Serialize, Debug)]
|
||||
struct Tweet {
|
||||
text: String,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
media: Option<TweetMediasIds>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
reply: Option<TweetReply>,
|
||||
#[serde(skip_serializing_if = "Option::is_none")]
|
||||
poll: Option<TweetPoll>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug)]
|
||||
struct TweetMediasIds {
|
||||
media_ids: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug)]
|
||||
struct TweetReply {
|
||||
in_reply_to_tweet_id: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug)]
|
||||
pub struct TweetPoll {
|
||||
pub options: Vec<String>,
|
||||
pub duration_minutes: u16,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
struct TweetResponse {
|
||||
data: TweetResponseData,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
struct TweetResponseData {
|
||||
id: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
struct UploadMediaResponse {
|
||||
media_id: u64,
|
||||
processing_info: Option<UploadMediaResponseProcessingInfo>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
struct UploadMediaResponseProcessingInfo {
|
||||
state: UploadMediaResponseProcessingInfoState,
|
||||
check_after_secs: Option<u64>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Debug)]
|
||||
enum UploadMediaResponseProcessingInfoState {
|
||||
#[serde(rename = "failed")]
|
||||
Failed,
|
||||
#[serde(rename = "succeeded")]
|
||||
Succeeded,
|
||||
#[serde(rename = "pending")]
|
||||
Pending,
|
||||
#[serde(rename = "in_progress")]
|
||||
InProgress,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug)]
|
||||
struct MediaMetadata {
|
||||
media_id: u64,
|
||||
alt_text: MediaMetadataAltText,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug)]
|
||||
struct MediaMetadataAltText {
|
||||
text: String,
|
||||
}
|
||||
|
||||
#[derive(Serialize, Debug, oauth1_request::Request)]
|
||||
struct UploadMediaCommand {
|
||||
command: String,
|
||||
media_id: String,
|
||||
}
|
||||
|
||||
/// This function returns the OAuth1 Token object from TwitterConfig
|
||||
fn get_token(config: &TwitterConfig) -> Token {
|
||||
oauth1_request::Token::from_parts(
|
||||
config.consumer_key.to_string(),
|
||||
config.consumer_secret.to_string(),
|
||||
config.oauth_token.to_string(),
|
||||
config.oauth_token_secret.to_string(),
|
||||
)
|
||||
}
|
||||
|
||||
/// This functions deletes a tweet, given its id
|
||||
pub async fn delete_tweet(config: &TwitterConfig, id: u64) -> Result<(), Box<dyn Error>> {
|
||||
debug!("Deleting Tweet {}", id);
|
||||
let empty_request = EmptyRequest {}; // Why? Because fuck you, that’s why!
|
||||
let token = get_token(config);
|
||||
let delete_uri = format!("{}/{}", TWITTER_API_TWEET_URL, id);
|
||||
|
||||
let client = Client::new();
|
||||
let res = client
|
||||
.delete(&delete_uri)
|
||||
.header(
|
||||
"Authorization",
|
||||
oauth1_request::delete(
|
||||
&delete_uri,
|
||||
&empty_request,
|
||||
&token,
|
||||
oauth1_request::HMAC_SHA1,
|
||||
),
|
||||
)
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
if !res.status().is_success() {
|
||||
return Err(OolatoocsError::new(&format!("Cannot delete Tweet {}", id)).into());
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// This function generates a media_ids vec to be used by Twitter
|
||||
pub async fn generate_media_ids(config: &TwitterConfig, media_attach: &[Attachment]) -> Vec<u64> {
|
||||
let mut medias: Vec<u64> = vec![];
|
||||
|
||||
let media_attachments = media_attach.to_owned();
|
||||
let mut stream = stream::iter(media_attachments)
|
||||
.map(|media| {
|
||||
let twitter_config = config.clone();
|
||||
tokio::task::spawn(async move {
|
||||
match media.r#type {
|
||||
AttachmentType::Image => {
|
||||
upload_simple_media(&twitter_config, &media.url, &media.description).await
|
||||
}
|
||||
AttachmentType::Gifv => {
|
||||
upload_chunk_media(&twitter_config, &media.url, "tweet_gif").await
|
||||
}
|
||||
AttachmentType::Video => {
|
||||
upload_chunk_media(&twitter_config, &media.url, "tweet_video").await
|
||||
}
|
||||
_ => Err::<u64, Box<dyn Error + Send + Sync>>(
|
||||
OolatoocsError::new(&format!(
|
||||
"Cannot treat this type of media: {}",
|
||||
&media.url
|
||||
))
|
||||
.into(),
|
||||
),
|
||||
}
|
||||
})
|
||||
})
|
||||
.buffered(4);
|
||||
|
||||
while let Some(result) = stream.next().await {
|
||||
match result {
|
||||
Ok(Ok(v)) => medias.push(v),
|
||||
Ok(Err(e)) => warn!("Cannot treat media: {}", e),
|
||||
Err(e) => error!("Something went wrong when joining the main thread: {}", e),
|
||||
}
|
||||
}
|
||||
|
||||
medias
|
||||
}
|
||||
|
||||
/// This function uploads simple images from Mastodon to Twitter and returns the media id from Twitter
|
||||
async fn upload_simple_media(
|
||||
config: &TwitterConfig,
|
||||
u: &str,
|
||||
d: &Option<String>,
|
||||
) -> Result<u64, Box<dyn Error + Send + Sync>> {
|
||||
// initiate request parameters
|
||||
let empty_request = EmptyRequest {}; // Why? Because fuck you, that’s why!
|
||||
let token = get_token(config);
|
||||
|
||||
// retrieve the length and bytes stream from the given URL
|
||||
let dl = reqwest::get(u).await?;
|
||||
let content_length = dl
|
||||
.content_length()
|
||||
.ok_or(format!("Cannot get content length for {}", u))?;
|
||||
let stream = dl.bytes_stream();
|
||||
|
||||
debug!("Ref download URL: {}", u);
|
||||
|
||||
// upload the media
|
||||
let client = Client::new();
|
||||
let res = client
|
||||
.post(TWITTER_UPLOAD_MEDIA_URL)
|
||||
.header(
|
||||
"Authorization",
|
||||
oauth1_request::post(
|
||||
TWITTER_UPLOAD_MEDIA_URL,
|
||||
&empty_request,
|
||||
&token,
|
||||
oauth1_request::HMAC_SHA1,
|
||||
),
|
||||
)
|
||||
.multipart(Form::new().part(
|
||||
"media",
|
||||
Part::stream_with_length(Body::wrap_stream(stream), content_length),
|
||||
))
|
||||
.send()
|
||||
.await?
|
||||
.json::<UploadMediaResponse>()
|
||||
.await?;
|
||||
|
||||
debug!("Media ID: {}", res.media_id);
|
||||
|
||||
// update the metadata
|
||||
if let Some(metadata) = d {
|
||||
debug!("Metadata found! Processing…");
|
||||
metadata_create(config, res.media_id, metadata).await?;
|
||||
}
|
||||
|
||||
Ok(res.media_id)
|
||||
}
|
||||
|
||||
/// This function updates the metadata given the current media_id and token
|
||||
async fn metadata_create(
|
||||
config: &TwitterConfig,
|
||||
id: u64,
|
||||
m: &str,
|
||||
) -> Result<(), Box<dyn Error + Send + Sync>> {
|
||||
let token = get_token(config);
|
||||
let empty_request = EmptyRequest {};
|
||||
|
||||
let media_metadata = MediaMetadata {
|
||||
media_id: id,
|
||||
alt_text: MediaMetadataAltText {
|
||||
text: m.to_string(),
|
||||
},
|
||||
};
|
||||
|
||||
debug!("Metadata to process: {}", m);
|
||||
|
||||
let client = Client::new();
|
||||
let metadata = client
|
||||
.post(TWITTER_METADATA_MEDIA_URL)
|
||||
.header(
|
||||
"Authorization",
|
||||
oauth1_request::post(
|
||||
TWITTER_METADATA_MEDIA_URL,
|
||||
&empty_request,
|
||||
&token,
|
||||
oauth1_request::HMAC_SHA1,
|
||||
),
|
||||
)
|
||||
.json(&media_metadata)
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
debug!("Metadata processed with return code: {}", metadata.status());
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// This posts video/gif to Twitter and returns the media id from Twitter
|
||||
async fn upload_chunk_media(
|
||||
config: &TwitterConfig,
|
||||
u: &str,
|
||||
t: &str,
|
||||
) -> Result<u64, Box<dyn Error + Send + Sync>> {
|
||||
let empty_request = EmptyRequest {};
|
||||
let token = get_token(config);
|
||||
|
||||
// retrieve the length, type and bytes stream from the given URL
|
||||
let mut dl = reqwest::get(u).await?;
|
||||
let content_length = dl
|
||||
.content_length()
|
||||
.ok_or(format!("Cannot get content length for {}", u))?;
|
||||
let content_headers = dl.headers().clone();
|
||||
let content_type = content_headers
|
||||
.get("Content-Type")
|
||||
.ok_or(format!("Cannot get content type for {}", u))?
|
||||
.to_str()?;
|
||||
|
||||
debug!("Init the slot for uploading media: {}", u);
|
||||
// init the slot for uploading
|
||||
let client = Client::new();
|
||||
let orig_media_id = client
|
||||
.post(TWITTER_UPLOAD_MEDIA_URL)
|
||||
.header(
|
||||
"Authorization",
|
||||
oauth1_request::post(
|
||||
TWITTER_UPLOAD_MEDIA_URL,
|
||||
&empty_request,
|
||||
&token,
|
||||
oauth1_request::HMAC_SHA1,
|
||||
),
|
||||
)
|
||||
.multipart(
|
||||
Form::new()
|
||||
.text("command", "INIT")
|
||||
.text("media_type", content_type.to_owned())
|
||||
.text("total_bytes", content_length.to_string())
|
||||
.text("media_category", t.to_string()),
|
||||
)
|
||||
.send()
|
||||
.await?
|
||||
.json::<UploadMediaResponse>()
|
||||
.await?;
|
||||
|
||||
debug!("Slot initiated with ID: {}", orig_media_id.media_id);
|
||||
|
||||
debug!("Appending media to ID: {}", orig_media_id.media_id);
|
||||
// append the media to the corresponding slot
|
||||
let mut segment: u8 = 0;
|
||||
while let Some(chunk) = dl.chunk().await? {
|
||||
debug!(
|
||||
"Appending segment {} for media ID {}",
|
||||
segment, orig_media_id.media_id
|
||||
);
|
||||
let chunk_size: u64 = chunk.len().try_into().unwrap();
|
||||
let res = client
|
||||
.post(TWITTER_UPLOAD_MEDIA_URL)
|
||||
.header(
|
||||
"Authorization",
|
||||
oauth1_request::post(
|
||||
TWITTER_UPLOAD_MEDIA_URL,
|
||||
&empty_request,
|
||||
&token,
|
||||
oauth1_request::HMAC_SHA1,
|
||||
),
|
||||
)
|
||||
.multipart(
|
||||
Form::new()
|
||||
.text("command", "APPEND")
|
||||
.text("media_id", orig_media_id.media_id.to_string())
|
||||
.text("segment_index", segment.to_string())
|
||||
.part("media", Part::stream_with_length(chunk, chunk_size)),
|
||||
)
|
||||
.send()
|
||||
.await?;
|
||||
|
||||
if !res.status().is_success() {
|
||||
return Err(
|
||||
OolatoocsError::new(&format!("Cannot upload part {} of {}", segment, u)).into(),
|
||||
);
|
||||
}
|
||||
|
||||
segment += 1;
|
||||
}
|
||||
|
||||
debug!("Finalize media ID: {}", orig_media_id.media_id);
|
||||
// Finalizing task
|
||||
let fin = client
|
||||
.post(TWITTER_UPLOAD_MEDIA_URL)
|
||||
.header(
|
||||
"Authorization",
|
||||
oauth1_request::post(
|
||||
TWITTER_UPLOAD_MEDIA_URL,
|
||||
&empty_request,
|
||||
&token,
|
||||
oauth1_request::HMAC_SHA1,
|
||||
),
|
||||
)
|
||||
.multipart(
|
||||
Form::new()
|
||||
.text("command", "FINALIZE")
|
||||
.text("media_id", orig_media_id.media_id.to_string()),
|
||||
)
|
||||
.send()
|
||||
.await?
|
||||
.json::<UploadMediaResponse>()
|
||||
.await?;
|
||||
|
||||
if let Some(p_info) = fin.processing_info {
|
||||
if let Some(wait_sec) = p_info.check_after_secs {
|
||||
debug!(
|
||||
"Processing is not finished yet for ID {}, waiting {} secs",
|
||||
orig_media_id.media_id, wait_sec
|
||||
);
|
||||
// getting here, we have a status and a check_after_secs
|
||||
// this status can be anything but we will check it afterwards
|
||||
// whatever happens, we can wait here before proceeding
|
||||
sleep(Duration::from_secs(wait_sec)).await;
|
||||
|
||||
let command = UploadMediaCommand {
|
||||
command: "STATUS".to_string(),
|
||||
media_id: orig_media_id.media_id.to_string(),
|
||||
};
|
||||
|
||||
loop {
|
||||
debug!(
|
||||
"Checking on status for ID {} after waiting {} secs",
|
||||
orig_media_id.media_id, wait_sec
|
||||
);
|
||||
|
||||
let status = client
|
||||
.get(TWITTER_UPLOAD_MEDIA_URL)
|
||||
.header(
|
||||
"Authorization",
|
||||
oauth1_request::get(
|
||||
TWITTER_UPLOAD_MEDIA_URL,
|
||||
&command,
|
||||
&token,
|
||||
oauth1_request::HMAC_SHA1,
|
||||
),
|
||||
)
|
||||
.query(&command)
|
||||
.send()
|
||||
.await?
|
||||
.json::<UploadMediaResponse>()
|
||||
.await?;
|
||||
|
||||
let p_status = status.processing_info.unwrap(); // shouldn’t be None at this point
|
||||
match p_status.state {
|
||||
UploadMediaResponseProcessingInfoState::Failed => {
|
||||
debug!("Processing has failed!");
|
||||
return Err(OolatoocsError::new(&format!(
|
||||
"Upload for {} (id: {}) has failed",
|
||||
u, orig_media_id.media_id
|
||||
))
|
||||
.into());
|
||||
}
|
||||
UploadMediaResponseProcessingInfoState::Succeeded => {
|
||||
debug!("Processing has succeeded, exiting loop!");
|
||||
break;
|
||||
}
|
||||
UploadMediaResponseProcessingInfoState::Pending
|
||||
| UploadMediaResponseProcessingInfoState::InProgress => {
|
||||
debug!(
|
||||
"Processing still pending, waiting {} secs more…",
|
||||
p_status.check_after_secs.unwrap() // unwrap is safe here,
|
||||
// check_after_secs is only present
|
||||
// when status is pending or in
|
||||
// progress
|
||||
);
|
||||
sleep(Duration::from_secs(p_status.check_after_secs.unwrap())).await;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Ok(orig_media_id.media_id)
|
||||
}
|
||||
|
||||
pub fn transform_poll(p: &Poll) -> TweetPoll {
|
||||
let poll_end_datetime = p.expires_at.unwrap(); // should be safe at this point
|
||||
let now = Utc::now();
|
||||
let diff = poll_end_datetime.signed_duration_since(now);
|
||||
|
||||
TweetPoll {
|
||||
options: p
|
||||
.options
|
||||
.iter()
|
||||
.map(|i| i.title.chars().take(25).collect::<String>())
|
||||
.collect(),
|
||||
duration_minutes: diff.num_minutes().try_into().unwrap(), // safe here, number is positive
|
||||
// and can’t be over 21600
|
||||
}
|
||||
}
|
||||
|
||||
/// This posts Tweets with all the associated medias
|
||||
pub async fn post_tweet(
|
||||
config: &TwitterConfig,
|
||||
content: String,
|
||||
medias: Vec<u64>,
|
||||
reply_to: Option<u64>,
|
||||
poll: Option<TweetPoll>,
|
||||
) -> Result<u64, Box<dyn Error>> {
|
||||
let empty_request = EmptyRequest {}; // Why? Because fuck you, that’s why!
|
||||
let token = get_token(config);
|
||||
|
||||
let tweet = Tweet {
|
||||
text: content,
|
||||
media: medias.is_empty().not().then(|| TweetMediasIds {
|
||||
media_ids: medias.iter().map(|m| m.to_string()).collect(),
|
||||
}),
|
||||
reply: reply_to.map(|s| TweetReply {
|
||||
in_reply_to_tweet_id: s.to_string(),
|
||||
}),
|
||||
poll,
|
||||
};
|
||||
|
||||
let client = Client::new();
|
||||
let res = client
|
||||
.post(TWITTER_API_TWEET_URL)
|
||||
.header(
|
||||
"Authorization",
|
||||
oauth1_request::post(
|
||||
TWITTER_API_TWEET_URL,
|
||||
&empty_request,
|
||||
&token,
|
||||
oauth1_request::HMAC_SHA1,
|
||||
),
|
||||
)
|
||||
.json(&tweet)
|
||||
.send()
|
||||
.await?
|
||||
.json::<TweetResponse>()
|
||||
.await?;
|
||||
|
||||
Ok(res.data.id.parse::<u64>().unwrap())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use megalodon::entities::PollOption;
|
||||
|
||||
#[test]
|
||||
fn test_transform_poll() {
|
||||
let poll = Poll {
|
||||
id: "youpi".to_string(),
|
||||
expires_at: Some(Utc::now()),
|
||||
expired: false,
|
||||
multiple: false,
|
||||
votes_count: 0,
|
||||
voters_count: None,
|
||||
options: vec![
|
||||
PollOption {
|
||||
title: "Je suis beaucoup trop long comme option, tronque-moi !".to_string(),
|
||||
votes_count: None,
|
||||
},
|
||||
PollOption {
|
||||
title: "nope".to_string(),
|
||||
votes_count: None,
|
||||
},
|
||||
],
|
||||
voted: None,
|
||||
emojis: vec![],
|
||||
};
|
||||
|
||||
let tweet_poll_res = transform_poll(&poll);
|
||||
let tweet_pool_expected = TweetPoll {
|
||||
duration_minutes: 0,
|
||||
options: vec!["Je suis beaucoup trop lon".to_string(), "nope".to_string()],
|
||||
};
|
||||
|
||||
assert_eq!(tweet_poll_res.options, tweet_pool_expected.options);
|
||||
}
|
||||
}
|
25
src/utils.rs
25
src/utils.rs
@@ -3,11 +3,11 @@ use megalodon::entities::status::Tag;
|
||||
use regex::Regex;
|
||||
use std::error::Error;
|
||||
|
||||
/// Generate 2 contents out of 1 if that content is > 280 chars, None else
|
||||
/// Generate 2 contents out of 1 if that content is > 300 chars, None else
|
||||
pub fn generate_multi_tweets(content: &str) -> Option<(String, String)> {
|
||||
// Twitter webforms are utf-8 encoded, so we cannot count on len(), we don’t need
|
||||
// encode_utf16().count()
|
||||
if twitter_count(content) <= 280 {
|
||||
if twitter_count(content) <= 300 {
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -38,7 +38,13 @@ fn twitter_count(content: &str) -> usize {
|
||||
|
||||
for word in split_content {
|
||||
if word.starts_with("http://") || word.starts_with("https://") {
|
||||
count += 23;
|
||||
// It’s not that simple. Bsky adapts itself to the URL.
|
||||
// https://github.com -> 10 chars
|
||||
// https://github.com/ -> 10 chars
|
||||
// https://github.com/NVNTLabs -> 19 chars
|
||||
// https://github.com/NVNTLabs/ -> 20 chars
|
||||
// so taking the maximum here to simplify things
|
||||
count += 26;
|
||||
} else {
|
||||
count += word.chars().count();
|
||||
}
|
||||
@@ -100,11 +106,11 @@ mod tests {
|
||||
|
||||
let content = "Shoot out to https://y.ml/ !";
|
||||
|
||||
assert_eq!(twitter_count(content), 38);
|
||||
assert_eq!(twitter_count(content), 41);
|
||||
|
||||
let content = "this is the link https://www.google.com/tamerelol/youpi/tonperemdr/tarace.html if you like! What if I shit a final";
|
||||
|
||||
assert_eq!(twitter_count(content), 76);
|
||||
assert_eq!(twitter_count(content), 79);
|
||||
|
||||
let content = "multi ple space";
|
||||
|
||||
@@ -112,7 +118,7 @@ mod tests {
|
||||
|
||||
let content = "This link is LEEEEET\n\nhttps://www.factornews.com/actualites/ca-sent-le-sapin-pour-free-radical-design-49985.html";
|
||||
|
||||
assert_eq!(twitter_count(content), 45);
|
||||
assert_eq!(twitter_count(content), 48);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -131,6 +137,13 @@ mod tests {
|
||||
let youpi = generate_multi_tweets(&tweet_content);
|
||||
|
||||
assert_eq!(None, youpi);
|
||||
|
||||
// test with 299 chars
|
||||
let tweet_content = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate vulver amico tio".to_string();
|
||||
|
||||
let youpi = generate_multi_tweets(&tweet_content);
|
||||
|
||||
assert_eq!(None, youpi);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
Reference in New Issue
Block a user