Advertisement
Guest User

Untitled

a guest
Aug 18th, 2017
49
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.23 KB | None | 0 0
  1. package joy.reactor.data.mappers.post
  2.  
  3. import android.text.TextUtils
  4. import joy.reactor.data.enteties.Image
  5. import joy.reactor.data.http.HttpClient
  6. import org.jsoup.nodes.Element
  7. import java.util.*
  8.  
  9. /**
  10.  * Created by omazhukin on 4/14/2016.
  11.  */
  12. class PostImagesThumbnailParser(private val element: Element) {
  13.  
  14.     var imagesList = ArrayList<Image>();
  15.  
  16.     fun getExpandedImages(): MutableList<Image> {
  17.         return imagesList;
  18.     }
  19.  
  20.     fun load(): Image? {
  21.         val imgList = element.getElementsByClass("image")
  22.  
  23.         for (img in imgList) {
  24.             if (img != null) {
  25.                 val gif = GifThumbnailParser(img).load()
  26.                 if (gif != null) {
  27.                     // This prevents from gif losing due to the preview
  28.                     imagesList.add(gif)
  29.                 } else {
  30.                     val imageScr = img.select("a[href] img")
  31.  
  32.                     if (imageScr.isEmpty()) {
  33.                         continue
  34.                     }
  35.  
  36.                     val attr = imageScr.attr("height")
  37.  
  38.                     if (attr.contains("%")) {
  39.                         throw IllegalStateException("Unsupported Height")
  40.                     }
  41.  
  42.                     val height = parseDimen(imageScr[0], "height")
  43.                     val width = parseDimen(imageScr[0], "width");
  44.  
  45.                     imagesList.add(Image(getImageLink(imageScr[0]), width, height))
  46.                 }
  47.             }
  48.         }
  49.  
  50.         if (imagesList.size > 0) {
  51.             return imagesList[0];
  52.         } else {
  53.             return null;
  54.         }
  55.     }
  56.  
  57.     private fun getImageLink(img: Element): String {
  58.         return if (hasFull(img)) {
  59.             img.parent().attr("href").replace("(/full/).+(-\\d+\\.)".toRegex(), "$1$2")
  60.         } else {
  61.             img.attr("src").replace("(/post/).+(-\\d+\\.)".toRegex(), "$1$2")
  62.         }
  63.     }
  64.  
  65.     private fun parseDimen(img: Element, attrName: String): Int {
  66.         val attr = img.attr(attrName)
  67.         if (attr == null || TextUtils.isEmpty(attr)) {
  68.             return 0;
  69.         } else {
  70.             return Integer.parseInt(attr);
  71.         }
  72.     }
  73.  
  74.     private fun hasFull(img: Element): Boolean {
  75.         return "a" == img.parent().tagName()
  76.     }
  77. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement