3 import sys, os, getopt, time, random
4 import manga.lib, manga.profile
10 def msg(vl, msg, *args):
12 sys.stderr.write("getmanga: " + (msg % args) + "\n")
14 def getprop(nm, default=None):
15 if "dl-" + nm in mprof.props:
16 return mprof.props["dl-" + nm]
30 for t, i in page.stack:
33 ret += "%0*i" % (digits(len(t) + 1), i + 1)
36 def expand(pattern, page):
41 p = pattern.find('%', fp)
43 if si < len(page.stack):
44 sys.stderr.write("getmanga: pattern %s did not match page %s\n" %
45 (pattern, "/".join(t.name for t, i in page.stack)))
47 return ret + pattern[fp:]
53 if si >= len(page.stack):
54 sys.stderr.write("getmanga: pattern %s did not match page %s\n" %
55 (pattern, "/".join(t.name for t, i in page.stack)))
57 t, ti = page.stack[si]
60 ret += "%0*i" % (digits(len(t) + 1), ti + 1)
66 sys.stderr.write("getmanga: %s: unknown specified `%s'\n" % (m))
69 def download(mng, tdir, pattern):
70 exts = ["", ".jpg", ".jpeg", ".png", ".gif"]
71 fmts = {"PNG": "png", "JPEG": "jpeg", "GIF": "gif"}
72 for page in manga.lib.cursor(mng):
76 nm = expand(pattern, page)
77 path = os.path.join(tdir, nm)
78 if any(os.path.exists(path + ext) for ext in exts):
79 msg(2, "%s exists, skipping", nm)
81 msg(1, "getting %s...", nm)
82 with page.open() as fp:
83 with open(path, "wb") as out:
90 img = Image.open(path)
96 sys.stderr.write("getmanga: warning: could not determine file format of %s, leaving as is\n" % nm)
98 os.rename(path, path + "." + fmts[fmt])
99 msg(3, "%s -> %s", nm, nm + "." + fmts[fmt])
100 cwait = abs(random.gauss(0, 1) * wait)
101 msg(2, "waiting %.1f s...", cwait)
105 out.write("usage: getmanga [-hv] [-w WAIT] [-p PROFILE] DIRECTORY [LIBRARY ID]\n")
108 global verbose, wait, mprof, props
110 opts, args = getopt.getopt(sys.argv[1:], "hvp:w:")
127 if not os.path.isdir(tdir):
128 sys.stderr.write("getmanga: %s: not a directory\n" % (tdir))
131 pfile = os.path.join(tdir, ".props")
133 if os.path.exists(pfile):
134 with open(pfile, "r") as fp:
135 for words in splitlines(f):
136 if words[0] == "set" and len(words) > 2:
137 props[words[1]] = words[2]
138 elif words[0] == "lset" and len(words) > 1:
139 props[words[1]] = words[2:]
142 profile = manga.profile.profile.last()
144 profile = manga.profile.profile.byname(profnm)
150 libnm, mid = args[1:3]
151 elif isinstance(props.get("manga"), list):
152 libnm, mid = props["manga"]
154 sys.stderr.write("getmanga: %s: id is neither saved nor given\n" % (tdir))
157 lib = manga.lib.findlib(libnm)
159 sys.stderr.write("getmanga: no such library: %s\n" % (libnm))
164 sys.stderr.write("getmanga: no such manga: %s\n" % (mid))
166 mprof = profile.getmanga(libnm, mng.id)
168 download(mprof.open(), tdir, getprop("pattern"))
170 if __name__ == "__main__":
173 except KeyboardInterrupt: