LoginSignup
38
20

More than 5 years have passed since last update.

クックパッドに意地でもカロリーを表示させるChrome拡張機能を作った話

Last updated at Posted at 2017-05-24

はじめに

稀にクックパッドを使うけど

  • 材料のカロリー表示されないの?
  • 一部のレシピでは表示されるの?
  • 有料会員だけ?
  • 太らせるつもり?

とか思うわけですよ。

「無いんだったら、自分で作ればいいのよ!」ということで作ってみました。

実装

処理の流れは以下の通り。
1. レシピへのアクセスを検知して材料名を取得
2. 材料名を Microsoft Translator テキスト API で英語に変換
3. 英語に変換された材料名から FatSecret REST API でカロリー情報を取得
4. 取得したカロリー情報をブラウザ上に表示

caloriepad-chrome-system-configuration

Chrome Extension

爆速でChrome拡張機能を作成する」を参考にしながら以下の機能を実装しました。

  • レシピの材料名を取得
  • Ruby on Rails で構築した API へのリクエスト
  • カロリー情報を表示

Microsoft Translator テキスト API

以下は、Ruby on Rails での実装になります。

認証

あらかじめ「Translator API を使い始める」を参考にして、ocp_apim_subscription_key を取得しています。

def authenticate(ocp_apim_subscription_key)
  uri = URI.parse("https://api.cognitive.microsoft.com/sts/v1.0/issueToken")
  request = Net::HTTP::Post.new(uri.request_uri)
  request["Ocp-Apim-Subscription-Key"] = ocp_apim_subscription_key
  request.body = {}.to_json
  response = generate_https(uri).request(request)
  @access_tokne = response.body
end

def generate_https(uri)
  https = Net::HTTP.new(uri.host, uri.port)
  https.use_ssl = true
  https
end

翻訳

日本語の食材名を英語に変換しています。

def to_english(text)
  uri = URI.parse("https://api.microsofttranslator.com/V2/Http.svc/Translate")
  uri.query = URI.encode_www_form(generate_params(text))
  request = Net::HTTP::Get.new(uri.request_uri)
  request["Authorization"] = "Bearer #{@access_tokne}"
  response = generate_https(uri).request(request)
  ApplicationController.helpers.strip_tags(response.body)
end

def generate_params(text)
  params = Hash.new
  params.store("text", text)
  params.store("to", "en")
  params
end

FatSecret REST API

FatSecret REST API を使うことで、FatSecret の持つ栄養に関するデータを利用することができます。今回は、ライブラリとして whistler/Fatsecret を使っています。

以下は、Ruby on Rails での実装になります。

認証

あらかじめ Consumer Key と Shared Secret を、Account Registration から取得しています。

def initialize(consumer_key, shared_secret)
  FatSecret.init(consumer_key, shared_secret)
end

検索

英語に変換した食材名で検索しています。

def search_food(food_name)
  FatSecret.search_food(food_name)
end

完成

画像と材料の下部にカロリーを表示しています。

caloriepad-chrome

公開

拡張機能は、Chrome ウェブストアで公開しています。
https://chrome.google.com/webstore/detail/caloriepad/ajlecdbdhhopiadkcdfkkedmeeanepec?hl=ja

ソースコードは、GitHub で公開しています。
https://github.com/shimomo/caloriepad-api
https://github.com/shimomo/caloriepad-chrome-extension

おわりに

とりあえずクックパッドにカロリーを表示させることに成功しました。
ただ、一部のレシピでカロリーが表示されていないので、それは今後の課題ということで。

38
20
1

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
38
20