Class: UssdEngine::Middleware::NsanoProcessor

Inherits:
Object
  • Object
show all
Defined in:
lib/ussd_engine/middleware/nsano_processor.rb

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ NsanoProcessor

Returns a new instance of NsanoProcessor.



6
7
8
# File 'lib/ussd_engine/middleware/nsano_processor.rb', line 6

def initialize(app)
  @app = app
end

Instance Method Details

#call(env) ⇒ Object



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
# File 'lib/ussd_engine/middleware/nsano_processor.rb', line 10

def call(env)
  input = env["rack.input"].read
  env["rack.input"].rewind
  if input.present?
    params = JSON.parse input
    if params["network"].present? && params["UserSessionID"].present?
      request_id = "nsano::request_id::#{params["UserSessionID"]}"
      env["ussd_engine.request"] = {
        provider: :nsano,
        network: params["network"].to_sym,
        msisdn: Phonelib.parse(params["msisdn"]).e164,
        type: Config.cache&.read(request_id).present? ? :response : :initial,
        input: params["msg"].presence,
        network: params["network"],
      }
    end
  end

  status, headers, response = @app.call(env)

  if env["ussd_engine.response"].present? && env["ussd_engine.request"][:provider] == :nsano
    if env["ussd_engine.response"][:type] == :terminal
      Config.cache&.write(request_id, nil)
    else
      Config.cache&.write(request_id, 1)
    end

    status = 200
    response =
      {
        USSDResp: {
          action: env["ussd_engine.response"][:type] == :terminal ? :prompt : :input,
          menus: "",
          title: env["ussd_engine.response"][:body],
        },
      }.to_json
    headers = headers.merge({ "Content-Type" => "application/json", "Content-Length" => response.bytesize.to_s })
    response = [response]
  end
  [status, headers, response]
end