~electric/shop-oregon-local

ref: 3cebeff497d3f7fd2a451c28eba3584357d11ed3 shop-oregon-local/lib/shop_local/clothing_tree_search_provider.ex -rw-r--r-- 2.2 KiB
3cebeff4Micah D Add static stuff.. probably shouldnt commit all this 5 months ago
                                                                                
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
defmodule ShopLocal.ClothingTreeSearchProvider do
  import ShopLocal.SearchProvider

  def search(name, s, opts \\ []) do
    search_with_cache(name, s, &fetch/1, opts)
  end

  def fetch(s) do
    case HTTPoison.get("https://www.clothes-tree.com/search?q=#{s}") do
      {:ok, %HTTPoison.Response{status_code: 200, body: body}} ->
        {:ok, document} = Floki.parse_document(body)
        results = document
                  |> Floki.find(".main-content .product-item")
                  |> Enum.map(fn (k) -> 
                    name = k
                           |> Floki.find(".product-item__title") 
                           |> Floki.text
                    link = k
                           |> Floki.find("a.product-item__link") 
                           |> Floki.attribute("href")
                    image_src = k
                                |> Floki.find("img.product-item__image")
                                |> Floki.attribute("src")
                                |> List.first

                    price = case Floki.find(k, ".product-item__meta__inner p:last-child") do
                      [{_tag, _attrs, price_children}] ->
                        price_parts =price_children
                                     |> List.last
                                     |> String.trim 
                                     |> String.replace("$", "") |> Float.parse

                        case price_parts do
                          {res, _} -> res
                          :error -> nil
                        end
                      _ -> nil
                    end

                      %{
                        provider: "Clothes Tree",
                        name: name,
                        desc: "",
                        price: price,
                        link: link,
                        image_src: image_src
                      } 
                  end)
                  |> Enum.filter(fn 
                    %{ name: "" } -> false
                    _ -> true
                  end)
        {:ok, results}
        {:ok, %HTTPoison.Response{status_code: 404}} ->
        {:error, "Not found." }
        {:error, %HTTPoison.Error{reason: reason}} ->
        {:error, reason}
    end
  end
end