1package com.bumptech.glide.load.model.stream;
2
3import android.content.Context;
4import com.bumptech.glide.Glide;
5import com.bumptech.glide.load.model.ModelCache;
6import com.bumptech.glide.load.model.GlideUrl;
7import com.bumptech.glide.load.model.ModelLoader;
8import com.bumptech.glide.load.data.DataFetcher;
9
10import java.io.InputStream;
11
12/**
13 * A base class for loading images over http/https. Can be subclassed for use with any model that can be translated
14 * in to an image.
15 *
16 * @param <T> The type of the model
17 */
18public abstract class BaseGlideUrlLoader<T> implements StreamModelLoader<T> {
19    private final ModelLoader<GlideUrl, InputStream> concreteLoader;
20    private final ModelCache<T, GlideUrl> modelCache;
21
22    public BaseGlideUrlLoader(Context context) {
23        this(context, null);
24    }
25
26    public BaseGlideUrlLoader(Context context, ModelCache<T, GlideUrl> modelCache) {
27        this(Glide.buildModelLoader(GlideUrl.class, InputStream.class, context), modelCache);
28    }
29
30    @SuppressWarnings("unused")
31    public BaseGlideUrlLoader(ModelLoader<GlideUrl, InputStream> concreteLoader) {
32        this(concreteLoader, null);
33    }
34
35    public BaseGlideUrlLoader(ModelLoader<GlideUrl, InputStream> concreteLoader, ModelCache<T, GlideUrl> modelCache) {
36        this.concreteLoader = concreteLoader;
37        this.modelCache = modelCache;
38    }
39
40    @Override
41    public DataFetcher<InputStream> getResourceFetcher(T model, int width, int height) {
42        GlideUrl result = null;
43        if (modelCache != null) {
44            result = modelCache.get(model, width, height);
45        }
46
47        if (result == null) {
48            String stringURL = getUrl(model, width, height);
49            result = new GlideUrl(stringURL);
50
51            if (modelCache != null) {
52                modelCache.put(model, width, height, result);
53            }
54        }
55
56        return concreteLoader.getResourceFetcher(result, width, height);
57    }
58
59    /**
60     * Get a valid url http:// or https:// for the given model and dimensions as a string
61     *
62     * @param model The model
63     * @param width The width of the view/target the image will be loaded into
64     * @param height The height of the view/target the image will be loaded into
65     * @return The String url
66     */
67    protected abstract String getUrl(T model, int width, int height);
68}
69