simplify media.py

- drop mediaPrefix & the mediaURL-based downloading
- always create the media folder
- remove move() in preparation for a single collection approach
This commit is contained in:
Damien Elmes 2011-09-11 00:25:22 +09:00
parent cf8288a5e0
commit 7e1df75cc2
4 changed files with 9 additions and 121 deletions

View file

@ -79,8 +79,7 @@ def _buildImg(deck, latex, fname, model):
texfile = file(namedtmp("tmp.tex"), "w") texfile = file(namedtmp("tmp.tex"), "w")
texfile.write(latex) texfile.write(latex)
texfile.close() texfile.close()
# make sure we have a valid mediaDir mdir = deck.media.dir()
mdir = deck.media.dir(create=True)
oldcwd = os.getcwd() oldcwd = os.getcwd()
png = namedtmp("tmp.png") png = namedtmp("tmp.png")
try: try:

View file

@ -9,8 +9,6 @@ from anki.lang import _
class MediaManager(object): class MediaManager(object):
# can be altered at the class level for dropbox, etc
mediaPrefix = ""
# other code depends on this order, so don't reorder # other code depends on this order, so don't reorder
regexps = ("(?i)(\[sound:([^]]+)\])", regexps = ("(?i)(\[sound:([^]]+)\])",
"(?i)(<img[^>]+src=[\"']?([^\"'>]+)[\"']?[^>]*>)") "(?i)(<img[^>]+src=[\"']?([^\"'>]+)[\"']?[^>]*>)")
@ -18,52 +16,22 @@ class MediaManager(object):
def __init__(self, deck): def __init__(self, deck):
self.deck = deck self.deck = deck
self._dir = None self._dir = None
self._updateDir()
def dir(self, create=False): def dir(self):
"Call with create=None to retrieve dir without creating." if not self._dir:
if self._dir: self._dir = re.sub("(?i)\.(anki)$", ".media", self.deck.path)
return self._dir if not os.path.exists(self._dir):
elif create == None: os.makedirs(self._dir)
return self._updateDir(create) os.chdir(self._dir)
elif create:
self._updateDir(True)
return self._dir return self._dir
def _updateDir(self, create=False):
if self.mediaPrefix:
dir = os.path.join(
self.mediaPrefix, os.path.basename(self.deck.path))
else:
dir = self.deck.path
dir = re.sub("(?i)\.(anki)$", ".media", dir)
if create == None:
# don't create, but return dir
return dir
if not os.path.exists(dir):
if not create:
return
# will raise error if we can't create
os.makedirs(dir)
# change to the current dir
os.chdir(dir)
self._dir = dir
def move(self, old):
if not old:
return
self._dir = None
new = self.dir(create=None)
shutil.copytree(old, new)
shutil.rmtree(old)
# Adding media # Adding media
########################################################################## ##########################################################################
def addFile(self, opath): def addFile(self, opath):
"""Copy PATH to MEDIADIR, and return new filename. """Copy PATH to MEDIADIR, and return new filename.
If the same name exists, compare checksums.""" If the same name exists, compare checksums."""
mdir = self.dir(create=True) mdir = self.dir()
# remove any dangerous characters # remove any dangerous characters
base = re.sub(r"[][<>:/\\&]", "", os.path.basename(opath)) base = re.sub(r"[][<>:/\\&]", "", os.path.basename(opath))
dst = os.path.join(mdir, base) dst = os.path.join(mdir, base)
@ -177,69 +145,3 @@ If the same name exists, compare checksums."""
for f in self.mediaFiles(p[type]): for f in self.mediaFiles(p[type]):
files.add(f) files.add(f)
return files return files
# Download missing
##########################################################################
def downloadMissing(self):
raise Exception()
urlbase = self.deck.getVar("mediaURL")
if not urlbase:
return None
mdir = self.deck.dir(create=True)
missing = 0
grabbed = 0
for c, (f, sum) in enumerate(self.deck.db.all(
"select file, csum from media")):
path = os.path.join(mdir, f)
if not os.path.exists(path):
try:
rpath = urlbase + f
url = urllib2.urlopen(rpath)
open(f, "wb").write(url.read())
grabbed += 1
except:
if sum:
# the file is supposed to exist
return (False, rpath)
else:
# ignore and keep going
missing += 1
#self.deck.updateProgress(label=_("File %d...") % (grabbed+missing))
return (True, grabbed, missing)
# Convert remote links to local ones
##########################################################################
def downloadRemote(self):
raise Exception()
mdir = self.deck.dir(create=True)
refs = {}
for (question, answer) in self.deck.db.all(
"select question, answer from cards"):
for txt in (question, answer):
for f in mediaFiles(txt, remote=True):
refs[f] = True
failed = []
passed = []
for c, link in enumerate(refs.keys()):
try:
path = namedtmp(os.path.basename(link))
url = urllib2.urlopen(link)
open(path, "wb").write(url.read())
newpath = copyToMedia(self.deck, path)
passed.append([link, newpath])
except:
failed.append(link)
#self.deck.updateProgress(label=_("Download %d...") % c)
for (url, name) in passed:
self.deck.db.execute(
"update fields set value = replace(value, :url, :name)",
url=url, name=name)
#self.deck.updateProgress(label=_("Updating references..."))
#self.deck.updateProgress(label=_("Updating cards..."))
# rebuild entire q/a cache
for m in self.deck.models:
self.deck.updateCardsFromModel(m, dirty=True)
return (passed, failed)

View file

@ -7,8 +7,6 @@ from anki.hooks import addHook
def test_latex(): def test_latex():
d = getEmptyDeck() d = getEmptyDeck()
# no media directory to start
assert not d.media.dir()
# change latex cmd to simulate broken build # change latex cmd to simulate broken build
import anki.latex import anki.latex
anki.latex.latexCmd[0] = "nolatex" anki.latex.latexCmd[0] = "nolatex"
@ -16,8 +14,6 @@ def test_latex():
f = d.newFact() f = d.newFact()
f['Front'] = u"[latex]hello[/latex]" f['Front'] = u"[latex]hello[/latex]"
d.addFact(f) d.addFact(f)
# adding will have created the media
assert d.media.dir()
# but since latex couldn't run, it will be empty # but since latex couldn't run, it will be empty
assert len(os.listdir(d.media.dir())) == 0 assert len(os.listdir(d.media.dir())) == 0
# check the error message # check the error message

View file

@ -41,7 +41,7 @@ def test_strings():
def test_deckIntegration(): def test_deckIntegration():
d = getEmptyDeck() d = getEmptyDeck()
# create a media dir # create a media dir
d.media.dir(create=True) d.media.dir()
# put a file into it # put a file into it
file = unicode(os.path.join(testDir, "support/fake.png")) file = unicode(os.path.join(testDir, "support/fake.png"))
d.media.addFile(file) d.media.addFile(file)
@ -59,12 +59,3 @@ def test_deckIntegration():
ret = d.media.check() ret = d.media.check()
assert ret[0] == ["fake2.png"] assert ret[0] == ["fake2.png"]
assert ret[1] == ["foo.jpg"] assert ret[1] == ["foo.jpg"]
def test_rename():
d = getEmptyDeck()
# put a file into it
file = unicode(os.path.join(testDir, "support/fake.png"))
d.media.addFile(file)
new = d.path.replace(".anki", "2.anki")
d.rename(new)