Пример #1
0
def _DoMain(argv):
  parser = argparse.ArgumentParser()
  parser.add_argument("--out", help="Path for java output.")
  parser.add_argument("--srcjar", help="Path for srcjar output.")
  options = parser.parse_args(argv)
  if not options.out and not options.srcjar:
    parser.print_help()
    sys.exit(-1)

  values = {}
  values['GOOGLE_API_KEY'] = google_api_keys.GetAPIKey()
  values['GOOGLE_API_KEY_PHYSICAL_WEB_TEST'] = (google_api_keys.
      GetAPIKeyPhysicalWebTest())
  values['GOOGLE_CLIENT_ID_MAIN'] = google_api_keys.GetClientID('MAIN')
  values['GOOGLE_CLIENT_SECRET_MAIN'] = google_api_keys.GetClientSecret('MAIN')
  values['GOOGLE_CLIENT_ID_CLOUD_PRINT'] = google_api_keys.GetClientID(
      'CLOUD_PRINT')
  values['GOOGLE_CLIENT_SECRET_CLOUD_PRINT'] = google_api_keys.GetClientSecret(
      'CLOUD_PRINT')
  values['GOOGLE_CLIENT_ID_REMOTING'] = google_api_keys.GetClientID('REMOTING')
  values['GOOGLE_CLIENT_SECRET_REMOTING'] = google_api_keys.GetClientSecret(
      'REMOTING')
  values['GOOGLE_CLIENT_ID_REMOTING_HOST'] = google_api_keys.GetClientID(
      'REMOTING_HOST')
  values['GOOGLE_CLIENT_SECRET_REMOTING_HOST'] = (google_api_keys.
      GetClientSecret('REMOTING_HOST'))
  values['GOOGLE_CLIENT_ID_REMOTING_IDENTITY_API'] = (google_api_keys.
      GetClientID('REMOTING_IDENTITY_API'))

  if options.out:
    _DoWriteJavaOutput(options.out, values)
  if options.srcjar:
    _DoWriteJarOutput(options.srcjar, values)
Пример #2
0
def _DoMain(argv):
    parser = argparse.ArgumentParser()
    parser.add_argument("--out", help="Path for java output.")
    parser.add_argument("--srcjar", help="Path for srcjar output.")
    options = parser.parse_args(argv)
    if not options.out and not options.srcjar:
        parser.print_help()
        sys.exit(-1)

    values = {}
    values['GOOGLE_API_KEY'] = google_api_keys.GetAPIKey()
    values['GOOGLE_API_KEY_ANDROID_NON_STABLE'] = (
        google_api_keys.GetAPIKeyAndroidNonStable())
    values['GOOGLE_CLIENT_ID_MAIN'] = google_api_keys.GetClientID('MAIN')
    values['GOOGLE_CLIENT_SECRET_MAIN'] = google_api_keys.GetClientSecret(
        'MAIN')
    values['GOOGLE_CLIENT_ID_REMOTING'] = google_api_keys.GetClientID(
        'REMOTING')
    values['GOOGLE_CLIENT_SECRET_REMOTING'] = google_api_keys.GetClientSecret(
        'REMOTING')
    values['GOOGLE_CLIENT_ID_REMOTING_HOST'] = google_api_keys.GetClientID(
        'REMOTING_HOST')
    values['GOOGLE_CLIENT_SECRET_REMOTING_HOST'] = (
        google_api_keys.GetClientSecret('REMOTING_HOST'))
    values['GOOGLE_CLIENT_ID_REMOTING_IDENTITY_API'] = (
        google_api_keys.GetClientID('REMOTING_IDENTITY_API'))

    if options.out:
        _DoWriteJavaOutput(options.out, values)
    if options.srcjar:
        _DoWriteJarOutput(options.srcjar, values)
Пример #3
0
def buildWebApp(buildtype, version, destination, zip_path, manifest_template,
                webapp_type, appid, app_client_id, app_name, app_description,
                app_capabilities, manifest_key, files, files_listfile,
                locales_listfile, jinja_paths, service_environment, use_gcd):
    """Does the main work of building the webapp directory and zipfile.

  Args:
    buildtype: the type of build ("Official", "Release" or "Dev").
    destination: A string with path to directory where the webapp will be
                 written.
    zipfile: A string with path to the zipfile to create containing the
             contents of |destination|.
    manifest_template: jinja2 template file for manifest.
    webapp_type: webapp type ("v1", "v2", "v2_pnacl" or "app_remoting").
    appid: A string with the Remoting Application Id (only used for app
           remoting webapps). If supplied, it defaults to using the
           test API server.
    app_client_id: The OAuth2 client ID for the webapp.
    app_name: A string with the name of the application.
    app_description: A string with the description of the application.
    app_capabilities: A set of strings naming the capabilities that should be
                      enabled for this application.
    manifest_key: The manifest key for the webapp.
    files: An array of strings listing the paths for resources to include
           in this webapp.
    files_listfile: The name of a file containing a list of files, one per
                    line, identifying the resources to include in this webapp.
                    This is an alternate to specifying the files directly via
                    the 'files' option. The files listed in this file are
                    appended to the files passed via the 'files' option, if any.
    locales_listfile: The name of a file containing a list of locales, one per
                      line, which are copied, along with their directory
                      structure, from the _locales directory down.
    jinja_paths: An array of paths to search for {%include} directives in
                 addition to the directory containing the manifest template.
    service_environment: Used to point the webapp to one of the
                         dev/test/staging/vendor/prod/prod-testing environments
    use_gcd: True if GCD support should be enabled.
  """

    # Load the locales files from the locales_listfile.
    if not locales_listfile:
        raise Exception('You must specify a locales_listfile')
    locales = []
    with open(locales_listfile) as input:
        for s in input:
            locales.append(s.rstrip())

    # Load the files from the files_listfile.
    if files_listfile:
        with open(files_listfile) as input:
            for s in input:
                files.append(s.rstrip())

    # Ensure a fresh directory.
    try:
        shutil.rmtree(destination)
    except OSError:
        if os.path.exists(destination):
            raise
        else:
            pass
    os.makedirs(destination, 0775)

    if buildtype != 'Official' and buildtype != 'Release' and buildtype != 'Dev':
        raise Exception('Unknown buildtype: ' + buildtype)

    jinja_context = {
        'webapp_type': webapp_type,
        'buildtype': buildtype,
    }

    # Copy all the files.
    for current_file in files:
        destination_file = os.path.join(destination,
                                        os.path.basename(current_file))

        # Process *.jinja2 files as jinja2 templates
        if current_file.endswith(".jinja2"):
            destination_file = destination_file[:-len(".jinja2")]
            processJinjaTemplate(current_file, jinja_paths, destination_file,
                                 jinja_context)
        else:
            shutil.copy2(current_file, destination_file)

    # Copy all the locales, preserving directory structure
    destination_locales = os.path.join(destination, '_locales')
    os.mkdir(destination_locales, 0775)
    remoting_locales = os.path.join(destination, 'remoting_locales')
    os.mkdir(remoting_locales, 0775)
    for current_locale in locales:
        extension = os.path.splitext(current_locale)[1]
        if extension == '.json':
            locale_id = os.path.split(os.path.split(current_locale)[0])[1]
            destination_dir = os.path.join(destination_locales, locale_id)
            destination_file = os.path.join(destination_dir,
                                            os.path.split(current_locale)[1])
            os.mkdir(destination_dir, 0775)
            shutil.copy2(current_locale, destination_file)
        elif extension == '.pak':
            destination_file = os.path.join(remoting_locales,
                                            os.path.split(current_locale)[1])
            shutil.copy2(current_locale, destination_file)
        else:
            raise Exception('Unknown extension: ' + current_locale)

    # Set client plugin type.
    # TODO(wez): Use 'native' in app_remoting until b/17441659 is resolved.
    client_plugin = 'pnacl' if webapp_type == 'v2_pnacl' else 'native'
    findAndReplace(os.path.join(destination, 'plugin_settings.js'),
                   "'CLIENT_PLUGIN_TYPE'", "'" + client_plugin + "'")

    # Allow host names for google services/apis to be overriden via env vars.
    oauth2AccountsHost = os.environ.get('OAUTH2_ACCOUNTS_HOST',
                                        'https://accounts.google.com')
    oauth2ApiHost = os.environ.get('OAUTH2_API_HOST',
                                   'https://www.googleapis.com')
    directoryApiHost = os.environ.get('DIRECTORY_API_HOST',
                                      'https://www.googleapis.com')

    is_app_remoting_webapp = webapp_type == 'app_remoting'
    is_prod_service_environment = service_environment == 'vendor' or \
                                  service_environment == 'prod' or \
                                  service_environment == 'prod-testing'
    if is_app_remoting_webapp:
        appRemotingApiHost = os.environ.get('APP_REMOTING_API_HOST', None)
        appRemotingApplicationId = os.environ.get(
            'APP_REMOTING_APPLICATION_ID', None)

        # Release/Official builds are special because they are what we will upload
        # to the web store.  The checks below will validate that prod builds are
        # being generated correctly (no overrides) and with the correct buildtype.
        # They also verify that folks are not accidentally building dev/test/staging
        # apps for release (no impersonation) instead of dev.
        if is_prod_service_environment and buildtype == 'Dev':
            raise Exception(
                "Prod environment cannot be built for 'dev' builds")

        if buildtype != 'Dev':
            if not is_prod_service_environment:
                raise Exception('Invalid service_environment targeted for ' +
                                buildtype + ': ' + service_environment)
            if appid != None:
                raise Exception('Cannot pass in an appid for ' + buildtype +
                                ' builds: ' + service_environment)
            if appRemotingApiHost != None:
                raise Exception(
                    'Cannot set APP_REMOTING_API_HOST env var for ' +
                    buildtype + ' builds')
            if appRemotingApplicationId != None:
                raise Exception(
                    'Cannot set APP_REMOTING_APPLICATION_ID env var for ' +
                    buildtype + ' builds')

        # If an Application ID was set (either from service_environment variable or
        # from a command line argument), hardcode it, otherwise get it at runtime.
        effectiveAppId = appRemotingApplicationId or appid
        if effectiveAppId:
            appRemotingApplicationId = "'" + effectiveAppId + "'"
        else:
            appRemotingApplicationId = "chrome.i18n.getMessage('@@extension_id')"
        findAndReplace(os.path.join(destination, 'plugin_settings.js'),
                       "'APP_REMOTING_APPLICATION_ID'",
                       appRemotingApplicationId)

    oauth2BaseUrl = oauth2AccountsHost + '/o/oauth2'
    oauth2ApiBaseUrl = oauth2ApiHost + '/oauth2'
    directoryApiBaseUrl = directoryApiHost + '/chromoting/v1'

    if is_app_remoting_webapp:
        # Set the apiary endpoint and then set the endpoint version
        if not appRemotingApiHost:
            if is_prod_service_environment:
                appRemotingApiHost = 'https://www.googleapis.com'
            else:
                appRemotingApiHost = 'https://www-googleapis-test.sandbox.google.com'

        if service_environment == 'dev':
            appRemotingServicePath = '/appremoting/v1beta1_dev'
        elif service_environment == 'test':
            appRemotingServicePath = '/appremoting/v1beta1'
        elif service_environment == 'staging':
            appRemotingServicePath = '/appremoting/v1beta1_staging'
        elif service_environment == 'vendor':
            appRemotingServicePath = '/appremoting/v1beta1_vendor'
        elif service_environment == 'prod':
            appRemotingServicePath = '/appremoting/v1beta1'
        elif service_environment == 'prod-testing':
            appRemotingServicePath = '/appremoting/v1beta1_prod_testing'
        else:
            raise Exception('Unknown service environment: ' +
                            service_environment)
        appRemotingApiBaseUrl = appRemotingApiHost + appRemotingServicePath
    else:
        appRemotingApiBaseUrl = ''

    replaceBool(destination, 'USE_GCD', use_gcd)
    replaceString(destination, 'OAUTH2_BASE_URL', oauth2BaseUrl)
    replaceString(destination, 'OAUTH2_API_BASE_URL', oauth2ApiBaseUrl)
    replaceString(destination, 'DIRECTORY_API_BASE_URL', directoryApiBaseUrl)
    if is_app_remoting_webapp:
        replaceString(destination, 'APP_REMOTING_API_BASE_URL',
                      appRemotingApiBaseUrl)

    # Substitute hosts in the manifest's CSP list.
    # Ensure we list the API host only once if it's the same for multiple APIs.
    googleApiHosts = ' '.join(set([oauth2ApiHost, directoryApiHost]))

    # WCS and the OAuth trampoline are both hosted on talkgadget. Split them into
    # separate suffix/prefix variables to allow for wildcards in manifest.json.
    talkGadgetHostSuffix = os.environ.get('TALK_GADGET_HOST_SUFFIX',
                                          'talkgadget.google.com')
    talkGadgetHostPrefix = os.environ.get('TALK_GADGET_HOST_PREFIX',
                                          'https://chromoting-client.')
    oauth2RedirectHostPrefix = os.environ.get('OAUTH2_REDIRECT_HOST_PREFIX',
                                              'https://chromoting-oauth.')

    # Use a wildcard in the manifest.json host specs if the prefixes differ.
    talkGadgetHostJs = talkGadgetHostPrefix + talkGadgetHostSuffix
    talkGadgetBaseUrl = talkGadgetHostJs + '/talkgadget/'
    if talkGadgetHostPrefix == oauth2RedirectHostPrefix:
        talkGadgetHostJson = talkGadgetHostJs
    else:
        talkGadgetHostJson = 'https://*.' + talkGadgetHostSuffix

    # Set the correct OAuth2 redirect URL.
    oauth2RedirectHostJs = oauth2RedirectHostPrefix + talkGadgetHostSuffix
    oauth2RedirectHostJson = talkGadgetHostJson
    oauth2RedirectPath = '/talkgadget/oauth/chrome-remote-desktop'
    oauth2RedirectBaseUrlJs = oauth2RedirectHostJs + oauth2RedirectPath
    oauth2RedirectBaseUrlJson = oauth2RedirectHostJson + oauth2RedirectPath
    if buildtype == 'Official':
        oauth2RedirectUrlJs = (
            "'" + oauth2RedirectBaseUrlJs +
            "/rel/' + chrome.i18n.getMessage('@@extension_id')")
        oauth2RedirectUrlJson = oauth2RedirectBaseUrlJson + '/rel/*'
    else:
        oauth2RedirectUrlJs = "'" + oauth2RedirectBaseUrlJs + "/dev'"
        oauth2RedirectUrlJson = oauth2RedirectBaseUrlJson + '/dev*'
    thirdPartyAuthUrlJs = oauth2RedirectBaseUrlJs + '/thirdpartyauth'
    thirdPartyAuthUrlJson = oauth2RedirectBaseUrlJson + '/thirdpartyauth*'
    replaceString(destination, 'TALK_GADGET_URL', talkGadgetBaseUrl)
    findAndReplace(os.path.join(destination, 'plugin_settings.js'),
                   "'OAUTH2_REDIRECT_URL'", oauth2RedirectUrlJs)

    # Configure xmpp server and directory bot settings in the plugin.
    replaceBool(destination, 'XMPP_SERVER_USE_TLS',
                getenvBool('XMPP_SERVER_USE_TLS', True))
    xmppServer = os.environ.get('XMPP_SERVER', 'talk.google.com:443')
    replaceString(destination, 'XMPP_SERVER', xmppServer)
    replaceString(
        destination, 'DIRECTORY_BOT_JID',
        os.environ.get('DIRECTORY_BOT_JID', '*****@*****.**'))
    replaceString(destination, 'THIRD_PARTY_AUTH_REDIRECT_URL',
                  thirdPartyAuthUrlJs)

    # Set the correct API keys.
    # For overriding the client ID/secret via env vars, see google_api_keys.py.
    apiClientId = google_api_keys.GetClientID('REMOTING')
    apiClientSecret = google_api_keys.GetClientSecret('REMOTING')
    apiKey = google_api_keys.GetAPIKeyRemoting()

    if is_app_remoting_webapp and buildtype != 'Dev':
        if not app_client_id:
            raise Exception('Invalid app_client_id passed in: "' +
                            app_client_id + '"')
        apiClientIdV2 = app_client_id + '.apps.googleusercontent.com'
    else:
        apiClientIdV2 = google_api_keys.GetClientID('REMOTING_IDENTITY_API')

    replaceString(destination, 'API_CLIENT_ID', apiClientId)
    replaceString(destination, 'API_CLIENT_SECRET', apiClientSecret)
    replaceString(destination, 'API_KEY', apiKey)

    # Write the application capabilities.
    appCapabilities = ','.join(
        ['remoting.ClientSession.Capability.' + x for x in app_capabilities])
    findAndReplace(os.path.join(destination, 'app_capabilities.js'),
                   "'APPLICATION_CAPABILITIES'", appCapabilities)

    # Use a consistent extension id for dev builds.
    # AppRemoting builds always use the dev app id - the correct app id gets
    # written into the manifest later.
    if is_app_remoting_webapp:
        if buildtype != 'Dev':
            if not manifest_key:
                raise Exception('Invalid manifest_key passed in: "' +
                                manifest_key + '"')
            manifestKey = '"key": "' + manifest_key + '",'
        else:
            manifestKey = '"key": "remotingdevbuild",'
    elif buildtype != 'Official':
        # TODO(joedow): Update the chromoting webapp GYP entries to include keys.
        manifestKey = '"key": "remotingdevbuild",'
    else:
        manifestKey = ''

    # Generate manifest.
    if manifest_template:
        context = {
            'webapp_type': webapp_type,
            'FULL_APP_VERSION': version,
            'MANIFEST_KEY_FOR_UNOFFICIAL_BUILD': manifestKey,
            'OAUTH2_REDIRECT_URL': oauth2RedirectUrlJson,
            'TALK_GADGET_HOST': talkGadgetHostJson,
            'THIRD_PARTY_AUTH_REDIRECT_URL': thirdPartyAuthUrlJson,
            'REMOTING_IDENTITY_API_CLIENT_ID': apiClientIdV2,
            'OAUTH2_BASE_URL': oauth2BaseUrl,
            'OAUTH2_API_BASE_URL': oauth2ApiBaseUrl,
            'DIRECTORY_API_BASE_URL': directoryApiBaseUrl,
            'APP_REMOTING_API_BASE_URL': appRemotingApiBaseUrl,
            'OAUTH2_ACCOUNTS_HOST': oauth2AccountsHost,
            'GOOGLE_API_HOSTS': googleApiHosts,
            'APP_NAME': app_name,
            'APP_DESCRIPTION': app_description,
            'OAUTH_GDRIVE_SCOPE': '',
            'USE_GCD': use_gcd,
            'XMPP_SERVER': xmppServer,
        }
        if 'GOOGLE_DRIVE' in app_capabilities:
            context['OAUTH_GDRIVE_SCOPE'] = (
                '"https://docs.google.com/feeds/", '
                '"https://www.googleapis.com/auth/drive",')
        processJinjaTemplate(manifest_template, jinja_paths,
                             os.path.join(destination, 'manifest.json'),
                             context)

    # Make the zipfile.
    createZip(zip_path, destination)

    return 0
Пример #4
0
def buildWebApp(buildtype, version, destination, zip_path,
                manifest_template, appid, app_client_id, app_name,
                app_description, app_capabilities, manifest_key, files,
                files_listfile, locales_listfile, jinja_paths,
                service_environment, use_gcd):
  """Does the main work of building the webapp directory and zipfile.

  Args:
    buildtype: the type of build ("Official", "Release" or "Dev").
    destination: A string with path to directory where the webapp will be
                 written.
    zipfile: A string with path to the zipfile to create containing the
             contents of |destination|.
    manifest_template: jinja2 template file for manifest.
    appid: A string with the Remoting Application Id (only used for app
           remoting webapps). If supplied, it defaults to using the
           test API server.
    app_client_id: The OAuth2 client ID for the webapp.
    app_name: A string with the name of the application.
    app_description: A string with the description of the application.
    app_capabilities: A set of strings naming the capabilities that should be
                      enabled for this application.
    manifest_key: The manifest key for the webapp.
    files: An array of strings listing the paths for resources to include
           in this webapp.
    files_listfile: The name of a file containing a list of files, one per
                    line, identifying the resources to include in this webapp.
                    This is an alternate to specifying the files directly via
                    the 'files' option. The files listed in this file are
                    appended to the files passed via the 'files' option, if any.
    locales_listfile: The name of a file containing a list of locales, one per
                      line, which are copied, along with their directory
                      structure, from the _locales directory down.
    jinja_paths: An array of paths to search for {%include} directives in
                 addition to the directory containing the manifest template.
    service_environment: Used to point the webapp to the dev/prod environments.
    use_gcd: True if GCD support should be enabled.
  """

  # Load the locales files from the locales_listfile.
  if not locales_listfile:
    raise Exception('You must specify a locales_listfile')
  locales = []
  with open(locales_listfile) as input:
    for s in input:
      locales.append(s.rstrip())

  # Load the files from the files_listfile.
  if files_listfile:
    with open(files_listfile) as input:
      for s in input:
        files.append(s.rstrip())

#Ensure a fresh directory.
  try:
    shutil.rmtree(destination)
  except OSError:
    if os.path.exists(destination):
      raise
    else:
      pass
  os.makedirs(destination, 0775)

  if buildtype != 'Official' and buildtype != 'Release' and buildtype != 'Dev':
    raise Exception('Unknown buildtype: ' + buildtype)

  jinja_context = {
    'buildtype': buildtype,
  }

  # Copy all the files.
  for current_file in files:
    destination_file = os.path.join(destination, os.path.basename(current_file))

    # Process *.jinja2 files as jinja2 templates
    if current_file.endswith(".jinja2"):
      destination_file = destination_file[:-len(".jinja2")]
      processJinjaTemplate(current_file, jinja_paths,
                           destination_file, jinja_context)
    else:
      shutil.copy2(current_file, destination_file)

  # Copy all the locales, preserving directory structure
  destination_locales = os.path.join(destination, '_locales')
  os.mkdir(destination_locales, 0775)
  remoting_locales = os.path.join(destination, 'remoting_locales')
  os.mkdir(remoting_locales, 0775)
  for current_locale in locales:
    extension = os.path.splitext(current_locale)[1]
    if extension == '.json':
      locale_id = os.path.split(os.path.split(current_locale)[0])[1]
      destination_dir = os.path.join(destination_locales, locale_id)
      destination_file = os.path.join(destination_dir,
                                      os.path.split(current_locale)[1])
      os.mkdir(destination_dir, 0775)
      shutil.copy2(current_locale, destination_file)
    elif extension == '.pak':
      destination_file = os.path.join(remoting_locales,
                                      os.path.split(current_locale)[1])
      shutil.copy2(current_locale, destination_file)
    else:
      raise Exception('Unknown extension: ' + current_locale)

  is_prod_service_environment = service_environment == 'prod'

  # Allow host names for google services/apis to be overriden via env vars.
  oauth2AccountsHost = os.environ.get(
      'OAUTH2_ACCOUNTS_HOST', 'https://accounts.google.com')
  oauth2ApiHost = os.environ.get(
      'OAUTH2_API_HOST', 'https://www.googleapis.com')
  directoryApiHost = os.environ.get(
      'DIRECTORY_API_HOST', 'https://www.googleapis.com')
  remotingApiHost = os.environ.get(
      'REMOTING_API_HOST', 'https://remoting-pa.googleapis.com')

  oauth2BaseUrl = oauth2AccountsHost + '/o/oauth2'
  oauth2ApiBaseUrl = oauth2ApiHost + '/oauth2'
  directoryApiBaseUrl = directoryApiHost + '/chromoting/v1'
  telemetryApiBaseUrl = remotingApiHost + '/v1/events'

  replaceBool(destination, 'USE_GCD', use_gcd)
  replaceString(destination, 'OAUTH2_BASE_URL', oauth2BaseUrl)
  replaceString(destination, 'OAUTH2_API_BASE_URL', oauth2ApiBaseUrl)
  replaceString(destination, 'DIRECTORY_API_BASE_URL', directoryApiBaseUrl)
  replaceString(destination, 'TELEMETRY_API_BASE_URL', telemetryApiBaseUrl)

  # Substitute hosts in the manifest's CSP list.
  # Ensure we list the API host only once if it's the same for multiple APIs.
  googleApiHosts = ' '.join(set([oauth2ApiHost, directoryApiHost]))

  # WCS and the OAuth trampoline are both hosted on talkgadget. Split them into
  # separate suffix/prefix variables to allow for wildcards in manifest.json.
  talkGadgetHostSuffix = os.environ.get(
      'TALK_GADGET_HOST_SUFFIX', 'talkgadget.google.com')
  talkGadgetHostPrefix = os.environ.get(
      'TALK_GADGET_HOST_PREFIX', 'https://chromoting-client.')
  oauth2RedirectHostPrefix = os.environ.get(
      'OAUTH2_REDIRECT_HOST_PREFIX', 'https://chromoting-oauth.')

  # Use a wildcard in the manifest.json host specs if the prefixes differ.
  talkGadgetHostJs = talkGadgetHostPrefix + talkGadgetHostSuffix
  talkGadgetBaseUrl = talkGadgetHostJs + '/talkgadget'
  if talkGadgetHostPrefix == oauth2RedirectHostPrefix:
    talkGadgetHostJson = talkGadgetHostJs
  else:
    talkGadgetHostJson = 'https://*.' + talkGadgetHostSuffix

  # Set the correct OAuth2 redirect URL.
  oauth2RedirectHostJs = oauth2RedirectHostPrefix + talkGadgetHostSuffix
  oauth2RedirectHostJson = talkGadgetHostJson
  oauth2RedirectPath = '/talkgadget/oauth/chrome-remote-desktop'
  oauth2RedirectBaseUrlJs = oauth2RedirectHostJs + oauth2RedirectPath
  oauth2RedirectBaseUrlJson = oauth2RedirectHostJson + oauth2RedirectPath
  if buildtype == 'Official':
    oauth2RedirectUrlJs = ("'" + oauth2RedirectBaseUrlJs +
                           "/rel/' + chrome.i18n.getMessage('@@extension_id')")
    oauth2RedirectUrlJson = oauth2RedirectBaseUrlJson + '/rel/*'
  else:
    oauth2RedirectUrlJs = "'" + oauth2RedirectBaseUrlJs + "/dev'"
    oauth2RedirectUrlJson = oauth2RedirectBaseUrlJson + '/dev*'
  thirdPartyAuthUrlJs = oauth2RedirectBaseUrlJs + '/thirdpartyauth'
  thirdPartyAuthUrlJson = oauth2RedirectBaseUrlJson + '/thirdpartyauth*'
  xmppServer = os.environ.get('XMPP_SERVER', 'talk.google.com:443')

  replaceString(destination, 'TALK_GADGET_URL', talkGadgetBaseUrl)
  findAndReplace(os.path.join(destination, 'plugin_settings.js'),
                 "'OAUTH2_REDIRECT_URL'", oauth2RedirectUrlJs)

  # Configure xmpp server and directory bot settings in the plugin.
  xmpp_server_user_tls = getenvBool('XMPP_SERVER_USE_TLS', True)
  if (buildtype != 'Dev' and not xmpp_server_user_tls):
    raise Exception('TLS can must be enabled in non Dev builds.')

  replaceBool(
      destination, 'XMPP_SERVER_USE_TLS', xmpp_server_user_tls)
  replaceString(destination, 'XMPP_SERVER', xmppServer)
  replaceString(destination, 'DIRECTORY_BOT_JID',
                os.environ.get('DIRECTORY_BOT_JID',
                               '*****@*****.**'))
  replaceString(destination, 'THIRD_PARTY_AUTH_REDIRECT_URL',
                thirdPartyAuthUrlJs)

  # Set the correct API keys.
  # For overriding the client ID/secret via env vars, see google_api_keys.py.
  apiClientId = google_api_keys.GetClientID('REMOTING')
  apiClientSecret = google_api_keys.GetClientSecret('REMOTING')

  apiClientIdV2 = os.environ.get(
      'REMOTING_IDENTITY_API_CLIENT_ID',
      google_api_keys.GetClientID('REMOTING_IDENTITY_API'))

  replaceString(destination, 'API_CLIENT_ID', apiClientId)
  replaceString(destination, 'API_CLIENT_SECRET', apiClientSecret)

  # Use a fixed key in the app manifest. For dev builds, this ensures that the
  # app can be run directly from the output directory. For official CRD builds,
  # it allows QA to test the app without uploading it to Chrome Web Store.
  manifest_key = 'remotingdevbuild'

  # Generate manifest.
  if manifest_template:
    context = {
        'FULL_APP_VERSION': version,
        'MANIFEST_KEY': manifest_key,
        'OAUTH2_REDIRECT_URL': oauth2RedirectUrlJson,
        'TALK_GADGET_HOST': talkGadgetHostJson,
        'THIRD_PARTY_AUTH_REDIRECT_URL': thirdPartyAuthUrlJson,
        'REMOTING_IDENTITY_API_CLIENT_ID': apiClientIdV2,
        'OAUTH2_BASE_URL': oauth2BaseUrl,
        'OAUTH2_API_BASE_URL': oauth2ApiBaseUrl,
        'DIRECTORY_API_BASE_URL': directoryApiBaseUrl,
        'TELEMETRY_API_BASE_URL':telemetryApiBaseUrl ,
        'CLOUD_PRINT_URL': '',
        'OAUTH2_ACCOUNTS_HOST': oauth2AccountsHost,
        'GOOGLE_API_HOSTS': googleApiHosts,
        'APP_NAME': app_name,
        'APP_DESCRIPTION': app_description,
        'OAUTH_CLOUD_PRINT_SCOPE': '',
        'OAUTH_GDRIVE_SCOPE': '',
        'USE_GCD': use_gcd,
        'XMPP_SERVER': xmppServer,
        # An URL match pattern that is added to the |permissions| section of the
        # manifest in case some URLs are redirected by corporate proxies.
        'PROXY_URL' : os.environ.get('PROXY_URL', ''),
    }
    if 'CLOUD_PRINT' in app_capabilities:
      context['OAUTH_CLOUD_PRINT_SCOPE'] = ('"https://www.googleapis.com/auth/cloudprint",')
      context['CLOUD_PRINT_URL'] = ('"https://www.google.com/cloudprint/*",')
    if 'GOOGLE_DRIVE' in app_capabilities:
      context['OAUTH_GDRIVE_SCOPE'] = ('"https://docs.google.com/feeds/", '
                                       '"https://www.googleapis.com/auth/drive",')
    processJinjaTemplate(manifest_template,
                         jinja_paths,
                         os.path.join(destination, 'manifest.json'),
                         context)

  # Make the zipfile.
  build_utils.ZipDir(
    zip_path, destination,
    zip_prefix_path=os.path.splitext(os.path.basename(zip_path))[0])

  return 0
Пример #5
0
def buildWebApp(buildtype, version, mimetype, destination, zip_path, plugin,
                files, locales, patches):
    """Does the main work of building the webapp directory and zipfile.

  Args:
    buildtype: the type of build ("Official" or "Dev")
    mimetype: A string with mimetype of plugin.
    destination: A string with path to directory where the webapp will be
                 written.
    zipfile: A string with path to the zipfile to create containing the
             contents of |destination|.
    plugin: A string with path to the binary plugin for this webapp.
    files: An array of strings listing the paths for resources to include
           in this webapp.
    locales: An array of strings listing locales, which are copied, along
             with their directory structure from the _locales directory down.
    patches: An array of strings listing patch files to be applied to the
             webapp directory. Paths in the patch file should be relative to
             the remoting/webapp directory, for example a/main.html. Since
             'git diff -p' works relative to the src/ directory, patches
             obtained this way will need to be edited.
  """
    # Ensure a fresh directory.
    try:
        shutil.rmtree(destination)
    except OSError:
        if os.path.exists(destination):
            raise
        else:
            pass
    os.mkdir(destination, 0775)

    # Use symlinks on linux and mac for faster compile/edit cycle.
    #
    # On Windows Vista platform.system() can return 'Microsoft' with some
    # versions of Python, see http://bugs.python.org/issue1082
    # should_symlink = platform.system() not in ['Windows', 'Microsoft']
    #
    # TODO(ajwong): Pending decision on http://crbug.com/27185 we may not be
    # able to load symlinked resources.
    should_symlink = False

    # Copy all the files.
    for current_file in files:
        destination_file = os.path.join(destination,
                                        os.path.basename(current_file))
        destination_dir = os.path.dirname(destination_file)
        if not os.path.exists(destination_dir):
            os.makedirs(destination_dir, 0775)

        if should_symlink:
            # TODO(ajwong): Detect if we're vista or higher.  Then use win32file
            # to create a symlink in that case.
            targetname = os.path.relpath(os.path.realpath(current_file),
                                         os.path.realpath(destination_file))
            os.symlink(targetname, destination_file)
        else:
            shutil.copy2(current_file, destination_file)

    # Copy all the locales, preserving directory structure
    destination_locales = os.path.join(destination, "_locales")
    os.mkdir(destination_locales, 0775)
    remoting_locales = os.path.join(destination, "remoting_locales")
    os.mkdir(remoting_locales, 0775)
    for current_locale in locales:
        extension = os.path.splitext(current_locale)[1]
        if extension == '.json':
            locale_id = os.path.split(os.path.split(current_locale)[0])[1]
            destination_dir = os.path.join(destination_locales, locale_id)
            destination_file = os.path.join(destination_dir,
                                            os.path.split(current_locale)[1])
            os.mkdir(destination_dir, 0775)
            shutil.copy2(current_locale, destination_file)
        elif extension == '.pak':
            destination_file = os.path.join(remoting_locales,
                                            os.path.split(current_locale)[1])
            shutil.copy2(current_locale, destination_file)
        else:
            raise Exception("Unknown extension: " + current_locale)

    # Create fake plugin files to appease the manifest checker.
    # It requires that if there is a plugin listed in the manifest that
    # there be a file in the plugin with that name.
    names = [
        'remoting_host_plugin.dll',  # Windows
        'remoting_host_plugin.plugin',  # Mac
        'libremoting_host_plugin.ia32.so',  # Linux 32
        'libremoting_host_plugin.x64.so'  # Linux 64
    ]
    pluginName = os.path.basename(plugin)

    for name in names:
        if name != pluginName:
            path = os.path.join(destination, name)
            f = open(path, 'w')
            f.write("placeholder for %s" % (name))
            f.close()

    # Copy the plugin. On some platforms (e.g. ChromeOS) plugin compilation may be
    # disabled, in which case we don't need to copy anything.
    if plugin:
        newPluginPath = os.path.join(destination, pluginName)
        if os.path.isdir(plugin):
            # On Mac we have a directory.
            shutil.copytree(plugin, newPluginPath)
        else:
            shutil.copy2(plugin, newPluginPath)

        # Strip the linux build.
        if ((platform.system() == 'Linux') and (buildtype == 'Official')):
            subprocess.call(["strip", newPluginPath])

    # Patch the files, if necessary. Do this before updating any placeholders
    # in case any of the diff contexts refer to the placeholders.
    for patch in patches:
        patchfile = os.path.join(os.getcwd(), patch)
        if subprocess.call([
                'patch', '-d', destination, '-i', patchfile, '-p1', '-F0', '-s'
        ]) != 0:
            print 'Patch ' + patch + ' failed to apply.'
            return 1

    # Set the version number in the manifest version.
    findAndReplace(os.path.join(destination, 'manifest.json'),
                   'FULL_APP_VERSION', version)

    # Set the correct mimetype.
    findAndReplace(os.path.join(destination, 'plugin_settings.js'),
                   'HOST_PLUGIN_MIMETYPE', mimetype)

    # Allow host names for google services/apis to be overriden via env vars.
    oauth2AccountsHost = os.environ.get('OAUTH2_ACCOUNTS_HOST',
                                        'https://accounts.google.com')
    oauth2ApiHost = os.environ.get('OAUTH2_API_HOST',
                                   'https://www.googleapis.com')
    directoryApiHost = os.environ.get('DIRECTORY_API_HOST',
                                      'https://www.googleapis.com')
    oauth2BaseUrl = oauth2AccountsHost + '/o/oauth2'
    oauth2ApiBaseUrl = oauth2ApiHost + '/oauth2'
    directoryApiBaseUrl = directoryApiHost + '/chromoting/v1'
    replaceUrl(destination, 'OAUTH2_BASE_URL', oauth2BaseUrl)
    replaceUrl(destination, 'OAUTH2_API_BASE_URL', oauth2ApiBaseUrl)
    replaceUrl(destination, 'DIRECTORY_API_BASE_URL', directoryApiBaseUrl)
    # Substitute hosts in the manifest's CSP list.
    findAndReplace(os.path.join(destination, 'manifest.json'),
                   'OAUTH2_ACCOUNTS_HOST', oauth2AccountsHost)
    # Ensure we list the API host only once if it's the same for multiple APIs.
    googleApiHosts = ' '.join(set([oauth2ApiHost, directoryApiHost]))
    findAndReplace(os.path.join(destination, 'manifest.json'),
                   'GOOGLE_API_HOSTS', googleApiHosts)

    # WCS and the OAuth trampoline are both hosted on talkgadget. Split them into
    # separate suffix/prefix variables to allow for wildcards in manifest.json.
    talkGadgetHostSuffix = os.environ.get('TALK_GADGET_HOST_SUFFIX',
                                          'talkgadget.google.com')
    talkGadgetHostPrefix = os.environ.get('TALK_GADGET_HOST_PREFIX',
                                          'https://chromoting-client.')
    oauth2RedirectHostPrefix = os.environ.get('OAUTH2_REDIRECT_HOST_PREFIX',
                                              'https://chromoting-oauth.')

    # Use a wildcard in the manifest.json host specs if the prefixes differ.
    talkGadgetHostJs = talkGadgetHostPrefix + talkGadgetHostSuffix
    talkGadgetBaseUrl = talkGadgetHostJs + '/talkgadget/'
    if talkGadgetHostPrefix == oauth2RedirectHostPrefix:
        talkGadgetHostJson = talkGadgetHostJs
    else:
        talkGadgetHostJson = 'https://*.' + talkGadgetHostSuffix

    # Set the correct OAuth2 redirect URL.
    oauth2RedirectHostJs = oauth2RedirectHostPrefix + talkGadgetHostSuffix
    oauth2RedirectHostJson = talkGadgetHostJson
    oauth2RedirectPath = '/talkgadget/oauth/chrome-remote-desktop'
    oauth2RedirectBaseUrlJs = oauth2RedirectHostJs + oauth2RedirectPath
    oauth2RedirectBaseUrlJson = oauth2RedirectHostJson + oauth2RedirectPath
    if buildtype == 'Official':
        oauth2RedirectUrlJs = (
            "'" + oauth2RedirectBaseUrlJs +
            "/rel/' + chrome.i18n.getMessage('@@extension_id')")
        oauth2RedirectUrlJson = oauth2RedirectBaseUrlJson + '/rel/*'
    else:
        oauth2RedirectUrlJs = "'" + oauth2RedirectBaseUrlJs + "/dev'"
        oauth2RedirectUrlJson = oauth2RedirectBaseUrlJson + '/dev*'
    thirdPartyAuthUrlJs = "'" + oauth2RedirectBaseUrlJs + "/thirdpartyauth'"
    thirdPartyAuthUrlJson = oauth2RedirectBaseUrlJson + '/thirdpartyauth*'
    findAndReplace(os.path.join(destination, 'plugin_settings.js'),
                   "'TALK_GADGET_URL'", "'" + talkGadgetBaseUrl + "'")
    findAndReplace(os.path.join(destination, 'plugin_settings.js'),
                   "'OAUTH2_REDIRECT_URL'", oauth2RedirectUrlJs)
    findAndReplace(os.path.join(destination, 'manifest.json'),
                   'TALK_GADGET_HOST', talkGadgetHostJson)
    findAndReplace(os.path.join(destination, 'manifest.json'),
                   'OAUTH2_REDIRECT_URL', oauth2RedirectUrlJson)

    # Configure xmpp server and directory bot settings in the plugin.
    xmppServerAddress = os.environ.get('XMPP_SERVER_ADDRESS',
                                       'talk.google.com:5222')
    xmppServerUseTls = os.environ.get('XMPP_SERVER_USE_TLS', 'true')
    directoryBotJid = os.environ.get('DIRECTORY_BOT_JID',
                                     '*****@*****.**')

    findAndReplace(os.path.join(destination, 'plugin_settings.js'),
                   "'XMPP_SERVER_ADDRESS'", "'" + xmppServerAddress + "'")
    findAndReplace(os.path.join(destination, 'plugin_settings.js'),
                   "Boolean('XMPP_SERVER_USE_TLS')", xmppServerUseTls)
    findAndReplace(os.path.join(destination, 'plugin_settings.js'),
                   "'DIRECTORY_BOT_JID'", "'" + directoryBotJid + "'")
    findAndReplace(os.path.join(destination, 'plugin_settings.js'),
                   "'THIRD_PARTY_AUTH_REDIRECT_URL'", thirdPartyAuthUrlJs)
    findAndReplace(os.path.join(destination, 'manifest.json'),
                   "THIRD_PARTY_AUTH_REDIRECT_URL", thirdPartyAuthUrlJson)

    # Set the correct API keys.
    # For overriding the client ID/secret via env vars, see google_api_keys.py.
    apiClientId = google_api_keys.GetClientID('REMOTING')
    apiClientSecret = google_api_keys.GetClientSecret('REMOTING')
    apiClientIdV2 = google_api_keys.GetClientID('REMOTING_IDENTITY_API')

    findAndReplace(os.path.join(destination, 'plugin_settings.js'),
                   "'API_CLIENT_ID'", "'" + apiClientId + "'")
    findAndReplace(os.path.join(destination, 'plugin_settings.js'),
                   "'API_CLIENT_SECRET'", "'" + apiClientSecret + "'")
    findAndReplace(os.path.join(destination, 'manifest.json'),
                   '"REMOTING_IDENTITY_API_CLIENT_ID"',
                   '"' + apiClientIdV2 + '"')

    # Use a consistent extension id for unofficial builds.
    if buildtype != 'Official':
        manifestKey = '"key": "remotingdevbuild",'
    else:
        manifestKey = ''
    findAndReplace(os.path.join(destination, 'manifest.json'),
                   'MANIFEST_KEY_FOR_UNOFFICIAL_BUILD', manifestKey)

    # Make the zipfile.
    createZip(zip_path, destination)

    return 0
Пример #6
0
def buildWebApp(buildtype, version, mimetype, destination, zip_path, plugin,
                files, locales):
    """Does the main work of building the webapp directory and zipfile.

  Args:
    buildtype: the type of build ("Official" or "Dev")
    mimetype: A string with mimetype of plugin.
    destination: A string with path to directory where the webapp will be
                 written.
    zipfile: A string with path to the zipfile to create containing the
             contents of |destination|.
    plugin: A string with path to the binary plugin for this webapp.
    files: An array of strings listing the paths for resources to include
           in this webapp.
    locales: An array of strings listing locales, which are copied, along
             with their directory structure from the _locales directory down.
  """
    # Ensure a fresh directory.
    try:
        shutil.rmtree(destination)
    except OSError:
        if os.path.exists(destination):
            raise
        else:
            pass
    os.mkdir(destination, 0775)

    # Use symlinks on linux and mac for faster compile/edit cycle.
    #
    # On Windows Vista platform.system() can return 'Microsoft' with some
    # versions of Python, see http://bugs.python.org/issue1082
    # should_symlink = platform.system() not in ['Windows', 'Microsoft']
    #
    # TODO(ajwong): Pending decision on http://crbug.com/27185 we may not be
    # able to load symlinked resources.
    should_symlink = False

    # Copy all the files.
    for current_file in files:
        destination_file = os.path.join(destination,
                                        os.path.basename(current_file))
        destination_dir = os.path.dirname(destination_file)
        if not os.path.exists(destination_dir):
            os.makedirs(destination_dir, 0775)

        if should_symlink:
            # TODO(ajwong): Detect if we're vista or higher.  Then use win32file
            # to create a symlink in that case.
            targetname = os.path.relpath(os.path.realpath(current_file),
                                         os.path.realpath(destination_file))
            os.symlink(targetname, destination_file)
        else:
            shutil.copy2(current_file, destination_file)

    # Copy all the locales, preserving directory structure
    destination_locales = os.path.join(destination, "_locales")
    os.mkdir(destination_locales, 0775)
    chromium_locale_dir = "/_locales/"
    chrome_locale_dir = "/_locales.official/"
    for current_locale in locales:
        pos = current_locale.find(chromium_locale_dir)
        locale_len = len(chromium_locale_dir)
        if (pos == -1):
            pos = current_locale.find(chrome_locale_dir)
            locale_len = len(chrome_locale_dir)
        if (pos == -1):
            raise "Missing locales directory in " + current_locale
        subtree = current_locale[pos + locale_len:]
        pos = subtree.find("/")
        if (pos == -1):
            raise "Malformed locale: " + current_locale
        locale_id = subtree[:pos]
        messages = subtree[pos + 1:]
        destination_dir = os.path.join(destination_locales, locale_id)
        destination_file = os.path.join(destination_dir, messages)
        os.mkdir(destination_dir, 0775)
        shutil.copy2(current_locale, destination_file)

    # Create fake plugin files to appease the manifest checker.
    # It requires that if there is a plugin listed in the manifest that
    # there be a file in the plugin with that name.
    names = [
        'remoting_host_plugin.dll',  # Windows
        'remoting_host_plugin.plugin',  # Mac
        'libremoting_host_plugin.ia32.so',  # Linux 32
        'libremoting_host_plugin.x64.so'  # Linux 64
    ]
    pluginName = os.path.basename(plugin)

    for name in names:
        if name != pluginName:
            path = os.path.join(destination, name)
            f = open(path, 'w')
            f.write("placeholder for %s" % (name))
            f.close()

    # Copy the plugin.
    pluginName = os.path.basename(plugin)
    newPluginPath = os.path.join(destination, pluginName)
    if os.path.isdir(plugin):
        # On Mac we have a directory.
        shutil.copytree(plugin, newPluginPath)
    else:
        shutil.copy2(plugin, newPluginPath)

    # Strip the linux build.
    if ((platform.system() == 'Linux') and (buildtype == 'Official')):
        subprocess.call(["strip", newPluginPath])

    # Set the version number in the manifest version.
    findAndReplace(os.path.join(destination, 'manifest.json'),
                   'FULL_APP_VERSION', version)

    # Set the correct mimetype.
    findAndReplace(os.path.join(destination, 'plugin_settings.js'),
                   'HOST_PLUGIN_MIMETYPE', mimetype)

    # Set the correct OAuth2 redirect URL.
    baseUrl = ('https://chromoting-oauth.talkgadget.google.com/'
               'talkgadget/oauth/chrome-remote-desktop')
    if (buildtype == 'Official'):
        oauth2RedirectUrlJs = (
            "'" + baseUrl +
            "/rel/' + chrome.i18n.getMessage('@@extension_id')")
        oauth2RedirectUrlJson = baseUrl + '/rel/*'
    else:
        oauth2RedirectUrlJs = "'" + baseUrl + "/dev'"
        oauth2RedirectUrlJson = baseUrl + '/dev*'
    findAndReplace(os.path.join(destination, 'plugin_settings.js'),
                   "'OAUTH2_REDIRECT_URL'", oauth2RedirectUrlJs)
    findAndReplace(os.path.join(destination, 'manifest.json'),
                   "OAUTH2_REDIRECT_URL", oauth2RedirectUrlJson)

    # Set the correct API keys.
    apiClientId = google_api_keys.GetClientID('REMOTING')
    apiClientSecret = google_api_keys.GetClientSecret('REMOTING')

    findAndReplace(os.path.join(destination, 'plugin_settings.js'),
                   "'API_CLIENT_ID'", "'" + apiClientId + "'")
    findAndReplace(os.path.join(destination, 'plugin_settings.js'),
                   "'API_CLIENT_SECRET'", "'" + apiClientSecret + "'")

    # Make the zipfile.
    createZip(zip_path, destination)
Пример #7
0
def buildWebApp(buildtype, version, destination, zip_path, manifest_template,
                webapp_type, app_id, app_name, app_description, files, locales,
                jinja_paths, service_environment):
    """Does the main work of building the webapp directory and zipfile.

  Args:
    buildtype: the type of build ("Official", "Release" or "Dev").
    destination: A string with path to directory where the webapp will be
                 written.
    zipfile: A string with path to the zipfile to create containing the
             contents of |destination|.
    manifest_template: jinja2 template file for manifest.
    webapp_type: webapp type ("v1", "v2", "v2_pnacl" or "app_remoting").
    app_id: A string with the Remoting Application Id (only used for app
             remoting webapps). If supplied, it defaults to using the
             test API server.
    app_name: A string with the name of the application.
    app_description: A string with the description of the application.
    files: An array of strings listing the paths for resources to include
           in this webapp.
    locales: An array of strings listing locales, which are copied, along
             with their directory structure from the _locales directory down.
    jinja_paths: An array of paths to search for {%include} directives in
                 addition to the directory containing the manifest template.
    service_environment: Used to point the webApp to one of the
                         dev/test/staging/prod environments
  """
    # Ensure a fresh directory.
    try:
        shutil.rmtree(destination)
    except OSError:
        if os.path.exists(destination):
            raise
        else:
            pass
    os.mkdir(destination, 0775)

    if buildtype != 'Official' and buildtype != 'Release' and buildtype != 'Dev':
        raise Exception('Unknown buildtype: ' + buildtype)

    # Use symlinks on linux and mac for faster compile/edit cycle.
    #
    # On Windows Vista platform.system() can return 'Microsoft' with some
    # versions of Python, see http://bugs.python.org/issue1082
    # should_symlink = platform.system() not in ['Windows', 'Microsoft']
    #
    # TODO(ajwong): Pending decision on http://crbug.com/27185 we may not be
    # able to load symlinked resources.
    should_symlink = False

    # Copy all the files.
    for current_file in files:
        destination_file = os.path.join(destination,
                                        os.path.basename(current_file))
        destination_dir = os.path.dirname(destination_file)
        if not os.path.exists(destination_dir):
            os.makedirs(destination_dir, 0775)

        if should_symlink:
            # TODO(ajwong): Detect if we're vista or higher.  Then use win32file
            # to create a symlink in that case.
            targetname = os.path.relpath(os.path.realpath(current_file),
                                         os.path.realpath(destination_file))
            os.symlink(targetname, destination_file)
        else:
            shutil.copy2(current_file, destination_file)

    # Copy all the locales, preserving directory structure
    destination_locales = os.path.join(destination, '_locales')
    os.mkdir(destination_locales, 0775)
    remoting_locales = os.path.join(destination, 'remoting_locales')
    os.mkdir(remoting_locales, 0775)
    for current_locale in locales:
        extension = os.path.splitext(current_locale)[1]
        if extension == '.json':
            locale_id = os.path.split(os.path.split(current_locale)[0])[1]
            destination_dir = os.path.join(destination_locales, locale_id)
            destination_file = os.path.join(destination_dir,
                                            os.path.split(current_locale)[1])
            os.mkdir(destination_dir, 0775)
            shutil.copy2(current_locale, destination_file)
        elif extension == '.pak':
            destination_file = os.path.join(remoting_locales,
                                            os.path.split(current_locale)[1])
            shutil.copy2(current_locale, destination_file)
        else:
            raise Exception('Unknown extension: ' + current_locale)

    # Set client plugin type.
    # TODO(wez): Use 'native' in app_remoting until b/17441659 is resolved.
    client_plugin = 'pnacl' if webapp_type == 'v2_pnacl' else 'native'
    findAndReplace(os.path.join(destination, 'plugin_settings.js'),
                   "'CLIENT_PLUGIN_TYPE'", "'" + client_plugin + "'")

    # Allow host names for google services/apis to be overriden via env vars.
    oauth2AccountsHost = os.environ.get('OAUTH2_ACCOUNTS_HOST',
                                        'https://accounts.google.com')
    oauth2ApiHost = os.environ.get('OAUTH2_API_HOST',
                                   'https://www.googleapis.com')
    directoryApiHost = os.environ.get('DIRECTORY_API_HOST',
                                      'https://www.googleapis.com')

    if webapp_type == 'app_remoting':
        appRemotingApiHost = os.environ.get('APP_REMOTING_API_HOST', None)
        appRemotingApplicationId = os.environ.get(
            'APP_REMOTING_APPLICATION_ID', None)

        # Release/Official builds are special because they are what we will upload
        # to the web store.  The checks below will validate that prod builds are
        # being generated correctly (no overrides) and with the correct buildtype.
        # They also verify that folks are not accidentally building dev/test/staging
        # apps for release (no impersonation) instead of dev.
        if service_environment == 'prod' and buildtype == 'Dev':
            raise Exception(
                "Prod environment cannot be built for 'dev' builds")

        if buildtype != 'Dev':
            if service_environment != 'prod':
                raise Exception('Invalid service_environment targeted for ' +
                                buildtype + ': ' + service_environment)
            if 'out/Release' not in destination:
                raise Exception(
                    'Prod builds must be placed in the out/Release folder')
            if app_id != None:
                raise Exception('Cannot pass in an app_id for ' + buildtype +
                                ' builds: ' + service_environment)
            if appRemotingApiHost != None:
                raise Exception(
                    'Cannot set APP_REMOTING_API_HOST env var for ' +
                    buildtype + ' builds')
            if appRemotingApplicationId != None:
                raise Exception(
                    'Cannot set APP_REMOTING_APPLICATION_ID env var for ' +
                    buildtype + ' builds')

        # If an Application ID was set (either from service_environment variable or
        # from a command line argument), hardcode it, otherwise get it at runtime.
        effectiveAppId = appRemotingApplicationId or app_id
        if effectiveAppId:
            appRemotingApplicationId = "'" + effectiveAppId + "'"
        else:
            appRemotingApplicationId = "chrome.i18n.getMessage('@@extension_id')"
        findAndReplace(os.path.join(destination, 'plugin_settings.js'),
                       "'APP_REMOTING_APPLICATION_ID'",
                       appRemotingApplicationId)

    oauth2BaseUrl = oauth2AccountsHost + '/o/oauth2'
    oauth2ApiBaseUrl = oauth2ApiHost + '/oauth2'
    directoryApiBaseUrl = directoryApiHost + '/chromoting/v1'

    if webapp_type == 'app_remoting':
        # Set the apiary endpoint and then set the endpoint version
        if not appRemotingApiHost:
            if service_environment == 'prod':
                appRemotingApiHost = 'https://www.googleapis.com'
            else:
                appRemotingApiHost = 'https://www-googleapis-test.sandbox.google.com'

        if service_environment == 'dev':
            appRemotingServicePath = '/appremoting/v1beta1_dev'
        elif service_environment == 'test':
            appRemotingServicePath = '/appremoting/v1beta1'
        elif service_environment == 'staging':
            appRemotingServicePath = '/appremoting/v1beta1_staging'
        elif service_environment == 'prod':
            appRemotingServicePath = '/appremoting/v1beta1'
        else:
            raise Exception('Unknown service environment: ' +
                            service_environment)
        appRemotingApiBaseUrl = appRemotingApiHost + appRemotingServicePath
    else:
        appRemotingApiBaseUrl = ''

    replaceString(destination, 'OAUTH2_BASE_URL', oauth2BaseUrl)
    replaceString(destination, 'OAUTH2_API_BASE_URL', oauth2ApiBaseUrl)
    replaceString(destination, 'DIRECTORY_API_BASE_URL', directoryApiBaseUrl)
    if webapp_type == 'app_remoting':
        replaceString(destination, 'APP_REMOTING_API_BASE_URL',
                      appRemotingApiBaseUrl)

    # Substitute hosts in the manifest's CSP list.
    # Ensure we list the API host only once if it's the same for multiple APIs.
    googleApiHosts = ' '.join(set([oauth2ApiHost, directoryApiHost]))

    # WCS and the OAuth trampoline are both hosted on talkgadget. Split them into
    # separate suffix/prefix variables to allow for wildcards in manifest.json.
    talkGadgetHostSuffix = os.environ.get('TALK_GADGET_HOST_SUFFIX',
                                          'talkgadget.google.com')
    talkGadgetHostPrefix = os.environ.get('TALK_GADGET_HOST_PREFIX',
                                          'https://chromoting-client.')
    oauth2RedirectHostPrefix = os.environ.get('OAUTH2_REDIRECT_HOST_PREFIX',
                                              'https://chromoting-oauth.')

    # Use a wildcard in the manifest.json host specs if the prefixes differ.
    talkGadgetHostJs = talkGadgetHostPrefix + talkGadgetHostSuffix
    talkGadgetBaseUrl = talkGadgetHostJs + '/talkgadget/'
    if talkGadgetHostPrefix == oauth2RedirectHostPrefix:
        talkGadgetHostJson = talkGadgetHostJs
    else:
        talkGadgetHostJson = 'https://*.' + talkGadgetHostSuffix

    # Set the correct OAuth2 redirect URL.
    oauth2RedirectHostJs = oauth2RedirectHostPrefix + talkGadgetHostSuffix
    oauth2RedirectHostJson = talkGadgetHostJson
    oauth2RedirectPath = '/talkgadget/oauth/chrome-remote-desktop'
    oauth2RedirectBaseUrlJs = oauth2RedirectHostJs + oauth2RedirectPath
    oauth2RedirectBaseUrlJson = oauth2RedirectHostJson + oauth2RedirectPath
    if buildtype == 'Official':
        oauth2RedirectUrlJs = (
            "'" + oauth2RedirectBaseUrlJs +
            "/rel/' + chrome.i18n.getMessage('@@extension_id')")
        oauth2RedirectUrlJson = oauth2RedirectBaseUrlJson + '/rel/*'
    else:
        oauth2RedirectUrlJs = "'" + oauth2RedirectBaseUrlJs + "/dev'"
        oauth2RedirectUrlJson = oauth2RedirectBaseUrlJson + '/dev*'
    thirdPartyAuthUrlJs = oauth2RedirectBaseUrlJs + '/thirdpartyauth'
    thirdPartyAuthUrlJson = oauth2RedirectBaseUrlJson + '/thirdpartyauth*'
    replaceString(destination, 'TALK_GADGET_URL', talkGadgetBaseUrl)
    findAndReplace(os.path.join(destination, 'plugin_settings.js'),
                   "'OAUTH2_REDIRECT_URL'", oauth2RedirectUrlJs)

    # Configure xmpp server and directory bot settings in the plugin.
    findAndReplace(os.path.join(destination, 'plugin_settings.js'),
                   "Boolean('XMPP_SERVER_USE_TLS')",
                   os.environ.get('XMPP_SERVER_USE_TLS', 'true'))
    replaceString(
        destination, 'XMPP_SERVER_FOR_IT2ME_HOST',
        os.environ.get('XMPP_SERVER_FOR_IT2ME_HOST', 'talk.google.com:5222'))
    replaceString(
        destination, 'XMPP_SERVER_FOR_CLIENT',
        os.environ.get('XMPP_SERVER_FOR_CLIENT', 'talk.google.com:443'))
    replaceString(
        destination, 'DIRECTORY_BOT_JID',
        os.environ.get('DIRECTORY_BOT_JID', '*****@*****.**'))
    replaceString(destination, 'THIRD_PARTY_AUTH_REDIRECT_URL',
                  thirdPartyAuthUrlJs)

    # Set the correct API keys.
    # For overriding the client ID/secret via env vars, see google_api_keys.py.
    apiClientId = google_api_keys.GetClientID('REMOTING')
    apiClientSecret = google_api_keys.GetClientSecret('REMOTING')
    apiClientIdV2 = google_api_keys.GetClientID('REMOTING_IDENTITY_API')

    replaceString(destination, 'API_CLIENT_ID', apiClientId)
    replaceString(destination, 'API_CLIENT_SECRET', apiClientSecret)

    # Use a consistent extension id for dev builds.
    # AppRemoting builds always use the dev app id - the correct app id gets
    # written into the manifest later.
    if buildtype != 'Official' or webapp_type == 'app_remoting':
        manifestKey = '"key": "remotingdevbuild",'
    else:
        manifestKey = ''

    # Generate manifest.
    if manifest_template:
        context = {
            'webapp_type': webapp_type,
            'FULL_APP_VERSION': version,
            'MANIFEST_KEY_FOR_UNOFFICIAL_BUILD': manifestKey,
            'OAUTH2_REDIRECT_URL': oauth2RedirectUrlJson,
            'TALK_GADGET_HOST': talkGadgetHostJson,
            'THIRD_PARTY_AUTH_REDIRECT_URL': thirdPartyAuthUrlJson,
            'REMOTING_IDENTITY_API_CLIENT_ID': apiClientIdV2,
            'OAUTH2_BASE_URL': oauth2BaseUrl,
            'OAUTH2_API_BASE_URL': oauth2ApiBaseUrl,
            'DIRECTORY_API_BASE_URL': directoryApiBaseUrl,
            'APP_REMOTING_API_BASE_URL': appRemotingApiBaseUrl,
            'OAUTH2_ACCOUNTS_HOST': oauth2AccountsHost,
            'GOOGLE_API_HOSTS': googleApiHosts,
            'APP_NAME': app_name,
            'APP_DESCRIPTION': app_description,
        }
        processJinjaTemplate(manifest_template, jinja_paths,
                             os.path.join(destination, 'manifest.json'),
                             context)

    # Make the zipfile.
    createZip(zip_path, destination)

    return 0
Пример #8
0
def buildWebApp(buildtype, version, destination, zip_path, manifest_template,
                webapp_type, files, locales):
    """Does the main work of building the webapp directory and zipfile.

  Args:
    buildtype: the type of build ("Official" or "Dev").
    destination: A string with path to directory where the webapp will be
                 written.
    zipfile: A string with path to the zipfile to create containing the
             contents of |destination|.
    manifest_template: jinja2 template file for manifest.
    webapp_type: webapp type ("v1", "v2" or "v2_pnacl").
    files: An array of strings listing the paths for resources to include
           in this webapp.
    locales: An array of strings listing locales, which are copied, along
             with their directory structure from the _locales directory down.
  """
    # Ensure a fresh directory.
    try:
        shutil.rmtree(destination)
    except OSError:
        if os.path.exists(destination):
            raise
        else:
            pass
    os.mkdir(destination, 0775)

    # Use symlinks on linux and mac for faster compile/edit cycle.
    #
    # On Windows Vista platform.system() can return 'Microsoft' with some
    # versions of Python, see http://bugs.python.org/issue1082
    # should_symlink = platform.system() not in ['Windows', 'Microsoft']
    #
    # TODO(ajwong): Pending decision on http://crbug.com/27185 we may not be
    # able to load symlinked resources.
    should_symlink = False

    # Copy all the files.
    for current_file in files:
        destination_file = os.path.join(destination,
                                        os.path.basename(current_file))
        destination_dir = os.path.dirname(destination_file)
        if not os.path.exists(destination_dir):
            os.makedirs(destination_dir, 0775)

        if should_symlink:
            # TODO(ajwong): Detect if we're vista or higher.  Then use win32file
            # to create a symlink in that case.
            targetname = os.path.relpath(os.path.realpath(current_file),
                                         os.path.realpath(destination_file))
            os.symlink(targetname, destination_file)
        else:
            shutil.copy2(current_file, destination_file)

    # Copy all the locales, preserving directory structure
    destination_locales = os.path.join(destination, "_locales")
    os.mkdir(destination_locales, 0775)
    remoting_locales = os.path.join(destination, "remoting_locales")
    os.mkdir(remoting_locales, 0775)
    for current_locale in locales:
        extension = os.path.splitext(current_locale)[1]
        if extension == '.json':
            locale_id = os.path.split(os.path.split(current_locale)[0])[1]
            destination_dir = os.path.join(destination_locales, locale_id)
            destination_file = os.path.join(destination_dir,
                                            os.path.split(current_locale)[1])
            os.mkdir(destination_dir, 0775)
            shutil.copy2(current_locale, destination_file)
        elif extension == '.pak':
            destination_file = os.path.join(remoting_locales,
                                            os.path.split(current_locale)[1])
            shutil.copy2(current_locale, destination_file)
        else:
            raise Exception("Unknown extension: " + current_locale)

    # Set client plugin type.
    client_plugin = 'pnacl' if webapp_type == 'v2_pnacl' else 'native'
    findAndReplace(os.path.join(destination, 'plugin_settings.js'),
                   "'CLIENT_PLUGIN_TYPE'", "'" + client_plugin + "'")

    # Allow host names for google services/apis to be overriden via env vars.
    oauth2AccountsHost = os.environ.get('OAUTH2_ACCOUNTS_HOST',
                                        'https://accounts.google.com')
    oauth2ApiHost = os.environ.get('OAUTH2_API_HOST',
                                   'https://www.googleapis.com')
    directoryApiHost = os.environ.get('DIRECTORY_API_HOST',
                                      'https://www.googleapis.com')
    oauth2BaseUrl = oauth2AccountsHost + '/o/oauth2'
    oauth2ApiBaseUrl = oauth2ApiHost + '/oauth2'
    directoryApiBaseUrl = directoryApiHost + '/chromoting/v1'
    replaceString(destination, 'OAUTH2_BASE_URL', oauth2BaseUrl)
    replaceString(destination, 'OAUTH2_API_BASE_URL', oauth2ApiBaseUrl)
    replaceString(destination, 'DIRECTORY_API_BASE_URL', directoryApiBaseUrl)
    # Substitute hosts in the manifest's CSP list.
    # Ensure we list the API host only once if it's the same for multiple APIs.
    googleApiHosts = ' '.join(set([oauth2ApiHost, directoryApiHost]))

    # WCS and the OAuth trampoline are both hosted on talkgadget. Split them into
    # separate suffix/prefix variables to allow for wildcards in manifest.json.
    talkGadgetHostSuffix = os.environ.get('TALK_GADGET_HOST_SUFFIX',
                                          'talkgadget.google.com')
    talkGadgetHostPrefix = os.environ.get('TALK_GADGET_HOST_PREFIX',
                                          'https://chromoting-client.')
    oauth2RedirectHostPrefix = os.environ.get('OAUTH2_REDIRECT_HOST_PREFIX',
                                              'https://chromoting-oauth.')

    # Use a wildcard in the manifest.json host specs if the prefixes differ.
    talkGadgetHostJs = talkGadgetHostPrefix + talkGadgetHostSuffix
    talkGadgetBaseUrl = talkGadgetHostJs + '/talkgadget/'
    if talkGadgetHostPrefix == oauth2RedirectHostPrefix:
        talkGadgetHostJson = talkGadgetHostJs
    else:
        talkGadgetHostJson = 'https://*.' + talkGadgetHostSuffix

    # Set the correct OAuth2 redirect URL.
    oauth2RedirectHostJs = oauth2RedirectHostPrefix + talkGadgetHostSuffix
    oauth2RedirectHostJson = talkGadgetHostJson
    oauth2RedirectPath = '/talkgadget/oauth/chrome-remote-desktop'
    oauth2RedirectBaseUrlJs = oauth2RedirectHostJs + oauth2RedirectPath
    oauth2RedirectBaseUrlJson = oauth2RedirectHostJson + oauth2RedirectPath
    if buildtype == 'Official':
        oauth2RedirectUrlJs = (
            "'" + oauth2RedirectBaseUrlJs +
            "/rel/' + chrome.i18n.getMessage('@@extension_id')")
        oauth2RedirectUrlJson = oauth2RedirectBaseUrlJson + '/rel/*'
    else:
        oauth2RedirectUrlJs = "'" + oauth2RedirectBaseUrlJs + "/dev'"
        oauth2RedirectUrlJson = oauth2RedirectBaseUrlJson + '/dev*'
    thirdPartyAuthUrlJs = oauth2RedirectBaseUrlJs + "/thirdpartyauth"
    thirdPartyAuthUrlJson = oauth2RedirectBaseUrlJson + '/thirdpartyauth*'
    replaceString(destination, "TALK_GADGET_URL", talkGadgetBaseUrl)
    findAndReplace(os.path.join(destination, 'plugin_settings.js'),
                   "'OAUTH2_REDIRECT_URL'", oauth2RedirectUrlJs)

    # Configure xmpp server and directory bot settings in the plugin.
    xmppServerAddress = os.environ.get('XMPP_SERVER_ADDRESS',
                                       'talk.google.com:5222')
    xmppServerUseTls = os.environ.get('XMPP_SERVER_USE_TLS', 'true')
    directoryBotJid = os.environ.get('DIRECTORY_BOT_JID',
                                     '*****@*****.**')

    findAndReplace(os.path.join(destination, 'plugin_settings.js'),
                   "Boolean('XMPP_SERVER_USE_TLS')", xmppServerUseTls)
    replaceString(destination, "XMPP_SERVER_ADDRESS", xmppServerAddress)
    replaceString(destination, "DIRECTORY_BOT_JID", directoryBotJid)
    replaceString(destination, "THIRD_PARTY_AUTH_REDIRECT_URL",
                  thirdPartyAuthUrlJs)

    # Set the correct API keys.
    # For overriding the client ID/secret via env vars, see google_api_keys.py.
    apiClientId = google_api_keys.GetClientID('REMOTING')
    apiClientSecret = google_api_keys.GetClientSecret('REMOTING')
    apiClientIdV2 = google_api_keys.GetClientID('REMOTING_IDENTITY_API')

    replaceString(destination, "API_CLIENT_ID", apiClientId)
    replaceString(destination, "API_CLIENT_SECRET", apiClientSecret)

    # Use a consistent extension id for unofficial builds.
    if buildtype != 'Official':
        manifestKey = '"key": "remotingdevbuild",'
    else:
        manifestKey = ''

    # Generate manifest.
    context = {
        'webapp_type': webapp_type,
        'FULL_APP_VERSION': version,
        'MANIFEST_KEY_FOR_UNOFFICIAL_BUILD': manifestKey,
        'OAUTH2_REDIRECT_URL': oauth2RedirectUrlJson,
        'TALK_GADGET_HOST': talkGadgetHostJson,
        'THIRD_PARTY_AUTH_REDIRECT_URL': thirdPartyAuthUrlJson,
        'REMOTING_IDENTITY_API_CLIENT_ID': apiClientIdV2,
        'OAUTH2_BASE_URL': oauth2BaseUrl,
        'OAUTH2_API_BASE_URL': oauth2ApiBaseUrl,
        'DIRECTORY_API_BASE_URL': directoryApiBaseUrl,
        'OAUTH2_ACCOUNTS_HOST': oauth2AccountsHost,
        'GOOGLE_API_HOSTS': googleApiHosts,
    }
    processJinjaTemplate(manifest_template,
                         os.path.join(destination, 'manifest.json'), context)

    # Make the zipfile.
    createZip(zip_path, destination)

    return 0