UserAgentData.js.flow 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. /**
  2. * Copyright (c) 2013-present, Facebook, Inc.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. *
  7. * @providesModule UserAgentData
  8. */
  9. /**
  10. * Usage note:
  11. * This module makes a best effort to export the same data we would internally.
  12. * At Facebook we use a server-generated module that does the parsing and
  13. * exports the data for the client to use. We can't rely on a server-side
  14. * implementation in open source so instead we make use of an open source
  15. * library to do the heavy lifting and then make some adjustments as necessary.
  16. * It's likely there will be some differences. Some we can smooth over.
  17. * Others are going to be harder.
  18. */
  19. 'use strict';
  20. var UAParser = require('ua-parser-js');
  21. var UNKNOWN = 'Unknown';
  22. var PLATFORM_MAP = {
  23. 'Mac OS': 'Mac OS X'
  24. };
  25. /**
  26. * Convert from UAParser platform name to what we expect.
  27. */
  28. function convertPlatformName(name) {
  29. return PLATFORM_MAP[name] || name;
  30. }
  31. /**
  32. * Get the version number in parts. This is very naive. We actually get major
  33. * version as a part of UAParser already, which is generally good enough, but
  34. * let's get the minor just in case.
  35. */
  36. function getBrowserVersion(version) {
  37. if (!version) {
  38. return {
  39. major: '',
  40. minor: ''
  41. };
  42. }
  43. var parts = version.split('.');
  44. return {
  45. major: parts[0],
  46. minor: parts[1]
  47. };
  48. }
  49. /**
  50. * Get the UA data fom UAParser and then convert it to the format we're
  51. * expecting for our APIS.
  52. */
  53. var parser = new UAParser();
  54. var results = parser.getResult();
  55. // Do some conversion first.
  56. var browserVersionData = getBrowserVersion(results.browser.version);
  57. var uaData = {
  58. browserArchitecture: results.cpu.architecture || UNKNOWN,
  59. browserFullVersion: results.browser.version || UNKNOWN,
  60. browserMinorVersion: browserVersionData.minor || UNKNOWN,
  61. browserName: results.browser.name || UNKNOWN,
  62. browserVersion: results.browser.major || UNKNOWN,
  63. deviceName: results.device.model || UNKNOWN,
  64. engineName: results.engine.name || UNKNOWN,
  65. engineVersion: results.engine.version || UNKNOWN,
  66. platformArchitecture: results.cpu.architecture || UNKNOWN,
  67. platformName: convertPlatformName(results.os.name) || UNKNOWN,
  68. platformVersion: results.os.version || UNKNOWN,
  69. platformFullVersion: results.os.version || UNKNOWN
  70. };
  71. module.exports = uaData;