Module: BlackStack::Netting

Defined in:
lib/functions.rb

Overview


Network


Defined Under Namespace

Classes: ApiCallException

Constant Summary collapse

CALL_METHOD_GET =
'get'
CALL_METHOD_POST =
'post'
DEFAULT_SSL_VERIFY_MODE =
OpenSSL::SSL::VERIFY_NONE
SUCCESS =
'success'
DEFAULT_OPEN_TIMEOUT =

seconds to wait for the initial connection

10
DEFAULT_READ_TIMEOUT =

seconds to wait for each response

30
DEFAULT_RETRY_ATTEMPTS =
3
@@lockfiles =
[]
@@max_api_call_channels =

0 means infinite

0

Class Method Summary collapse

Class Method Details

.add_param(url, param_name, param_value) ⇒ Object

Add a parameter to the url. It doesn’t validate if the param already exists.



1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
# File 'lib/functions.rb', line 1131

def self.add_param(url, param_name, param_value)
  uri = URI(url)
  params = URI.decode_www_form(uri.query || '')

  if (params.size==0)
    params << [param_name, param_value]
    uri.query = URI.encode_www_form(params)
    return uri.to_s
  else
    uri.query = URI.encode_www_form(params)
    return uri.to_s + "&" + param_name + "=" + param_value
  end
end

.api_call(url, params = {}, method = BlackStack::Netting::CALL_METHOD_POST, ssl_verify_mode = BlackStack::Netting::DEFAULT_SSL_VERIFY_MODE, max_retries = 5) ⇒ Object

TODO: deprecated



1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
# File 'lib/functions.rb', line 1011

def self.api_call(url, params={}, method=BlackStack::Netting::CALL_METHOD_POST, ssl_verify_mode=BlackStack::Netting::DEFAULT_SSL_VERIFY_MODE, max_retries=5)
  nTries = 0
  bSuccess = false
  parsed = nil
  sError = ""
  while (nTries < max_retries && bSuccess == false)
    begin
      nTries = nTries + 1
      res = BlackStack::Netting::call_post(url, params, ssl_verify_mode) if method==BlackStack::Netting::CALL_METHOD_POST
      res = BlackStack::Netting::call_get(url, params, ssl_verify_mode) if method==BlackStack::Netting::CALL_METHOD_GET
      parsed = JSON.parse(res.body)
      if (parsed['status']==BlackStack::Netting::SUCCESS)
        bSuccess = true
      else
        sError = "Status: #{parsed['status'].to_s}. Description: #{parsed['value'].to_s}."
      end
    rescue Errno::ECONNREFUSED => e
      sError = "Errno::ECONNREFUSED:" + e.to_console
    rescue => e2
      sError = "Exception:" + e2.to_console
    end
  end # while

  if (bSuccess==false)
    raise "#{sError}"
  end
end

.call_get(url, params = {}, ssl_verify_mode = BlackStack::Netting::DEFAULT_SSL_VERIFY_MODE, support_redirections = true) ⇒ Object

New call_get



906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
# File 'lib/functions.rb', line 906

def self.call_get(url, params = {}, ssl_verify_mode=BlackStack::Netting::DEFAULT_SSL_VERIFY_MODE, support_redirections=true)
  uri = URI(url)
  uri.query = URI.encode_www_form(params)
  Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https', :verify_mode => ssl_verify_mode) do |http|
    req = Net::HTTP::Get.new uri
    #req.body = body if !body.nil?
    res = http.request req
    case res
    when Net::HTTPSuccess then res
    when Net::HTTPRedirection then BlackStack::Netting::call_get(URI(res['location']), params, ssl_verify_mode, false) if support_redirections
    else
      res.error!
    end
  end
end

.call_post(url, body = {}, ssl_verify_mode = BlackStack::Netting::DEFAULT_SSL_VERIFY_MODE, support_redirections = true) ⇒ Object

Call the API and return th result.

Unlike Net::HTTP::Post, this method support complex json descriptors in order to submit complex data strucutres to access points. For more information about support for complex data structures, reference to: github.com/leandrosardi/mysaas/issues/59

url: valid internet address body: hash of body to attach in the call ssl_verify_mode: you can disabele SSL verification here. max_channels: this method use lockfiles to prevent an excesive number of API calls from each datacenter. There is not allowed more simultaneous calls than max_channels.

TODO: parameter support_redirections has been deprecated.



934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
# File 'lib/functions.rb', line 934

def self.call_post(url,
  body = {},
  ssl_verify_mode = BlackStack::Netting::DEFAULT_SSL_VERIFY_MODE,
  support_redirections = true)

  max_redirects = 5
  attempts      = 0

  while attempts < DEFAULT_RETRY_ATTEMPTS
    begin
      # Create a basic Faraday connection
      conn = Faraday.new(
        url: url, #"#{uri.scheme}://#{uri.host}:#{uri.port}", 
        ssl: { verify: ssl_verify_mode != OpenSSL::SSL::VERIFY_NONE },
        request: {
          open_timeout: DEFAULT_OPEN_TIMEOUT,
          timeout:      DEFAULT_READ_TIMEOUT
        }
      ) do |f|
        f.adapter Faraday.default_adapter
      end

      # Perform the initial POST request
      response = conn.post(uri.path) do |req|
        req.body = JSON.generate(body) # Manually serialize to JSON
        req.headers['Content-Type'] = 'application/json'
        req.headers['Accept']       = 'application/json'
      end

      # Manually handle HTTP redirects if requested
      redirect_count = 0
      while support_redirections &&
        response.status.between?(300, 399) &&
        response.headers['location'] &&
        redirect_count < max_redirects

        redirect_count += 1
        new_url = URI.join(url, response.headers['location']).to_s

        # Update `url` for the next iteration
        url = new_url
        uri = URI.parse(new_url)

        response = conn.post(uri.path) do |req|
          req.body = JSON.generate(body)
          req.headers['Content-Type'] = 'application/json'
          req.headers['Accept']       = 'application/json'
        end
      end

      # Raise an error if the final response is not 2xx
      unless response.success?
        raise "HTTP #{response.status}: #{response.body}"
      end

      # If all is good, return the Faraday response object
      return response

    rescue Errno::ETIMEDOUT, Timeout::Error, Faraday::ConnectionFailed => e
      # Basic retry logic for transient network errors
      attempts += 1
      if attempts < DEFAULT_RETRY_ATTEMPTS
        sleep_time = 2**attempts
        sleep(sleep_time)  # Exponential backoff
        retry
      else
        # Too many failures, re-raise
        raise e
      end
    rescue => e
      # For any other error, just re-raise
      raise e
    end
  end
end

.change_param(url, param_name, param_value) ⇒ Object

Changes the value of a parameter in the url. It doesn’t validate if the param already exists.



1146
1147
1148
1149
1150
1151
1152
1153
# File 'lib/functions.rb', line 1146

def self.change_param(url, param_name, param_value)
  uri = URI(url)
#  params = URI.decode_www_form(uri.query || [])
  params = CGI.parse(uri.query)
  params["start"] = param_value
  uri.query = URI.encode_www_form(params)
  uri.to_s
end

.download(url, to) ⇒ Object

Download a file from an url to a local folder. url: must be somedomain.net instead of somedomain.net/, otherwise, it will throw exception. to: must be a valid path to a folder.



1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
# File 'lib/functions.rb', line 1042

def self.download(url, to)
  uri = URI(url)
  domain = uri.host.start_with?('www.') ? uri.host[4..-1] : uri.host
  path = uri.path
  filename = path.split("/").last
  Net::HTTP.start(domain) do |http|
    resp = http.get(path)
    open(to, "wb") do |file|
      file.write(resp.body)
    end
  end
end

.file_age(filename) ⇒ Object

returns the age in days of the given file



1078
1079
1080
# File 'lib/functions.rb', line 1078

def self.file_age(filename)
  (Time.now - File.ctime(filename))/(24*3600)
end

.get_host_without_www(url) ⇒ Object

Removes the ‘www.’ from an URL.



1062
1063
1064
1065
1066
# File 'lib/functions.rb', line 1062

def self.get_host_without_www(url)
  url = "http://#{url}" if URI.parse(url).scheme.nil?
  host = URI.parse(url).host.downcase
  host.start_with?('www.') ? host[4..-1] : host
end

.get_redirect(url) ⇒ Object

Get the final URL if a web page is redirecting.



1069
1070
1071
1072
1073
1074
1075
# File 'lib/functions.rb', line 1069

def self.get_redirect(url)
  uri = URI.parse(url)
  protocol = uri.scheme
  host = uri.host.downcase
  res = Net::HTTP.get_response(uri)
  "#{protocol}://#{host}#{res['location']}"
end

.get_url_extension(url) ⇒ Object

Return the extension of the last path into an URL. Example: get_url_extension(“connect.data.com/sitemap_index.xml?foo_param=foo_value”) => “.xml”



1057
1058
1059
# File 'lib/functions.rb', line 1057

def self.get_url_extension(url)
  return File.extname(URI.parse(url).path.to_s)
end

.getDomainFromEmail(email) ⇒ Object



1183
1184
1185
1186
1187
1188
1189
# File 'lib/functions.rb', line 1183

def self.getDomainFromEmail(email)
  if email.email?
    return email.split("@").last
  else
    raise "getDomainFromEmail: Wrong email format."
  end
end

.getDomainFromUrl(url) ⇒ Object

get the domain from any url



1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
# File 'lib/functions.rb', line 1167

def self.getDomainFromUrl(url)
  if (url !~ /^http:\/\//i && url !~ /^https:\/\//i)
    url = "http://#{url}"
  end

  if (URI.parse(url).host == nil)
    raise "Cannot get domain for #{url}"
  end

  if (url.to_s.length>0)
    return URI.parse(url).host.sub(/^www\./, '')
  else
    return nil
  end
end

.getMailHandler(email) ⇒ Object

raise an exception if email is not a valid email address. return an array with the companies who are hosting an email address, by running the linux command host.



1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
# File 'lib/functions.rb', line 1224

def self.getMailHandler(email)
  value = email
  # raise an exception if the data type is an email, but the email is not valid.
  raise "Email #{value} is not valid" if !value.email?
  # extract the domain from the email
  domain = value.split('@').last
  # run the `host` command
  s = `host -t mx #{domain}`
  # extract the domains from the output
  a = s.split("\n").map { |l| l.split.last }
  # extract the company who is hosting the mail
  a.map { |d| d.split('.').last(2).join('.') }.uniq
end

.getWhoisDomains(domain, allow_heuristic_to_avoid_hosting_companies = false) ⇒ Object



1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
# File 'lib/functions.rb', line 1191

def self.getWhoisDomains(domain, allow_heuristic_to_avoid_hosting_companies=false)
  a = Array.new
  c = Whois::Client.new
  r = c.lookup(domain)

  res = r.to_s.scan(/Registrant Email: (#{BlackStack::Strings::MATCH_EMAIL})/).first
  if (res!=nil)
    a << BlackStack::Netting::getDomainFromEmail(res[0].downcase)
  end

  res = r.to_s.scan(/Admin Email: (#{BlackStack::Strings::MATCH_EMAIL})/).first
  if (res!=nil)
    a << BlackStack::Netting::getDomainFromEmail(res[0].downcase)
  end

  res = r.to_s.scan(/Tech Email: (#{BlackStack::Strings::MATCH_EMAIL})/).first
  if (res!=nil)
    a << BlackStack::Netting::getDomainFromEmail(res[0].downcase)
  end

  # remover duplicados
  a = a.uniq

  #
  if (allow_heuristic_to_avoid_hosting_companies==true)
    # TODO: develop this feature
  end

  return a
end

.isPersonalEmail?(email) ⇒ Boolean

raise an exception if email is not a valid email address. return if the email domain is gmail, hotmail, outlook, yahoo, comcast, aol, msn or sbcglobal.

Returns:

  • (Boolean)


1240
1241
1242
1243
1244
1245
1246
1247
1248
# File 'lib/functions.rb', line 1240

def self.isPersonalEmail?(email)
  value = email
  # raise an exception if the data type is an email, but the email is not valid.
  raise "Email #{value} is not valid" if !value.email?
  # extract the domain from the email
  domain = value.split('@').last
  #
  return domain=~/gmail\.com/ || domain=~/hotmail\.com/ || domain=~/outlook\.com/ || domain=~/yahoo\.com/ || domain=~/comcast\.com/ || domain=~/aol\.com/ || domain=~/msn\.com/ || domain=~/sbcglobal\.net/ ? true : false
end

.lockfilesObject



877
878
879
# File 'lib/functions.rb', line 877

def self.lockfiles()
  @@lockfiles
end

.max_api_call_channelsObject



873
874
875
# File 'lib/functions.rb', line 873

def self.max_api_call_channels()
  @@max_api_call_channels
end

.params(url) ⇒ Object

returns a hash with the parametes in the url



1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
# File 'lib/functions.rb', line 1118

def self.params(url)
  # TODO: Corregir este parche:
  # => El codigo de abajo usa la URL de una busqueda en google. Esta url generara una excepcion cuando se intenta parsear sus parametros.
  # => Ejecutar las 2 lineas de abajo para verificar.
  # => url = "https://www.google.com/webhp#q=[lead+generation]+%22John%22+%22Greater+New+York+City+Area+*+Financial+Services%22+site:linkedin.com%2Fpub+-site:linkedin.com%2Fpub%2Fdir"
  # => p = CGI::parse(URI.parse(url).query)
  # => La linea de abajo hace un gsbub que hace que esta url siga funcionando como busqueda de google, y ademas se posible parsearla.
  url = url.gsub("webhp#q=", "webhp?q=")

  return CGI::parse(URI.parse(url).query)
end

.set(h) ⇒ Object



881
882
883
884
885
886
887
888
889
890
# File 'lib/functions.rb', line 881

def self.set(h)
  @@max_api_call_channels = h[:max_api_call_channels]
  @@lockfiles = []

  i = 0
  while i<@@max_api_call_channels
    @@lockfiles << File.open("./apicall.channel_#{i.to_s}.lock", "w")
    i+=1
  end
end

.set_param(url, param_name, param_value) ⇒ Object

Change or add the value of a parameter in the url, depending if the parameter already exists or not.



1156
1157
1158
1159
1160
1161
1162
1163
1164
# File 'lib/functions.rb', line 1156

def self.set_param(url, param_name, param_value)
  params = BlackStack::Netting::params(url)
  if ( params.has_key?(param_name) == true )
    newurl = BlackStack::Netting::change_param(url, param_name, param_value)
  else
    newurl = BlackStack::Netting::add_param(url, param_name, param_value)
  end
  return newurl
end