@@ -86,18 +86,28 @@ impl TextFile {
8686pub struct MediaFile {
8787 pub id : Uuid ,
8888 pub title : String ,
89- content : Vec < Bytes > ,
89+ pub content : Vec < Bytes > ,
9090}
9191
9292impl MediaFile {
93- pub fn new ( title : String , content : Vec < Bytes > ) -> Self {
93+ pub ( crate ) fn new ( title : String , content : Vec < Bytes > ) -> Self {
9494 Self {
9595 id : Uuid :: new_v4 ( ) ,
9696 title,
9797 content,
9898 }
9999 }
100100
101+ pub fn from_u8 ( filename : String , data : Vec < u8 > ) -> Self {
102+ let chunk_size = 1024 ;
103+ let content: Vec < Bytes > = data
104+ . chunks ( chunk_size)
105+ . map ( |chunk| chunk. to_vec ( ) )
106+ . collect ( ) ;
107+
108+ Self :: new ( filename, content)
109+ }
110+
101111 pub fn get_title ( & self ) -> & str {
102112 & self . title
103113 }
@@ -304,4 +314,33 @@ pub enum ServerType {
304314 ChatServer ,
305315 TextServer ,
306316 MediaServer ,
317+ }
318+
319+ pub mod file_conversion {
320+ use super :: * ;
321+ use std:: fs;
322+ use std:: path:: Path ;
323+
324+ pub fn file_to_media_file ( file_path : & str ) -> Result < MediaFile , Box < dyn std:: error:: Error > > {
325+ let filename = Path :: new ( file_path)
326+ . file_name ( )
327+ . and_then ( |name| name. to_str ( ) )
328+ . unwrap_or ( "unknown" )
329+ . to_string ( ) ;
330+
331+ let data = fs:: read ( file_path. to_string ( ) ) ?;
332+ Ok ( MediaFile :: from_u8 ( filename, data) )
333+ }
334+
335+ pub fn file_to_text_file ( file_path : & str ) -> Result < TextFile , Box < dyn std:: error:: Error > > {
336+ let filename = Path :: new ( file_path)
337+ . file_stem ( )
338+ . and_then ( |name| name. to_str ( ) )
339+ . unwrap_or ( "unknown" )
340+ . to_string ( ) ;
341+
342+ let content = fs:: read_to_string ( file_path. to_string ( ) ) ?;
343+
344+ Ok ( TextFile :: new ( filename, content, vec ! [ ] ) )
345+ }
307346}
0 commit comments