GeoIpLookup.coffee 1.5 KB

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