GeoIpLookup.coffee 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. request = require("request")
  2. settings = require("settings-sharelatex")
  3. _ = require("underscore")
  4. logger = require("logger-sharelatex")
  5. currencyMappings = {
  6. "GB":"GBP"
  7. "US":"USD"
  8. "CH":"CHF"
  9. "NZ":"NZD"
  10. "AU":"AUD"
  11. "DK":"DKK"
  12. "NO":"NOK"
  13. "CA":"CAD"
  14. "SE":"SEK"
  15. }
  16. # Countries which would likely prefer Euro's
  17. EuroCountries = ["AT", "BE", "BG", "HR", "CY", "CZ",
  18. "EE", "FI", "FR", "DE", "EL", "HU", "IE",
  19. "IT", "LV", "LT", "LU", "MT", "NL", "PL", "PT",
  20. "RO", "SK", "SI", "ES"]
  21. _.each EuroCountries, (country)-> currencyMappings[country] = "EUR"
  22. module.exports = GeoIpLookup =
  23. getDetails : (ip, callback)->
  24. if !ip?
  25. e = new Error("no ip passed")
  26. return callback(e)
  27. ip = ip.trim().split(" ")[0]
  28. opts =
  29. url: "#{settings.apis.geoIpLookup.url}/#{ip}"
  30. timeout: 1000
  31. json:true
  32. logger.log ip:ip, opts:opts, "getting geo ip details"
  33. request.get opts, (err, res, ipDetails)->
  34. if err?
  35. logger.err err:err, ip:ip, "error getting ip details"
  36. callback(err, ipDetails)
  37. getCurrencyCode : (ip, callback)->
  38. GeoIpLookup.getDetails ip, (err, ipDetails)->
  39. if err? or !ipDetails?
  40. logger.err err:err, ip:ip, "problem getting currencyCode for ip, defaulting to USD"
  41. return callback(null, "USD")
  42. countryCode = ipDetails?.country_code?.toUpperCase()
  43. currencyCode = currencyMappings[countryCode] || "USD"
  44. logger.log ip:ip, currencyCode:currencyCode, ipDetails:ipDetails, "got currencyCode for ip"
  45. callback(err, currencyCode)