get rid of multiple get_from_api definitions, put it in application_controller and...
[opensuse:software-o-o.git] / app / controllers / application_controller.rb
1 # Filters added to this controller apply to all controllers in the application.
2 # Likewise, all the methods added will be available for all controllers.
3
4 require 'net/https'
5
6 class ApplicationController < ActionController::Base
7
8   before_filter :set_language
9   before_filter :set_distributions
10   
11   helper :all # include all helpers, all the time
12   require "rexml/document"
13
14   init_gettext('software')
15
16   protected
17
18   def rescue_action_locally( exception )
19     rescue_action_in_public( exception )
20   end
21
22   def rescue_action_in_public(exception)
23     @message = exception.message
24     if request.xhr?
25       render :template => "error", :layout => false, :status => 400
26     else
27       render :template => 'error', :layout => "application", :status => 400
28     end
29   end
30
31   def set_language
32     if cookies[:lang]
33       @lang = cookies[:lang]
34     elsif params[:lang]
35       @lang = params[:lang][0]
36     end
37     @lang.gsub!(/_/, '-') if @lang
38     if !@lang || !LANGUAGES.include?( @lang )
39       if !request.compatible_language_from(LANGUAGES).blank?
40         @lang = request.compatible_language_from(LANGUAGES).dup
41       else
42         @lang = "en"
43       end
44     end
45     @lang.gsub!(/-/, '_')
46     GetText.locale = @lang
47   end
48
49
50   def set_distributions
51     @distributions = Rails.cache.fetch('distributions', :expires_in => 120.minutes) do
52       load_distributions
53     end
54   end
55
56
57   # load available distributions
58   def load_distributions
59     uri = URI.parse("http://#{API_HOST}/distributions")
60     request = Net::HTTP::Get.new(uri.path)
61     logger.debug "Loading distributions from #{uri}"
62     @distributions = Array.new
63     begin
64       Net::HTTP.start(uri.host, uri.port) do |http|
65         http.read_timeout = 30
66         response = http.request(request)
67         unless( response.kind_of? Net::HTTPSuccess )
68           logger.error "Cannot load distributions: '#{response.code}', message: \n#{response.body}"
69         else
70           doc = REXML::Document.new response.body
71           doc.elements.each("distributions/distribution") { |element|
72             dist = [element.elements['name'].text, element.elements['project'].text]
73             @distributions << dist
74           }
75         end
76       end
77       @distributions << ["ALL Distributions", 'ALL']
78       return @distributions
79     rescue Exception => e
80       logger.error "Error while loading distributions from '#{uri}': " + e.to_s
81     end
82     return nil
83   end
84
85   # special version of render json with JSONP capabilities (only needed for rails < 3.0)
86   def render_json(json, options = {})
87     callback, variable = params[:callback], params[:variable]
88     response = begin
89       if callback && variable
90         "var #{variable} = #{json};\n#{callback}(#{variable});"
91       elsif variable
92         "var #{variable} = #{json};"
93       elsif callback
94         "#{callback}(#{json});"
95       else
96         json
97       end
98     end
99     render({:content_type => :js, :text => response}.merge(options))
100   end
101
102   private
103
104   def get_from_api(path)
105     host, port = API_HOST.split(/:/)
106     if defined? API_SSL and API_SSL
107       port ||= 443
108     else
109       port ||= 80
110     end
111     begin
112       http = Net::HTTP.new(host, port)
113       if defined? API_SSL and API_SSL
114         http.use_ssl = true
115         http.verify_mode = OpenSSL::SSL::VERIFY_NONE
116       end
117       request = Net::HTTP::Get.new(path)
118       request['x-username'] = ICHAIN_USER if defined? ICHAIN_USER
119       request['x-password'] = ICHAIN_PASS if defined? ICHAIN_PASS
120       request.basic_auth BA_USER, BA_PASS if defined? BA_USER and defined? BA_PASS
121       http.read_timeout = 15
122       response = http.request(request)
123       case response
124         when Net::HTTPSuccess
125           response
126         else
127           raise "Response was: #{response} #{response.body}"
128       end
129     rescue Exception => e
130       logger.error "Error connecting to #{host}:#{port}: #{e.to_s}"
131       return nil
132     end
133   end
134
135 end