0f2510dd544218279d8ddcaa1beae3ad097d631c
[fanfix.git] / src / be / nikiroo / fanfix / library / WebLibrary.java
1 package be.nikiroo.fanfix.library;
2
3 import java.io.File;
4 import java.io.IOException;
5 import java.io.InputStream;
6 import java.net.URL;
7 import java.util.ArrayList;
8 import java.util.HashMap;
9 import java.util.List;
10 import java.util.Map;
11
12 import org.json.JSONArray;
13 import org.json.JSONObject;
14
15 import be.nikiroo.fanfix.Instance;
16 import be.nikiroo.fanfix.data.Chapter;
17 import be.nikiroo.fanfix.data.JsonIO;
18 import be.nikiroo.fanfix.data.MetaData;
19 import be.nikiroo.fanfix.data.Paragraph;
20 import be.nikiroo.fanfix.data.Paragraph.ParagraphType;
21 import be.nikiroo.fanfix.data.Story;
22 import be.nikiroo.utils.IOUtils;
23 import be.nikiroo.utils.Image;
24 import be.nikiroo.utils.Progress;
25 import be.nikiroo.utils.Version;
26
27 /**
28 * This {@link BasicLibrary} will access a remote server to list the available
29 * stories, and download the ones you try to load to the local directory
30 * specified in the configuration.
31 * <p>
32 * This remote library uses http:// or https://.
33 *
34 * @author niki
35 */
36 public class WebLibrary extends BasicLibrary {
37 private String host;
38 private int port;
39 private final String key;
40 private final String subkey;
41
42 // informative only (server will make the actual checks)
43 private boolean rw;
44
45 /**
46 * Create a {@link RemoteLibrary} linked to the given server.
47 * <p>
48 * Note that the key is structured:
49 * <tt><b><i>xxx</i></b>(|<b><i>yyy</i></b>|<b>wl</b>)(|<b>rw</b>)</tt>
50 * <p>
51 * Note that anything before the first pipe (<tt>|</tt>) character is
52 * considered to be the encryption key, anything after that character is
53 * called the subkey (including the other pipe characters and flags!).
54 * <p>
55 * This is important because the subkey (including the pipe characters and
56 * flags) must be present as-is in the server configuration file to be
57 * allowed.
58 * <ul>
59 * <li><b><i>xxx</i></b>: the encryption key used to communicate with the
60 * server</li>
61 * <li><b><i>yyy</i></b>: the secondary key</li>
62 * <li><b>rw</b>: flag to allow read and write access if it is not the
63 * default on this server</li>
64 * <li><b>wl</b>: flag to allow access to all the stories (bypassing the
65 * whitelist if it exists)</li>
66 * </ul>
67 * <p>
68 * Some examples:
69 * <ul>
70 * <li><b>my_key</b>: normal connection, will take the default server
71 * options</li>
72 * <li><b>my_key|agzyzz|wl</b>: will ask to bypass the white list (if it
73 * exists)</li>
74 * <li><b>my_key|agzyzz|rw</b>: will ask read-write access (if the default
75 * is read-only)</li>
76 * <li><b>my_key|agzyzz|wl|rw</b>: will ask both read-write access and white
77 * list bypass</li>
78 * </ul>
79 *
80 * @param key
81 * the key that will allow us to exchange information with the
82 * server
83 * @param host
84 * the host to contact or NULL for localhost
85 * @param port
86 * the port to contact it on
87 */
88 public WebLibrary(String key, String host, int port) {
89 int index = -1;
90 if (key != null) {
91 index = key.indexOf('|');
92 }
93
94 if (index >= 0) {
95 this.key = key.substring(0, index);
96 this.subkey = key.substring(index + 1);
97 } else {
98 this.key = key;
99 this.subkey = "";
100 }
101
102 this.rw = subkey.contains("|rw");
103
104 this.host = host;
105 this.port = port;
106 }
107
108 /**
109 * Return the version of the program running server-side.
110 * <p>
111 * Never returns NULL.
112 *
113 * @return the version or an empty {@link Version} if not known
114 */
115 public Version getVersion() {
116 try {
117 InputStream in = post(WebLibraryUrls.VERSION_URL);
118 try {
119 return new Version(IOUtils.readSmallStream(in));
120 } finally {
121 in.close();
122 }
123 } catch (IOException e) {
124 }
125
126 return new Version();
127 }
128
129 /**
130 * Stop the server.
131 *
132 * @throws IOException
133 * in case of I/O errors
134 */
135 public void stop() throws IOException {
136 try {
137 post(WebLibraryUrls.EXIT_URL, null).close();
138 } catch (Exception e) {
139 try {
140 Thread.sleep(200);
141 } catch (InterruptedException e1) {
142 }
143 if (getStatus() != Status.UNAVAILABLE) {
144 throw new IOException("Cannot exit the library", e);
145 }
146 }
147 }
148
149 @Override
150 public Status getStatus() {
151 try {
152 post(WebLibraryUrls.INDEX_URL).close();
153 } catch (IOException e) {
154 try {
155 post("/style.css").close();
156 return Status.UNAUTHORIZED;
157 } catch (IOException ioe) {
158 return Status.UNAVAILABLE;
159 }
160 }
161
162 return rw ? Status.READ_WRITE : Status.READ_ONLY;
163 }
164
165 @Override
166 public String getLibraryName() {
167 return (rw ? "[READ-ONLY] " : "") + host + ":" + port + " ("
168 + getVersion() + ")";
169 }
170
171 @Override
172 public Image getCover(String luid) throws IOException {
173 InputStream in = post(WebLibraryUrls.getStoryUrlCover(luid));
174 try {
175 Image img = new Image(in);
176 if (img.getSize() > 0) {
177 return img;
178 }
179
180 return null;
181 } finally {
182 in.close();
183 }
184 }
185
186 @Override
187 public Image getCustomSourceCover(String source) throws IOException {
188 InputStream in = post(WebLibraryUrls.getCoverUrlSource(source));
189 try {
190 Image img = new Image(in);
191 if (img.getSize() > 0) {
192 return img;
193 }
194
195 return null;
196 } finally {
197 in.close();
198 }
199 }
200
201 @Override
202 public Image getCustomAuthorCover(String author) throws IOException {
203 InputStream in = post(WebLibraryUrls.getCoverUrlAuthor(author));
204 try {
205 Image img = new Image(in);
206 if (img.getSize() > 0) {
207 return img;
208 }
209
210 return null;
211 } finally {
212 in.close();
213 }
214 }
215
216 @Override
217 public void setSourceCover(String source, String luid) throws IOException {
218 Map<String, String> post = new HashMap<String, String>();
219 post.put("luid", luid);
220 post(WebLibraryUrls.getCoverUrlSource(source), post).close();
221 }
222
223 @Override
224 public void setAuthorCover(String author, String luid) throws IOException {
225 Map<String, String> post = new HashMap<String, String>();
226 post.put("luid", luid);
227 post(WebLibraryUrls.getCoverUrlAuthor(author), post).close();
228 }
229
230 @Override
231 public synchronized Story getStory(final String luid, Progress pg)
232 throws IOException {
233 if (pg == null) {
234 pg = new Progress();
235 }
236
237 Story story;
238 InputStream in = post(WebLibraryUrls.getStoryUrlJson(luid));
239 try {
240 JSONObject json = new JSONObject(IOUtils.readSmallStream(in));
241 story = JsonIO.toStory(json);
242 } finally {
243 in.close();
244 }
245
246 int max = 0;
247 for (Chapter chap : story) {
248 max += chap.getParagraphs().size();
249 }
250 pg.setMinMax(0, max);
251
252 story.getMeta().setCover(getCover(luid));
253 int chapNum = 1;
254 for (Chapter chap : story) {
255 int number = 1;
256 for (Paragraph para : chap) {
257 if (para.getType() == ParagraphType.IMAGE) {
258 InputStream subin = post(
259 WebLibraryUrls.getStoryUrl(luid, chapNum, number));
260 try {
261 Image img = new Image(subin);
262 if (img.getSize() > 0) {
263 para.setContentImage(img);
264 }
265 } finally {
266 subin.close();
267 }
268 }
269
270 pg.add(1);
271 number++;
272 }
273
274 chapNum++;
275 }
276
277 pg.done();
278 return story;
279 }
280
281 @Override
282 protected List<MetaData> getMetas(Progress pg) throws IOException {
283 List<MetaData> metas = new ArrayList<MetaData>();
284 InputStream in = post(WebLibraryUrls.LIST_URL_METADATA);
285 JSONArray jsonArr = new JSONArray(IOUtils.readSmallStream(in));
286 for (int i = 0; i < jsonArr.length(); i++) {
287 JSONObject json = jsonArr.getJSONObject(i);
288 metas.add(JsonIO.toMetaData(json));
289 }
290
291 return metas;
292 }
293
294 @Override
295 // Could work (more slowly) without it
296 public MetaData imprt(final URL url, Progress pg) throws IOException {
297 if (pg == null) {
298 pg = new Progress();
299 }
300
301 // Import the file locally if it is actually a file
302
303 if (url == null || url.getProtocol().equalsIgnoreCase("file")) {
304 return super.imprt(url, pg);
305 }
306
307 // Import it remotely if it is an URL
308
309 try {
310 String luid = null;
311
312 Map<String, String> post = new HashMap<String, String>();
313 post.put("url", url.toString());
314 InputStream in = post(WebLibraryUrls.IMPRT_URL_IMPORT, post);
315 try {
316 luid = IOUtils.readSmallStream(in);
317 } finally {
318 in.close();
319 }
320
321 Progress subPg = null;
322 do {
323 try {
324 Thread.sleep(2000);
325 } catch (InterruptedException e) {
326 }
327
328 in = post(WebLibraryUrls.getImprtProgressUrl(luid));
329 try {
330 subPg = JsonIO.toProgress(
331 new JSONObject(IOUtils.readSmallStream(in)));
332 pg.setName(subPg.getName());
333 pg.setMinMax(subPg.getMin(), subPg.getMax());
334 pg.setProgress(subPg.getProgress());
335 } catch (Exception e) {
336 subPg = null;
337 } finally {
338 in.close();
339 }
340 } while (subPg != null);
341
342 in = post(WebLibraryUrls.getStoryUrlMetadata(luid));
343 try {
344 return JsonIO.toMetaData(
345 new JSONObject(IOUtils.readSmallStream(in)));
346 } finally {
347 in.close();
348 }
349 } finally {
350 pg.done();
351 }
352 }
353
354 @Override
355 // Could work (more slowly) without it
356 protected synchronized void changeSTA(final String luid,
357 final String newSource, final String newTitle,
358 final String newAuthor, Progress pg) throws IOException {
359 MetaData meta = getInfo(luid);
360 if (meta != null) {
361 if (!meta.getSource().equals(newSource)) {
362 Map<String, String> post = new HashMap<String, String>();
363 post.put("value", newSource);
364 post(WebLibraryUrls.getStoryUrlSource(luid), post).close();
365 }
366 if (!meta.getTitle().equals(newTitle)) {
367 Map<String, String> post = new HashMap<String, String>();
368 post.put("value", newTitle);
369 post(WebLibraryUrls.getStoryUrlTitle(luid), post).close();
370 }
371 if (!meta.getAuthor().equals(newAuthor)) {
372 Map<String, String> post = new HashMap<String, String>();
373 post.put("value", newAuthor);
374 post(WebLibraryUrls.getStoryUrlAuthor(luid), post).close();
375 }
376 }
377 }
378
379 @Override
380 public synchronized void delete(String luid) throws IOException {
381 post(WebLibraryUrls.getDeleteUrlStory(luid), null).close();
382 }
383
384 @Override
385 protected void updateInfo(MetaData meta) {
386 // Will be taken care of directly server side
387 }
388
389 @Override
390 protected void invalidateInfo(String luid) {
391 // Will be taken care of directly server side
392 }
393
394 // The following methods are only used by Save and Delete in BasicLibrary:
395
396 @Override
397 protected String getNextId() {
398 throw new java.lang.InternalError("Should not have been called");
399 }
400
401 @Override
402 protected void doDelete(String luid) throws IOException {
403 throw new java.lang.InternalError("Should not have been called");
404 }
405
406 @Override
407 protected Story doSave(Story story, Progress pg) throws IOException {
408 throw new java.lang.InternalError("Should not have been called");
409 }
410
411 //
412
413 @Override
414 public File getFile(final String luid, Progress pg) {
415 throw new java.lang.InternalError(
416 "Operation not supportorted on remote Libraries");
417 }
418
419 // starts with "/", never NULL
420 private InputStream post(String path) throws IOException {
421 return post(path, null);
422 }
423
424 // starts with "/", never NULL
425 private InputStream post(String path, Map<String, String> post)
426 throws IOException {
427 URL url = new URL(host + ":" + port + path);
428
429 if (post == null) {
430 post = new HashMap<String, String>();
431 }
432 post.put("login", subkey);
433 post.put("password", key);
434
435 return Instance.getInstance().getCache().openNoCache(url, null, post,
436 null, null);
437 }
438 }