1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2013 Matthieu Lucas <lucasmatthieu@gmail.com>
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
9 # http://www.apache.org/licenses/LICENSE-2.0
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
17 # Curl services: `CurlHTTPRequest` and `CurlMail`
23 # Shared Curl library handle
25 # Usually, you do not have to use this attribute, it instancied by `CurlHTTPRequest` and `CurlMail`.
26 # But in some cases you may want to finalize it to free some small resources.
27 # However, if Curl services are needed once again, this attribute must be manually set.
28 var curl
: Curl = new Curl is lazy
, writable
31 # Curl library handle, it is initialized and released with this class
35 private var native
= new NativeCurl.easy_init
37 # Check for correct initialization
38 fun is_ok
: Bool do return self.native
.is_init
40 redef fun finalize_once
do if is_ok
then native
.easy_clean
46 private var curl
: Curl = sys
.curl
48 # Shall this request be verbose?
49 var verbose
: Bool = false is writable
51 # Intern perform method, lowest level of request launching
52 private fun perform
: nullable CurlResponseFailed
54 if not self.curl
.is_ok
then return answer_failure
(0, "Curl instance is not correctly initialized")
58 err
= self.curl
.native
.easy_setopt
(new CURLOption.verbose
, self.verbose
)
59 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
61 err
= self.curl
.native
.easy_perform
62 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
67 # Intern method with return a failed answer with given code and message
68 private fun answer_failure
(error_code
: Int, error_msg
: String): CurlResponseFailed
70 return new CurlResponseFailed(error_code
, error_msg
)
77 super NativeCurlCallbacks
80 var datas
: nullable HeaderMap = null is writable
81 var headers
: nullable HeaderMap = null is writable
82 var delegate
: nullable CurlCallbacks = null is writable
84 # Set the user agent for all following HTTP requests
85 fun user_agent
=(name
: String)
87 curl
.native
.easy_setopt
(new CURLOption.user_agent
, name
)
90 # Execute HTTP request with settings configured through attribute
91 fun execute
: CurlResponse
93 if not self.curl
.is_ok
then return answer_failure
(0, "Curl instance is not correctly initialized")
95 var success_response
= new CurlResponseSuccess
96 var callback_receiver
: CurlCallbacks = success_response
97 if self.delegate
!= null then callback_receiver
= self.delegate
.as(not null)
101 err
= self.curl
.native
.easy_setopt
(new CURLOption.follow_location
, 1)
102 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
104 err
= self.curl
.native
.easy_setopt
(new CURLOption.url
, url
)
105 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
108 err
= self.curl
.native
.register_callback_header
(callback_receiver
)
109 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
111 err
= self.curl
.native
.register_callback_body
(callback_receiver
)
112 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
115 var headers
= self.headers
116 if headers
!= null then
117 var headers_joined
= headers
.join_pairs
(": ")
118 err
= self.curl
.native
.easy_setopt
(new CURLOption.httpheader
, headers_joined
.to_curlslist
)
119 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
123 var datas
= self.datas
124 if datas
!= null then
125 var postdatas
= datas
.to_url_encoded
(self.curl
)
126 err
= self.curl
.native
.easy_setopt
(new CURLOption.postfields
, postdatas
)
127 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
130 var err_resp
= perform
131 if err_resp
!= null then return err_resp
133 var st_code
= self.curl
.native
.easy_getinfo_long
(new CURLInfoLong.response_code
)
134 if not st_code
== null then success_response
.status_code
= st_code
.response
136 return success_response
139 # Download to file given resource
140 fun download_to_file
(output_file_name
: nullable String): CurlResponse
142 var success_response
= new CurlFileResponseSuccess
144 var callback_receiver
: CurlCallbacks = success_response
145 if self.delegate
!= null then callback_receiver
= self.delegate
.as(not null)
149 err
= self.curl
.native
.easy_setopt
(new CURLOption.follow_location
, 1)
150 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
152 err
= self.curl
.native
.easy_setopt
(new CURLOption.url
, url
)
153 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
155 err
= self.curl
.native
.register_callback_header
(callback_receiver
)
156 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
158 err
= self.curl
.native
.register_callback_stream
(callback_receiver
)
159 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
162 if not output_file_name
== null then
163 opt_name
= output_file_name
164 else if not self.url
.substring
(self.url
.length-1
, self.url
.length
) == "/" then
165 opt_name
= self.url
.basename
("")
167 return answer_failure
(0, "Unable to extract file name, please specify one")
170 success_response
.file
= new FileWriter.open
(opt_name
)
171 if not success_response
.file
.is_writable
then
172 return answer_failure
(0, "Unable to create associated file")
175 var err_resp
= perform
176 if err_resp
!= null then return err_resp
178 var st_code
= self.curl
.native
.easy_getinfo_long
(new CURLInfoLong.response_code
)
179 if not st_code
== null then success_response
.status_code
= st_code
.response
181 var speed
= self.curl
.native
.easy_getinfo_double
(new CURLInfoDouble.speed_download
)
182 if not speed
== null then success_response
.speed_download
= speed
.response
184 var size
= self.curl
.native
.easy_getinfo_double
(new CURLInfoDouble.size_download
)
185 if not size
== null then success_response
.size_download
= size
.response
187 var time
= self.curl
.native
.easy_getinfo_double
(new CURLInfoDouble.total_time
)
188 if not time
== null then success_response
.total_time
= time
.response
190 success_response
.file
.close
192 return success_response
199 super NativeCurlCallbacks
201 # Address of the sender
202 var from
: nullable String is writable
205 var to
: nullable Array[String] is writable
208 var subject
: nullable String is writable
211 var body
: nullable String is writable
214 var cc
: nullable Array[String] is writable
216 # BCC recipients (hidden from other recipients)
217 var bcc
: nullable Array[String] is writable
220 var headers
= new HeaderMap is lazy
, writable
223 var headers_body
= new HeaderMap is lazy
, writable
225 private var supported_outgoing_protocol
: Array[String] = ["smtp", "smtps"]
227 # Helper method to add pair values to mail content while building it (ex: "To:", "address@mail.com")
228 private fun add_pair_to_content
(str
: String, att
: String, val
: nullable String): String
230 if val
!= null then return "{str}{att}{val}\n"
231 return "{str}{att}\n"
234 # Helper method to add entire list of pairs to mail content
235 private fun add_pairs_to_content
(content
: String, pairs
: HeaderMap): String
237 for h_key
, h_val
in pairs
do content
= add_pair_to_content
(content
, h_key
, h_val
)
241 # Check for host and protocol availability
242 private fun is_supported_outgoing_protocol
(host
: String): CURLCode
244 var host_reach
= host
.split_with
("://")
245 if host_reach
.length
> 1 and supported_outgoing_protocol
.has
(host_reach
[0]) then return once
new CURLCode.ok
246 return once
new CURLCode.unsupported_protocol
249 # Configure server host and user credentials if needed.
250 fun set_outgoing_server
(host
: String, user
: nullable String, pwd
: nullable String): nullable CurlResponseFailed
252 # Check Curl initialisation
253 if not self.curl
.is_ok
then return answer_failure
(0, "Curl instance is not correctly initialized")
258 err
= is_supported_outgoing_protocol
(host
)
259 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
261 err
= self.curl
.native
.easy_setopt
(new CURLOption.url
, host
)
262 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
265 if not user
== null and not pwd
== null then
266 err
= self.curl
.native
.easy_setopt
(new CURLOption.username
, user
)
267 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
269 err
= self.curl
.native
.easy_setopt
(new CURLOption.password
, pwd
)
270 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
276 # Execute Mail request with settings configured through attribute
277 fun execute
: nullable CurlResponseFailed
279 if not self.curl
.is_ok
then return answer_failure
(0, "Curl instance is not correctly initialized")
281 var lines
= new Array[String]
284 var headers
= self.headers
285 if not headers
.is_empty
then
286 for k
, v
in headers
do lines
.add
"{k}{v}"
290 var all_recipients
= new Array[String]
292 if to
!= null and to
.length
> 0 then
293 lines
.add
"To:{to.join(",")}"
294 all_recipients
.append to
298 if cc
!= null and cc
.length
> 0 then
299 lines
.add
"Cc:{cc.join(",")}"
300 all_recipients
.append cc
304 if bcc
!= null and bcc
.length
> 0 then all_recipients
.append bcc
306 if all_recipients
.is_empty
then return answer_failure
(0, "There must be at lease one recipient")
308 var err
= self.curl
.native
.easy_setopt
(new CURLOption.follow_location
, 1)
309 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
311 err
= self.curl
.native
.easy_setopt
(new CURLOption.mail_rcpt
, all_recipients
.to_curlslist
)
312 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
316 if not from
== null then
317 lines
.add
"From:{from}"
319 err
= self.curl
.native
.easy_setopt
(new CURLOption.mail_from
, from
)
320 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
324 var subject
= self.subject
325 if subject
== null then subject
= "" # Default
326 lines
.add
"Subject: {subject}"
329 var headers_body
= self.headers_body
330 if not headers_body
.is_empty
then
331 for k
, v
in headers_body
do lines
.add
"{k}{v}"
336 if body
== null then body
= "" # Default
342 err
= self.curl
.native
.register_callback_read
(self)
343 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
345 var content
= lines
.join
("\n")
346 err
= self.curl
.native
.register_read_datas_callback
(self, content
)
347 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
349 var err_resp
= perform
350 if err_resp
!= null then return err_resp
356 # Callbacks Interface, allow you to manage in your way the different streams
357 interface CurlCallbacks
358 super NativeCurlCallbacks
361 # Abstract Curl request response
362 abstract class CurlResponse
365 # Failed Response Class returned when errors during configuration are raised
366 class CurlResponseFailed
370 var error_msg
: String
373 # Success Abstract Response Success Class
374 abstract class CurlResponseSuccessIntern
378 var headers
= new HashMap[String, String]
380 # Receive headers from request due to headers callback registering
381 redef fun header_callback
(line
)
383 var splitted
= line
.split_with
(':')
384 if splitted
.length
> 1 then
385 var key
= splitted
.shift
386 self.headers
[key
] = splitted
.to_s
391 # Success Response Class of a basic response
392 class CurlResponseSuccess
393 super CurlResponseSuccessIntern
398 # Receive body from request due to body callback registering
399 redef fun body_callback
(line
) do
400 self.body_str
= "{self.body_str}{line}"
404 # Success Response Class of a downloaded File
405 class CurlFileResponseSuccess
406 super CurlResponseSuccessIntern
409 var speed_download
= 0
410 var size_download
= 0
412 private var file
: nullable FileWriter = null
414 # Receive bytes stream from request due to stream callback registering
415 redef fun stream_callback
(buffer
)
421 # Pseudo map associating `String` to `String` for HTTP exchanges
423 # This structure differs from `Map` as each key can have multiple associations
424 # and the order of insertion is important to some services.
426 private var array
= new Array[Couple[String, String]]
428 # Add a `value` associated to `key`
429 fun []=(key
, value
: String)
431 array
.add
new Couple[String, String](key
, value
)
434 # Get a list of the keys associated to `key`
435 fun [](k
: String): Array[String]
437 var res
= new Array[String]
438 for c
in array
do if c
.first
== k
then res
.add c
.second
442 # Iterate over all the associations in `self`
443 fun iterator
: MapIterator[String, String] do return new HeaderMapIterator(self)
445 # Get `self` as a single string for HTTP POST
447 # Require: `curl.is_ok`
448 fun to_url_encoded
(curl
: Curl): String
452 var lines
= new Array[String]
454 if k
.length
== 0 then continue
456 k
= curl
.native
.escape
(k
)
457 v
= curl
.native
.escape
(v
)
460 return lines
.join
("&")
463 # Concatenate couple of 'key value' separated by 'sep' in Array
464 fun join_pairs
(sep
: String): Array[String]
466 var col
= new Array[String]
467 for k
, v
in self do col
.add
("{k}{sep}{v}")
471 # Number of values in `self`
472 fun length
: Int do return array
.length
475 fun is_empty
: Bool do return array
.is_empty
478 private class HeaderMapIterator
479 super MapIterator[String, String]
482 var iterator
: Iterator[Couple[String, String]] = map
.array
.iterator
is lazy
484 redef fun is_ok
do return self.iterator
.is_ok
485 redef fun next
do self.iterator
.next
486 redef fun item
do return self.iterator
.item
.second
487 redef fun key
do return self.iterator
.item
.first