Skip to content

Instantly share code, notes, and snippets.

@akaegi
Last active December 7, 2021 14:11
Show Gist options
  • Save akaegi/23c5f5cb129fda2c38b62d1dd98dedeb to your computer and use it in GitHub Desktop.
Save akaegi/23c5f5cb129fda2c38b62d1dd98dedeb to your computer and use it in GitHub Desktop.
Publish Android app bundle to Google App Center internal track
if [[ -z "$APPCENTER_PLAY_STORE_PUBLISH_TO_INTERNAL_TRACK" ]]; then
echo "Define environment variable APPCENTER_PLAY_STORE_PUBLISH_TO_INTERNAL_TRACK to run this post-build script."
exit 0
fi
PACKAGE_NAME=com.aa.xfspike
echo "Installing required Python packages"
pip3 install httplib2 google-api-python-client oauth2client
if [[ ! -z "$ANDROID_PUBLISHER_CREDENTIALS" ]]; then
echo "Credentials defined"
fi
#echo "Build dir is $APPCENTER_SOURCE_DIRECTORY"
#echo "Output dir is $APPCENTER_OUTPUT_DIRECTORY"
echo "Uploading Bundle to Internal Track of Google Play"
python3 $APPCENTER_SOURCE_DIRECTORY/XFSpike.Android/publish-bundle.py \
--track internal --package-name $PACKAGE_NAME \
--bundle $APPCENTER_OUTPUT_DIRECTORY/../bundle/$PACKAGE_NAME.aab
echo "Completed uploading bundle to Google Play - $ANDROID_IDENTIFIER"
#!/usr/bin/env python
#
# Adapted 2021 Andreas Kägi
# Adapted from https://github.com/microsoft/appcenter/issues/125#issuecomment-587602542
#
# Original Copyright below:
#
# Copyright 2014 Marta Rodriguez.
#
# Licensed under the Apache License, Version 2.0 (the 'License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
""" Publishes an Android app bundle (aab) to one of the Google Play tracks. Tested with internal track only. """
import json
import argparse
import os
import base64
import httplib2
from oauth2client.service_account import ServiceAccountCredentials
from oauth2client.client import AccessTokenRefreshError
from googleapiclient.discovery import build
import mimetypes
mimetypes.add_type('application/octet-stream', '.apk')
mimetypes.add_type('application/octet-stream', '.aab')
def upload(package_name: str, bundle: str, track: str, service_account_credentials: str = None):
# Create an httplib2.Http object to handle our HTTP requests and authorize it
# with the Credentials. Note that the first parameter, service_account_name,
# is the Email address created for the Service account. It must be the email
# address associated with the key that was created.
if service_account_credentials:
with open(service_account_credentials, 'r') as file_obj:
keyfile_dict = json.load(file_obj)
else:
# env variable name same as in gradle-play-publisher
# (https://github.com/Triple-T/gradle-play-publisher#authenticating-gradle-play-publisher)
keyfile_contents_base64 = os.getenv('ANDROID_PUBLISHER_CREDENTIALS', None)
keyfile_contents = base64.b64decode(keyfile_contents_base64)
if keyfile_contents is None:
raise Exception('Neither service_account_credentials file given nor '
'ANDROID_PUBLISHER_CREDENTIALS environment variable is set.')
keyfile_dict = json.loads(keyfile_contents)
credentials = ServiceAccountCredentials.from_json_keyfile_dict(
keyfile_dict,
['https://www.googleapis.com/auth/androidpublisher'])
http = httplib2.Http(timeout=2 * 60) # 2 minutes connect timeout
http_auth = credentials.authorize(http=http)
service = build('androidpublisher', 'v3', http=http_auth)
try:
edit_request = service.edits().insert(body={}, packageName=package_name)
result = edit_request.execute()
edit_id = result['id']
bundle_response = service.edits().bundles().upload(
editId=edit_id,
packageName=package_name,
media_body=bundle).execute()
version_code = bundle_response['versionCode']
print(f'Bundle with version code {version_code} has been successfully uploaded (edit not yet commited)')
track_response = service.edits().tracks().update(
editId=edit_id,
track=track,
packageName=package_name,
body={
'track': track,
'releases': [
{
# version name by default taken from apk versionName,
# see https://developers.google.com/android-publisher/api-ref/rest/v3/edits.tracks#Release
'versionCodes': [version_code],
'releaseNotes': [
{'language': 'en-US', 'text': 'Internal testing release'},
],
'status': 'completed'
}]
}).execute()
print(f'Track {track} updated (edit not yet commited): {track_response}')
commit_request = service.edits().commit(
editId=edit_id,
packageName=package_name).execute()
print(f'Edit commited: {commit_request}')
except AccessTokenRefreshError as e:
print('The credentials have been revoked or expired, please re-run the application to re-authorize')
raise e
def main():
parser = argparse.ArgumentParser()
parser.add_argument('-p', '--package-name', required=True, help='Package name. Example: com.android.sample')
parser.add_argument('-s', '--service_account_credentials',
default=None, help='Service account credentials json file. '
'If not given, the credentials are taken from environment variable '
'ANDROID_PUBLISHER_CREDENTIALS that must contain the contents of the '
'JSON file in base64 encoding.')
parser.add_argument('-b', '--bundle', required=True, help='Path to the bundle file (aab) to upload')
parser.add_argument('-t', '--track', choices=['alpha', 'beta', 'production', 'rollout', 'internal'],
default='internal', help='Track where bundle is published to')
args = parser.parse_args()
upload(
package_name=args.package_name,
service_account_credentials=args.service_account_credentials,
bundle=args.bundle,
track=args.track)
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment