Milestone3
[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     @distributions = Array.new
60     begin
61       response = get_from_api("distributions")
62       doc = REXML::Document.new response.body
63       doc.elements.each("distributions/distribution") { |element|
64         dist = [element.elements['name'].text, element.elements['project'].text]
65         @distributions << dist
66       }
67       @distributions << ["ALL Distributions", 'ALL']
68     rescue Exception => e
69       logger.error "Error while loading distributions: " + e.to_s
70       @distributions = nil
71     end
72     return @distributions
73   end
74
75   # special version of render json with JSONP capabilities (only needed for rails < 3.0)
76   def render_json(json, options = {})
77     callback, variable = params[:callback], params[:variable]
78     response = begin
79       if callback && variable
80         "var #{variable} = #{json};\n#{callback}(#{variable});"
81       elsif variable
82         "var #{variable} = #{json};"
83       elsif callback
84         "#{callback}(#{json});"
85       else
86         json
87       end
88     end
89     render({:content_type => :js, :text => response}.merge(options))
90   end
91
92   private
93
94   def get_from_api(path)
95     uri_str = "#{API_HOST}/#{path}".gsub(' ', '%20')
96     uri = URI.parse(uri_str)
97     logger.debug "Loading from api: #{uri_str}"
98     begin
99       http = Net::HTTP.new(uri.host, uri.port)
100       if  uri.scheme == 'https'
101         http.use_ssl = true
102         http.verify_mode = OpenSSL::SSL::VERIFY_NONE
103       end
104       request = Net::HTTP::Get.new("#{uri.path}?#{uri.query}")
105       api_user = API_USERNAME if defined? API_USERNAME
106       api_pass = API_PASSWORD if defined? API_PASSWORD
107       request['x-username'] = api_user
108       request.basic_auth  api_user, api_pass unless (api_user.blank? || api_pass.blank?)
109       http.read_timeout = 15
110       response = http.request(request)
111       case response
112       when Net::HTTPSuccess then response;
113       else
114         raise "Response was: #{response} #{response.body}"
115       end
116     rescue Exception => e
117       raise "Error connecting to #{uri_str}: #{e.to_s}"
118       return nil
119     end
120   end
121
122 end