BVB Source Codes

ForkHub Show HttpImageGetter.java Source code

Return Download ForkHub: download HttpImageGetter.java Source code - Download ForkHub Source code - Type:.java
  1. /*
  2.  * Copyright 2012 GitHub Inc.
  3.  *
  4.  * Licensed under the Apache License, Version 2.0 (the "License");
  5.  * you may not use this file except in compliance with the License.
  6.  * You may obtain a copy of the License at
  7.  *
  8.  *  http://www.apache.org/licenses/LICENSE-2.0
  9.  *
  10.  * Unless required by applicable law or agreed to in writing, software
  11.  * distributed under the License is distributed on an "AS IS" BASIS,
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13.  * See the License for the specific language governing permissions and
  14.  * limitations under the License.
  15.  */
  16. package com.github.mobile.util;
  17.  
  18. import static android.util.Base64.DEFAULT;
  19. import static android.view.View.GONE;
  20. import static android.view.View.VISIBLE;
  21. import static java.lang.Integer.MAX_VALUE;
  22. import static org.eclipse.egit.github.core.client.IGitHubConstants.HOST_DEFAULT;
  23. import android.accounts.Account;
  24. import android.content.Context;
  25. import android.graphics.Bitmap;
  26. import android.graphics.drawable.BitmapDrawable;
  27. import android.graphics.drawable.Drawable;
  28. import android.net.Uri;
  29. import android.text.Html.ImageGetter;
  30. import android.text.TextUtils;
  31. import android.util.Base64;
  32. import android.widget.TextView;
  33.  
  34. import com.github.mobile.R;
  35. import com.github.mobile.accounts.AuthenticatedUserTask;
  36. import com.google.inject.Inject;
  37.  
  38. import java.io.IOException;
  39. import java.util.HashMap;
  40. import java.util.List;
  41. import java.util.Map;
  42.  
  43. import org.eclipse.egit.github.core.RepositoryContents;
  44. import org.eclipse.egit.github.core.RepositoryId;
  45. import org.eclipse.egit.github.core.service.ContentsService;
  46.  
  47. import okhttp3.OkHttpClient;
  48. import okhttp3.Request;
  49. import okhttp3.Response;
  50.  
  51. /**
  52.  * Getter for an image
  53.  */
  54. public class HttpImageGetter implements ImageGetter {
  55.  
  56.     private static class LoadingImageGetter implements ImageGetter {
  57.  
  58.         private final Drawable image;
  59.  
  60.         private LoadingImageGetter(final Context context, final int size) {
  61.             int imageSize = ServiceUtils.getIntPixels(context, size);
  62.             image = context.getResources().getDrawable(R.drawable.image_loading_icon);
  63.             image.setBounds(0, 0, imageSize, imageSize);
  64.         }
  65.  
  66.         @Override
  67.         public Drawable getDrawable(String source) {
  68.             return image;
  69.         }
  70.     }
  71.  
  72.     private static boolean containsImages(final String html) {
  73.         return html.contains("<img");
  74.     }
  75.  
  76.     private final LoadingImageGetter loading;
  77.  
  78.     private final Context context;
  79.  
  80.     private int width;
  81.  
  82.     private final Map<Object, CharSequence> rawHtmlCache = new HashMap<Object, CharSequence>();
  83.  
  84.     private final Map<Object, CharSequence> fullHtmlCache = new HashMap<Object, CharSequence>();
  85.  
  86.     private final ContentsService service;
  87.  
  88.     /**
  89.      * Create image getter for context
  90.      *
  91.      * @param context
  92.      * @param service
  93.      */
  94.     @Inject
  95.     public HttpImageGetter(Context context, ContentsService service) {
  96.         this.context = context;
  97.         this.service = service;
  98.         width = (int) (ServiceUtils.getDisplayWidth(context) * 0.90);
  99.         loading = new LoadingImageGetter(context, 24);
  100.     }
  101.  
  102.     private HttpImageGetter show(final TextView view, final CharSequence html) {
  103.         if (TextUtils.isEmpty(html))
  104.             return hide(view);
  105.  
  106.         view.setText(html);
  107.         view.setVisibility(VISIBLE);
  108.         view.setTag(null);
  109.         return this;
  110.     }
  111.  
  112.     private HttpImageGetter hide(final TextView view) {
  113.         view.setText(null);
  114.         view.setVisibility(GONE);
  115.         view.setTag(null);
  116.         return this;
  117.     }
  118.  
  119.     /**
  120.      * Encode given HTML string and map it to the given id
  121.      *
  122.      * @param id
  123.      * @param html
  124.      * @return this image getter
  125.      */
  126.     public HttpImageGetter encode(final Object id, final String html) {
  127.         if (TextUtils.isEmpty(html))
  128.             return this;
  129.  
  130.         CharSequence encoded = HtmlUtils.encode(html, loading);
  131.         // Use default encoding if no img tags
  132.         if (containsImages(html)) {
  133.             CharSequence currentEncoded = rawHtmlCache.put(id, encoded);
  134.             // Remove full html if raw html has changed
  135.             if (currentEncoded == null
  136.                     || !currentEncoded.toString().equals(encoded.toString()))
  137.                 fullHtmlCache.remove(id);
  138.         } else {
  139.             rawHtmlCache.remove(id);
  140.             fullHtmlCache.put(id, encoded);
  141.         }
  142.         return this;
  143.     }
  144.  
  145.     /**
  146.      * Bind text view to HTML string
  147.      *
  148.      * @param view
  149.      * @param html
  150.      * @param id
  151.      * @return this image getter
  152.      */
  153.     public HttpImageGetter bind(final TextView view, final String html,
  154.             final Object id) {
  155.         if (TextUtils.isEmpty(html))
  156.             return hide(view);
  157.  
  158.         CharSequence encoded = fullHtmlCache.get(id);
  159.         if (encoded != null)
  160.             return show(view, encoded);
  161.  
  162.         encoded = rawHtmlCache.get(id);
  163.         if (encoded == null) {
  164.             encoded = HtmlUtils.encode(html, loading);
  165.             if (containsImages(html))
  166.                 rawHtmlCache.put(id, encoded);
  167.             else {
  168.                 rawHtmlCache.remove(id);
  169.                 fullHtmlCache.put(id, encoded);
  170.                 return show(view, encoded);
  171.             }
  172.         }
  173.  
  174.         if (TextUtils.isEmpty(encoded))
  175.             return hide(view);
  176.  
  177.         show(view, encoded);
  178.         view.setTag(id);
  179.         new AuthenticatedUserTask<CharSequence>(context) {
  180.  
  181.             @Override
  182.             protected CharSequence run(Account account) throws Exception {
  183.                 return HtmlUtils.encode(html, HttpImageGetter.this);
  184.             }
  185.  
  186.             @Override
  187.             protected void onSuccess(final CharSequence html) throws Exception {
  188.                 fullHtmlCache.put(id, html);
  189.  
  190.                 if (id.equals(view.getTag()))
  191.                     show(view, html);
  192.             }
  193.         }.execute();
  194.         return this;
  195.     }
  196.  
  197.     /**
  198.      * Request an image using the contents API if the source URI is a path to a
  199.      * file already in the repository
  200.      *
  201.      * @param source
  202.      * @return
  203.      * @throws IOException
  204.      */
  205.     private Drawable requestRepositoryImage(final String source) throws IOException {
  206.         if (TextUtils.isEmpty(source))
  207.             return null;
  208.  
  209.         Uri uri = Uri.parse(source);
  210.         if (!HOST_DEFAULT.equals(uri.getHost()))
  211.             return null;
  212.  
  213.         List<String> segments = uri.getPathSegments();
  214.         if (segments.size() < 5)
  215.             return null;
  216.  
  217.         String prefix = segments.get(2);
  218.         // Two types of urls supported:
  219.         // github.com/github/android/raw/master/app/res/drawable-xhdpi/app_icon.png
  220.         // github.com/github/android/blob/master/app/res/drawable-xhdpi/app_icon.png?raw=true
  221.         if (!("raw".equals(prefix) || ("blob".equals(prefix) && !TextUtils
  222.                 .isEmpty(uri.getQueryParameter("raw")))))
  223.             return null;
  224.  
  225.         String owner = segments.get(0);
  226.         if (TextUtils.isEmpty(owner))
  227.             return null;
  228.         String name = segments.get(1);
  229.         if (TextUtils.isEmpty(name))
  230.             return null;
  231.         String branch = segments.get(3);
  232.         if (TextUtils.isEmpty(branch))
  233.             return null;
  234.  
  235.         StringBuilder path = new StringBuilder(segments.get(4));
  236.         for (int i = 5; i < segments.size(); i++) {
  237.             String segment = segments.get(i);
  238.             if (!TextUtils.isEmpty(segment))
  239.                 path.append('/').append(segment);
  240.         }
  241.  
  242.         if (TextUtils.isEmpty(path))
  243.             return null;
  244.  
  245.         List<RepositoryContents> contents = service.getContents(
  246.                 RepositoryId.create(owner, name), path.toString(), branch);
  247.         if (contents != null && contents.size() == 1) {
  248.             byte[] content = Base64.decode(contents.get(0).getContent(),
  249.                     DEFAULT);
  250.             Bitmap bitmap = ImageUtils.getBitmap(content, width, MAX_VALUE);
  251.             if (bitmap == null)
  252.                 return loading.getDrawable(source);
  253.             BitmapDrawable drawable = new BitmapDrawable(
  254.                     context.getResources(), bitmap);
  255.             drawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight());
  256.             return drawable;
  257.         } else
  258.             return null;
  259.     }
  260.  
  261.     @Override
  262.     public Drawable getDrawable(final String source) {
  263.         try {
  264.             Drawable repositoryImage = requestRepositoryImage(source);
  265.             if (repositoryImage != null)
  266.                 return repositoryImage;
  267.         } catch (Exception e) {
  268.             // Ignore and attempt request over regular HTTP request
  269.         }
  270.  
  271.         try {
  272.             Request request = new Request.Builder().url(source).build();
  273.             OkHttpClient client = new OkHttpClient();
  274.             Response response = client.newCall(request).execute();
  275.  
  276.             Bitmap bitmap = ImageUtils.getBitmap(response.body().bytes(), width, MAX_VALUE);
  277.             if (bitmap == null)
  278.                 return loading.getDrawable(source);
  279.             BitmapDrawable drawable = new BitmapDrawable(context.getResources(), bitmap);
  280.             drawable.setBounds(0, 0, bitmap.getWidth(), bitmap.getHeight());
  281.             return drawable;
  282.         } catch (IOException e) {
  283.             return loading.getDrawable(source);
  284.         }
  285.     }
  286. }
  287.  
downloadHttpImageGetter.java Source code - Download ForkHub Source code
Related Source Codes/Software:
css-element-queries - CSS-Element-Queries Polyfill. proof-of-concept for... 2017-05-09
shortid - Short id generator. Url-friendly. Non-predictable.... 2017-05-09
philm - Movie collection and information app for Android. 2017-05-09
DIGITS - Deep Learning GPU Training System ... 2017-05-09
skatejs - SkateJS is a web component library designed to giv... 2017-05-09
i18n-js - It's a small library to provide the I18n translati... 2017-05-09
api-standards - 2017-05-09
MiaowShow - IOS video broadcast program 2017-05-09
csscomb.js - CSS coding style formatter (Maintenance) ... 2017-05-09
LocationManager - Easily get the device's current location on iOS. 2017-05-09
CRYENGINE - CRYENGINE is a powerful real-time game development... 2017-06-11
postal - 2017-06-11
reactide - Reactide is the first dedicated IDE for React web ... 2017-06-11
rkt - rkt is a pod-native container engine for Linux. It... 2017-06-11
uWebSockets - Tiny WebSockets https://for... 2017-06-11
realworld - TodoMVC for the RealWorld - Exemplary fullstack Me... 2017-06-11
goreplay - GoReplay is an open-source tool for capturing and ... 2017-06-10
pyenv - Simple Python version management 2017-06-10
redux-saga - An alternative side effect model for Redux apps ... 2017-06-10
angular-starter - 2017-06-10

 Back to top