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 is writable
81 var headers
: nullable HeaderMap is writable
82 var delegate
: nullable CurlCallbacks is writable
84 # Set the user agent for all following HTTP requests
85 var user_agent
: nullable String is writable
87 # Execute HTTP request with settings configured through attribute
88 fun execute
: CurlResponse
90 if not self.curl
.is_ok
then return answer_failure
(0, "Curl instance is not correctly initialized")
92 var success_response
= new CurlResponseSuccess
93 var callback_receiver
: CurlCallbacks = success_response
94 if self.delegate
!= null then callback_receiver
= self.delegate
.as(not null)
98 err
= self.curl
.native
.easy_setopt
(new CURLOption.follow_location
, 1)
99 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
101 err
= self.curl
.native
.easy_setopt
(new CURLOption.url
, url
)
102 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
104 var user_agent
= user_agent
105 if user_agent
!= null then
106 err
= curl
.native
.easy_setopt
(new CURLOption.user_agent
, user_agent
)
107 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
111 err
= self.curl
.native
.register_callback_header
(callback_receiver
)
112 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
114 err
= self.curl
.native
.register_callback_body
(callback_receiver
)
115 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
118 var headers
= self.headers
119 if headers
!= null then
120 var headers_joined
= headers
.join_pairs
(": ")
121 err
= self.curl
.native
.easy_setopt
(new CURLOption.httpheader
, headers_joined
.to_curlslist
)
122 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
126 var datas
= self.datas
127 if datas
!= null then
128 var postdatas
= datas
.to_url_encoded
(self.curl
)
129 err
= self.curl
.native
.easy_setopt
(new CURLOption.postfields
, postdatas
)
130 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
133 var err_resp
= perform
134 if err_resp
!= null then return err_resp
136 var st_code
= self.curl
.native
.easy_getinfo_long
(new CURLInfoLong.response_code
)
137 if not st_code
== null then success_response
.status_code
= st_code
139 return success_response
142 # Download to file given resource
143 fun download_to_file
(output_file_name
: nullable String): CurlResponse
145 var success_response
= new CurlFileResponseSuccess
147 var callback_receiver
: CurlCallbacks = success_response
148 if self.delegate
!= null then callback_receiver
= self.delegate
.as(not null)
152 err
= self.curl
.native
.easy_setopt
(new CURLOption.follow_location
, 1)
153 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
155 err
= self.curl
.native
.easy_setopt
(new CURLOption.url
, url
)
156 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
158 err
= self.curl
.native
.register_callback_header
(callback_receiver
)
159 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
161 err
= self.curl
.native
.register_callback_stream
(callback_receiver
)
162 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
165 if not output_file_name
== null then
166 opt_name
= output_file_name
167 else if not self.url
.substring
(self.url
.length-1
, self.url
.length
) == "/" then
168 opt_name
= self.url
.basename
("")
170 return answer_failure
(0, "Unable to extract file name, please specify one")
173 success_response
.file
= new FileWriter.open
(opt_name
)
174 if not success_response
.file
.is_writable
then
175 return answer_failure
(0, "Unable to create associated file")
178 var err_resp
= perform
179 if err_resp
!= null then return err_resp
181 var st_code
= self.curl
.native
.easy_getinfo_long
(new CURLInfoLong.response_code
)
182 if not st_code
== null then success_response
.status_code
= st_code
184 var speed
= self.curl
.native
.easy_getinfo_double
(new CURLInfoDouble.speed_download
)
185 if not speed
== null then success_response
.speed_download
= speed
187 var size
= self.curl
.native
.easy_getinfo_double
(new CURLInfoDouble.size_download
)
188 if not size
== null then success_response
.size_download
= size
190 var time
= self.curl
.native
.easy_getinfo_double
(new CURLInfoDouble.total_time
)
191 if not time
== null then success_response
.total_time
= time
193 success_response
.file
.close
195 return success_response
203 # var mail = new CurlMail("sender@example.org",
204 # to=["to@example.org"], cc=["bob@example.org"])
206 # mail.headers_body["Content-Type:"] = """text/html; charset="UTF-8""""
207 # mail.headers_body["Content-Transfer-Encoding:"] = "quoted-printable"
209 # mail.body = "<h1>Here you can write HTML stuff.</h1>"
210 # mail.subject = "Hello From My Nit Program"
213 # var error = mail.set_outgoing_server("smtps://smtp.example.org:465",
214 # "user@example.org", "mypassword")
215 # if error != null then
216 # print "Mail Server Error: {error}"
221 # error = mail.execute
222 # if error != null then
223 # print "Transfer Error: {error}"
229 super NativeCurlCallbacks
231 # Address of the sender
232 var from
: nullable String is writable
235 var to
: nullable Array[String] is writable
238 var subject
: nullable String is writable
241 var body
: nullable String is writable
244 var cc
: nullable Array[String] is writable
246 # BCC recipients (hidden from other recipients)
247 var bcc
: nullable Array[String] is writable
250 var headers
= new HeaderMap is lazy
, writable
253 var headers_body
= new HeaderMap is lazy
, writable
255 # Protocols supported to send mail to a server
257 # Default value at `["smtp", "smtps"]`
258 var supported_outgoing_protocol
: Array[String] = ["smtp", "smtps"]
260 # Helper method to add pair values to mail content while building it (ex: "To:", "address@mail.com")
261 private fun add_pair_to_content
(str
: String, att
: String, val
: nullable String): String
263 if val
!= null then return "{str}{att}{val}\n"
264 return "{str}{att}\n"
267 # Helper method to add entire list of pairs to mail content
268 private fun add_pairs_to_content
(content
: String, pairs
: HeaderMap): String
270 for h_key
, h_val
in pairs
do content
= add_pair_to_content
(content
, h_key
, h_val
)
274 # Check for host and protocol availability
275 private fun is_supported_outgoing_protocol
(host
: String): CURLCode
277 var host_reach
= host
.split_with
("://")
278 if host_reach
.length
> 1 and supported_outgoing_protocol
.has
(host_reach
[0]) then return once
new CURLCode.ok
279 return once
new CURLCode.unsupported_protocol
282 # Configure server host and user credentials if needed.
283 fun set_outgoing_server
(host
: String, user
: nullable String, pwd
: nullable String): nullable CurlResponseFailed
285 # Check Curl initialisation
286 if not self.curl
.is_ok
then return answer_failure
(0, "Curl instance is not correctly initialized")
291 err
= is_supported_outgoing_protocol
(host
)
292 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
294 err
= self.curl
.native
.easy_setopt
(new CURLOption.url
, host
)
295 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
298 if not user
== null and not pwd
== null then
299 err
= self.curl
.native
.easy_setopt
(new CURLOption.username
, user
)
300 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
302 err
= self.curl
.native
.easy_setopt
(new CURLOption.password
, pwd
)
303 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
309 # Execute Mail request with settings configured through attribute
310 fun execute
: nullable CurlResponseFailed
312 if not self.curl
.is_ok
then return answer_failure
(0, "Curl instance is not correctly initialized")
314 var lines
= new Array[String]
317 var headers
= self.headers
318 if not headers
.is_empty
then
319 for k
, v
in headers
do lines
.add
"{k}{v}"
323 var all_recipients
= new Array[String]
325 if to
!= null and to
.length
> 0 then
326 lines
.add
"To:{to.join(",")}"
327 all_recipients
.append to
331 if cc
!= null and cc
.length
> 0 then
332 lines
.add
"Cc:{cc.join(",")}"
333 all_recipients
.append cc
337 if bcc
!= null and bcc
.length
> 0 then all_recipients
.append bcc
339 if all_recipients
.is_empty
then return answer_failure
(0, "There must be at lease one recipient")
341 var err
= self.curl
.native
.easy_setopt
(new CURLOption.follow_location
, 1)
342 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
344 err
= self.curl
.native
.easy_setopt
(new CURLOption.mail_rcpt
, all_recipients
.to_curlslist
)
345 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
349 if not from
== null then
350 lines
.add
"From:{from}"
352 err
= self.curl
.native
.easy_setopt
(new CURLOption.mail_from
, from
)
353 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
357 var subject
= self.subject
358 if subject
== null then subject
= "" # Default
359 lines
.add
"Subject: {subject}"
362 var headers_body
= self.headers_body
363 if not headers_body
.is_empty
then
364 for k
, v
in headers_body
do lines
.add
"{k}{v}"
369 if body
== null then body
= "" # Default
375 err
= self.curl
.native
.register_callback_read
(self)
376 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
378 var content
= lines
.join
("\n")
379 err
= self.curl
.native
.register_read_datas_callback
(self, content
)
380 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
382 var err_resp
= perform
383 if err_resp
!= null then return err_resp
389 # Callbacks Interface, allow you to manage in your way the different streams
390 interface CurlCallbacks
391 super NativeCurlCallbacks
394 # Abstract Curl request response
395 abstract class CurlResponse
398 # Failed Response Class returned when errors during configuration are raised
399 class CurlResponseFailed
403 var error_msg
: String
405 redef fun to_s
do return "{error_msg} ({error_code})"
408 # Success Abstract Response Success Class
409 abstract class CurlResponseSuccessIntern
413 var headers
= new HashMap[String, String]
415 # Receive headers from request due to headers callback registering
416 redef fun header_callback
(line
)
418 var splitted
= line
.split_with
(':')
419 if splitted
.length
> 1 then
420 var key
= splitted
.shift
421 self.headers
[key
] = splitted
.to_s
426 # Success Response Class of a basic response
427 class CurlResponseSuccess
428 super CurlResponseSuccessIntern
433 # Receive body from request due to body callback registering
434 redef fun body_callback
(line
) do
435 self.body_str
= "{self.body_str}{line}"
439 # Success Response Class of a downloaded File
440 class CurlFileResponseSuccess
441 super CurlResponseSuccessIntern
444 var speed_download
= 0.0
445 var size_download
= 0.0
447 private var file
: nullable FileWriter = null
449 # Receive bytes stream from request due to stream callback registering
450 redef fun stream_callback
(buffer
)
456 # Pseudo map associating `String` to `String` for HTTP exchanges
458 # This structure differs from `Map` as each key can have multiple associations
459 # and the order of insertion is important to some services.
461 private var array
= new Array[Couple[String, String]]
463 # Add a `value` associated to `key`
464 fun []=(key
, value
: String)
466 array
.add
new Couple[String, String](key
, value
)
469 # Get a list of the keys associated to `key`
470 fun [](k
: String): Array[String]
472 var res
= new Array[String]
473 for c
in array
do if c
.first
== k
then res
.add c
.second
477 # Iterate over all the associations in `self`
478 fun iterator
: MapIterator[String, String] do return new HeaderMapIterator(self)
480 # Get `self` as a single string for HTTP POST
482 # Require: `curl.is_ok`
483 fun to_url_encoded
(curl
: Curl): String
487 var lines
= new Array[String]
489 if k
.length
== 0 then continue
491 k
= curl
.native
.escape
(k
)
492 v
= curl
.native
.escape
(v
)
495 return lines
.join
("&")
498 # Concatenate couple of 'key value' separated by 'sep' in Array
499 fun join_pairs
(sep
: String): Array[String]
501 var col
= new Array[String]
502 for k
, v
in self do col
.add
("{k}{sep}{v}")
506 # Number of values in `self`
507 fun length
: Int do return array
.length
510 fun is_empty
: Bool do return array
.is_empty
513 private class HeaderMapIterator
514 super MapIterator[String, String]
517 var iterator
: Iterator[Couple[String, String]] = map
.array
.iterator
is lazy
519 redef fun is_ok
do return self.iterator
.is_ok
520 redef fun next
do self.iterator
.next
521 redef fun item
do return self.iterator
.item
.second
522 redef fun key
do return self.iterator
.item
.first