Module: Fcmpush::Batch

Included in:
Client
Defined in:
lib/fcmpush/batch.rb

Constant Summary collapse

PART_BOUNDRY =
'__END_OF_PART__'.freeze

Instance Method Summary collapse

Instance Method Details

#create_part(request, part_boundry, idx) ⇒ Object



15
16
17
18
19
20
21
22
23
24
# File 'lib/fcmpush/batch.rb', line 15

def create_part(request, part_boundry, idx)
  serialized_request = serialize_sub_request(request)
  "--#{part_boundry}\r\n" \
    "Content-Length: #{serialized_request.length}\r\n" \
    "Content-Type: application/http\r\n" \
    "Content-Id: #{idx + 1}\r\n" \
    "Content-Transfer-Encoding: binary\r\n" \
    "\r\n" \
    "#{serialized_request}\r\n"
end

#make_batch_payload(messages, headers) ⇒ Object



5
6
7
8
9
10
11
12
13
# File 'lib/fcmpush/batch.rb', line 5

def make_batch_payload(messages, headers)
  uri = URI.join(domain, path)
  subrequests = messages.map do |payload|
    req = Net::HTTP::Post.new(uri, headers)
    req.body = payload
    req
  end
  subrequests.map.with_index { |req, idx| create_part(req, PART_BOUNDRY, idx) }.join + "--#{PART_BOUNDRY}\r\n"
end

#serialize_sub_request(request) ⇒ Object



26
27
28
29
30
31
32
33
34
35
# File 'lib/fcmpush/batch.rb', line 26

def serialize_sub_request(request)
  body_str = request.body.is_a?(String) ? request.body : request.body.to_json
  subreqest = "POST #{request.path} HTTP/1.1\r\n" \
              "Content-Length: #{body_str.length}\r\n"
  request.to_hash.each do |k, v|
    subreqest += "#{k}: #{v.join(';')}\r\n"
  end
  subreqest += "\r\n" \
               "#{body_str}\r\n"
end