9
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

#NervesJPAdvent Calendar 2021

Day 5

日本語で書かれた記事を海外のトモダチに英語で伝えたい

Posted at

はじめに

  • Nerves Newsletter1という全編英語のニュースレターに日本語の記事が取り上げられていました
  • そうだ! 海外のトモダチにJapanにはNervesの記事がありますよ〜 をGoogle translateにURLをくっつけた一覧でお伝えしたいと@kikuyuta 先生が発案されました
  • 一覧にするならタイトルも日本語→英語にしておきたいところです
  • そうだ! Googleスプレッドシートの=googletranslate(A2, "ja", "en")みたいなことをすればいいや!
  • これらをやってみました〜 ということを記事にしてみました
  • この記事は2021/06/26(土) 00:00 〜 2021/06/28(月) 23:59開催のautoracex #34という純粋なもくもく会での成果です

作ってみる

  • https://qiita.com/settings/tokens/new からアクセストークンをつくります
    • read_qiita
  • QIITA_READ環境変数をセットします
  • Elixir 1.12をインストールしておきます

ソースコードを書く

links.exs
# Elixir 1.12 !!!
# usage:
# set QIITA_READ
# $ elixir links.exs
# $ cat output.tsv | pbcopy
# paste Google spread sheet

Mix.install([
  {:httpoison, "~> 1.8"},
  {:jason, "~> 1.2"},
  {:timex, "~> 3.7"},
  {:nimble_csv, "~> 1.1"}
])

defmodule Qiita.Api do
  @token System.get_env("QIITA_READ")
  @headers [
    Authorization: "Bearer #{@token}",
    Accept: "Application/json; Charset=utf-8",
    "Content-Type": "application/json"
  ]
  @options [timeout: 50_000, recv_timeout: 50_000]
  @base_url "https://qiita.com/api/v2"
  @per_page 100

  def items(tags) when is_list(tags) do
    query(tags)
    |> do_items()
  end

  def items(query) when is_bitstring(query) do
    %{"query" => query}
    |> URI.encode_query()
    |> do_items()
  end

  defp do_items(query) do
    total_count(query) |> max_page() |> do_items(query)
  end

  defp do_items(0, _query), do: []

  defp do_items(max_page, query) do
    1..max_page
    |> Enum.reduce([], fn page, acc ->
      "#{@base_url}/items?#{query}&per_page=#{@per_page}&page=#{page}"
      |> HTTPoison.get!(@headers, @options)
      |> Map.get(:body)
      |> Jason.decode()
      |> handle_json_decode()
      |> then(& acc ++ &1)
    end)
  end

  defp query(tags) do
    %{"query" => tags |> Enum.map(&"tag:#{&1}") |> Enum.join(" ")}
    |> URI.encode_query()
  end

  defp total_count(query) do
    "#{@base_url}/items?#{query}&per_page=1"
    |> HTTPoison.get!(@headers, @options)
    |> Map.get(:headers)
    |> Enum.filter(fn {key, _} -> key == "Total-Count" end)
    |> Enum.at(0)
    |> elem(1)
    |> String.to_integer()
  end

  defp max_page(total_count) when rem(total_count, @per_page) == 0 do
    div(total_count, @per_page)
    |> min(100)
  end

  defp max_page(total_count) do
    (div(total_count, @per_page) + 1)
    |> min(100)
  end

  defp handle_json_decode({:error, _}), do: []

  defp handle_json_decode({:ok, map}) do
    Enum.map(
      map,
      &Map.take(&1, [
        "title",
        "likes_count",
        "updated_at",
        "created_at",
        "url",
        "user",
        "tags",
        "private"
      ])
    )
    |> Enum.map(fn %{
                     "user" => %{"id" => user_id},
                     "updated_at" => updated_at,
                     "created_at" => created_at,
                     "tags" => tags
                   } = item ->
      updated_at = Timex.parse!(updated_at, "{ISO:Extended}") |> Timex.to_datetime()
      created_at = Timex.parse!(created_at, "{ISO:Extended}") |> Timex.to_datetime()
      tags = Enum.map(tags, &Map.get(&1, "name"))

      item
      |> Map.delete("user")
      |> Map.delete("tags")
      |> Map.merge(%{
        "user_id" => user_id,
        "updated_at" => updated_at,
        "created_at" => created_at,
        "tags" => tags
      })
    end)
    |> Enum.reject(&Map.get(&1, "private"))
  end
end


# Run

items =
  Qiita.Api.items("Nerves")
  |> Enum.with_index(2)
  |> Enum.map(fn {%{"title" => title, "likes_count" => likes_count, "url" => url, "user_id" => user_id}, index} ->
    [title, "=googletranslate(A#{index}, \"ja\", \"en\")", user_id, likes_count, "https://translate.google.com/translate?hl=en&sl=ja&u=#{url}"]
  end)


NimbleCSV.define(MyParser, separator: "\t")

MyParser.dump_to_iodata([~w(title googletranslate user_id likes_count url)] ++ items)
|> IO.iodata_to_binary()
|> then(& File.write("output.tsv", &1))

Run

$ elixir links.exs
  • output.tsvの内容をGoogleスプレッドシートにはりましょう
  • そうするとこんな感じの一覧が得られます :tada::tada::tada:

スクリーンショット 2021-06-24 21.23.40.png

Wrapping up :lgtm::lgtm::lgtm::lgtm:

https___qiita-user-contents.imgix.net_https%3A%2F%2Fqiita-image-store.s3.ap-northeast-1.amazonaws.com%2F0%2F240349%2F5ef22bb9-f357-778c-1bff-b018cce54948.png_ixlib=rb-1.2.png

  1. Nerves Newsletter申し込みフォーム

9
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?