1 package be
.nikiroo
.fanfix
;
3 import java
.io
.BufferedOutputStream
;
5 import java
.io
.FileInputStream
;
6 import java
.io
.FileOutputStream
;
7 import java
.io
.IOException
;
8 import java
.io
.InputStream
;
9 import java
.net
.CookieHandler
;
10 import java
.net
.CookieManager
;
11 import java
.net
.CookiePolicy
;
12 import java
.net
.CookieStore
;
13 import java
.net
.HttpCookie
;
14 import java
.net
.HttpURLConnection
;
15 import java
.net
.URISyntaxException
;
17 import java
.net
.URLConnection
;
18 import java
.util
.Date
;
20 import java
.util
.zip
.GZIPInputStream
;
22 import javax
.imageio
.ImageIO
;
24 import be
.nikiroo
.fanfix
.bundles
.Config
;
25 import be
.nikiroo
.fanfix
.supported
.BasicSupport
;
26 import be
.nikiroo
.utils
.IOUtils
;
27 import be
.nikiroo
.utils
.MarkableFileInputStream
;
30 * This cache will manage Internet (and local) downloads, as well as put the
31 * downloaded files into a cache.
33 * As long the cached resource is not too old, it will use it instead of
34 * retrieving the file again.
41 private long tooOldChanging
;
42 private long tooOldStable
;
43 private CookieManager cookies
;
46 * Create a new {@link Cache} object.
49 * the directory to use as cache
51 * the User-Agent to use to download the resources
52 * @param hoursChanging
53 * the number of hours after which a cached file that is thought
54 * to change ~often is considered too old (or -1 for
57 * the number of hours after which a LARGE cached file that is
58 * thought to change rarely is considered too old (or -1 for
62 * in case of I/O error
64 public Cache(File dir
, String UA
, int hoursChanging
, int hoursStable
)
68 this.tooOldChanging
= 1000 * 60 * 60 * hoursChanging
;
69 this.tooOldStable
= 1000 * 60 * 60 * hoursStable
;
77 if (dir
== null || !dir
.exists()) {
78 throw new IOException("Cannot create the cache directory: "
79 + (dir
== null ?
"null" : dir
.getAbsolutePath()));
82 cookies
= new CookieManager();
83 cookies
.setCookiePolicy(CookiePolicy
.ACCEPT_ALL
);
84 CookieHandler
.setDefault(cookies
);
88 * Open a resource (will load it from the cache if possible, or save it into
89 * the cache after downloading if not).
92 * the resource to open
94 * the support to use to download the resource
96 * TRUE for more stable resources, FALSE when they often change
98 * @return the opened resource, NOT NULL
100 * @throws IOException
101 * in case of I/O error
103 public InputStream
open(URL url
, BasicSupport support
, boolean stable
)
105 // MUST NOT return null
106 return open(url
, support
, stable
, url
);
110 * Open a resource (will load it from the cache if possible, or save it into
111 * the cache after downloading if not).
113 * The cached resource will be assimilated to the given original {@link URL}
116 * the resource to open
118 * the support to use to download the resource
120 * TRUE for more stable resources, FALSE when they often change
122 * the original {@link URL} used to locate the cached resource
124 * @return the opened resource, NOT NULL
126 * @throws IOException
127 * in case of I/O error
129 public InputStream
open(URL url
, BasicSupport support
, boolean stable
,
130 URL originalUrl
) throws IOException
{
131 // MUST NOT return null
133 InputStream in
= load(originalUrl
, false, stable
);
136 save(url
, support
, originalUrl
);
137 } catch (IOException e
) {
138 throw new IOException("Cannot save the url: "
139 + (url
== null ?
"null" : url
.toString()), e
);
142 // Was just saved, can load old, so, will not be null
143 in
= load(originalUrl
, true, stable
);
147 } catch (IOException e
) {
148 throw new IOException("Cannot open the url: "
149 + (url
== null ?
"null" : url
.toString()), e
);
154 * Refresh the resource into cache if needed.
157 * the resource to open
159 * the support to use to download the resource
161 * TRUE for more stable resources, FALSE when they often change
163 * @throws IOException
164 * in case of I/O error
166 public void refresh(URL url
, BasicSupport support
, boolean stable
)
168 File cached
= getCached(url
);
169 if (cached
.exists() && !isOld(cached
, stable
)) {
173 open(url
, support
, stable
).close();
177 * Check the resource to see if it is in the cache.
180 * the resource to check
182 * @return TRUE if it is
185 public boolean check(URL url
) {
186 return getCached(url
).exists();
190 * Open a resource (will load it from the cache if possible, or save it into
191 * the cache after downloading if not) as an Image, then save it where
194 * This version will not always work properly if the original file was not
198 * the resource to open
200 * @return the opened resource image
202 * @throws IOException
203 * in case of I/O error
205 public void saveAsImage(URL url
, File target
) throws IOException
{
206 URL cachedUrl
= new URL(url
.toString());
207 File cached
= getCached(cachedUrl
);
209 if (!cached
.exists() || isOld(cached
, true)) {
210 InputStream imageIn
= open(url
, null, true);
211 ImageIO
.write(IOUtils
.toImage(imageIn
), Instance
.getConfig()
212 .getString(Config
.IMAGE_FORMAT_CONTENT
).toLowerCase(),
216 IOUtils
.write(new FileInputStream(cached
), target
);
220 * Manually add this item to the cache.
225 * a unique ID for this resource
227 * @return the resulting {@link File}
229 * @throws IOException
230 * in case of I/O error
232 public File
addToCache(InputStream in
, String uniqueID
) throws IOException
{
233 File file
= getCached(new File(uniqueID
).toURI().toURL());
234 IOUtils
.write(in
, file
);
239 * Clean the cache (delete the cached items).
242 * only clean the files that are considered too old
244 * @return the number of cleaned items
246 public int cleanCache(boolean onlyOld
) {
248 for (File file
: dir
.listFiles()) {
249 if (!onlyOld
|| isOld(file
, true)) {
253 System
.err
.println("Cannot delete temporary file: "
254 + file
.getAbsolutePath());
262 * Open a resource from the cache if it exists.
265 * the resource to open
267 * @return the opened resource if found, NULL i not
269 * @throws IOException
270 * in case of I/O error
272 private InputStream
load(URL url
, boolean allowOld
, boolean stable
)
274 File cached
= getCached(url
);
275 if (cached
.exists() && !isOld(cached
, stable
)) {
276 return new MarkableFileInputStream(new FileInputStream(cached
));
283 * Save the given resource to the cache.
288 * the {@link BasicSupport} used to download it
290 * the original {@link URL} used to locate the cached resource
292 * @throws IOException
293 * in case of I/O error
294 * @throws URISyntaxException
296 private void save(URL url
, BasicSupport support
, URL originalUrl
)
298 URLConnection conn
= url
.openConnection();
300 conn
.setRequestProperty("User-Agent", UA
);
301 conn
.setRequestProperty("Cookie", generateCookies(support
));
302 conn
.setRequestProperty("Accept-Encoding", "gzip");
303 if (support
!= null && support
.getCurrentReferer() != null) {
304 conn
.setRequestProperty("Referer", support
.getCurrentReferer()
306 conn
.setRequestProperty("Host", support
.getCurrentReferer()
313 if (conn
instanceof HttpURLConnection
314 && ((HttpURLConnection
) conn
).getResponseCode() / 100 == 3) {
315 String newUrl
= conn
.getHeaderField("Location");
316 save(new URL(newUrl
), support
, originalUrl
);
320 InputStream in
= conn
.getInputStream();
321 if ("gzip".equals(conn
.getContentEncoding())) {
322 in
= new GZIPInputStream(in
);
326 File cached
= getCached(originalUrl
);
327 BufferedOutputStream out
= new BufferedOutputStream(
328 new FileOutputStream(cached
));
330 byte[] buf
= new byte[4096];
332 while ((len
= in
.read(buf
)) > 0) {
333 out
.write(buf
, 0, len
);
344 * Check if the {@link File} is too old according to
345 * {@link Cache#tooOldChanging}.
350 * TRUE to denote files that are not supposed to change too often
352 * @return TRUE if it is
354 private boolean isOld(File file
, boolean stable
) {
355 long max
= tooOldChanging
;
364 long time
= new Date().getTime() - file
.lastModified();
366 System
.err
.println("Timestamp in the future for file: "
367 + file
.getAbsolutePath());
370 return time
< 0 || time
> max
;
374 * Get the cache resource from the cache if it is present for this
379 * @return the cached version if present, NULL if not
381 private File
getCached(URL url
) {
382 String name
= url
.getHost();
383 if (name
== null || name
.length() == 0) {
384 name
= url
.getFile();
386 name
= url
.toString();
389 name
= name
.replace('/', '_').replace(':', '_');
391 return new File(dir
, name
);
395 * Generate the cookie {@link String} from the local {@link CookieStore} so
396 * it is ready to be passed.
400 private String
generateCookies(BasicSupport support
) {
401 StringBuilder builder
= new StringBuilder();
402 for (HttpCookie cookie
: cookies
.getCookieStore().getCookies()) {
403 if (builder
.length() > 0) {
407 // TODO: check if format is ok
408 builder
.append(cookie
.toString());
411 if (support
!= null) {
412 for (Map
.Entry
<String
, String
> set
: support
.getCookies()
414 if (builder
.length() > 0) {
417 builder
.append(set
.getKey());
419 builder
.append(set
.getValue());
423 return builder
.toString();