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
= new CCurl.easy_init
28 assert curlInstance
:self.prim_curl
.is_init
else
29 print
"Curl must be instancied to be used"
33 # Check for correct initialization
34 fun is_ok
: Bool do return self.prim_curl
.is_init
36 # Release Curl instance
37 fun destroy
do self.prim_curl
.easy_clean
43 var verbose
: Bool = false is writable
44 private var curl
: nullable Curl = null
46 # Launch request method
47 fun execute
: CurlResponse is abstract
49 # Intern perform method, lowest level of request launching
50 private fun perform
: nullable CurlResponseFailed
52 if not self.curl
.is_ok
then return answer_failure
(0, "Curl instance is not correctly initialized")
56 err
= self.curl
.prim_curl
.easy_setopt
(new CURLOption.verbose
, self.verbose
)
57 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
59 err
= self.curl
.prim_curl
.easy_perform
60 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
65 # Intern method with return a failed answer with given code and message
66 private fun answer_failure
(error_code
: Int, error_msg
: String): CurlResponseFailed
68 return new CurlResponseFailed(error_code
, error_msg
)
76 super CurlCallbacksRegisterIntern
79 var datas
: nullable HeaderMap = null is writable
80 var headers
: nullable HeaderMap = null is writable
82 # Set the user agent for all following HTTP requests
83 fun user_agent
=(name
: String)
85 curl
.prim_curl
.easy_setopt
(new CURLOption.user_agent
, name
)
88 init (url
: String, curl
: nullable Curl) is old_style_init
do
93 # Execute HTTP request with settings configured through attribute
96 if not self.curl
.is_ok
then return answer_failure
(0, "Curl instance is not correctly initialized")
98 var success_response
= new CurlResponseSuccess
99 var callback_receiver
: CurlCallbacks = success_response
100 if self.delegate
!= null then callback_receiver
= self.delegate
.as(not null)
104 err
= self.curl
.prim_curl
.easy_setopt
(new CURLOption.follow_location
, 1)
105 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
107 err
= self.curl
.prim_curl
.easy_setopt
(new CURLOption.url
, url
)
108 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
111 err
= self.curl
.prim_curl
.register_callback
(callback_receiver
, new CURLCallbackType.header
)
112 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
114 err
= self.curl
.prim_curl
.register_callback
(callback_receiver
, new CURLCallbackType.body
)
115 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
118 if self.headers
!= null then
119 var headers_joined
= self.headers
.join_pairs
(": ")
120 err
= self.curl
.prim_curl
.easy_setopt
(new CURLOption.httpheader
, headers_joined
.to_curlslist
)
121 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
125 if self.datas
!= null then
126 var postdatas
= self.datas
.to_url_encoded
(self.curl
.prim_curl
)
127 err
= self.curl
.prim_curl
.easy_setopt
(new CURLOption.postfields
, postdatas
)
128 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
131 var err_resp
= perform
132 if err_resp
!= null then return err_resp
134 var st_code
= self.curl
.prim_curl
.easy_getinfo_long
(new CURLInfoLong.response_code
)
135 if not st_code
== null then success_response
.status_code
= st_code
.response
137 return success_response
140 # Download to file given resource
141 fun download_to_file
(output_file_name
: nullable String): CurlResponse
143 var success_response
= new CurlFileResponseSuccess
145 var callback_receiver
: CurlCallbacks = success_response
146 if self.delegate
!= null then callback_receiver
= self.delegate
.as(not null)
150 err
= self.curl
.prim_curl
.easy_setopt
(new CURLOption.follow_location
, 1)
151 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
153 err
= self.curl
.prim_curl
.easy_setopt
(new CURLOption.url
, url
)
154 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
156 err
= self.curl
.prim_curl
.register_callback
(callback_receiver
, new CURLCallbackType.header
)
157 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
159 err
= self.curl
.prim_curl
.register_callback
(callback_receiver
, new CURLCallbackType.stream
)
160 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
163 if not output_file_name
== null then
164 opt_name
= output_file_name
165 else if not self.url
.substring
(self.url
.length-1
, self.url
.length
) == "/" then
166 opt_name
= self.url
.basename
("")
168 return answer_failure
(0, "Unable to extract file name, please specify one")
171 success_response
.i_file
= new OFile.open
(opt_name
.to_cstring
)
172 if not success_response
.i_file
.is_valid
then
173 success_response
.i_file
.close
174 return answer_failure
(0, "Unable to create associated file")
177 var err_resp
= perform
178 if err_resp
!= null then return err_resp
180 var st_code
= self.curl
.prim_curl
.easy_getinfo_long
(new CURLInfoLong.response_code
)
181 if not st_code
== null then success_response
.status_code
= st_code
.response
183 var speed
= self.curl
.prim_curl
.easy_getinfo_double
(new CURLInfoDouble.speed_download
)
184 if not speed
== null then success_response
.speed_download
= speed
.response
186 var size
= self.curl
.prim_curl
.easy_getinfo_double
(new CURLInfoDouble.size_download
)
187 if not size
== null then success_response
.size_download
= size
.response
189 var time
= self.curl
.prim_curl
.easy_getinfo_double
(new CURLInfoDouble.total_time
)
190 if not time
== null then success_response
.total_time
= time
.response
192 success_response
.i_file
.close
194 return success_response
199 class CurlMailRequest
203 var headers
: nullable HeaderMap = null is writable
204 var headers_body
: nullable HeaderMap = null is writable
205 var from
: nullable String = null is writable
206 var to
: nullable Array[String] = null is writable
207 var cc
: nullable Array[String] = null is writable
208 var bcc
: nullable Array[String] = null is writable
209 var subject
: nullable String = "" is writable
210 var body
: nullable String = "" is writable
211 private var supported_outgoing_protocol
: Array[String] = ["smtp", "smtps"]
213 init (curl
: nullable Curl) is old_style_init
do
217 # Helper method to add conventional space while building entire mail
218 private fun add_conventional_space
(str
: String):String do return "{str}\n" end
220 # Helper method to add pair values to mail content while building it (ex: "To:", "address@mail.com")
221 private fun add_pair_to_content
(str
: String, att
: String, val
: nullable String):String
223 if val
!= null then return "{str}{att}{val}\n"
224 return "{str}{att}\n"
227 # Helper method to add entire list of pairs to mail content
228 private fun add_pairs_to_content
(content
: String, pairs
: HeaderMap):String
230 for h_key
, h_val
in pairs
do content
= add_pair_to_content
(content
, h_key
, h_val
)
234 # Check for host and protocol availability
235 private fun is_supported_outgoing_protocol
(host
: String):CURLCode
237 var host_reach
= host
.split_with
("://")
238 if host_reach
.length
> 1 and supported_outgoing_protocol
.has
(host_reach
[0]) then return once
new CURLCode.ok
239 return once
new CURLCode.unsupported_protocol
242 # Configure server host and user credentials if needed.
243 fun set_outgoing_server
(host
: String, user
: nullable String, pwd
: nullable String): nullable CurlResponseFailed
245 # Check Curl initialisation
246 if not self.curl
.is_ok
then return answer_failure
(0, "Curl instance is not correctly initialized")
251 err
= is_supported_outgoing_protocol
(host
)
252 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
253 err
= self.curl
.prim_curl
.easy_setopt
(new CURLOption.url
, host
)
254 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
257 if not user
== null and not pwd
== null then
258 err
= self.curl
.prim_curl
.easy_setopt
(new CURLOption.username
, user
)
259 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
260 err
= self.curl
.prim_curl
.easy_setopt
(new CURLOption.password
, pwd
)
261 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
267 # Execute Mail request with settings configured through attribute
270 if not self.curl
.is_ok
then return answer_failure
(0, "Curl instance is not correctly initialized")
272 var success_response
= new CurlMailResponseSuccess
275 if self.headers
!= null then
276 content
= add_pairs_to_content
(content
, self.headers
.as(not null))
280 var g_rec
= new Array[String]
281 if self.to
!= null and self.to
.length
> 0 then
282 content
= add_pair_to_content
(content
, "To:", self.to
.join
(","))
283 g_rec
.append
(self.to
.as(not null))
285 if self.cc
!= null and self.cc
.length
> 0 then
286 content
= add_pair_to_content
(content
, "Cc:", self.cc
.join
(","))
287 g_rec
.append
(self.cc
.as(not null))
289 if self.bcc
!= null and self.bcc
.length
> 0 then g_rec
.append
(self.bcc
.as(not null))
291 if g_rec
.length
< 1 then return answer_failure
(0, "The mail recipients can not be empty")
295 err
= self.curl
.prim_curl
.easy_setopt
(new CURLOption.follow_location
, 1)
296 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
298 err
= self.curl
.prim_curl
.easy_setopt
(new CURLOption.mail_rcpt
, g_rec
.to_curlslist
)
299 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
302 if not self.from
== null then
303 content
= add_pair_to_content
(content
, "From:", self.from
)
304 err
= self.curl
.prim_curl
.easy_setopt
(new CURLOption.mail_from
, self.from
.as(not null))
305 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
309 content
= add_pair_to_content
(content
, "Subject:", self.subject
)
312 if self.headers_body
!= null then
313 content
= add_pairs_to_content
(content
, self.headers_body
.as(not null))
317 content
= add_conventional_space
(content
)
318 content
= add_pair_to_content
(content
, "", self.body
)
319 content
= add_conventional_space
(content
)
320 err
= self.curl
.prim_curl
.register_callback
(self, once
new CURLCallbackType.read
)
321 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
322 err
= self.curl
.prim_curl
.register_read_datas_callback
(self, content
)
323 if not err
.is_ok
then return answer_failure
(err
.to_i
, err
.to_s
)
325 var err_resp
= perform
326 if err_resp
!= null then return err_resp
328 return success_response
332 # Callbacks Interface, allow you to manage in your way the different streams
333 interface CurlCallbacks
337 # Callbacks attributes
338 abstract class CurlCallbacksRegisterIntern
339 var delegate
: nullable CurlCallbacks = null is writable
342 # Abstract Curl request response
343 abstract class CurlResponse
346 # Failed Response Class returned when errors during configuration are raised
347 class CurlResponseFailed
351 var error_msg
: String
354 # Success Abstract Response Success Class
355 abstract class CurlResponseSuccessIntern
359 var headers
= new HashMap[String, String]
361 # Receive headers from request due to headers callback registering
362 redef fun header_callback
(line
)
364 var splitted
= line
.split_with
(':')
365 if splitted
.length
> 1 then
366 var key
= splitted
.shift
367 self.headers
[key
] = splitted
.to_s
372 # Success Response Class of a basic response
373 class CurlResponseSuccess
374 super CurlResponseSuccessIntern
379 # Receive body from request due to body callback registering
380 redef fun body_callback
(line
: String)
382 self.body_str
= "{self.body_str}{line}"
386 # Success Response Class of mail request
387 class CurlMailResponseSuccess
388 super CurlResponseSuccessIntern
391 # Success Response Class of a downloaded File
392 class CurlFileResponseSuccess
393 super CurlResponseSuccessIntern
396 var speed_download
= 0
397 var size_download
= 0
399 private var i_file
: nullable OFile = null
401 # Receive bytes stream from request due to stream callback registering
402 redef fun stream_callback
(buffer
, size
, count
)
404 self.i_file
.write
(buffer
, size
, count
)
408 # Pseudo map associating Strings to Strings,
409 # each key can have multiple associations
410 # and the order of insertion is important.
412 private var arr
= new Array[Couple[String, String]]
414 fun []=(k
, v
: String) do arr
.add
(new Couple[String, String](k
, v
))
416 fun [](k
: String): Array[String]
418 var res
= new Array[String]
419 for c
in arr
do if c
.first
== k
then res
.add
(c
.second
)
423 fun iterator
: MapIterator[String, String] do return new HeaderMapIterator(self)
425 # Convert Self to a single string used to post http fields
426 fun to_url_encoded
(curl
: CCurl): String
428 assert curlNotInitialized
: curl
.is_init
else
429 print
"to_url_encoded required a valid instance of CCurl Object."
432 var length
= self.length
439 if i
< length-1
then str
= "{str}&"
446 # Concatenate couple of 'key value' separated by 'sep' in Array
447 fun join_pairs
(sep
: String): Array[String]
449 var col
= new Array[String]
450 for k
, v
in self do col
.add
("{k}{sep}{v}")
454 fun length
: Int do return arr
.length
455 fun is_empty
: Bool do return arr
.is_empty
458 class HeaderMapIterator
459 super MapIterator[String, String]
461 private var iterator
: Iterator[Couple[String, String]]
462 init(map
: HeaderMap) is old_style_init
do self.iterator
= map
.arr
.iterator
464 redef fun is_ok
do return self.iterator
.is_ok
465 redef fun next
do self.iterator
.next
466 redef fun item
do return self.iterator
.item
.second
467 redef fun key
do return self.iterator
.item
.first