diff --git a/.github/workflows/deploy_android.yml b/.github/workflows/deploy_android.yml new file mode 100644 index 0000000..de1b2b6 --- /dev/null +++ b/.github/workflows/deploy_android.yml @@ -0,0 +1,58 @@ +name: Android Build +on: + release: + types: [published] + +jobs: + deploy-android: + name: Android - Deploy Production + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v1 + - run: | + echo "${{ secrets.ANDROID_KEYSTORE_BASE64 }}" >> buyit.keystore.asc + echo "${{ secrets.GOOGLE_SERVICES_BASE64 }}" >> google-services.json.asc + echo "${{ secrets.FIREBASE_BASE64 }}" >> firebase.json.asc + echo "${{ secrets.ENVFILE_PROD_BASE64 }}" >> .env.prod.asc + echo "${{ secrets.GOOGLE_KEY_BASE64 }}" >> google-key.json.asc + gpg -d --passphrase "${{ secrets.ANDROID_KEYSTORE_BASE64_PASSPHRASE }}" --batch buyit.keystore.asc > android/app/buyit.keystore + gpg -d --passphrase "${{ secrets.ENVFILE_PROD_BASE64_PASSPHRASE }}" --batch .env.prod.asc > .env.prod + gpg -d --passphrase "${{ secrets.GOOGLE_KEY_BASE64_PASSPHRASE }}" --batch google-key.json.asc > google-key.json + gpg -d --passphrase "${{ secrets.FIREBASE_BASE64_PASSPHRASE }}" --batch firebase.json.asc > firebase.json + gpg -d --passphrase "${{ secrets.GOOGLE_SERVICES_BASE64_PASSPHRASE }}" --batch google-services.json.asc > ./android/app/src/production/google-services.json + + - uses: actions/setup-node@v1 + with: + node-version: '12.x' + + - uses: actions/setup-ruby@v1 + with: + ruby-version: '2.x' + + - name: Get the version name + id: get_version_name + run: echo ::set-output name=VERSION_NAME::$(git describe --tags --abbrev=0) + + - name: Get the build number + id: get_build_number + run: echo ::set-output name=BUILD_NUMBER::$(git log --pretty=format:'' | wc -l) + + - name: Install Fastlane + run: | + gem install bundler + gem update bundler + + - name: Deploy Production + run: fastlane bundle_android_production + env: + ANDROID_KEYSTORE_URL: ${{ secrets.ANDROID_KEYSTORE_URL }} + ANDROID_KEYSTORE_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PASSWORD }} + ANDROID_KEYSTORE_ALIAS: ${{ secrets.ANDROID_KEYSTORE_ALIAS }} + ANDROID_KEYSTORE_PRIVATE_KEY_PASSWORD: ${{ secrets.ANDROID_KEYSTORE_PRIVATE_KEY_PASSWORD }} + PACKAGE_NAME: ${{ secrets.PACKAGE_NAME }} + ENVFILE: '.env.prod' + ANDROID_KEYSTORE_PATH: 'buyit.keystore' + UPLOAD_TO_STORE: 'true' + GOOGLE_KEY: 'google-key.json' + BUILD_NUMBER: ${{ steps.get_build_number.outputs.BUILD_NUMBER }} + VERSION_NAME: ${{ steps.get_version_name.outputs.VERSION_NAME }} diff --git a/.gitignore b/.gitignore index 5ce4dc6..a9bc299 100644 --- a/.gitignore +++ b/.gitignore @@ -67,4 +67,8 @@ buck-out/ coverage .env.* -google-services.json \ No newline at end of file +google-services.json +*.asc* +fastlane/report.xml +*.pem +google-key.json \ No newline at end of file diff --git a/README.en.md b/README.en.md index 3c3364c..5864611 100644 --- a/README.en.md +++ b/README.en.md @@ -29,13 +29,15 @@ Read this in other languages: [English](README.en.md), [Português](README.md) ## Firebase + This project uses `Firebase` as a BAS (Backend as a Service), so in order to run the project, you need to configure these settings in code. -First, you need create a project in `Firebase` (Two projects if you want to separate the development environment from production environment), to configure the project for Android, add the **google-services.json** in folders *./android/app/src/development* and *./android/app/src/production*. +First, you need create a project in `Firebase` (Two projects if you want to separate the development environment from production environment), to configure the project for Android, add the **google-services.json** in folders _./android/app/src/development_ and _./android/app/src/production_. -After that, you need to adjust the *ADMOB* for the ads, to configure this, you need to create 3 files into your root folder(where package.json is present), each file with the following information: +After that, you need to adjust the _ADMOB_ for the ads, to configure this, you need to create 3 files into your root folder(where package.json is present), each file with the following information: - **firebase.json** + ``` { "react-native": { @@ -44,7 +46,9 @@ After that, you need to adjust the *ADMOB* for the ads, to configure this, you n } } ``` + - **.env.dev** + ``` DEFAULT_ENVIRONMENT=development ADMOB_APP_ID=ADMOB_APP_ID @@ -55,6 +59,7 @@ ADMOB_INTERSTITIAL_ID_CAMPAING= ``` - **.env.prod** + ``` DEFAULT_ENVIRONMENT=production ADMOB_APP_ID=ADMOB_APP_ID @@ -67,17 +72,13 @@ ADMOB_INTERSTITIAL_ID_CAMPAING= > **Note:**, In spite having `ADMOB BANNER _ID_*` in the development environment, while you are using the project in development mode, it will only show test ads. ## Creating a build -To build the project, install all the dependencies using command `yarn install` after that execute `yarn android:dev` to start the app in debug mode using the development lane. To generate the app in debug mode using the production lane requires a **keystore** configured and in your *$HOME*, after configured it with the name *buyit.keystore* execute in project root `yarn android:prod`. + +To build the project, install all the dependencies using command `yarn install` after that execute `yarn android:dev` to start the app in debug mode using the development lane. ## After creating a build, app closes after launch, what should I do? -If you created the build following above instructions and when you launch the app in emulator/device it opens and closes immediately, go into the folder *./android* in *terminal* and execute `./gradlew clean` and try to build the app again. + +If you created the build following above instructions and when you launch the app in emulator/device it opens and closes immediately, go into the folder _./android_ in _terminal_ and execute `./gradlew clean` and try to build the app again. ## Create a build in release -To create a build in production release, you need to go to folder *./android* and execute the following command `./gradlew assembleProduction` passing the environments variable: - -- `ENVFILE=.env.prod` -- `BITRISEIO_ANDROID_KEYSTORE_PASSWORD="YOUR_KEYSTORE_PASSWORD"` -- `BITRISEIO_ANDROID_KEYSTORE_ALIAS="YOUR_KEYSTORE_ALIAS"` -- `BITRISEIO_ANDROID_KEYSTORE_PRIVATE_KEY_PASSWORD="YOUR_KEYSTORE_PRIVATE_PASSWORD"` -- `BITRISE_BUILD_NUMBER="BUILD_NUMBER_DESIRED"` -- `BITRISE_VERSION_NUMBER="VERSION_NUMBER_DESIRED"` + +To create a build in development release, just run `fastlane release_android_development`, if you wanna create a build in production release, see the documentation [HOW_TO_DEPLOY](https://github.com/salomaoluiz/BuyIt/blob/main/fastlane/HOW_TO_DEPLOY.en.md) diff --git a/README.md b/README.md index e1aba78..a3e970d 100644 --- a/README.md +++ b/README.md @@ -29,13 +29,15 @@ Read this in other languages: [English](README.en.md), [Português](README.md) ## Firebase + Para esse projeto foi utilizado o Firebase como forma de BAS, logo é preciso realizar algumas configurações no projeto. -Primeiro é preciso criar um projeto no firebase (dois projetos se você deseja separar o ambiente de desenvolvimento do ambiente de produção), configurar o projeto para Android e adicionando o **google-services.json** nas pastas *./android/app/src/development* e *./android/app/src/production*. +Primeiro é preciso criar um projeto no firebase (dois projetos se você deseja separar o ambiente de desenvolvimento do ambiente de produção), configurar o projeto para Android e adicionando o **google-services.json** nas pastas _./android/app/src/development_ e _./android/app/src/production_. Realizada essas configurações iniciais é preciso também ajustar o ADMOB para as publicidades dentro do projeto, para configurar isso é preciso que crie 3 arquivos, sendo cada um deles com as seguintes informações: - **firebase.json** + ``` { "react-native": { @@ -44,7 +46,9 @@ Realizada essas configurações iniciais é preciso também ajustar o ADMOB para } } ``` + - **.env.dev** + ``` DEFAULT_ENVIRONMENT=development ADMOB_APP_ID=ADMOB_APP_ID @@ -55,6 +59,7 @@ ADMOB_INTERSTITIAL_ID_CAMPAING= ``` - **.env.prod** + ``` DEFAULT_ENVIRONMENT=production ADMOB_APP_ID=ADMOB_APP_ID @@ -67,16 +72,13 @@ ADMOB_INTERSTITIAL_ID_CAMPAING= Observe que apesar de ter um `ADMOB_BANNER_ID_*` no ambiente de desenvolvimento, enquanto você utilizar o projeto sem ser em release, ele irá apresentar as propagandas de teste somente. ## Realizando build -Para realizar o build do projeto, tenha todas as dependências instaladas usando o `yarn install` em seguida execute `yarn android:dev` para iniciar em modo debug na lane de desenvolvimento. Para gerar um app em debug na lane de produção é preciso ter uma **keystore** configurada e presente na sua *$HOME*, após configura-la com o nome *buyit.keystore* execute na raiz do projeto `yarn android:prod`. + +Para realizar o build do projeto, tenha todas as dependências instaladas usando o `yarn install` em seguida execute `yarn android:dev` para iniciar em modo debug na lane de desenvolvimento. ### Após gerar meu build ele abre e fecha o app, o que fazer? -Caso você tenha gerado um build e ao tentar abrir ele no emulador/device ele abrir e fechar o app, vá até a pasta *./android* e execute `./gradlew clean` e tente realizar o build novamente. + +Caso você tenha gerado um build e ao tentar abrir ele no emulador/device ele abrir e fechar o app, vá até a pasta _./android_ e execute `./gradlew clean` e tente realizar o build novamente. ## Gerar build em release -Para gerar build em production release, é preciso ir na pasta *./android* e executar o seguinte comando `./gradlew assembleProduction`, passando as seguintes variáveis de ambiente: -- `ENVFILE=.env.prod` -- `BITRISEIO_ANDROID_KEYSTORE_PASSWORD="SUA_KEYSTORE_PASSWORD"` -- `BITRISEIO_ANDROID_KEYSTORE_ALIAS="SUA_KEYSTORE_ALIAS"` -- `BITRISEIO_ANDROID_KEYSTORE_PRIVATE_KEY_PASSWORD="SUA_KEYSTORE_PRIVATE_PASSWORD"` -- `BITRISE_BUILD_NUMBER="BUILD_NUMBER_DESEJADA"` -- `BITRISE_VERSION_NUMBER="VERSION_NUMBER_DESEJADA"` \ No newline at end of file + +Para gerar build release na lane de desenvolvimento basta executar `fastlane release_android_development`, para realizar o deploy de produção veja a documentação [HOW_TO_DEPLOY](https://github.com/salomaoluiz/BuyIt/blob/main/fastlane/HOW_TO_DEPLOY.md) diff --git a/android/app/build.gradle b/android/app/build.gradle index 0e7e06f..9f8ee6c 100644 --- a/android/app/build.gradle +++ b/android/app/build.gradle @@ -97,11 +97,6 @@ apply from: "../../node_modules/react-native/react.gradle" */ def enableSeparateBuildPerCPUArchitecture = false -/** - * Run Proguard to shrink the Java bytecode in release builds. - */ -def enableProguardInReleaseBuilds = false - /** * The preferred build flavor of JavaScriptCore. * @@ -129,8 +124,26 @@ project.ext.envConfigFiles = [ */ def enableHermes = project.ext.react.get("enableHermes", false); -def getVersionCode = System.getenv('ANDROID_VERSION_CODE') ? System.getenv('ANDROID_VERSION_CODE') as int : 1; -def getVersionName = System.getenv('ANDROID_VERSION_NAME') ? System.getenv('ANDROID_VERSION_NAME') : "1.0"; +def getVersionCode = project.hasProperty('buildVersionCode') ? project.property('buildVersionCode') as int : 1; +def getVersionName = project.hasProperty('buildVersionName') ? project.property('buildVersionName') : "1.0"; +def getPackageName = project.hasProperty('buildPackageName') ? project.property('buildPackageName') : "br.com.jacobysoftware.buyit"; + +def buildStoreFilePath = project.hasProperty('buildStoreFilePath') ? project.property('buildStoreFilePath') : 'debug.keystore' +def signingFile = new File(System.getenv('HOME') + '/buyit.keystore') +def buildStoreFile; +if(buildStoreFilePath.contains('http')){ + new URL(buildStoreFilePath).withInputStream{ i -> signingFile.withOutputStream{ it << i }} + buildStoreFile = file(System.getenv("HOME")+"/buyit.keystore") +} else { + buildStoreFile = file(buildStoreFilePath) +} + +def buildStorePassword = project.hasProperty('buildStorePassword') ? project.property('buildStorePassword') : "android" +def buildKeyAlias = project.hasProperty('buildKeyAlias') ? project.property('buildKeyAlias') : "androiddebugkey" +def buildKeyPassword = project.hasProperty('buildKeyPassword') ? project.property('buildKeyPassword') : "android" +def enableMinifyInReleaseBuilds = true +def enableShrinkInReleaseBuilds = true + crashlytics { enableNdk true } @@ -142,12 +155,12 @@ android { } defaultConfig { - applicationId "br.com.jacobysoftware.buyit" + applicationId getPackageName minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion versionCode getVersionCode versionName getVersionName - resValue "string", "build_config_package", "br.com.jacobysoftware.buyit" + resValue "string", "build_config_package", 'br.com.jacobysoftware.buyit' multiDexEnabled true missingDimensionStrategy 'react-native-camera', 'general' } @@ -167,14 +180,10 @@ android { keyPassword 'android' } release { - def signingFile = new File(System.getenv('HOME') + '/buyit.keystore') - if (!signingFile.exists()) { - new URL(System.getenv('BITRISEIO_ANDROID_KEYSTORE_URL')).withInputStream{ i -> signingFile.withOutputStream{ it << i }} - } - storeFile file(System.getenv('HOME') + '/buyit.keystore') - storePassword System.getenv('BITRISEIO_ANDROID_KEYSTORE_PASSWORD') - keyAlias System.getenv('BITRISEIO_ANDROID_KEYSTORE_ALIAS') - keyPassword System.getenv('BITRISEIO_ANDROID_KEYSTORE_PRIVATE_KEY_PASSWORD') + storeFile buildStoreFile + storePassword buildStorePassword + keyAlias buildKeyAlias + keyPassword buildKeyPassword } } buildTypes { @@ -185,7 +194,8 @@ android { // Caution! In production, you need to generate your own keystore file. // see https://facebook.github.io/react-native/docs/signed-apk-android. signingConfig signingConfigs.release - minifyEnabled enableProguardInReleaseBuilds + minifyEnabled enableMinifyInReleaseBuilds + shrinkResources enableShrinkInReleaseBuilds proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" } } diff --git a/android/app/proguard-rules.pro b/android/app/proguard-rules.pro index 11b0257..0e55828 100644 --- a/android/app/proguard-rules.pro +++ b/android/app/proguard-rules.pro @@ -8,3 +8,5 @@ # http://developer.android.com/guide/developing/tools/proguard.html # Add any project specific keep options here: + +-keep class br.com.jacobysoftware.buyit.BuildConfig { *; } \ No newline at end of file diff --git a/fastlane/Fastfile b/fastlane/Fastfile new file mode 100644 index 0000000..07f5787 --- /dev/null +++ b/fastlane/Fastfile @@ -0,0 +1,139 @@ +OUT_DIR = ENV['DEPLOY_DIR'] || 'build/' +ANDROID_KEYSTORE_PATH = ENV['ANDROID_KEYSTORE_PATH'] +ANDROID_KEYSTORE_PASSWORD = ENV['ANDROID_KEYSTORE_PASSWORD'] +ANDROID_KEYSTORE_ALIAS = ENV['ANDROID_KEYSTORE_ALIAS'] +ANDROID_KEYSTORE_PRIVATE_KEY_PASSWORD = ENV['ANDROID_KEYSTORE_PRIVATE_KEY_PASSWORD'] +BUILD_NUMBER = ENV["BUILD_NUMBER"] || 1 +VERSION_NAME = ENV["VERSION_NAME"] || 'v0.0' +PACKAGE_NAME = ENV["PACKAGE_NAME"] || 'br.com.jacobysoftware.buyit' +UPLOAD_TO_STORE = ENV["UPLOAD_TO_STORE"] == "true" ? true : false + +before_all do + sh 'yarn' +end + +desc 'Realizando o build debug para o ambiente de desenvolvimento' +lane :debug_android_development do + ENV['ENVFILE'] = '.env.dev' + gradle(task: 'clean', project_dir: 'android/') + + gradle( + task: 'assemble', + flavor: 'development', + build_type: 'debug', + project_dir: './android', + properties: { + 'buildVersionName' => VERSION_NAME, + 'buildVersionCode' => BUILD_NUMBER, + 'buildPackageName' => PACKAGE_NAME + } + ) + + copy_artifacts( + :task => 'assemble', + :flavor => 'development' + ) + +end + +desc 'Realizando o build release para o ambiente de desenvolvimento' +lane :release_android_development do + ENV['ENVFILE'] = '.env.dev' + gradle(task: 'clean', project_dir: 'android/') + + gradle( + task: 'assemble', + flavor: 'development', + build_type: 'release', + project_dir: './android', + properties: { + 'buildVersionName' => VERSION_NAME, + 'buildVersionCode' => BUILD_NUMBER, + 'buildPackageName' => PACKAGE_NAME + } + ) + + copy_artifacts( + :task => 'assemble', + :flavor => 'development' + ) + +end + + +desc 'Realizando o build release para o ambiente de producao' +lane :release_android_production do + ENV['ENVFILE'] = '.env.prod' + + gradle(task: 'clean', project_dir: 'android/') + + gradle( + task: 'assemble', + flavor: 'production', + build_type: 'release', + project_dir: './android', + properties: { + 'buildVersionName' => VERSION_NAME, + 'buildVersionCode' => BUILD_NUMBER, + 'buildStoreFilePath' => ANDROID_KEYSTORE_PATH, + 'buildStorePassword' => ANDROID_KEYSTORE_PASSWORD, + 'buildKeyAlias' => ANDROID_KEYSTORE_ALIAS, + 'buildKeyPassword' => ANDROID_KEYSTORE_PRIVATE_KEY_PASSWORD, + 'buildPackageName' => PACKAGE_NAME, + }, + ) + + copy_artifacts( + :task => 'assemble', + :flavor => 'production' + ) +end + +desc 'Realizando o build release para enviar o ambiente de producao' +lane :bundle_android_production do + ENV['ENVFILE'] = '.env.prod' + + gradle(task: 'clean', project_dir: 'android/') + + gradle( + task: 'bundle', + flavor: 'production', + build_type: 'release', + project_dir: './android', + properties: { + 'buildVersionName' => VERSION_NAME, + 'buildVersionCode' => BUILD_NUMBER, + 'buildStoreFilePath' => ANDROID_KEYSTORE_PATH, + 'buildStorePassword' => ANDROID_KEYSTORE_PASSWORD, + 'buildKeyAlias' => ANDROID_KEYSTORE_ALIAS, + 'buildKeyPassword' => ANDROID_KEYSTORE_PRIVATE_KEY_PASSWORD, + 'buildPackageName' => PACKAGE_NAME, + }, + ) + + copy_artifacts( + :task => 'bundle', + :flavor => 'production' + ) + + if UPLOAD_TO_STORE + upload_to_play_store( + track: 'internal', + aab: "./fastlane/build/BuyIt-production.aab", + json_key: ENV['GOOGLE_KEY'], + package_name: ENV['PACKAGE_NAME'], + skip_upload_apk: true + ) + end +end + +def copy_artifacts(params = {}) + task = params[:task] + flavor = params[:flavor] + artifact_location = task === 'assemble' ? lane_context[SharedValues::GRADLE_APK_OUTPUT_PATH] : lane_context[SharedValues::GRADLE_AAB_OUTPUT_PATH] + artifact_extension = task === 'assemble' ? 'apk' : 'aab' + + UI.message "Movendo para \"#{OUT_DIR}\"" + sh "mkdir -p #{OUT_DIR}" + sh "cp #{artifact_location} #{File.join(OUT_DIR, 'BuyIt-' + flavor + '.' + artifact_extension)}" +end \ No newline at end of file diff --git a/fastlane/HOW_TO_DEPLOY.en.md b/fastlane/HOW_TO_DEPLOY.en.md new file mode 100644 index 0000000..4a25147 --- /dev/null +++ b/fastlane/HOW_TO_DEPLOY.en.md @@ -0,0 +1,74 @@ +# How to configure automatic deploy + +The project is configured to realize the automatic deploy to intern test environment of Google Play always than a tag is opened, but for that is necessary some settings. + +## Getting the required files + +Some files maybe you have, as `google-services.json`, `.env.prod`, `firebase.json` e `buyit.keystore`. If you don't have configured yet, see the [README](https://github.com/salomaoluiz/BuyIt/blob/main/README.en.md). + +Now we need a last file, a service account key, for that, open your Google Cloud Platform. + +1. If you have noone project, go to "Select a project" on upper right side and clique on "New Project", choose a name for the project and click on "Create". +2. Following, go to "API & Services" on left side and click on "ENABLE APIS AND SERVICES", search by "Google Play Android Developer API", than active it. +3. You will be redirect to API screen, on left side, click on "Credentials" , go to "Create credentials" and select "Service account". +4. Choose a name and a describe to you service account, than click on "Create". +5. Choose the role "Owner" and click on "Done", we don't need grant users access. +6. After created the service account, click on that to open it, and go to "Keys", and click on "ADD KEY" and "Create new Key", choose the "JSON" type and click on "Create" +7. This will download the key, save that on project root with the name `google-key.json`. + +## Adding the service account to Google Play Console + +Now we need add this service account on allowed list users in Google Play. + +1. Go to services account details and copy the "Email" value. +2. Now access your Google Play Console account in "All apps" screen. +3. On left side, go on "Users and permissions". +4. Go on "Invite new users" and add the email what we just copy. +5. Select the the app what you wanna add, and select the permission "Release apps to testing tracks" and apply. +6. Lastly, click on "Invite user" and "Send invite". + +## Adding the project to Google Play Console + +We need to add too the project what we just created on Google Cloud Platform in our Google Play Console account. + +1. On screen of Google Play Console where has all apps, on left side, go on "Settings", and "Developer account" and finally "API Access". +2. Select "Link existing project" and select the project what you have created on the first step at this doc and click on "Link project". + +Very well, with this we have our project configured to do the project manual deploy, if you wanna do this, just run on project root: + +```bash +ANDROID_KEYSTORE_PASSWORD=$ANDROID_KEYSTORE_PASSWORD ANDROID_KEYSTORE_ALIAS=$ANDROID_KEYSTORE_ALIAS ANDROID_KEYSTORE_PRIVATE_KEY_PASSWORD=$ANDROID_KEYSTORE_PRIVATE_KEY_PASSWORD ENVFILE=.env.prod VERSION_NAME="v0.0.2" BUILD_NUMBER="2" ANDROID_KEYSTORE_PATH="$HOME/buyit.keystore" UPLOAD_TO_STORE=true GOOGLE_KEY="google-key.json" PACKAGE_NAME=$PACKAGE_NAME fastlane bundle_android_production +``` + +If you use `release_android_production` instead `bundle_android_production`, you will be create a apk without deploy to Google Play. + +## Setting github keys + +Ok, we can do the local deploy, but now we need set the github to receive the secrets and with that dispatch the automatic action on every tag opened. + +How github secrets don't accept binary files, we need convert every of our files into strings, to they be converted again on pipeline. To convert we go use the command: + +```bash +gpg -c --armor file_path +``` + +It will go ask by a password and at finish will create a file `file_path.asc`. + +Convert this following files and save the password used in each file. + +In github, go on "Settings" and in left side go on "Secrets". Now you go create the following credentials, being they respectively `PASSWORD_TO_CONVERT -> CONVERTED_FILE`: + +- **buyit.keystore**: ANDROID_KEYSTORE_BASE64_PASSPHRASE -> ANDROID_KEYSTORE_BASE64 +- **.env.prod**: ENVFILE_PROD_BASE64_PASSPHRASE -> ENVFILE_PROD_BASE64 +- **google-key.json**: GOOGLE_KEY_BASE64_PASSPHRASE -> GOOGLE_KEY_BASE64 +- **google-services.json**: GOOGLE_SERVICES_BASE64_PASSPHRASE -> GOOGLE_SERVICES_BASE64 +- **firebase.json**: FIREBASE_BASE64_PASSPHRASE -> FIREBASE_BASE64 + +Ok, now just add in secrets the following keys to realize the app build: + +- ANDROID_KEYSTORE_ALIAS +- ANDROID_KEYSTORE_PASSWORD +- ANDROID_KEYSTORE_PRIVATE_KEY_PASSWORD +- PACKAGE_NAME - Being this the package name of your project, for example `br.com.testeapp` + +Very well, now everything are done to deploy your app on internal track in every new tag. For default, the deploy will be doing with BUILD_NUMBER as the total of commits present on tag, and the BUILD_NAME are the tag name. diff --git a/fastlane/HOW_TO_DEPLOY.md b/fastlane/HOW_TO_DEPLOY.md new file mode 100644 index 0000000..e595691 --- /dev/null +++ b/fastlane/HOW_TO_DEPLOY.md @@ -0,0 +1,75 @@ +# Como configurar o deploy automatico + +O projeto está configurado para realizar o deploy automaticamente para o ambiente de teste interno da google play sempre que uma tag for aberta, mas para isso é preciso realizar algumas configurações. + +## Obtendo arquivos necessárias + +Alguns arquivos você já deve ter configurado, como `google-services.json`, `.env.prod`, `firebase.json` e `buyit.keystore`. Caso não os tenha configurado ainda, veja o [README](https://github.com/salomaoluiz/BuyIt/blob/main/README.md). + +Precisamos ainda de um ultimo arquivo, uma chave de conta de serviço, para isso, abra o Google Cloud Platform. + +1. Se você não possuir nenhum projeto, vá em "Selecione um projeto" no canto superior direito e clique em "Novo Projeto", escolha um nome para o projeto e clique em "Criar". +2. Em seguida, vá em "API e serviços" no lado esquerdo, clique em "ATIVAR APIS E SERVIÇOS" e pesquise por "Google Play Android Developer API" `"Google Play Custom App Publishing API"`, e ative-a. +3. Você será redirecionado para a tela da API, clique no lado esquerdo em "Credenciais", vá em "Criar credenciais" e selecione "Conta de Serviço". +4. Escolha um nome e uma descrição para a conta de serviço e clique em "Criar". +5. Escolha a permissão "Proprietario" e clique em "Continuar". +6. Clique em "Concluir" para pular a etapa de conceder acesso a essa conta de serviço a usuários. +7. Criada a conta de serviço, clique nela para abrir e vá em "Chaves", e clique em "ADICIONAR CHAVE" e "Criar nova Chave", escolha o tipo "JSON" e clique em "Criar". +8. Ele irá baixar a chave, salve ela na raíz do projeto com o nome `google-key.json`. + +## Adicionando a conta de serviço ao Google Play Console + +Precisamos agora adicionar essa conta de serviço que acabamos de criar aos usuários permitidos do Google Play. + +1. Vá em detalhes da conta de serviço e copie o valor do "Email". +2. Acesse a sua conta do Google Play Console, na tela de "Todos os Apps". +3. No lado esquerdo vá em "Usuários e permissões". +4. Vá em "Convidar novo usuário" e adicione o email que acabamos de copiar. +5. Selecione o app desejado e selecione a permissão "Liberar apps para as faixas de teste" e aplique. +6. Por fim, clique em "Convidar usuário" e "Enviar convite" + +## Adicionando projeto ao Google Play Console + +Precisamos agora adicionar o projeto que criamos no Google Cloud Platform na nossa conta do Google Play Console. + +1. Na tela do Google Play Console onde tem todos os apps, no lado esquerdo vá em "Configurações", depois em "Conta de desenvolvedor" e por fim "Acesso à API". +2. Selecione "Vincular projeto existente" e selecione o projeto que você criou no primeiro passo desse documento e clique em "Vincular projeto". + +Muito bem, com isso nós já temos o nosso projeto configurado para realizar o deploy do projeto manualmente, se você quiser fazer isso, basta executar na raiz do projeto: + +```bash +ANDROID_KEYSTORE_PASSWORD=$ANDROID_KEYSTORE_PASSWORD ANDROID_KEYSTORE_ALIAS=$ANDROID_KEYSTORE_ALIAS ANDROID_KEYSTORE_PRIVATE_KEY_PASSWORD=$ANDROID_KEYSTORE_PRIVATE_KEY_PASSWORD ENVFILE=.env.prod VERSION_NAME="v0.0.2" BUILD_NUMBER="2" ANDROID_KEYSTORE_PATH="$HOME/buyit.keystore" UPLOAD_TO_STORE=true GOOGLE_KEY="google-key.json" PACKAGE_NAME=$PACKAGE_NAME fastlane bundle_android_production +``` + +Se você usar `release_android_production` ao invés de `bundle_android_production` será criado um apk em produção, sem subir para o Google Play. + +## Configurando chaves para o github + +Muito bem, já conseguimos fazer deploy localmente, mas agora precisamos configurar o github para receber esses secrets e poder disparar a action automaticamente em toda tag. + +Como os secrets do github não aceitam arquivos binários, nós precisamos converter cada um dos nossos arquivos em strings para que ele seja convertido novamente durante o pipeline. Converteremos usando o comando: + +```bash +gpg -c --armor file_path +``` + +Ele irá pedir uma senha e ao finalizar vai criar um arquivo `file_path.asc`. + +Converta todos os arquivos e salve a senha usada em cada arquivo. + +No github vá em "Settings" e no lado esquerdo em "Secrets". Agora você vai criar as seguintes credênciais, sendo elas respectivamente `SENHA_PARA_CONVERTER -> ARQUIVO CONVERTIDO` + +- **buyit.keystore**: ANDROID_KEYSTORE_BASE64_PASSPHRASE -> ANDROID_KEYSTORE_BASE64 +- **.env.prod**: ENVFILE_PROD_BASE64_PASSPHRASE -> ENVFILE_PROD_BASE64 +- **google-key.json**: GOOGLE_KEY_BASE64_PASSPHRASE -> GOOGLE_KEY_BASE64 +- **google-services.json**: GOOGLE_SERVICES_BASE64_PASSPHRASE -> GOOGLE_SERVICES_BASE64 +- **firebase.json**: FIREBASE_BASE64_PASSPHRASE -> FIREBASE_BASE64 + +Muito bem, agora basta colocar nas secrets os seguintes environments para realizar o build o app: + +- ANDROID_KEYSTORE_ALIAS +- ANDROID_KEYSTORE_PASSWORD +- ANDROID_KEYSTORE_PRIVATE_KEY_PASSWORD +- PACKAGE_NAME - Sendo este o nome do pacote, por exemplo `br.com.testeapp` + +Muito bem, agora tudo está pronto para fazer deploy para o ambiente de teste sempre que abrir uma tag nova. Por padrão ele irá realizar um deploy com o BUILD_NUMBER sendo a quantidade de commits presente na tag, e o BUILD_NAME sendo o nome da tag. diff --git a/fastlane/README.md b/fastlane/README.md new file mode 100644 index 0000000..f526cd5 --- /dev/null +++ b/fastlane/README.md @@ -0,0 +1,43 @@ +fastlane documentation +================ +# Installation + +Make sure you have the latest version of the Xcode command line tools installed: + +``` +xcode-select --install +``` + +Install _fastlane_ using +``` +[sudo] gem install fastlane -NV +``` +or alternatively using `brew install fastlane` + +# Available Actions +### debug_android_development +``` +fastlane debug_android_development +``` +Realizando o build debug para o ambiente de desenvolvimento +### release_android_development +``` +fastlane release_android_development +``` +Realizando o build release para o ambiente de desenvolvimento +### release_android_production +``` +fastlane release_android_production +``` +Realizando o build release para o ambiente de producao +### bundle_android_production +``` +fastlane bundle_android_production +``` +Realizando o build release para enviar o ambiente de producao + +---- + +This README.md is auto-generated and will be re-generated every time [fastlane](https://fastlane.tools) is run. +More information about fastlane can be found on [fastlane.tools](https://fastlane.tools). +The documentation of fastlane can be found on [docs.fastlane.tools](https://docs.fastlane.tools). diff --git a/package.json b/package.json index bd77e17..9b8118b 100644 --- a/package.json +++ b/package.json @@ -3,7 +3,7 @@ "version": "0.0.1", "private": true, "scripts": { - "android:dev": "ENVFILE=.env.dev react-native run-android --variant=developmentDebug", + "android:dev": "react-native run-android --variant=developmentDebug", "ios": "react-native run-ios", "start": "react-native start --reset-cache", "test": "jest", @@ -92,4 +92,4 @@ "pre-push": "yarn lint && yarn tsc && yarn test" } } -} +} \ No newline at end of file diff --git a/src/components/admob-banner/index.tsx b/src/components/admob-banner/index.tsx index 556fa39..3d6f5ce 100644 --- a/src/components/admob-banner/index.tsx +++ b/src/components/admob-banner/index.tsx @@ -4,9 +4,10 @@ import React from 'react'; import Config from 'react-native-config'; const AdmobBanner = () => { - const bannerAdID = __DEV__ - ? TestIds.BANNER - : Config.ADMOB_BANNER_ID_CAMPAING || Config.ADMOB_BANNER_ID_DEFAULT; + const bannerAdID = + Config['DEFAULT_ENVIRONMENT'] === 'development' + ? TestIds.BANNER + : Config.ADMOB_BANNER_ID_CAMPAING || Config.ADMOB_BANNER_ID_DEFAULT; return ( ({ __DEV__: false, })); jest.mock('react-native-config', () => ({ + DEFAULT_ENVIRONMENT: 'development', ADMOB_INTERSTITIAL_ID_DEFAULT: 'ADMOB_INTERSTITIAL_ID_DEFAULT', })); jest.mock('@react-native-firebase/admob', () => ({ diff --git a/src/firebase/admob.ts b/src/firebase/admob.ts index 55eccf5..ccb7746 100644 --- a/src/firebase/admob.ts +++ b/src/firebase/admob.ts @@ -16,10 +16,11 @@ const admobInit = () => { }; export const useInterstitialAd = () => { - const bannerAdID = __DEV__ - ? TestIds.INTERSTITIAL - : Config.ADMOB_INTERSTITIAL_ID_CAMPAING || - Config.ADMOB_INTERSTITIAL_ID_DEFAULT; + const bannerAdID = + Config['DEFAULT_ENVIRONMENT'] === 'development' + ? TestIds.INTERSTITIAL + : Config.ADMOB_INTERSTITIAL_ID_CAMPAING || + Config.ADMOB_INTERSTITIAL_ID_DEFAULT; const interstitial = InterstitialAd.createForAdRequest(bannerAdID, { requestNonPersonalizedAdsOnly: true,