use std::fmt;
use serde::Deserialize;
#[derive(Debug, Clone, Eq, PartialEq, Deserialize, Default)]
pub enum AttachmentType {
#[serde(rename = "event.attachment")]
#[default]
Attachment,
#[serde(rename = "event.minidump")]
Minidump,
#[serde(rename = "event.applecrashreport")]
AppleCrashReport,
#[serde(rename = "unreal.context")]
UnrealContext,
#[serde(rename = "unreal.logs")]
UnrealLogs,
#[serde(untagged)]
Custom(String),
}
impl AttachmentType {
pub fn as_str(&self) -> &str {
match self {
Self::Attachment => "event.attachment",
Self::Minidump => "event.minidump",
Self::AppleCrashReport => "event.applecrashreport",
Self::UnrealContext => "unreal.context",
Self::UnrealLogs => "unreal.logs",
Self::Custom(s) => s,
}
}
}
#[derive(Clone, PartialEq, Default)]
pub struct Attachment {
pub buffer: Vec<u8>,
pub filename: String,
pub content_type: Option<String>,
pub ty: Option<AttachmentType>,
}
impl Attachment {
pub fn to_writer<W>(&self, writer: &mut W) -> std::io::Result<()>
where
W: std::io::Write,
{
writeln!(
writer,
r#"{{"type":"attachment","length":{length},"filename":"{filename}","attachment_type":"{at}","content_type":"{ct}"}}"#,
filename = self.filename,
length = self.buffer.len(),
at = self
.ty
.as_ref()
.unwrap_or(&AttachmentType::default())
.as_str(),
ct = self
.content_type
.as_ref()
.unwrap_or(&"application/octet-stream".to_string())
)?;
writer.write_all(&self.buffer)?;
Ok(())
}
}
impl fmt::Debug for Attachment {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Attachment")
.field("buffer", &self.buffer.len())
.field("filename", &self.filename)
.field("content_type", &self.content_type)
.field("type", &self.ty)
.finish()
}
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json;
#[test]
fn test_attachment_type_deserialize() {
let result: AttachmentType = serde_json::from_str(r#""event.minidump""#).unwrap();
assert_eq!(result, AttachmentType::Minidump);
let result: AttachmentType = serde_json::from_str(r#""my.custom.type""#).unwrap();
assert_eq!(result, AttachmentType::Custom("my.custom.type".to_string()));
}
}