~weakty/galley

ref: 53abbc5f8302ee5e0dcfb3fecf03baf2d8d9974c galley/lib/mix/tasks/migration_aris.ex -rw-r--r-- 5.9 KiB
53abbc5f — teesloane Fix: only allow users who made recipe to edit ++ a month 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
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
defmodule Mix.Tasks.Db.MigrateAris do
  use Mix.Task

  @requirements ["app.start"]
  @shortdoc "Migrate from Ari's garden"
  @spec run(any) :: any
  def run(_) do
    json_file = Path.join(:code.priv_dir(:galley), "/repo/aris_garden.json")
    me = Galley.Accounts.get_user_by_email("weakty@theiceshelf.com")
    {:ok, json} = get_json(json_file)

    for {slug, recipe_data} <- json["recipes"],
        recipe = ari_to_galley(slug, recipe_data),
        do: insert_recipe(me, recipe)
  end

  defp insert_recipe(me, recipe) do
    case Galley.Recipes.insert_recipe(me, recipe) do
      {:ok, recipe} ->
        {:noreply, recipe}

      {:error, %Ecto.Changeset{} = changeset} ->
        IO.inspect(changeset, label: "error...........")
        {:noreply, changeset}
    end
  end

  def ari_to_galley(slug, ag) do
    %{
      "ingredients" => parse_ingredients(ag["ingredients"]),
      "notes" => "",
      "source" => ag["original_recipe"],
      "steps" => parse_steps(ag["instructions"]),
      "tags" => "#{ag["belongs_to"]}, #{ag["meal_type"]}",
      "time" => parse_timer(ag["time"]),
      "title" => ag["name"],
      "uploaded_images" => parse_images(slug, ag["imgs"]),
      "yields" => parse_yields(ag["serves"])
    }
  end

  defp parse_yields(serves) do
    if String.length(serves) === 1 do
      "#{serves} servings"
    else
        serves
    end

  end

  defp parse_images(slug, ag_imgs) do
    imgs = ag_imgs |> Enum.with_index |> Enum.map(fn {i, _index} ->
      key = "#{slug}-#{i}"
        %{
          "is_hero" => false,
          "key_s3" => key,
          "url" => "https://raw.githubusercontent.com/theiceshelf/arisgarden/master/src/assets/imgs/#{key}"
        }
    end)

    hero_key = "#{slug}-hero.JPG"
    old_hero_img =
        %{
          "is_hero" => true,
          "key_s3" => hero_key,
          "url" => "https://raw.githubusercontent.com/theiceshelf/arisgarden/master/src/assets/imgs/#{hero_key}"
        }
    [old_hero_img | imgs]

  end

  defp parse_steps(ag_steps) do
    for {step, index} <- Enum.with_index(ag_steps),
        {parsed_step, timer_str} = parse_single_step(step),
        into: %{},
        do:
          {index,
           %{
             "instruction" => parsed_step,
             "temp_id" => GalleyUtils.get_temp_id(),
             "timer" => timer_str |> parse_timer
           }}
  end

  # takes a string such as:
  # "[&: 4. Simmer | 00:10:00] Mix the [#: sugar-white | sugar], [#: water | water], [#: salt | salt]
  # and ginger slices and simmer for 10 minutes.
  #
  # and parses out a data structure of:
  # %{
  #   reconstructed_step: "Mix the sugar, water, salt and ginger slices and simmer for 10 minutes",
  #   timer: parse_time
  #   }
  def parse_single_step(step) do
    step_list = step |> String.graphemes()

    step_data =
      Enum.reduce(
        step_list,
        %{
          output: "",
          capturing: false,
          capturing_timer: false,
          capturing_ingredient: false,
          capturing_ingr_string: false,
          timer: ""
        },
        fn item, acc ->
          case item do
            "[" ->
              %{acc | output: acc.output, capturing: true}

            "]" ->
              %{
                acc
                | output: acc.output,
                  capturing: false,
                  capturing_ingredient: false,
                  capturing_ingr_string: false,
                  capturing_timer: false
              }

            "&" ->
              if acc.capturing do
                %{acc | capturing_timer: true}
              else
                acc
              end

            "#" ->
              if acc.capturing do
                %{acc | capturing_ingredient: true}
              else
                acc
              end

            "|" ->
              if acc.capturing && acc.capturing_ingredient do
                %{acc | capturing_ingr_string: true}
              else
                acc
              end

            _ ->
              if acc.capturing do
                cond do
                  acc.capturing_timer -> %{acc | timer: acc.timer <> item}
                  acc.capturing_ingr_string -> %{acc | output: acc.output <> item}
                  acc.capturing_ingredient -> %{acc | output: acc.output}
                  true -> acc
                end
              else
                %{acc | output: acc.output <> item}
              end
          end
        end
      )

    # trim the string, removing any consecutive 2x white space.
    {
      String.trim(step_data.output) |> String.split("  ") |> Enum.join(" "),
      step_data.timer |> String.split() |> List.last()
    }
  end

  defp parse_ingredients(ag_ingrs) do
    for {ingr, index} <- Enum.with_index(ag_ingrs),
        into: %{},
        do:
          {index,
           %{
             "ingredient" => ingr["ingredient"] |> String.downcase(),
             "measurement" => ingr["unit"],
             "quantity" => map_get_string(ingr, "quantity"),
             "temp_id" => GalleyUtils.get_temp_id()
           }}
  end

  defp parse_timer(nil), do: %{"hour" => 0, "minute" => 0}

  defp parse_timer(timer_str) do
    if String.length(timer_str) !== 8 do
      %{"hour" => 0, "minute" => 0}
    else
      timer_ints =
        timer_str
        |> String.split(":")
        |> Enum.map(&Integer.parse/1)
        |> Enum.map(fn i -> elem(i, 0) end)

      # timer_ints
      %{"hour" => Enum.at(timer_ints, 0), "minute" => Enum.at(timer_ints, 1)}
    end
  end

  defp map_get_string(m, k) do
    if Map.get(m, k) === "" do
      "1"
    else
      Map.get(m, k)
    end
  end

  # take the imgs array and construct link to raw jpg on github (for now)
  # and return:
  #
  #   %{
  #     "is_hero" => true,
  #     "key_s3" => "<interpolate>",
  #     "url" => "<github url>"
  #   }
  # defp upload_images() do
  # end

  def get_json(filename) do
    with {:ok, body} <- File.read(filename), {:ok, json} <- Poison.decode(body), do: {:ok, json}
  end
end