refactor: separate function for media ids

This commit is contained in:
VC
2022-11-05 07:57:03 +01:00
parent df75520175
commit de758c7bda
5 changed files with 68 additions and 48 deletions

View File

@@ -1,11 +1,62 @@
use crate::ScootalooError;
use crate::{twitter::get_tweet_media, ScootalooError};
use egg_mode::tweet::Tweet;
use elefren::prelude::*;
use log::{error, warn};
use reqwest::Url;
use std::error::Error;
use std::{borrow::Cow, error::Error};
use tokio::{
fs::{create_dir_all, File},
fs::{create_dir_all, remove_file, File},
io::copy,
};
/// Generate associative table between media ids and tweet extended entities
pub async fn generate_media_ids(
tweet: &Tweet,
cache_path: &str,
mastodon: &Mastodon,
) -> (String, Vec<String>) {
let mut media_ids: Vec<String> = vec![];
let mut media_url: String = "".to_string();
if let Some(m) = &tweet.extended_entities {
for media in &m.media {
// attribute the media url
media_url = media.url.clone();
let local_tweet_media_path = match get_tweet_media(media, cache_path).await {
Ok(m) => m,
Err(e) => {
error!("Cannot get tweet media for {}: {}", &media.url, e);
continue;
}
};
let mastodon_media_ids = match mastodon
.media(Cow::from(local_tweet_media_path.to_owned()))
{
Ok(m) => {
remove_file(&local_tweet_media_path).await.unwrap_or_else(|e|
warn!("Attachment for {} has been uploaded, but Im unable to remove the existing file: {}", &local_tweet_media_path, e));
m.id
}
Err(e) => {
error!(
"Attachment {} cannot be uploaded to Mastodon Instance: {}",
&local_tweet_media_path, e
);
// file is no longer useful, deleting
remove_file(&local_tweet_media_path).await.unwrap_or_else(|e|
warn!("Attachment for {} has been uploaded, but Im unable to remove the existing file: {}", &local_tweet_media_path, e));
continue;
}
};
media_ids.push(mastodon_media_ids);
}
}
(media_url, media_ids)
}
/// Gets and caches Twitter Media inside the determined temp dir
pub async fn cache_media(u: &str, t: &str) -> Result<String, Box<dyn Error>> {
// create dir