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 # Network functionnalities based on Curl_c module.
24 protected var prim_curl
: CCurl
28 self.prim_curl
= new CCurl.easy_init
29 assert curlInstance
:self.prim_curl
.is_init
else
30 print
"Curl must be instancied to be used"
34 # Check for correct initialization
35 fun is_ok
: Bool do return self.prim_curl
.is_init
37 # Get an HTTP Request object to perform your own
38 fun http_request
(url
: String): nullable CurlRequest
41 err
= self.prim_curl
.easy_setopt
(new CURLOption.follow_location
, 1)
42 if not err
.is_ok
then return null
44 err
= self.prim_curl
.easy_setopt
(new CURLOption.url
, url
)
45 if not err
.is_ok
then return null
47 return new CurlHTTPRequest(url
, self)
50 # Get a MAIL Request Object
51 fun mail_request
: nullable CurlMailRequest
54 err
= self.prim_curl
.easy_setopt
(new CURLOption.follow_location
, 1)
55 if not err
.is_ok
then return null
57 return new CurlMailRequest(self)
60 # Release Curl instance
61 fun destroy
do self.prim_curl
.easy_clean
67 var verbose
: Bool writable = false
68 private var curl
: nullable Curl = null
70 # Launch request method
71 fun execute
: CurlResponse is abstract
73 # Intern perform method, lowest level of request launching
74 private fun perform
: nullable CurlResponse
76 if not self.curl
.is_ok
then return answer_failure
(0, "Curl instance is not correctly initialized")
80 err
= self.curl
.prim_curl
.easy_setopt
(new CURLOption.verbose
, self.verbose
)
81 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
83 err
= self.curl
.prim_curl
.easy_perform
84 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
89 # Intern method with return a failed answer with given code and message
90 private fun answer_failure
(error_code
: Int, error_msg
: String): CurlResponse
92 return new CurlResponseFailed(error_code
, error_msg
)
100 super CurlCallbacksRegisterIntern
103 var datas
: nullable HeaderMap writable = null
104 var headers
: nullable HeaderMap writable = null
106 init (url
: String, curl
: nullable Curl)
112 # Execute HTTP request with settings configured through attribute
113 redef fun execute
: CurlResponse
115 if not self.curl
.is_ok
then return answer_failure
(0, "Curl instance is not correctly initialized")
117 var success_response
: CurlResponseSuccess = new CurlResponseSuccess
119 var callback_receiver
: CurlCallbacks = success_response
120 if self.delegate
!= null then callback_receiver
= self.delegate
.as(not null)
124 err
= self.curl
.prim_curl
.register_callback
(callback_receiver
, new CURLCallbackType.header
)
125 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
127 err
= self.curl
.prim_curl
.register_callback
(callback_receiver
, new CURLCallbackType.body
)
128 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
131 if self.headers
!= null then
132 var headers_joined
= self.headers
.join_pairs
(": ")
133 err
= self.curl
.prim_curl
.easy_setopt
(new CURLOption.httpheader
, headers_joined
.to_curlslist
)
134 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
138 if self.datas
!= null then
139 var postdatas
= self.datas
.to_url_encoded
(self.curl
.prim_curl
)
140 err
= self.curl
.prim_curl
.easy_setopt
(new CURLOption.postfields
, postdatas
)
141 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
144 var err_resp
= perform
145 if err_resp
!= null then return err_resp
147 var st_code
= self.curl
.prim_curl
.easy_getinfo_long
(new CURLInfoLong.response_code
)
148 if not st_code
== null then success_response
.status_code
= st_code
.response
150 return success_response
153 # Download to file given resource
154 fun download_to_file
(output_file_name
: nullable String): CurlResponse
156 var success_response
: CurlFileResponseSuccess = new CurlFileResponseSuccess
158 var callback_receiver
: CurlCallbacks = success_response
159 if self.delegate
!= null then callback_receiver
= self.delegate
.as(not null)
162 err
= self.curl
.prim_curl
.register_callback
(callback_receiver
, new CURLCallbackType.header
)
163 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
165 err
= self.curl
.prim_curl
.register_callback
(callback_receiver
, new CURLCallbackType.stream
)
166 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
168 var opt_name
:nullable String
169 if not output_file_name
== null then
170 opt_name
= output_file_name
171 else if not self.url
.substring
(self.url
.length-1
, self.url
.length
) == "/" then
172 opt_name
= self.url
.basename
("")
174 return answer_failure
(0, "Unable to extract file name, please specify one")
177 success_response
.i_file
= new OFile.open
(opt_name
.to_cstring
)
178 if not success_response
.i_file
.is_valid
then
179 success_response
.i_file
.close
180 return answer_failure
(0, "Unable to create associated file")
183 var err_resp
= perform
184 if err_resp
!= null then return err_resp
186 var st_code
= self.curl
.prim_curl
.easy_getinfo_long
(new CURLInfoLong.response_code
)
187 if not st_code
== null then success_response
.status_code
= st_code
.response
189 var speed
= self.curl
.prim_curl
.easy_getinfo_double
(new CURLInfoDouble.speed_download
)
190 if not speed
== null then success_response
.speed_download
= speed
.response
192 var size
= self.curl
.prim_curl
.easy_getinfo_double
(new CURLInfoDouble.size_download
)
193 if not size
== null then success_response
.size_download
= size
.response
195 var time
= self.curl
.prim_curl
.easy_getinfo_double
(new CURLInfoDouble.total_time
)
196 if not time
== null then success_response
.total_time
= time
.response
198 success_response
.i_file
.close
200 return success_response
205 class CurlMailRequest
209 var headers
: nullable HeaderMap writable = null
210 var headers_body
: nullable HeaderMap writable = null
211 var from
: nullable String writable = null
212 var to
: nullable Array[String] writable = null
213 var cc
: nullable Array[String] writable = null
214 var bcc
: nullable Array[String] writable = null
215 var subject
: nullable String writable = ""
216 var body
: nullable String writable = ""
217 private var supported_outgoing_protocol
: Array[String]
219 init (curl
: nullable Curl)
222 self.supported_outgoing_protocol
= once
["smtp", "smtps"]
225 # Helper method to add conventional space while building entire mail
226 private fun add_conventional_space
(str
: String):String do return "{str}\n" end
228 # Helper method to add pair values to mail content while building it (ex: "To:", "address@mail.com")
229 private fun add_pair_to_content
(str
: String, att
: String, val
: nullable String):String
231 if val
!= null then return "{str}{att}{val}\n"
232 return "{str}{att}\n"
235 # Helper method to add entire list of pairs to mail content
236 private fun add_pairs_to_content
(content
: String, pairs
: HeaderMap):String
238 for h_key
, h_val
in pairs
do content
= add_pair_to_content
(content
, h_key
, h_val
)
242 # Check for host and protocol availability
243 private fun is_supported_outgoing_protocol
(host
: String):CURLCode
245 var host_reach
= host
.split_with
("://")
246 if host_reach
.length
> 1 and supported_outgoing_protocol
.has
(host_reach
[0]) then return once
new CURLCode.ok
247 return once
new CURLCode.unsupported_protocol
250 # Configure server host and user credentials if needed.
251 fun set_outgoing_server
(host
: String, user
: nullable String, pwd
: nullable String):nullable CurlResponse
253 # Check Curl initialisation
254 if not self.curl
.is_ok
then return answer_failure
(0, "Curl instance is not correctly initialized")
259 err
= is_supported_outgoing_protocol
(host
)
260 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
261 err
= self.curl
.prim_curl
.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
.prim_curl
.easy_setopt
(new CURLOption.username
, user
)
267 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
268 err
= self.curl
.prim_curl
.easy_setopt
(new CURLOption.password
, pwd
)
269 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
275 # Execute Mail request with settings configured through attribute
276 redef fun execute
: CurlResponse
278 if not self.curl
.is_ok
then return answer_failure
(0, "Curl instance is not correctly initialized")
280 var success_response
: CurlMailResponseSuccess = new CurlMailResponseSuccess
284 if self.headers
!= null then
285 content
= add_pairs_to_content
(content
, self.headers
.as(not null))
289 var g_rec
= new Array[String]
290 if self.to
!= null and self.to
.length
> 0 then
291 content
= add_pair_to_content
(content
, "To:", self.to
.join
(","))
292 g_rec
.append
(self.to
.as(not null))
294 if self.cc
!= null and self.cc
.length
> 0 then
295 content
= add_pair_to_content
(content
, "Cc:", self.cc
.join
(","))
296 g_rec
.append
(self.cc
.as(not null))
298 if self.bcc
!= null and self.bcc
.length
> 0 then g_rec
.append
(self.bcc
.as(not null))
300 if g_rec
.length
< 1 then return answer_failure
(0, "The mail recipients can not be empty")
301 err
= self.curl
.prim_curl
.easy_setopt
(new CURLOption.mail_rcpt
, g_rec
.to_curlslist
)
302 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
305 if not self.from
== null then
306 content
= add_pair_to_content
(content
, "From:", self.from
)
307 err
= self.curl
.prim_curl
.easy_setopt
(new CURLOption.mail_from
, self.from
.as(not null))
308 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
312 content
= add_pair_to_content
(content
, "Subject:", self.subject
)
315 if self.headers_body
!= null then
316 content
= add_pairs_to_content
(content
, self.headers_body
.as(not null))
320 content
= add_conventional_space
(content
)
321 content
= add_pair_to_content
(content
, "", self.body
)
322 content
= add_conventional_space
(content
)
323 err
= self.curl
.prim_curl
.register_callback
(self, once
new CURLCallbackType.read
)
324 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
325 err
= self.curl
.prim_curl
.register_read_datas_callback
(self, content
)
326 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
328 var err_resp
= perform
329 if err_resp
!= null then return err_resp
331 return success_response
335 # Callbacks Interface, allow you to manage in your way the different streams
336 interface CurlCallbacks
340 # Callbacks attributes
341 abstract class CurlCallbacksRegisterIntern
342 var delegate
: nullable CurlCallbacks writable = null
345 # Abstract Curl request response
346 abstract class CurlResponse
349 # Failed Response Class returned when errors during configuration are raised
350 class CurlResponseFailed
354 var error_msg
: String
356 init (err_code
: Int, err_msg
: String)
358 self.error_code
= err_code
359 self.error_msg
= err_msg
363 # Success Abstract Response Success Class
364 abstract class CurlResponseSuccessIntern
368 var headers
: HashMap[String, String] = new HashMap[String, String]
370 # Receive headers from request due to headers callback registering
371 redef fun header_callback
(line
: String)
373 var splitted
= line
.split_with
(':')
374 if splitted
.length
> 1 then
375 var key
= splitted
.shift
376 self.headers
[key
] = splitted
.to_s
381 # Success Response Class of a basic response
382 class CurlResponseSuccess
383 super CurlResponseSuccessIntern
385 var body_str
: String = ""
386 var status_code
: Int = 0
388 # Receive body from request due to body callback registering
389 redef fun body_callback
(line
: String)
391 self.body_str
= "{self.body_str}{line}"
395 # Success Response Class of mail request
396 class CurlMailResponseSuccess
397 super CurlResponseSuccessIntern
400 # Success Response Class of a downloaded File
401 class CurlFileResponseSuccess
402 super CurlResponseSuccessIntern
404 var status_code
: Int = 0
405 var speed_download
: Int = 0
406 var size_download
: Int = 0
407 var total_time
: Int = 0
408 private var i_file
: nullable OFile = null
410 # Receive bytes stream from request due to stream callback registering
411 redef fun stream_callback
(buffer
: String, size
: Int, count
: Int)
413 self.i_file
.write
(buffer
, size
, count
)
417 # Pseudo map associating Strings to Strings,
418 # each key can have multiple associations
419 # and the order of insertion is important.
421 private var arr
= new Array[Couple[String, String]]
423 fun []=(k
, v
: String) do arr
.add
(new Couple[String, String](k
, v
))
425 fun [](k
: String): Array[String]
427 var res
= new Array[String]
428 for c
in arr
do if c
.first
== k
then res
.add
(c
.second
)
432 fun iterator
: MapIterator[String, String] do return new HeaderMapIterator(self)
434 # Convert Self to a single string used to post http fields
435 fun to_url_encoded
(curl
: CCurl): String
437 assert curlNotInitialized
: curl
.is_init
else
438 print
"to_url_encoded required a valid instance of CCurl Object."
441 var length
= self.length
448 if i
< length-1
then str
= "{str}&"
455 # Concatenate couple of 'key value' separated by 'sep' in Array
456 fun join_pairs
(sep
: String): Array[String]
458 var col
= new Array[String]
459 for k
, v
in self do col
.add
("{k}{sep}{v}")
463 fun length
: Int do return arr
.length
464 fun is_empty
: Bool do return arr
.is_empty
467 class HeaderMapIterator
468 super MapIterator[String, String]
470 private var iterator
: Iterator[Couple[String, String]]
471 init(map
: HeaderMap) do self.iterator
= map
.arr
.iterator
473 redef fun is_ok
do return self.iterator
.is_ok
474 redef fun next
do self.iterator
.next
475 redef fun item
do return self.iterator
.item
.second
476 redef fun key
do return self.iterator
.item
.first