Skip to content

Commit

Permalink
fix timestamps
Browse files Browse the repository at this point in the history
  • Loading branch information
decahedron1 committed Feb 9, 2024
1 parent 38f93c0 commit d1fa005
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
4 changes: 2 additions & 2 deletions src/youtube/types/get_live_chat.rs
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ use serde::{Deserialize, Serialize};
use serde_aux::prelude::*;
use url::Url;

use super::{Accessibility, CommandMetadata, Icon, ImageContainer, LocalizedText, UnlocalizedText};
use super::{deserialize_datetime_utc_from_microseconds, Accessibility, CommandMetadata, Icon, ImageContainer, LocalizedText, UnlocalizedText};
use crate::youtube::{
get_http_client,
util::{SimdJsonRequestBody, SimdJsonResponseBody},
Expand Down Expand Up @@ -183,7 +183,7 @@ pub struct MessageRendererBase {
pub author_badges: Option<Vec<AuthorBadge>>,
pub context_menu_endpoint: ContextMenuEndpoint,
pub id: String,
#[serde(deserialize_with = "deserialize_datetime_utc_from_milliseconds")]
#[serde(deserialize_with = "deserialize_datetime_utc_from_microseconds")]
pub timestamp_usec: DateTime<Utc>,
pub author_external_channel_id: String,
pub context_menu_accessibility: Accessibility
Expand Down
17 changes: 16 additions & 1 deletion src/youtube/types/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@
// See the License for the specific language governing permissions and
// limitations under the License.

use serde::Deserialize;
use serde::{de::Error, Deserialize, Deserializer};
use serde_aux::field_attributes::deserialize_number_from_string;
use simd_json::OwnedValue;

pub mod get_live_chat;
Expand Down Expand Up @@ -104,3 +105,17 @@ pub struct Emoji {
pub struct Icon {
pub icon_type: String
}

pub fn deserialize_datetime_utc_from_microseconds<'de, D>(deserializer: D) -> Result<chrono::DateTime<chrono::Utc>, D::Error>
where
D: Deserializer<'de>
{
use chrono::prelude::*;

let number = deserialize_number_from_string::<i64, D>(deserializer)?;
let seconds = number / 1_000_000;
let micros = (number % 1_000_000) as u32;
let nanos = micros * 1_000;

Ok(Utc.from_utc_datetime(&NaiveDateTime::from_timestamp_opt(seconds, nanos).ok_or_else(|| D::Error::custom("Couldn't parse the timestamp"))?))
}

0 comments on commit d1fa005

Please sign in to comment.