Changed profile interface a bit.
[automanga.git] / manga / profile.py
CommitLineData
375a030d
FT
1import os
2pj = os.path.join
3
4home = os.getenv("HOME")
5if home is None or not os.path.isdir(home):
6 raise Exception("Could not find home directory for profile keeping")
7basedir = pj(home, ".manga", "profiles")
8
9def openwdir(nm, mode="r"):
10 if os.path.exists(nm):
11 return open(nm, mode)
12 if mode != "r":
13 d = os.path.dirname(nm)
14 if not os.path.isdir(d):
15 os.makedirs(d)
16 return open(nm, mode)
17
18def splitline(line):
19 def bsq(c):
20 if c == "\\": return "\\"
21 elif c == '"': return '"'
22 elif c == " ": return " "
23 elif c == "n": return "\n"
24 else: return ""
25 ret = []
26 p = 0
27 buf = ""
28 a = False
29 while p < len(line):
30 c = line[p]
31 if c.isspace():
32 p += 1
33 else:
34 while p < len(line):
35 c = line[p]
36 p += 1
37 if c == '"':
38 a = True
39 while p < len(line):
40 c = line[p]
41 p += 1
42 if c == '"':
43 break
44 elif c == "\\" and p < len(line):
45 buf += bsq(line[p])
46 p += 1
47 else:
48 buf += c
49 elif c.isspace():
50 ret.append(buf)
51 buf = ""
012c4cae 52 a = False
375a030d
FT
53 break
54 elif c == "\\" and p < len(line):
55 buf += bsq(line[p])
56 p += 1
57 else:
58 buf += c
59 if a or buf != "":
60 ret.append(buf)
61 return ret
62
63def consline(*words):
64 buf = ""
65 for w in words:
66 if any((c == "\\" or c == '"' or c == "\n" for c in w)):
67 wb = ""
68 for c in w:
69 if c == "\\": wb += "\\\\"
70 elif c == '"': wb += '\\"'
71 elif c == "\n": wb += "\\n"
72 else: wb += c
73 w = wb
74 if w == "" or any((c.isspace() for c in w)):
75 w = '"' + w + '"'
76 if buf != "":
77 buf += " "
78 buf += w
79 return buf
80
81class manga(object):
43423668 82 def __init__(self, profile, libnm, id):
375a030d
FT
83 self.profile = profile
84 self.libnm = libnm
85 self.id = id
375a030d
FT
86 self.props = self.loadprops()
87
43423668
FT
88 def open(self):
89 import lib
90 return lib.findlib(self.libnm).byid(self.id)
91
92class memmanga(manga):
93 def __init__(self, profile, libnm, id):
94 super(memmanga, self).__init__(profile, libnm, id)
95
96 def loadprops(self):
97 return {}
98
99class filemanga(manga):
100 def __init__(self, profile, libnm, id, path):
101 self.path = path
102 super(filemanga, self).__init__(profile, libnm, id)
103
375a030d
FT
104 def loadprops(self):
105 ret = {}
106 with openwdir(self.path) as f:
107 for line in f:
108 words = splitline(line)
109 if len(words) < 1: continue
110 if words[0] == "set" and len(words) > 2:
111 ret[words[1]] = words[2]
112 elif words[0] == "lset" and len(words) > 1:
113 ret[words[1]] = words[2:]
114 return ret
115
43423668 116 def save(self):
375a030d
FT
117 with openwdir(self.path, "w") as f:
118 for key, val in self.props.iteritems():
119 if isinstance(val, str):
120 f.write(consline("set", key, val) + "\n")
121 else:
122 f.write(consline("lset", key, *val) + "\n")
123
375a030d
FT
124class profile(object):
125 def __init__(self, dir):
126 self.dir = dir
127 self.name = None
128
129 def getmapping(self):
130 seq = 0
131 ret = {}
132 if os.path.exists(pj(self.dir, "map")):
133 with openwdir(pj(self.dir, "map")) as f:
134 for ln in f:
135 words = splitline(ln)
136 if len(words) < 1:
137 continue
138 if words[0] == "seq" and len(words) > 1:
139 try:
140 seq = int(words[1])
141 except ValueError:
142 pass
143 elif words[0] == "manga" and len(words) > 3:
144 try:
145 ret[words[1], words[2]] = int(words[3])
146 except ValueError:
147 pass
148 return seq, ret
149
150 def savemapping(self, seq, m):
151 with openwdir(pj(self.dir, "map"), "w") as f:
152 f.write(consline("seq", str(seq)) + "\n")
153 for (libnm, id), num in m.iteritems():
154 f.write(consline("manga", libnm, id, str(num)) + "\n")
155
156 def getmanga(self, libnm, id, creat=False):
157 seq, m = self.getmapping()
158 if (libnm, id) in m:
43423668 159 return filemanga(self, libnm, id, pj(self.dir, "%i.manga" % m[(libnm, id)]))
375a030d
FT
160 if not creat:
161 raise KeyError("no such manga: (%s, %s)" % (libnm, id))
162 while True:
163 try:
164 fp = openwdir(pj(self.dir, "%i.manga" % seq), "wx")
165 except IOError:
166 seq += 1
167 else:
168 break
169 fp.close()
170 m[(libnm, id)] = seq
171 self.savemapping(seq, m)
43423668 172 return filemanga(self, libnm, id, pj(self.dir, "%i.manga" % seq))
375a030d
FT
173
174 def setlast(self):
175 if self.name is None:
176 raise ValueError("profile at " + self.dir + " has no name")
177 with openwdir(pj(basedir, "last"), "w") as f:
178 f.write(self.name + "\n")
179
271d68da
FT
180 def getaliases(self):
181 ret = {}
182 if os.path.exists(pj(self.dir, "alias")):
183 with openwdir(pj(self.dir, "alias")) as f:
184 for ln in f:
185 ln = splitline(ln)
186 if len(ln) < 1: continue
187 if ln[0] == "alias" and len(ln) > 3:
188 ret[ln[1]] = ln[2], ln[3]
189 return ret
190
191 def savealiases(self, map):
192 with openwdir(pj(self.dir, "alias"), "w") as f:
193 for nm, (libnm, id) in map.iteritems():
194 f.write(consline("alias", nm, libnm, id) + "\n")
195
196 def getalias(self, nm):
197 return self.getaliases()[nm]
198
199 def setalias(self, nm, libnm, id):
200 aliases = self.getaliases()
201 aliases[nm] = libnm, id
202 self.savealiases(aliases)
203
375a030d
FT
204 @classmethod
205 def byname(cls, name):
206 if not name or name == "last" or name[0] == '.':
207 raise KeyError("invalid profile name: " + name)
208 ret = cls(pj(basedir, name))
209 ret.name = name
210 return ret
211
212 @classmethod
213 def last(cls):
214 if not os.path.exists(pj(basedir, "last")):
215 raise KeyError("there is no last used profile")
216 with open(pj(basedir, "last")) as f:
217 return cls.byname(f.readline().strip())