librespot/core/src/date.rs

82 lines
2.1 KiB
Rust
Raw Normal View History

2022-01-14 22:28:09 +00:00
use std::{
convert::{TryFrom, TryInto},
fmt::Debug,
ops::Deref,
};
2022-01-14 22:28:09 +00:00
use time::{error::ComponentRange, Date as _Date, OffsetDateTime, PrimitiveDateTime, Time};
use crate::Error;
use librespot_protocol as protocol;
use protocol::metadata::Date as DateMessage;
2022-01-14 22:28:09 +00:00
impl From<ComponentRange> for Error {
fn from(err: ComponentRange) -> Self {
Error::out_of_range(err)
}
2021-12-16 21:42:37 +00:00
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
2022-01-14 22:28:09 +00:00
pub struct Date(pub OffsetDateTime);
impl Deref for Date {
2022-01-14 22:28:09 +00:00
type Target = OffsetDateTime;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl Date {
pub fn as_timestamp_ms(&self) -> i64 {
(self.0.unix_timestamp_nanos() / 1_000_000) as i64
}
pub fn from_timestamp_ms(timestamp: i64) -> Result<Self, Error> {
let date_time = OffsetDateTime::from_unix_timestamp_nanos(timestamp as i128 * 1_000_000)?;
2022-01-14 22:28:09 +00:00
Ok(Self(date_time))
}
2022-01-14 22:28:09 +00:00
pub fn as_utc(&self) -> OffsetDateTime {
self.0
}
2022-01-14 22:28:09 +00:00
pub fn from_utc(date_time: PrimitiveDateTime) -> Self {
Self(date_time.assume_utc())
}
pub fn now_utc() -> Self {
Self(OffsetDateTime::now_utc())
}
}
2022-01-14 22:28:09 +00:00
impl TryFrom<&DateMessage> for Date {
type Error = crate::Error;
fn try_from(msg: &DateMessage) -> Result<Self, Self::Error> {
// Some metadata contains a year, but no month. In that case just set January.
let month = if msg.has_month() {
msg.get_month() as u8
} else {
1
};
// Having no day will work, but may be unexpected: it will imply the last day
// of the month before. So prevent that, and just set day 1.
let day = if msg.has_day() {
msg.get_day() as u8
} else {
1
};
let date = _Date::from_calendar_date(msg.get_year(), month.try_into()?, day)?;
2022-01-14 22:28:09 +00:00
let time = Time::from_hms(msg.get_hour() as u8, msg.get_minute() as u8, 0)?;
Ok(Self::from_utc(PrimitiveDateTime::new(date, time)))
}
}
2022-01-14 22:28:09 +00:00
impl From<OffsetDateTime> for Date {
fn from(datetime: OffsetDateTime) -> Self {
Self(datetime)
}
}