e621: woopsie
[fanfix.git] / reader / BasicReader.java
... / ...
CommitLineData
1package be.nikiroo.fanfix.reader;
2
3import java.io.File;
4import java.io.IOException;
5import java.net.MalformedURLException;
6import java.net.URL;
7import java.text.ParseException;
8import java.text.SimpleDateFormat;
9import java.util.Date;
10import java.util.Map;
11import java.util.TreeMap;
12
13import be.nikiroo.fanfix.Instance;
14import be.nikiroo.fanfix.bundles.Config;
15import be.nikiroo.fanfix.bundles.UiConfig;
16import be.nikiroo.fanfix.data.MetaData;
17import be.nikiroo.fanfix.data.Story;
18import be.nikiroo.fanfix.library.BasicLibrary;
19import be.nikiroo.fanfix.library.LocalLibrary;
20import be.nikiroo.fanfix.supported.BasicSupport;
21import be.nikiroo.utils.Progress;
22import be.nikiroo.utils.StringUtils;
23import be.nikiroo.utils.serial.SerialUtils;
24
25/**
26 * The class that handles the different {@link Story} readers you can use.
27 * <p>
28 * All the readers should be accessed via {@link BasicReader#getReader()}.
29 *
30 * @author niki
31 */
32public abstract class BasicReader implements Reader {
33 private static BasicLibrary defaultLibrary = Instance.getInstance().getLibrary();
34 private static ReaderType defaultType = ReaderType.GUI;
35
36 private BasicLibrary lib;
37 private MetaData meta;
38 private Story story;
39 private int chapter;
40
41 /**
42 * Take the default reader type configuration from the config file.
43 */
44 static {
45 String typeString = Instance.getInstance().getConfig().getString(Config.READER_TYPE);
46 if (typeString != null && !typeString.isEmpty()) {
47 try {
48 ReaderType type = ReaderType.valueOf(typeString.toUpperCase());
49 defaultType = type;
50 } catch (IllegalArgumentException e) {
51 // Do nothing
52 }
53 }
54 }
55
56 @Override
57 public synchronized Story getStory(Progress pg) throws IOException {
58 if (story == null) {
59 story = getLibrary().getStory(meta.getLuid(), pg);
60 }
61
62 return story;
63 }
64
65 @Override
66 public BasicLibrary getLibrary() {
67 if (lib == null) {
68 lib = defaultLibrary;
69 }
70
71 return lib;
72 }
73
74 @Override
75 public void setLibrary(BasicLibrary lib) {
76 this.lib = lib;
77 }
78
79 @Override
80 public synchronized MetaData getMeta() {
81 return meta;
82 }
83
84 @Override
85 public synchronized void setMeta(MetaData meta) throws IOException {
86 setMeta(meta == null ? null : meta.getLuid()); // must check the library
87 }
88
89 @Override
90 public synchronized void setMeta(String luid) throws IOException {
91 story = null;
92 meta = getLibrary().getInfo(luid);
93
94 if (meta == null) {
95 throw new IOException("Cannot retrieve story from library: " + luid);
96 }
97 }
98
99 @Override
100 public synchronized void setMeta(URL url, Progress pg) throws IOException {
101 BasicSupport support = BasicSupport.getSupport(url);
102 if (support == null) {
103 throw new IOException("URL not supported: " + url.toString());
104 }
105
106 story = support.process(pg);
107 if (story == null) {
108 throw new IOException(
109 "Cannot retrieve story from external source: "
110 + url.toString());
111 }
112
113 meta = story.getMeta();
114 }
115
116 @Override
117 public int getChapter() {
118 return chapter;
119 }
120
121 @Override
122 public void setChapter(int chapter) {
123 this.chapter = chapter;
124 }
125
126 /**
127 * Return a new {@link BasicReader} ready for use if one is configured.
128 * <p>
129 * Can return NULL if none are configured.
130 *
131 * @return a {@link BasicReader}, or NULL if none configured
132 */
133 public static Reader getReader() {
134 try {
135 if (defaultType != null) {
136 return (Reader) SerialUtils.createObject(defaultType
137 .getTypeName());
138 }
139 } catch (Exception e) {
140 Instance.getInstance().getTraceHandler()
141 .error(new Exception("Cannot create a reader of type: " + defaultType + " (Not compiled in?)", e));
142 }
143
144 return null;
145 }
146
147 /**
148 * The default {@link Reader.ReaderType} used when calling
149 * {@link BasicReader#getReader()}.
150 *
151 * @return the default type
152 */
153 public static ReaderType getDefaultReaderType() {
154 return defaultType;
155 }
156
157 /**
158 * The default {@link Reader.ReaderType} used when calling
159 * {@link BasicReader#getReader()}.
160 *
161 * @param defaultType
162 * the new default type
163 */
164 public static void setDefaultReaderType(ReaderType defaultType) {
165 BasicReader.defaultType = defaultType;
166 }
167
168 /**
169 * Change the default {@link LocalLibrary} to open with the
170 * {@link BasicReader}s.
171 *
172 * @param lib
173 * the new {@link LocalLibrary}
174 */
175 public static void setDefaultLibrary(BasicLibrary lib) {
176 BasicReader.defaultLibrary = lib;
177 }
178
179 /**
180 * Return an {@link URL} from this {@link String}, be it a file path or an
181 * actual {@link URL}.
182 *
183 * @param sourceString
184 * the source
185 *
186 * @return the corresponding {@link URL}
187 *
188 * @throws MalformedURLException
189 * if this is neither a file nor a conventional {@link URL}
190 */
191 public static URL getUrl(String sourceString) throws MalformedURLException {
192 if (sourceString == null || sourceString.isEmpty()) {
193 throw new MalformedURLException("Empty url");
194 }
195
196 URL source = null;
197 try {
198 source = new URL(sourceString);
199 } catch (MalformedURLException e) {
200 File sourceFile = new File(sourceString);
201 source = sourceFile.toURI().toURL();
202 }
203
204 return source;
205 }
206
207 /**
208 * Describe a {@link Story} from its {@link MetaData} and return a list of
209 * title/value that represent this {@link Story}.
210 *
211 * @param meta
212 * the {@link MetaData} to represent
213 *
214 * @return the information
215 */
216 public static Map<String, String> getMetaDesc(MetaData meta) {
217 Map<String, String> metaDesc = new TreeMap<String, String>();
218
219 // TODO: i18n
220
221 StringBuilder tags = new StringBuilder();
222 for (String tag : meta.getTags()) {
223 if (tags.length() > 0) {
224 tags.append(", ");
225 }
226 tags.append(tag);
227 }
228
229 // TODO: i18n
230 metaDesc.put("Author", meta.getAuthor());
231 metaDesc.put("Publication date", formatDate(meta.getDate()));
232 metaDesc.put("Published on", meta.getPublisher());
233 metaDesc.put("URL", meta.getUrl());
234 String count = "";
235 if (meta.getWords() > 0) {
236 count = StringUtils.formatNumber(meta.getWords());
237 }
238 if (meta.isImageDocument()) {
239 metaDesc.put("Number of images", count);
240 } else {
241 metaDesc.put("Number of words", count);
242 }
243 metaDesc.put("Source", meta.getSource());
244 metaDesc.put("Subject", meta.getSubject());
245 metaDesc.put("Language", meta.getLang());
246 metaDesc.put("Tags", tags.toString());
247
248 return metaDesc;
249 }
250
251 /**
252 * Open the {@link Story} with an external reader (the program will be
253 * passed the main file associated with this {@link Story}).
254 *
255 * @param lib
256 * the {@link BasicLibrary} to select the {@link Story} from
257 * @param luid
258 * the {@link Story} LUID
259 * @param sync
260 * execute the process synchronously (wait until it is terminated
261 * before returning)
262 *
263 * @throws IOException
264 * in case of I/O error
265 */
266 @Override
267 public void openExternal(BasicLibrary lib, String luid, boolean sync)
268 throws IOException {
269 MetaData meta = lib.getInfo(luid);
270 File target = lib.getFile(luid, null);
271
272 openExternal(meta, target, sync);
273 }
274
275 /**
276 * Open the {@link Story} with an external reader (the program will be
277 * passed the given target file).
278 *
279 * @param meta
280 * the {@link Story} to load
281 * @param target
282 * the target {@link File}
283 * @param sync
284 * execute the process synchronously (wait until it is terminated
285 * before returning)
286 *
287 * @throws IOException
288 * in case of I/O error
289 */
290 protected void openExternal(MetaData meta, File target, boolean sync)
291 throws IOException {
292 String program = null;
293 if (meta.isImageDocument()) {
294 program = Instance.getInstance().getUiConfig().getString(UiConfig.IMAGES_DOCUMENT_READER);
295 } else {
296 program = Instance.getInstance().getUiConfig().getString(UiConfig.NON_IMAGES_DOCUMENT_READER);
297 }
298
299 if (program != null && program.trim().isEmpty()) {
300 program = null;
301 }
302
303 start(target, program, sync);
304 }
305
306 /**
307 * Start a file and open it with the given program if given or the first
308 * default system starter we can find.
309 *
310 * @param target
311 * the target to open
312 * @param program
313 * the program to use or NULL for the default system starter
314 * @param sync
315 * execute the process synchronously (wait until it is terminated
316 * before returning)
317 *
318 * @throws IOException
319 * in case of I/O error
320 */
321 protected void start(File target, String program, boolean sync)
322 throws IOException {
323
324 Process proc = null;
325 if (program == null) {
326 boolean ok = false;
327 for (String starter : new String[] { "xdg-open", "open", "see",
328 "start", "run" }) {
329 try {
330 Instance.getInstance().getTraceHandler().trace("starting external program");
331 proc = Runtime.getRuntime().exec(new String[] { starter, target.getAbsolutePath() });
332 ok = true;
333 break;
334 } catch (IOException e) {
335 }
336 }
337 if (!ok) {
338 throw new IOException("Cannot find a program to start the file");
339 }
340 } else {
341 Instance.getInstance().getTraceHandler().trace("starting external program");
342 proc = Runtime.getRuntime().exec(
343 new String[] { program, target.getAbsolutePath() });
344 }
345
346 if (proc != null && sync) {
347 try {
348 proc.waitFor();
349 } catch (InterruptedException e) {
350 }
351 }
352 }
353
354 static private String formatDate(String date) {
355 long ms = 0;
356
357 if (date != null && !date.isEmpty()) {
358 try {
359 ms = StringUtils.toTime(date);
360 } catch (ParseException e) {
361 }
362
363 if (ms <= 0) {
364 SimpleDateFormat sdf = new SimpleDateFormat(
365 "yyyy-MM-dd'T'HH:mm:ssSSS");
366 try {
367 ms = sdf.parse(date).getTime();
368 } catch (ParseException e) {
369 }
370 }
371
372 if (ms > 0) {
373 SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
374 return sdf.format(new Date(ms));
375 }
376 }
377
378 if (date == null) {
379 date = "";
380 }
381
382 // :(
383 return date;
384 }
385}