1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
|
package cgeo.geocaching.network;
import cgeo.geocaching.CgeoApplication;
import cgeo.geocaching.R;
import cgeo.geocaching.compatibility.Compatibility;
import cgeo.geocaching.connector.ConnectorFactory;
import cgeo.geocaching.files.LocalStorage;
import cgeo.geocaching.list.StoredList;
import cgeo.geocaching.utils.CancellableHandler;
import cgeo.geocaching.utils.FileUtils;
import cgeo.geocaching.utils.ImageUtils;
import cgeo.geocaching.utils.Log;
import ch.boye.httpclientandroidlib.HttpResponse;
import ch.boye.httpclientandroidlib.androidextra.Base64;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.eclipse.jdt.annotation.Nullable;
import rx.Observable;
import rx.Observable.OnSubscribeFunc;
import rx.Observer;
import rx.Scheduler;
import rx.Subscription;
import rx.schedulers.Schedulers;
import rx.subjects.PublishSubject;
import rx.subscriptions.CompositeSubscription;
import rx.subscriptions.Subscriptions;
import rx.util.functions.Func1;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Point;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.text.Html;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
public class HtmlImage implements Html.ImageGetter {
private static final String[] BLOCKED = new String[] {
"gccounter.de",
"gccounter.com",
"cachercounter/?",
"gccounter/imgcount.php",
"flagcounter.com",
"compteur-blog.net",
"counter.digits.com",
"andyhoppe",
"besucherzaehler-homepage.de",
"hitwebcounter.com",
"kostenloser-counter.eu",
"trendcounter.com",
"hit-counter-download.com",
"gcwetterau.de/counter"
};
public static final String SHARED = "shared";
final private String geocode;
/**
* on error: return large error image, if <code>true</code>, otherwise empty 1x1 image
*/
final private boolean returnErrorImage;
final private int listId;
final private boolean onlySave;
final private int maxWidth;
final private int maxHeight;
final private Resources resources;
// Background loading
final private PublishSubject<Observable<String>> loading = PublishSubject.create();
final Observable<String> waitForEnd = Observable.merge(loading).publish().refCount();
final CompositeSubscription subscription = new CompositeSubscription(waitForEnd.subscribe());
final private Scheduler downloadScheduler = Schedulers.executor(new ThreadPoolExecutor(5, 5, 5, TimeUnit.SECONDS,
new LinkedBlockingQueue<Runnable>()));
final private Set<String> downloading = new HashSet<String>();
public HtmlImage(final String geocode, final boolean returnErrorImage, final int listId, final boolean onlySave) {
this.geocode = geocode;
this.returnErrorImage = returnErrorImage;
this.listId = listId;
this.onlySave = onlySave;
Point displaySize = Compatibility.getDisplaySize();
this.maxWidth = displaySize.x - 25;
this.maxHeight = displaySize.y - 25;
this.resources = CgeoApplication.getInstance().getResources();
}
@Nullable
@Override
public BitmapDrawable getDrawable(final String url) {
if (!onlySave) {
return loadDrawable(url);
}
synchronized (downloading) {
if (!downloading.contains(url)) {
loading.onNext(fetchDrawable(url).map(new Func1<BitmapDrawable, String>() {
@Override
public String call(final BitmapDrawable bitmapDrawable) {
return url;
}
}));
downloading.add(url);
}
return null;
}
}
public Observable<BitmapDrawable> fetchDrawable(final String url) {
return Observable.create(new OnSubscribeFunc<BitmapDrawable>() {
@Override
public Subscription onSubscribe(final Observer<? super BitmapDrawable> observer) {
if (!subscription.isUnsubscribed()) {
observer.onNext(loadDrawable(url));
}
observer.onCompleted();
return Subscriptions.empty();
}
}).subscribeOn(downloadScheduler);
}
public void waitForBackgroundLoading(@Nullable final CancellableHandler handler) {
if (handler != null) {
handler.unsubscribeIfCancelled(subscription);
}
loading.onCompleted();
waitForEnd.toBlockingObservable().lastOrDefault(null);
}
private BitmapDrawable loadDrawable(final String url) {
// Reject empty and counter images URL
if (StringUtils.isBlank(url) || isCounter(url)) {
return getTransparent1x1Image(resources);
}
final boolean shared = url.contains("/images/icons/icon_");
final String pseudoGeocode = shared ? SHARED : geocode;
Bitmap image = loadImageFromStorage(url, pseudoGeocode, shared);
// Download image and save it to the cache
if (image == null) {
final File file = LocalStorage.getStorageFile(pseudoGeocode, url, true, true);
if (url.startsWith("data:image/")) {
if (url.contains(";base64,")) {
saveBase64ToFile(url, file);
} else {
Log.e("HtmlImage.getDrawable: unable to decode non-base64 inline image");
return null;
}
} else {
downloadOrRefreshCopy(url, file);
}
}
if (onlySave) {
return null;
}
// now load the newly downloaded image
if (image == null) {
image = loadImageFromStorage(url, pseudoGeocode, shared);
}
// get image and return
if (image == null) {
Log.d("HtmlImage.getDrawable: Failed to obtain image");
return returnErrorImage
? new BitmapDrawable(resources, BitmapFactory.decodeResource(resources, R.drawable.image_not_loaded))
: getTransparent1x1Image(resources);
}
return ImageUtils.scaleBitmapToFitDisplay(image);
}
private void downloadOrRefreshCopy(final String url, final File file) {
final String absoluteURL = makeAbsoluteURL(url);
if (absoluteURL != null) {
try {
final HttpResponse httpResponse = Network.getRequest(absoluteURL, null, file);
if (httpResponse != null) {
final int statusCode = httpResponse.getStatusLine().getStatusCode();
if (statusCode == 200) {
LocalStorage.saveEntityToFile(httpResponse, file);
} else if (statusCode == 304) {
if (!file.setLastModified(System.currentTimeMillis())) {
makeFreshCopy(file);
}
}
}
} catch (Exception e) {
Log.e("HtmlImage.downloadOrRefreshCopy", e);
}
}
}
private static void saveBase64ToFile(final String url, final File file) {
// TODO: when we use SDK level 8 or above, we can use the streaming version of the base64
// Android utilities.
OutputStream out = null;
try {
out = new FileOutputStream(file);
out.write(Base64.decode(StringUtils.substringAfter(url, ";base64,"), Base64.DEFAULT));
} catch (final IOException e) {
Log.e("HtmlImage.saveBase64ToFile: cannot write file for decoded inline image", e);
} finally {
IOUtils.closeQuietly(out);
}
}
/**
* Make a fresh copy of the file to reset its timestamp. On some storage, it is impossible
* to modify the modified time after the fact, in which case a brand new file must be
* created if we want to be able to use the time as validity hint.
*
* See Android issue 1699.
*
* @param file the file to refresh
*/
private static void makeFreshCopy(final File file) {
final File tempFile = new File(file.getParentFile(), file.getName() + "-temp");
if (file.renameTo(tempFile)) {
LocalStorage.copy(tempFile, file);
FileUtils.deleteIgnoringFailure(tempFile);
}
else {
Log.e("Could not reset timestamp of file " + file.getAbsolutePath());
}
}
private BitmapDrawable getTransparent1x1Image(final Resources res) {
return new BitmapDrawable(res, BitmapFactory.decodeResource(resources, R.drawable.image_no_placement));
}
@Nullable
private Bitmap loadImageFromStorage(final String url, final String pseudoGeocode, final boolean forceKeep) {
try {
final File file = LocalStorage.getStorageFile(pseudoGeocode, url, true, false);
final Bitmap image = loadCachedImage(file, forceKeep);
if (image != null) {
return image;
}
final File fileSec = LocalStorage.getStorageSecFile(pseudoGeocode, url, true);
return loadCachedImage(fileSec, forceKeep);
} catch (Exception e) {
Log.w("HtmlImage.loadImageFromStorage", e);
}
return null;
}
@Nullable
private String makeAbsoluteURL(final String url) {
// Check if uri is absolute or not, if not attach the connector hostname
// FIXME: that should also include the scheme
if (Uri.parse(url).isAbsolute()) {
return url;
}
final String host = ConnectorFactory.getConnector(geocode).getHost();
if (StringUtils.isNotEmpty(host)) {
final StringBuilder builder = new StringBuilder("http://");
builder.append(host);
if (!StringUtils.startsWith(url, "/")) {
// FIXME: explain why the result URL would be valid if the path does not start with
// a '/', or signal an error.
builder.append('/');
}
builder.append(url);
return builder.toString();
}
return null;
}
@Nullable
private Bitmap loadCachedImage(final File file, final boolean forceKeep) {
if (file.exists()) {
if (listId >= StoredList.STANDARD_LIST_ID || file.lastModified() > (new Date().getTime() - (24 * 60 * 60 * 1000)) || forceKeep) {
final BitmapFactory.Options bfOptions = new BitmapFactory.Options();
bfOptions.inTempStorage = new byte[16 * 1024];
bfOptions.inPreferredConfig = Bitmap.Config.RGB_565;
setSampleSize(file, bfOptions);
final Bitmap image = BitmapFactory.decodeFile(file.getPath(), bfOptions);
if (image == null) {
Log.e("Cannot decode bitmap from " + file.getPath());
}
return image;
}
}
return null;
}
private void setSampleSize(final File file, final BitmapFactory.Options bfOptions) {
//Decode image size only
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BufferedInputStream stream = null;
try {
stream = new BufferedInputStream(new FileInputStream(file));
BitmapFactory.decodeStream(stream, null, options);
} catch (FileNotFoundException e) {
Log.e("HtmlImage.setSampleSize", e);
} finally {
IOUtils.closeQuietly(stream);
}
int scale = 1;
if (options.outHeight > maxHeight || options.outWidth > maxWidth) {
scale = Math.max(options.outHeight / maxHeight, options.outWidth / maxWidth);
}
bfOptions.inSampleSize = scale;
}
private static boolean isCounter(final String url) {
for (String entry : BLOCKED) {
if (StringUtils.containsIgnoreCase(url, entry)) {
return true;
}
}
return false;
}
}
|