use crate::DbPool; use crate::api::ClientVersion; use crate::providers::Provider; use crate::status::*; use crate::util::cache::VideoCache; use crate::util::parse_abbreviated_number; use crate::util::time::parse_time_to_seconds; use crate::videos::{ServerOptions, VideoItem}; use async_trait::async_trait; use error_chain::error_chain; use htmlentity::entity::{ICodedDataTrait, decode}; use std::sync::{Arc, RwLock}; use std::vec; error_chain! { foreign_links { Io(std::io::Error); HttpRequest(wreq::Error); } } #[derive(Debug, Clone)] pub struct Tube8Provider { url: String, sites: Arc>>, stars: Arc>>, } impl Tube8Provider { pub fn new() -> Self { let provider = Tube8Provider { url: "https://www.tube8.com".to_string(), sites: Arc::new(RwLock::new(vec![FilterOption { id: "all".to_string(), title: "All".to_string(), }])), stars: Arc::new(RwLock::new(vec![FilterOption { id: "all".to_string(), title: "All".to_string(), }])), }; // Kick off the background load but return immediately provider } // Push one item with minimal lock time and dedup by id fn push_unique(target: &Arc>>, item: FilterOption) { if let Ok(mut vec) = target.write() { if !vec.iter().any(|x| x.id == item.id) { vec.push(item); // Optional: keep it sorted for nicer UX // vec.sort_by(|a,b| a.title.cmp(&b.title)); } } } fn build_channel(&self, clientversion: ClientVersion) -> Channel { let _ = clientversion; let sites: Vec = self .sites .read() .map(|g| g.clone()) // or: .map(|g| g.to_vec()) .unwrap_or_default(); // or: .unwrap_or_else(|_| Vec::new()) let stars: Vec = self .stars .read() .map(|g| g.clone()) // or: .map(|g| g.to_vec()) .unwrap_or_default(); // or: .unwrap_or_else(|_| Vec::new()) Channel { id: "tube8".to_string(), name: "Tube8".to_string(), description: "Tube8 Videos".to_string(), premium: false, favicon: "https://www.google.com/s2/favicons?sz=64&domain=www.tube8.com".to_string(), status: "active".to_string(), categories: vec![], options: vec![ ChannelOption { id: "sort".to_string(), title: "Sort".to_string(), description: "Sort the Videos".to_string(), systemImage: "list.number".to_string(), colorName: "blue".to_string(), options: vec![ FilterOption { id: "rating".into(), title: "Rating".into(), }, FilterOption { id: "mostviewed.html".into(), title: "Most Viewed".into(), }, FilterOption { id: "longest.html".into(), title: "Duration".into(), }, FilterOption { id: "newest.html".into(), title: "Newest".into(), }, ], multiSelect: false, }, ChannelOption { id: "sites".to_string(), title: "Sites".to_string(), description: "Filter for different Sites".to_string(), systemImage: "rectangle.stack".to_string(), colorName: "green".to_string(), options: sites, multiSelect: false, }, ChannelOption { id: "stars".to_string(), title: "Stars".to_string(), description: "Filter for different Pornstars".to_string(), systemImage: "star.fill".to_string(), colorName: "yellow".to_string(), options: stars, multiSelect: false, }, ], nsfw: true, cacheDuration: None, } } async fn get( &self, cache: VideoCache, page: u8, sort: &str, options: ServerOptions, ) -> Result> { let mut sort_string: String = match sort { "mostviewed.html" => "mostviewed.html/".to_string(), "longest.html" => "longest.html/".to_string(), "newest.html" => "newest.html/".to_string(), _ => "".to_string(), }; if options.sites.is_some() && !options.sites.as_ref().unwrap().is_empty() && options.sites.as_ref().unwrap() != "all" { sort_string = match sort { "mostviewed.html" => "?orderBy=mv&page=".to_string(), "longest.html" => "?orderBy=ln&page=".to_string(), "newest.html" => "?page=".to_string(), _ => "?orderBy=tr&page=".to_string(), }; } if options.stars.is_some() && !options.stars.as_ref().unwrap().is_empty() && options.stars.as_ref().unwrap() != "all" { sort_string = match sort { "mostviewed.html" => "views/?page=".to_string(), "longest.html" => "duration/?page=".to_string(), "newest.html" => "?page=".to_string(), _ => "rating/?page=".to_string(), }; } let video_url = format!("{}/{}{}", self.url, sort_string, page); let old_items = match cache.get(&video_url) { Some((time, items)) => { if time.elapsed().unwrap_or_default().as_secs() < 60 * 5 { return Ok(items.clone()); } else { items.clone() } } None => { vec![] } }; let mut requester = options.requester.clone().unwrap(); let text = requester.get(&video_url, None).await.unwrap(); let video_items: Vec = self.get_video_items_from_html(text.clone()); if !video_items.is_empty() { cache.remove(&video_url); cache.insert(video_url.clone(), video_items.clone()); } else { return Ok(old_items); } Ok(video_items) } async fn query( &self, cache: VideoCache, page: u8, query: &str, options: ServerOptions, ) -> Result> { let mut sort_string: String = match options.sort.as_ref().unwrap().as_str() { "mostviewed.html" => "&orderby=views&page=".to_string(), "longest.html" => "&orderby=longest&page=".to_string(), "newest.html" => "&orderby=newest&page=".to_string(), _ => "&orderby=rating&page=".to_string(), }; let mut search_string = query.to_string().to_ascii_lowercase().trim().to_string(); let mut video_url = format!( "{}/searches.html/?q={}{}{}", self.url, query, sort_string, page ); video_url = video_url.replace(" ", "+"); match self .stars .read() .unwrap() .iter() .find(|s| s.title.to_ascii_lowercase() == search_string) { Some(star) => { sort_string = match options.sort.as_ref().unwrap().as_str() { "mostviewed.html" => "views/?page=".to_string(), "longest.html" => "duration/?page=".to_string(), "newest.html" => "?page=".to_string(), _ => "rating/?page=".to_string(), }; video_url = format!("{}/{}{}{}", self.url, star.id, sort_string, page); } _ => {} } match self .sites .read() .unwrap() .iter() .find(|s| s.title.to_ascii_lowercase() == search_string) { Some(site) => { sort_string = match options.sort.as_ref().unwrap().as_str() { "mostviewed.html" => "?orderBy=mv&page=".to_string(), "longest.html" => "?orderBy=ln&page=".to_string(), "newest.html" => "?page=".to_string(), _ => "?orderBy=tr&page=".to_string(), }; video_url = format!("{}/{}{}{}", self.url, site.id, sort_string, page); } _ => {} } // Check our Video Cache. If the result is younger than 1 hour, we return it. let old_items = match cache.get(&video_url) { Some((time, items)) => { if time.elapsed().unwrap_or_default().as_secs() < 60 * 5 { return Ok(items.clone()); } else { let _ = cache.check().await; return Ok(items.clone()); } } None => { vec![] } }; let mut requester = options.requester.clone().unwrap(); let text = requester.get(&video_url, None).await.unwrap(); let video_items: Vec = self.get_video_items_from_html(text.clone()); if !video_items.is_empty() { cache.remove(&video_url); cache.insert(video_url.clone(), video_items.clone()); } else { return Ok(old_items); } Ok(video_items) } fn get_video_items_from_html(&self, html: String) -> Vec { if html.is_empty() { println!("HTML is empty"); return vec![]; } let mut items: Vec = Vec::new(); if !html.contains("video-box ") { return items; } let raw_videos = html.split("id=\"pagination\"").collect::>()[0] .split("-thumbs") .collect::>()[1] .split("video-box ") .collect::>()[1..] .to_vec(); for video_segment in &raw_videos { // let vid = video_segment.split("\n").collect::>(); // for (index, line) in vid.iter().enumerate() { // println!("Line {}: {}", index, line); // } let video_url: String = format!("{}{}", self.url, video_segment.split(">()[1] .split("\"") .collect::>()[0] .to_string()); let mut title = video_segment.split("alt=\"").collect::>()[1] .split("\"") .collect::>()[0] .to_string(); // html decode title = decode(title.as_bytes()).to_string().unwrap_or(title); let id = video_url.split("/").collect::>()[4].to_string(); let thumb = match video_segment.split("thumb-image ").collect::>()[1] .contains("data-src=\"") { true => video_segment.split("thumb-image ").collect::>()[1] .split("data-src=\"") .collect::>()[1] .split("\"") .collect::>()[0] .to_string(), false => video_segment.split("thumb-image ").collect::>()[1] .split("data-poster=\"") .collect::>()[1] .split("\"") .collect::>()[0] .to_string(), }; let raw_duration = video_segment .split("video-duration ") .collect::>()[1] .split("") .collect::>()[0] .split("") .collect::>() .last() .unwrap_or(&"") .replace("\n", "") .trim() .to_string(); let duration = parse_time_to_seconds(raw_duration.as_str()).unwrap_or(0) as u32; let views = parse_abbreviated_number( video_segment .split("") .collect::>()[1] .split("<") .collect::>()[0] .to_string() .as_str(), ) .unwrap_or(0) as u32; let site_name = title .split("]") .collect::>() .first() .unwrap_or(&"") .trim_start_matches("["); let site_id = self .get_site_id_from_name(site_name) .unwrap_or("".to_string()); let mut tags = match video_segment.contains("class=\"models\">") { true => video_segment .split("class=\"models\">") .collect::>()[1] .split("") .collect::>()[0] .split("href=\"") .collect::>()[1..] .into_iter() .map(|s| { Self::push_unique( &self.stars, FilterOption { id: s.split("/").collect::>()[4].to_string(), title: s.split(">").collect::>()[1] .split("<") .collect::>()[0] .trim() .to_string(), }, ); s.split(">").collect::>()[1] .split("<") .collect::>()[0] .trim() .to_string() }) .collect::>() .to_vec(), false => vec![], }; if !site_id.is_empty() { Self::push_unique( &self.sites, FilterOption { id: site_id, title: site_name.to_string(), }, ); tags.push(site_name.to_string()); } let video_item = VideoItem::new( id, title, video_url.to_string(), "omgxxx".to_string(), thumb, duration, ) .views(views) .preview(preview) .tags(tags); items.push(video_item); } return items; } } #[async_trait] impl Provider for Tube8Provider { async fn get_videos( &self, cache: VideoCache, pool: DbPool, sort: String, query: Option, page: String, per_page: String, options: ServerOptions, ) -> Vec { let _ = per_page; let _ = pool; let videos: std::result::Result, Error> = match query { Some(q) => { self.query(cache, page.parse::().unwrap_or(1), &q, options) .await } None => { self.get(cache, page.parse::().unwrap_or(1), &sort, options) .await } }; match videos { Ok(v) => v, Err(e) => { println!("Error fetching videos: {}", e); vec![] } } } fn get_channel(&self, clientversion: ClientVersion) -> Option { Some(self.build_channel(clientversion)) } }