-
Notifications
You must be signed in to change notification settings - Fork 27
Add mediafile import from memory #14
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
codecrafter404
wants to merge
2
commits into
yannickfunk:master
Choose a base branch
from
codecrafter404:master
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -17,7 +17,7 @@ use std::str::FromStr; | |
|
||
/// `Package` to pack `Deck`s and `media_files` and write them to a `.apkg` file | ||
/// | ||
/// Example: | ||
/// # Example (media files on the filesystem): | ||
/// ```rust | ||
/// use genanki_rs::{Package, Deck, Note, Model, Field, Template}; | ||
/// | ||
|
@@ -41,23 +41,90 @@ use std::str::FromStr; | |
/// let mut package = Package::new(vec![my_deck], vec!["sound.mp3", "images/image.jpg"])?; | ||
/// package.write_to_file("output.apkg")?; | ||
/// ``` | ||
/// # Example (media files from memory): | ||
/// ```rust | ||
/// use genanki_rs::{Package, Deck, Note, Model, Field, Template, MediaFile}; | ||
|
||
/// const VALID_MP3: &[u8] = | ||
/// b"\xff\xe3\x18\xc4\x00\x00\x00\x03H\x00\x00\x00\x00LAME3.98.2\x00\x00\x00\ | ||
/// \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ | ||
/// \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\ | ||
/// \x00\x00\x00\x00\x00\x00\x00\x00\x00\x00"; | ||
/// | ||
/// const VALID_JPG: &[u8] = | ||
/// b"\xff\xd8\xff\xdb\x00C\x00\x03\x02\x02\x02\x02\x02\x03\x02\x02\x02\x03\x03\ | ||
/// \x03\x03\x04\x06\x04\x04\x04\x04\x04\x08\x06\x06\x05\x06\t\x08\n\n\t\x08\t\ | ||
/// \t\n\x0c\x0f\x0c\n\x0b\x0e\x0b\t\t\r\x11\r\x0e\x0f\x10\x10\x11\x10\n\x0c\ | ||
/// \x12\x13\x12\x10\x13\x0f\x10\x10\x10\xff\xc9\x00\x0b\x08\x00\x01\x00\x01\ | ||
/// \x01\x01\x11\x00\xff\xcc\x00\x06\x00\x10\x10\x05\xff\xda\x00\x08\x01\x01\ | ||
/// \x00\x00?\x00\xd2\xcf \xff\xd9"; | ||
/// | ||
/// let model = Model::new( | ||
/// 1607392319, | ||
/// "Simple Model", | ||
/// vec![ | ||
/// Field::new("Question"), | ||
/// Field::new("Answer"), | ||
/// Field::new("MyMedia"), | ||
/// ], | ||
/// vec![Template::new("Card 1") | ||
/// .qfmt("{{Question}}{{Question}}<br>{{MyMedia}}") | ||
/// .afmt(r#"{{FrontSide}}<hr id="answer">{{Answer}}"#)], | ||
/// ); | ||
/// let mut deck = Deck::new(1234, "Example Deck", "Example Deck with media"); | ||
/// deck.add_note(Note::new(model.clone(), vec!["What is the capital of France?", "Paris", "[sound:sound.mp3]"])?); | ||
/// deck.add_note(Note::new(model.clone(), vec!["What is the capital of France?", "Paris", r#"<img src="image.jpg">"#])?); | ||
/// | ||
/// let mut package = Package::new_from_memory(vec![deck], vec![MediaFile::new_from_bytes(VALID_MP3, "sound.mp3"), MediaFile::new_from_bytes(VALID_JPG, "image.jpg")])?; | ||
/// package.write_to_file("output.apkg")?; | ||
/// ``` | ||
pub struct Package { | ||
decks: Vec<Deck>, | ||
media_files: Vec<PathBuf>, | ||
media_files: Vec<MediaFile>, | ||
} | ||
/// the location of the media files, either as a path on the filesystem or as bytes from memory | ||
pub enum MediaFile { | ||
/// a path on the filesystem | ||
Path(PathBuf), | ||
/// bytes of the file and a filename | ||
Bytes(Vec<u8>, String), | ||
} | ||
impl MediaFile { | ||
/// Create a new `MediaFile` from a path on the filesystem | ||
pub fn new_from_file<P: AsRef<Path>>(path: P) -> Self { | ||
Self::Path(path.as_ref().to_path_buf()) | ||
} | ||
|
||
/// Create a new `MediaFile` from a path on the filesystem using a `&str` | ||
pub fn new_from_file_path(path: &str) -> Result<Self, Error> { | ||
Ok(Self::Path(PathBuf::from_str(path)?)) | ||
} | ||
|
||
/// Create a new `MediaFile` from bytes from memory and a filename | ||
pub fn new_from_bytes(bytes: &[u8], name: &str) -> Self { | ||
Self::Bytes(bytes.to_vec(), name.to_owned()) | ||
} | ||
} | ||
impl Package { | ||
/// Create a new package with `decks` and `media_files` | ||
/// | ||
/// Returns `Err` if `media_files` are invalid | ||
pub fn new(decks: Vec<Deck>, media_files: Vec<&str>) -> Result<Self, Error> { | ||
let media_files = media_files | ||
.iter() | ||
.map(|&s| PathBuf::from_str(s)) | ||
.map(|&s| PathBuf::from_str(s).map(|p| MediaFile::Path(p))) | ||
.collect::<Result<Vec<_>, _>>()?; | ||
Ok(Self { decks, media_files }) | ||
} | ||
|
||
/// Create a new package with `decks` and `media_files`, | ||
/// where `media_files` can be bytes from memory or a path on the filesystem | ||
/// | ||
/// Returns `Err` if `media_files` are invalid | ||
pub fn new_from_memory(decks: Vec<Deck>, media_files: Vec<MediaFile>) -> Result<Self, Error> { | ||
Ok(Self { decks, media_files }) | ||
} | ||
|
||
/// Writes the package to any writer that implements Write and Seek | ||
pub fn write<W: Write + Seek>(&mut self, writer: W) -> Result<(), Error> { | ||
self.write_maybe_timestamp(writer, None) | ||
|
@@ -118,17 +185,20 @@ impl Package { | |
.media_files | ||
.iter() | ||
.enumerate() | ||
.collect::<HashMap<usize, &PathBuf>>(); | ||
.collect::<HashMap<usize, &MediaFile>>(); | ||
let media_map = media_file_idx_to_path | ||
.clone() | ||
.into_iter() | ||
.map(|(id, path)| { | ||
.map(|(id, media_file)| { | ||
( | ||
id.to_string(), | ||
path.file_name() | ||
.expect("Should always have a filename") | ||
.to_str() | ||
.expect("should always have string"), | ||
match media_file { | ||
MediaFile::Path(path) => path.file_name() | ||
.expect("Should always have a filename") | ||
.to_str() | ||
.expect("should always have string"), | ||
MediaFile::Bytes(_, name) => name, | ||
}, | ||
) | ||
}) | ||
.collect::<HashMap<String, &str>>(); | ||
|
@@ -138,11 +208,14 @@ impl Package { | |
.map_err(zip_error)?; | ||
outzip.write_all(media_json.as_bytes())?; | ||
|
||
for (idx, &path) in &media_file_idx_to_path { | ||
for (idx, &media_file) in &media_file_idx_to_path { | ||
outzip | ||
.start_file(idx.to_string(), FileOptions::default()) | ||
.map_err(zip_error)?; | ||
outzip.write_all(&read_file_bytes(path)?)?; | ||
outzip.write_all(&match media_file { | ||
MediaFile::Path(path) => read_file_bytes(path)?, | ||
MediaFile::Bytes(bytes, _) => bytes.clone(), | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. This clone is probably not required? |
||
})?; | ||
} | ||
outzip.finish().map_err(zip_error)?; | ||
Ok(()) | ||
|
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Would it be possible not to call
to_vec
here and just keep a reference to the bytes? Could potentially avoid a chunky memcopy