From f8ff7c0c38e89bcf394a0f22a68a0b1a59d7121a Mon Sep 17 00:00:00 2001 From: abdo Date: Sat, 22 May 2021 22:21:12 +0300 Subject: [PATCH] storeMediaFile: Add option to keep file with the same name (#257) --- actions/media.md | 2 ++ plugin/__init__.py | 11 +++++------ tests/test_media.py | 6 ++++-- 3 files changed, 11 insertions(+), 8 deletions(-) diff --git a/actions/media.md b/actions/media.md index 2412290..fd89065 100644 --- a/actions/media.md +++ b/actions/media.md @@ -4,6 +4,8 @@ Stores a file with the specified base64-encoded contents inside the media folder. Alternatively you can specify a absolute file path, or a url from where the file shell be downloaded. If more than one of `data`, `path` and `url` are provided, the `data` field will be used first, then `path`, and finally `url`. To prevent Anki from removing files not used by any cards (e.g. for configuration files), prefix the filename with an underscore. These files are still synchronized to AnkiWeb. + Any existing file with the same name is deleted by default. Set `deleteExisting` to false to prevent that + by [letting Anki give the new file a non-conflicting name](https://github.com/ankitects/anki/blob/aeba725d3ea9628c73300648f748140db3fdd5ed/rslib/src/media/files.rs#L194). *Sample request*: ```json diff --git a/plugin/__init__.py b/plugin/__init__.py index f6b670e..d1b3909 100644 --- a/plugin/__init__.py +++ b/plugin/__init__.py @@ -561,19 +561,18 @@ class AnkiConnect: @util.api() - def storeMediaFile(self, filename, data=None, path=None, url=None, skipHash=None): - if data: + def storeMediaFile(self, filename, data=None, path=None, url=None, skipHash=None, deleteExisting=True): + if not (data or path or url): + raise Exception('You must provide a "data", "path", or "url" field.') + if deleteExisting: self.deleteMediaFile(filename) + if data: mediaData = base64.b64decode(data) elif path: - self.deleteMediaFile(filename) with open(path, 'rb') as f: mediaData = f.read() elif url: - self.deleteMediaFile(filename) mediaData = util.download(url) - else: - raise Exception('You must either provide a "data" or a "url" field.') if skipHash is None: skip = False diff --git a/tests/test_media.py b/tests/test_media.py index 1de0ea5..cc2bd38 100755 --- a/tests/test_media.py +++ b/tests/test_media.py @@ -10,14 +10,16 @@ class TestMedia(unittest.TestCase): data = 'test' # storeMediaFile - util.invoke('storeMediaFile', filename='_test.txt', data=data) + util.invoke('storeMediaFile', filename=filename, data=data) + filename2 = util.invoke('storeMediaFile', filename=filename, data='testtest', deleteExisting=False) + self.assertNotEqual(filename2, filename) # retrieveMediaFile (part 1) media = util.invoke('retrieveMediaFile', filename=filename) self.assertEqual(media, data) names = util.invoke('getMediaFilesNames', pattern='_tes*.txt') - self.assertEqual(names, [filename]) + self.assertEqual(set(names), set([filename, filename2])) # deleteMediaFile util.invoke('deleteMediaFile', filename=filename)