kivanio (owner)

Fork Of

gist: 217558 by anonymous

Revisions

  • c47b37 Sat Oct 24 07:40:20 -0700 2009
  • 8039bf Sat Oct 24 07:39:30 -0700 2009
gist: 227908 Download_button fork
public
Public Clone URL: git://gist.github.com/227908.git
Embed All Files: show embed
content_servant.rb #
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
#--
# Copyright (c) 2009 Szymon Kurcab szymon.kurcab@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining
# a copy of this software and associated documentation files (the
# "Software"), to deal in the Software without restriction, including
# without limitation the rights to use, copy, modify, merge, publish,
# distribute, sublicense, and/or sell copies of the Software, and to
# permit persons to whom the Software is furnished to do so, subject to
# the following conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
# MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
# LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
# OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
# WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
#++
 
require 'net/https'
require 'rack'
 
module HostConfiguration
 
  # Volantis Systems Device Repository Web Service
  DRWS = {
    :host => 'rackcontest.volantis.com',
    :port => 8443,
    :path => '/drws',
    :user => 'drws',
    :passwd => 'drws'
  }
 
  TRANSCODERS = {
    :google => {
      :host => 'www.google.com',
      :port => 80,
      :path => '/gwt/n'
    },
    :volantis => {
      :host => 'rackcontest.volantis.com',
      :port => 8080,
      :path => '/mlAdapt'
    }
  }
 
end
 
class Rack::ContentServant
  include HostConfiguration
 
  PC_STRING = 'PC'
 
  def initialize(app, tc_engine)
    @host = TRANSCODERS[tc_engine][:host]
    @port = TRANSCODERS[tc_engine][:port]
    @path = TRANSCODERS[tc_engine][:path]
    @app = app
  end
 
  private
  def timeout_response
    [408, {"Content-Type" => "text/html"}, "408 Request Timeout"]
  end
 
  # detects client browser
  def client_browser(env)
    # Prepare HTTPS connection to the web service
    http = Net::HTTP.new(DRWS[:host], DRWS[:port])
    http.use_ssl = true
 
    req = Net::HTTP::Post.new(DRWS[:path] + '/device/name-by-headers')
    req.basic_auth(DRWS[:user], DRWS[:passwd])
    req['content-type'] = 'text/html'
 
    begin
      http.start { |h|
          response = h.request(req, "User-Agent: #{env["HTTP_USER_AGENT"]}")
          return response.body.match(/<device-name[^>]*>(.*?)<[^>]*>/)[1]
      }
    rescue Exception
      PC_STRING
    end
  end
 
  def pc?(env)
    client_browser(env).starts_with?(PC_STRING)
  end
 
end
 
class GoogleContentServant < Rack::ContentServant
 
  def initialize(app)
    super(app, :google)
  end
 
  # :api: plugin
  def call(env)
    if from_transcoder?(env) || pc?(env)
      @app.call(env)
    else
      get_transcoded_content(env)
    end
  end
 
  private
  def get_transcoded_content(env)
    http = Net::HTTP.new(@host)
    host = env['HTTP_X_FORWARDED_HOST'] || env['HTTP_HOST']
    uri = URI.parse('http://' + host + env['REQUEST_PATH'])
    uri.merge!(env['QUERY_STRING'])
    query = URI.escape(uri.to_s)
    begin
      response = http.get(@path + '?u=' + query, proxy_headers(env))
      [response.code.to_i, {"Content-Type" => response['content-type'] }, process_body(response.body)]
    rescue TimeoutError
      timeout_response
    end
  end
 
  # adds <base> tag to the page header for proper link handling
  def process_body(bdy)
    bdy.gsub(/<head[^>]*>(.*?)<\/head>/,"<head>#{$1}#{base_tag}</head>")
  end
 
  # infinite loop protection
  def from_transcoder?(env)
    env['Content Location'].to_s.starts_with?(@path)
  end
 
  def proxy_headers(env)
    h = {}
    add_if_set(h, 'Accept', env['HTTP_ACCEPT'])
    add_if_set(h, 'Accept Language', env['HTTP_ACCEPT_LANGUAGE'])
    add_if_set(h, 'Accept Encoding', env['HTTP_ACCEPT_ENCODING'])
    add_if_set(h, 'Cookie', env['HTTP_COOKIE'])
    add_if_set(h, 'Accept Charset', env['HTTP_ACCEPT_CHARSET'])
    add_if_set(h, 'User Agent', env['HTTP_USER_AGENT'])
    h
  end
 
  def add_if_set(hash, key, value)
    hash.merge!(key => value) unless value.blank?
  end
 
  def base_tag
    "<base href=\"http://#{@host}\" />"
  end
 
end
 
class VolantisContentServant < Rack::ContentServant
 
  def initialize(app)
    super(app, :volantis)
  end
 
  # :api: plugin
  def call(env)
    req_call = @app.call(env)
 
    # return direct application response if PC client or redirection
    if pc?(env) || (req_call.first / 100 == 3)
      return req_call
    else
      get_transcoded_content(env, req_call)
    end
  end
 
  private
  def get_transcoded_content(env, req_call)
      url = URI.parse("http://#{@host}:#{@port}#{@path}")
      begin
        Net::HTTP.start(url.host,url.port) {|http|
            response = http.post(url.path, set_content(env, req_call), { 'X-RMSC-PROTOCOL' => 'WAP2.0' } )
            processed = process_body(response.body)
            [processed[:code], processed[:headers], processed[:body]]
        }
      rescue TimeoutError
        timeout_response
      end
  end
 
  def process_body(bdy)
    ret = {}
    content = bdy.split("\r\n\r\n")
    ret[:body] = content.last
    ret[:headers] = {}
    content.first.split("\r\n").each_with_index { |e, i|
      if i == 0
        ret[:code] = e.split(' ')[1].to_i
      else
        k, v = e.split(':')
        ret[:headers].merge!(k.to_s => v.to_s)
      end
    }
    ret
  end
 
  def set_content(env, req_call)
    status, headers, response = req_call
    <<-CONTENT
#{env['REQUEST_METHOD']} / #{env['HTTP_VERSION']}
Host: #{env['HTTP_HOST']}
User-Agent: #{env['HTTP_USER_AGENT']}
Accept: #{env['HTTP_ACCEPT']}
Accept-Language: #{env['HTTP_ACCEPT_LANGUAGE']}
Accept-Encoding: #{env['HTTP_ACCEPT_ENCODING']}
Accept-Charset: #{env['HTTP_ACCEPT_CHARSET']}
Keep-Alive: #{env['HTTP_KEEP_ALIVE']}
Connection: #{env['HTTP_CONNECTION']}
Cookie: #{env['HTTP_COOKIE']}
 
HTTP/1.1 #{status} OK
Content-Length: #{::Rack::Utils.bytesize(response.body.to_s)}
Content-Type: #{headers['Content-Type']}
 
#{response.body}
CONTENT
  end
 
end
 
class Rack::ContentServantFactory
 
  def self.tc_engine(tc_engine = nil)
    case tc_engine
    when :google
      GoogleContentServant
    else
      VolantisContentServant
    end
  end
 
end