2012年2月29日水曜日

amazon affiliate

エロくローラーに貼るamazon associate(affiliate)をjsonで扱えてキャッシュ出来るrailsのcontrollerを作った。
app/controllerに置いて、Gemfileに gem 'amazon-ecs' を書いて、適当なパスをroutes.rbに書けば動くはず。
# 長ったらしい自慰行為ソースコードと説明文より動く実践コードってなかなか探しても無いものである。

sample
http://krewmen-psychobilly.rhcloud.com/api/0.7/get/affiliate/amazon?callback=callback
# -*- coding: utf-8 -*-
require 'rubygems'
require 'amazon/ecs'
require 'rakuten'
require 'pp'
require 'cgi'

class AffiliateController < ApplicationController

  def amazon

    @code = 200
    @message = nil
    @items = nil
    @max_pages = (params[:max_pages] =~ /^[0-9]+$/)?params[:max_pages]:1
    @max_images = (params[:max_images] =~ /^[0-9]+$/)?params[:max_images]:nil

    begin

      @items = Rails.cache.read("items_#{@max_pages}")
      unless @items
        @items = []

        Amazon::Ecs.options = {
          :associate_tag => 'xxx-22',
          :AWS_access_key_id => 'xxx',
          :AWS_secret_key => 'xxx',
          :country => :jp,
        }

        image_count = 0
        @max_pages.to_i.times do |page|

          res = Amazon::Ecs.item_search("検索キーワード", {:item_page => page + 1, :search_index => "DVD", :response_group => 'Medium', :sort => 'salesrank'})

          res.items.each do |item|
            if @max_images and @max_images.to_i <= image_count
              break
            end
            image_count += 1
            image = item.get("LargeImage/URL")
            if image
              @items.push({
                            :title  => item.get("ItemAttributes/Title"),
                            :actor  => item.get("ItemAttributes/Actor"),
                            :simage => item.get("SmallImage/URL"),
                            :mimage => item.get("MediumImage/URL"),
                            :image  => item.get("LargeImage/URL"),
                            :url    =>CGI::unescape(item.get("DetailPageURL"))
                          })
            end
          end

        end

        # 5min
        Rails.cache.write("items_#{@max_pages}", @items, :expires_in => 300)

      end

    rescue => err
      p err.to_s
      @code = 500
      @message = err.to_s
    end

    render :json => {:header => {:code => @code, :message => @message}, :body => {:items => @items}}, :callback => params[:callback]

  end

end

0 件のコメント:

コメントを投稿