diff --git a/docs/dev_environment.md b/docs/dev_environment.md index bda0d241f..472b7b826 100644 --- a/docs/dev_environment.md +++ b/docs/dev_environment.md @@ -1,881 +1,881 @@ # Requirements Please note that our dev environment currently only works on macOS and Linux. For the Linux instructions [head to the Linux configuration steps](linux_dev_environment.md).
Why not Windows? (click to expand)

It’s primarily because Apple only supports iOS development using macOS. It’s true that we could support web, keyserver, and Android development on other operating systems, but because of the Apple requirement, all of our active developers currently run macOS. We’d very much welcome a PR to build out support on Windows!

Unfortunately the dev environment is overall pretty heavy. You’ll ideally want a machine with at least 32 GiB of RAM, although 16 GiB should suffice. # Prerequisites ## Xcode Go to the [Mac App Store](https://apps.apple.com/us/app/xcode/id497799835) to install Xcode, or if you already have it, to update it to the latest version. Once Xcode is installed, open it up. If you are prompted, follow the instructions to install any “Additional Required Components”. Finally, you need to make sure that the Xcode “Command Line Tools” are installed. You can do this by running: ``` xcode-select --install ``` ## Homebrew Install [Homebrew](https://brew.sh/), a package manager for macOS. ## Node Next, install [Node](https://nodejs.org/) using Homebrew. We’re going to use version 16 to avoid some possible issues that come up on Apple silicon when we install project dependencies. ``` brew install node@16 && brew upgrade node@16 ``` The reason we use both `install` and `upgrade` is that there’s no single Homebrew command equivalent to “install if not installed, and upgrade if already installed”. ## PHP [PHP](https://www.php.net) is needed for Arcanist. As of macOS 12 (Monterey), PHP is no longer bundled with the OS and needs to be installed via Homebrew. ``` brew install php@7.4 && brew upgrade php@7.4 ``` ## Rust We use a Rust [implementation](https://github.com/novifinancial/opaque-ke) of the OPAQUE password-authenticated key exchange protocol, so you will need to install Rust to compile the static library. The easiest way to do this is with `rustup`. ``` curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh ``` ## ShellCheck [ShellCheck](https://www.shellcheck.net/) is a static analysis tool that provides warnings and suggestions for shell scripts. We’ll install ShellCheck using Homebrew. ``` brew install shellcheck && brew upgrade shellcheck ``` ## Yarn We use the [Yarn](https://yarnpkg.com/) package manager for JavaScript in our repo. ``` brew install yarn && brew upgrade yarn ``` ## Watchman Watchman is a tool from Facebook used in the React Native dev environment to watch for changes to your filesystem. ``` brew install watchman && brew upgrade watchman ``` ## Node Version Manager Node Version Manager (nvm) is a tool that ensures we use the same version of Node on our keyserver between prod and dev environments. ``` brew install nvm && brew upgrade nvm ``` After installing, Homebrew will print out some instructions under the Caveats section of its output. It will ask you to do two things: `mkdir ~/.nvm`, and to add some lines to your `~/.bash_profile` (or desired shell configuration file). We recommend that you append `--no-use` to the line that loads nvm, so that you continue to use your Homebrew-sourced Node distribution by default. These lines are different depending on if you’re on Apple silicon or Intel x86-64. If you’re on Apple silicon, you should add the following to your shell configuration file (note the addition of the `--no-use` flag on the line that loads nvm): ``` export NVM_DIR="$HOME/.nvm" [ -s "/opt/homebrew/opt/nvm/nvm.sh" ] && \. "/opt/homebrew/opt/nvm/nvm.sh" --no-use # This loads nvm [ -s "/opt/homebrew/opt/nvm/etc/bash_completion.d/nvm" ] && \. "/opt/homebrew/opt/nvm/etc/bash_completion.d/nvm" # This loads nvm bash_completion ``` Otherwise, if you’re on Intel x86-64, add the following to your shell configuration file: ``` export NVM_DIR="$HOME/.nvm" [ -s "/usr/local/opt/nvm/nvm.sh" ] && \. "/usr/local/opt/nvm/nvm.sh" --no-use # This loads nvm [ -s "/usr/local/opt/nvm/etc/bash_completion.d/nvm" ] && \. "/usr/local/opt/nvm/etc/bash_completion.d/nvm" # This loads nvm bash_completion ``` Now either close and reopen your terminal window or re-source your shell configuration file in order to load nvm: ``` source ~/.bash_profile ``` ## MariaDB For the keyserver database we use MariaDB, which is a community-driven fork of MySQL. In this step we’ll install MariaDB using Homebrew. ``` brew install mariadb && brew upgrade mariadb ``` Next we’ll configure MariaDB to start when your computer boots using `brew services`: ``` brew tap homebrew/services brew services start mariadb ``` Finally, you should set up a root password for your local MariaDB instance. To do this we’ll use the `mysqladmin` command. Note that many of MariaDB’s commands still use the “mysql” name for compatibility. ``` sudo mysqladmin -u root password ``` ## Redis We use Redis on the keyserver side as a message broker. ``` brew install redis && brew upgrade redis ``` We’ll set it up to start on boot with `brew services`: ``` brew services start redis ``` ## CocoaPods CocoaPods is a dependency management system for iOS development. React Native uses it to manage native modules. ``` brew install cocoapods && brew upgrade cocoapods ``` ## Reactotron Reactotron is an event tracker and logger that can be used to aid in debugging on React Native. ``` brew install reactotron && brew upgrade reactotron ``` ## React Dev Tools Chrome extension The React Dev Tools Chrome extension lets you inspect the React component tree for web applications in Chrome. You can install it by navigating [here](https://chrome.google.com/webstore/detail/react-developer-tools/fmkadmapgofadopljbjfkapdkoienihi) on Chrome. ## Redux Dev Tools Chrome extension The Redux Dev Tools Chrome extension lets you watch for Redux actions and inspect the Redux store state, both for web applications in Chrome, but also for our native applications using the “Remote DevTools” functionality. To install it, navigate [here](https://chrome.google.com/webstore/detail/redux-devtools/lmhkpmbekcpmknklioeibfkpmmfibljd) on Chrome. ## JDK We’ll need the Java Development Kit (JDK) for Android development. We’re using [SDKMAN!](https://sdkman.io/) to manage our JDK installation. Run the following to install SDKMAN!: ``` curl -s "https://get.sdkman.io" | bash ``` Now either close and reopen your terminal window or re-source your `~/.bash_profile` (or desired shell configuration file) in order to load SDKMAN!: ``` source ~/.bash_profile ``` You can run `sdk version` to see if SDKMAN! was installed properly. Run the following to install Azul Zulu 11 with SDKMAN!: ``` sdk install java 11.0.13-zulu ``` SDKMAN! takes care of setting up the `$JAVA_HOME` environment variable to point to the newly installed JDK. You can verify this by running `echo $JAVA_HOME`. ## Android Studio Start by downloading and installing [Android Studio](https://developer.android.com/studio/index.html) for your platform. When prompted to choose an installation type, select “Custom”. You’ll be prompted to select a JDK installation. If your SDKMAN!-sourced JDK doesn’t appear in the dropdown, you can find the absolute path to your installed JDK with the following command: ``` sdk home java 11.0.13-zulu ``` Make sure you check the boxes for the following: #### Intel x86-64: - `Android SDK` - `Android SDK Platform` - `Performance (Intel ® HAXM)` - `Android Virtual Device` #### Apple silicon: - `Android SDK` - `Android SDK Platform` - `Android Virtual Device` ### Android SDK Android Studio installs the latest Android SDK by default, but since React Native uses the Android 11 SDK specifically, we’ll need to install it using Android Studio’s SDK Manager. You can access the SDK Manager from the “Welcome to Android Studio” screen that pops up when you first open the application, from More Actions → SDK Manager. If you already have a project open, you can access it from Tools → SDK Manager. Once you have the SDK Manager open, select the “SDK Platforms” tab, and then check the box for “Show Package Details”. Now expand the “Android 11 (R)” section, and make sure the following subsections are checked: - `Android SDK Platform 30` #### Intel x86-64: - `Intel x86 Atom_64 System Image` or `Google APIs Intel x86 Atom System Image` #### Apple silicon: - `Google Play ARM 64 v8a System Image` Next, select the “SDK Tools” tab, and check the box for “Show Package Details”. Refer to `native/android/build.gradle` for specific tool versions and install the following: - Android SDK Build-Tools - NDK -- CMake version 3.10.2 +- CMake version 3.18.1 To finish the SDK Manager step, click “Apply” to download and install everything you’ve selected. ### Enable Android CLI commands You’ll need to append the following lines to your `~/.bash_profile` (or desired shell configuration file) in order for React Native to be able to build your Android project. ``` export ANDROID_HOME=$HOME/Library/Android/sdk export PATH=$PATH:$ANDROID_HOME/emulator export PATH=$PATH:$ANDROID_HOME/tools export PATH=$PATH:$ANDROID_HOME/tools/bin export PATH=$PATH:$ANDROID_HOME/platform-tools ``` Now either close and reopen your terminal window or re-source your shell configuration file in order to run the new commands: ``` source ~/.bash_profile ``` ## Flipper Flipper is a debugging tool for mobile applications from Facebook. We use it for JavaScript debugging using the Hermes runtime, and also use several plugins such as the React Dev Tools. You can download the latest version of Flipper for MacOS [here](https://www.facebook.com/fbflipper/public/mac). ### Flipper settings After opening Flipper, click the gear icon in the bottom left and navigate to “Settings”. Let’s set the Android SDK path. To find the path, open Android Studio and navigate to Preferences → Appearance & Behavior → System Settings → Android SDK. The explicit path of your Android SDK is defined in “Android SDK Location”. Use this path in Flipper Settings as the “Android SDK Location”. Also, enable the option for “React Native keyboard shortcuts” below. ### Flipper plugins Flipper has a plugin system that allows teams to integrate additional debugging tools into Flipper. We currently only use one plugin, which is for monitoring Redux state. To install it, open Flipper and click on the Plugin Manager on the top left sidebar. Type in “redux-debugger“ in the Install Plugins search bar and install the Flipper plugin with that name. ## idb Flipper relies on Facebook’s idb tool to debug iOS apps running on your device. We’ll need to install it: ``` brew tap facebook/fb brew install idb-companion pip3 install --user --upgrade fb-idb ``` Since we run `pip3 install` with `--user` instead of running it with `sudo`, the `idb` executable gets installed in your userdir. For me, running MacOS with Python 3.9, it got installed in `~/Library/Python/3.9/bin/idb`. For Flipper to be able to talk to `idb`, you’ll need to set the IDB Binary Location in the Flipper Settings. If you have trouble getting Flipper to work with a physical iOS device, it may be due to Python weirdness. The above steps have been tested with Python 3.9 sourced from Homebrew. Let @ashoat know if you have any trouble! ## Codegen for gRPC gRPC is a framework from Google for writing services. As a developer, you define your service’s API using Protobufs, and gRPC handles the networking and basic infrastructure for you. The codegen for gRPC takes files written in the [protocol buffers language](https://developers.google.com/protocol-buffers/docs/proto3) as input and outputs C++ code that enables a developer to create a client and a server that use gRPC for communication. Because of C++ build dependencies, this could not be bundled as an npm package. `brew` also fails to install the required version so if you want to generate files in your local environment, you have to manually install Protobuf. If you find yourself needing to modify the Protobuf schema files, you’ll need to set up the tools to run the codegen. Follow the steps below: - `brew install autoconf automake libtool curl make unzip` - `curl -L https://github.com/protocolbuffers/protobuf/releases/download/v3.15.8/protobuf-cpp-3.15.8.tar.gz --output protobuf-cpp-3.15.8.tar.gz` - `tar xfzv protobuf-cpp-3.15.8.tar.gz` - `cd protobuf-3.15.8` - `./configure` - `make` - `make check` - `sudo make install` After installing, you should be able to check the version of Protobuf like this: `protoc --version` After installing Protobuf, you will also need to install gRPC using `brew install grpc`. This will install the `grpc_cpp_plugin` for `protoc` (the Protobuf compiler), which is necessary for compiling gRPC schemas. Please note that the order is crucial here - you have to first install Protobuf and only then gRPC. This is because otherwise gRPC will install Protobuf automatically from its dependency list, but the version of Protobuf will be incorrect. ## Arcanist We use Phabricator for code review. To upload a “diff” to Phabricator, you’ll need to use a tool called Arcanist. To install Arcanist, we’ll need to clone its Git repository. Pick a place in your filesystem to store it, and then run this command: ``` git clone https://github.com/phacility/arcanist.git ``` Next, you’ll need to add the path `./arcanist/bin` to your `$PATH` in your `~/.bash_profile` (or desired shell configuration file): ``` export PATH=$PATH:~/src/arcanist/bin ``` Make sure to replace the `~/src` portion of the above with the location of the directory you installed Arcanist in. # Configuration ## Apache In both dev and prod environments we have Node configured to run on port 3000, with Apache proxying it across to port 80. The reason for Apache is so that we can use other tech stacks alongside Node. macOS comes with an Apache installation built in. We just need to configure it a little bit. First, we’ll edit the main Apache configuration file. ``` sudo vim /private/etc/apache2/httpd.conf ``` The following individual lines each need to be uncommented: ``` LoadModule proxy_module libexec/apache2/mod_proxy.so LoadModule proxy_http_module libexec/apache2/mod_proxy_http.so LoadModule proxy_wstunnel_module libexec/apache2/mod_proxy_wstunnel.so LoadModule userdir_module libexec/apache2/mod_userdir.so Include /private/etc/apache2/extra/httpd-userdir.conf ``` Next, we’ll edit the `http-userdir.conf` file. ``` sudo vim /private/etc/apache2/extra/httpd-userdir.conf ``` The following line needs to be uncommented: ``` Include /private/etc/apache2/users/*.conf ``` Now for the main course. We need to set up a configuration file for the current user. ``` sudo vim /private/etc/apache2/users/$USER.conf ``` ``` ProxyRequests on ProxyPass /comm/ws ws://localhost:3000/ws ProxyPass /comm/ http://localhost:3000/ ProxyPass /commlanding/ http://localhost:3000/commlanding/ RequestHeader set "X-Forwarded-Proto" expr=%{REQUEST_SCHEME} RequestHeader set "X-Forwarded-SSL" expr=%{HTTPS} ``` You’ll want to make sure that Apache can read your new file. ``` sudo chmod 644 /private/etc/apache2/users/$USER.conf ``` Finally, let’s restart Apache so it picks up the changes. ``` sudo apachectl restart ``` If you end up installing a macOS update you should go through the Apache configuration section again, as your Apache config in `httpd.conf` may have been restored to the default. ## MariaDB Next we’ll set up a MariaDB user and a fresh database. We’ll start by opening up a console using the `mysql` command. ``` mysql -u root -p ``` Type in the MariaDB root password you set up previously when prompted. Then, we’ll go ahead and create an empty database. ``` CREATE DATABASE comm; ``` Now we need to create a user that can access this database. For the following command, replace “password” with a unique password. ``` CREATE USER comm@localhost IDENTIFIED BY 'password'; ``` Finally, we will give permissions to this user to access this database. ``` GRANT ALL ON comm.* TO comm@localhost; ``` You can now exit the MariaDB console using Ctrl+D. ## TablePlus Feel free to use any MariaDB administration platform that you’re comfortable with. PHP was deprecated in macOS 12 (Monterey), leading many of us to switch to [TablePlus](https://tableplus.com/). After installing TablePlus, you need to open a new connection. After opening TablePlus, click the “Create a new connection” text at the bottom of the window that appears. - Alternatively, you can navigate through Connection → New... in the menu at the top of the display. Choose MariaDB from the database options that appear. You’ll be prompted for: - Name (Comm) - Host (localhost) - Port (3306 by default) - User (comm) - Password (the one you made when initializing the MariaDB server in the previous step) ## Android Emulator In order to test the Android app on your computer you’ll need to set up an Android Emulator. To do this we’ll need to open up the Virtual Device Manager in Android Studio. You can access the Virtual Device Manager from the “Welcome to Android Studio” screen that pops up when you first open the application, from More Actions → Virtual Device Manager. If you already have a project open, you can access it from Tools → Virtual Device Manager. With the Virtual Device Manager open, select “Create device” on the top left. Feel free to select any “device definition” that includes Play Store support. On the next screen you’ll be asked to select a system image. Go for the latest version of Android that’s been released. From there you can just hit Next and then Finish. You should then be able to start your new Android Virtual Device from the Virtual Device Manager. # Git repo ## Clone from GitHub Finally! It’s time to clone the repo from GitHub. ``` git clone git@github.com:CommE2E/comm.git ``` Once you have the repo cloned, you can run this command to pull in dependencies. ``` cd comm yarn cleaninstall ``` ## URLs The keyserver needs to know some info about paths in order to properly construct URLs. ``` mkdir -p keyserver/facts vim keyserver/facts/commapp_url.json ``` Your `commapp_url.json` file should look like this: ```json { "baseDomain": "http://localhost", "basePath": "/comm/", "baseRoutePath": "/", "https": false } ``` Additionally, we’ll create a file for the URLs in the landing page. ``` vim keyserver/facts/landing_url.json ``` Your `landing_url.json` file should look like this: ```json { "baseDomain": "http://localhost", "basePath": "/commlanding/", "baseRoutePath": "/commlanding/", "https": false } ``` ## MariaDB The keyserver side needs to see some config files before things can work. The first is a config file with MariaDB details. ``` cd keyserver mkdir secrets vim secrets/db_config.json ``` The DB config file should look like this: ```json { "host": "localhost", "user": "comm", "password": "password", "database": "comm", "dbType": "mariadb10.8" } ``` Make sure to replace the password with the one you set up for your `comm` MariaDB user earlier. ## Olm The second config file contains some details that the keyserver needs in order to launch Olm sessions to provide E2E encryption. We have a script that can generate this file for you. However, before we can run the script we’ll need to use Babel to transpile our source files into something Node can interpret. Babel will transpile the files in `src` into a new directory called `dist`. We’ll also use `rsync` to copy over files that don’t need transpilation. ``` cd keyserver yarn babel-build yarn rsync yarn script dist/scripts/generate-olm-config.js ``` This script will create the `keyserver/secrets/olm_config.json` config file. ## Phabricator The last configuration step is to set up an account on Phabricator, where we handle code review. Start by [logging in to Phabricator](https://phab.comm.dev) using your GitHub account. Next, make sure you’re inside the directory containing the Comm Git repository, and run the following command: ``` arc install-certificate ``` This command will help you connect your Phabricator account with the local Arcanist instance, allowing you to run `arc diff` and `arc land` commands. # Development ## Flow typechecker It’s good to run the `flow` typechecker frequently to make sure you’re not introducing any type errors. Flow treats each Yarn Workspace as a separate environment, and as such runs a separate type-checking server for each. This server is started when you first run `node_modules/.bin/flow` in each of the four Yarn Workspace folders. To make sure Flow runs from the command-line, you can edit your `$PATH` environmental variable in your `~/.bash_profile` file (or desired shell configuration file) to always include `./node_modules/.bin`. ``` export PATH=$PATH:./node_modules/.bin ``` As always, make sure you reload the `~/.bash_profile` after editing it: ``` source ~/.bash_profile ``` You should now be able to run `flow` in any of the Yarn workspaces: ``` cd lib flow ``` ## Running keyserver To run the web app, landing page, or the mobile app on the iOS Simulator or Android Emulator, you’ll need to run the keyserver. Open a new terminal and run: ``` cd keyserver yarn dev ``` This command runs three processes. The first two are to keep the `dist` folder updated whenever the `src` folder changes. They are “watch” versions of the same Babel and `rsync` commands we used to initially create the `dist` folder (before running the `generate-olm-config.js` script above). The final process is `nodemon`, which is similar to `node` except that it restarts whenever any of its source files (in the `dist` directory) changes. Note that if you run `yarn dev` in `keyserver` right after `yarn cleaninstall`, before Webpack is given a chance to build `app.build.cjs`/`landing.build.cjs` files, then Node will crash when it attempts to import those files. Just make sure to run `yarn dev` (or `yarn prod`) in `web` or `landing` before attempting to load the corresponding webpages. ## Running web app First, make sure that the keyserver is running. If you haven’t already, run: ``` cd keyserver yarn dev ``` Next, open a new terminal and run: ``` cd web yarn dev ``` You should now be able to load the web app in your web browser at http://localhost/comm/. This command will start two processes. One is `webpack-dev-server`, which will serve the JS files. `webpack-dev-server` also makes sure the website automatically hot-reloads whenever any of the source files change. The other process is `webpack --watch`, which will build the `app.build.cjs` file, as well as rebuilding it whenever any of the source files change. The `app.build.cjs` file is consumed by the Node server in order to pre-render the initial HTML from the web source (“Server-Side Rendering”). ## Running landing page First, make sure that the keyserver is running. If you haven’t already, run: ``` cd keyserver yarn dev ``` Next, open a new terminal and run: ``` cd landing yarn dev ``` You should now be able to load the landing page in your web browser at http://localhost/commlanding/. This runs the same two processes as the web app, but for the landing page. Note that the `landing.build.cjs` file (similar to the web app’s `app.build.cjs` file) is consumed by the Node server. ## Running mobile app on iOS Simulator First, make sure that the keyserver is running. If you haven’t already, run: ``` cd keyserver yarn dev ``` Next, make sure that the Metro bundler is running. If you haven’t already, open a new terminal and run: ``` cd native yarn dev ``` This command runs two processes. The first is the Metro bundler, which handles bundling our app’s JavaScript code and communicating with the debug build of the app running on either a physical or virtual device. The second is the `remotedev-server` for Redux, which is a proxy of sorts through which the Redux monitor (running in the Chrome extension) can communicate with the debug build of the app. Finally, open `native/ios/Comm.xcworkspace` in Xcode. Select a Simulator from the Scheme menu in the Workspace Toolbar. Then hit the Run button to build and run the project. ## Running mobile app on Android Emulator First, make sure that the keyserver is running. If you haven’t already, run: ``` cd keyserver yarn dev ``` Next, make sure that the Metro bundler is running. If you haven’t already, open a new terminal and run: ``` cd native yarn dev ``` This command runs two processes (see previous section for details). Next, boot up an Android Emulator using Android Studio’s Virtual Device Manager. You should have a single Android Emulator (or plugged-in device) running at one time. Finally, use this command to build and run the Android app: ``` cd native yarn react-native run-android ``` ## Running mobile app on physical iOS devices There are a few things you’ll need to do before you can deploy the app to a physical iOS device. ### Xcode settings First, in Xcode, open the Comm workspace `native/ios/Comm.xcworkspace`. Make sure that you’re signed into Xcode with an Apple Developer account (either the Comm developer team’s or your own). You can see any accounts currently associated with Xcode by navigating to Xcode → Preferences → Accounts. Next, you’ll want to ensure that the Comm project is configured with a valid Team, Bundle Identifier, and Provisioning Profile. To access these settings, navigate to View → Navigators → Project, and select the “Comm” project in the left sidebar. Then, select “Comm” from the “TARGETS” list, and navigate to the “Signing & Capabilities” tab. You should verify the following settings: #### Using a Comm development team Apple Developer account - Team - Comm Technologies, Inc. - Bundle Identifier - app.comm - Provisioning Profile - Make sure that the Provisioning Profile exists #### Using a Personal Apple Developer account - Team - Set this to a valid “Team”, which can just be your personal Apple Developer account. “Comm Technologies, Inc.” may be chosen by default, but it’s not valid if you’re using a personal Apple Developer account - Bundle Identifier - Pick a unique [Bundle Identifier](https://developer.apple.com/documentation/xcode/preparing-your-app-for-distribution) - Provisioning Profile - Make sure that the Provisioning Profile exists ### Building and deploying the app When you plug your iOS device into your machine for the first time, you’ll be prompted to enter your device passcode to enable debugging and deployment. Click the “Register” button in the dialog that Xcode displays if your device needs to be added to your Provisioning Profile. Make sure to pull the latest changes and clean the build folder before trying to deploy a build to your device. In Xcode, run Product → Clean Build Folder. If you’re running a debug build, you’ll need to check that the Metro bundler is running. If you haven’t already, open a new terminal and run: ``` cd native yarn dev ``` This command runs the Metro bundler and `remotedev-server` for Redux (see the “Running mobile app on iOS Simulator” section for more details). You should finally be ready to build and deploy the app in Xcode! Select your physical device from ”run destinations” in the Workspace Toolbar. Then hit the Run button to build and run the project. If you’re connecting to a local keyserver instance, you’ll want to “Allow Comm to Access” the “Local Network” in your device Settings. This toggle can be found from Settings → Comm. Note that this setting is not enabled by default, and you may have to re-enable it on subsequent build deployments. ### Connecting to local keyserver If you want your custom build of the app to connect to your local instance of the Node.js server (the `keyserver` subdirectory of the repo), you’ll need to do some additional work. First, confirm that your computer and physical iOS device are on the same network. If you’re running a local keyserver instance, you’ll need to be able to reach it with your device. Local keyservers run on the local IP address at port 8043. To find your machine’s local IP address, navigate to System Preferences → Network, and select the hardware interface you’re currently using to connect to the internet (Wi-Fi, or potentially a Thunderbolt port for ethernet connections). Next, click “Advanced” and go to the “TCP/IP” tab. Your local IP address is listed as the “IPv4 Address”. Try visiting this IP address using a browser on your device. It should display an “It works!” message if your iOS device can reach your machine. Finally, we need to direct the mobile app to use your local keyserver instance. There are a few different ways to do this, depending on your situation: - As long as you’re deploying a debug build, this strategy should work for you. You can create a `network.json` file in `native/facts` that will override the default. ``` mkdir -p native/facts vim native/facts/network.json ``` Your `network.json` file should look like the following, where `w.x.y.z` is the local IP address you found earlier: ```json { "natDevHostname": "w.x.y.z" } ``` You’ll need to delete and reinstall the app for changes to `native/facts/network.json` to take effect, as the default production URL is persisted in Redux. - If you’re deploying a release build, the above strategy won’t work. Your best bet to override the server URL is to get to the secret “Developer tools” menu option in the app. 1. You may need to use a real production account for this, since the server address will default to the production server if this is the first build you’ve deployed to the target device. 2. Next, in order for the “Developer tools” menu option to appear, you’ll need to add your user ID to [the list of user IDs in `staff.json`](https://github.com/CommE2E/comm/blob/master/lib/facts/staff.json). A good way to figure out your user ID is to use the Chrome Redux debugger to inspect the `currentUserInfo` property when logged into the web app. 3. Finally, you should be able to navigate to Profile → Developer tools in the app and set the address of the local server. It should look something like this: ``` http://w.x.y.z/comm ``` Where `w.x.y.z` is the local IP address you found earlier. - Alternately, if you’re on a release build and option 2 above seems like too much of a hassle, you should be able to simply change the value of [`productionNodeServerURL` in the code](https://github.com/CommE2E/comm/blob/9e6a13f1569787b498a72c890b12ce0dd8323804/native/utils/url-utils.js#L12). Note that you’ll need to delete and reinstall the app for this change to take effect, as the default production URL is persisted in Redux. ## Running Node scripts To run one of the scripts in `keyserver/src/scripts`, you should start by making sure that the Node server is running. If you haven’t already, open a new terminal and run: ``` cd keyserver yarn dev ``` Then, from the `keyserver` directory, run `yarn script dist/scripts/name.js`, where `name.js` is the file containing the script. ## Creating a new user To create a new user, [run the keyserver](#running-keyserver) and the [mobile app on iOS Simulator](#running-mobile-app-on-ios-simulator), and then select “Sign Up” in the app. When you sign up, a new user will be created on your local MariaDB instance. You can then log in on any device connected to your local keyserver. ## Codegen We use a couple of tools that automatically generate code. There is always a source of truth – usually some file(s) with schemas. ### Codegen for JSI JSI is a framework in React Native that allows C++ and JS to communicate synchronously and directly. The codegen for JSI takes a Flow schema and generates C++ files that enable communication between JS and C++ in `react-native` apps. The script to generate this code is written in JavaScript and is included as a npm package so no additional software is needed to use it. The schema has to be defined in Flow as an interface, and that interface must inherit from react-native’s `TurboModule` interface. To run the JSI codegen, just run: ``` cd native yarn codegen-jsi ``` The input Flow schemas are located in `native/schema`. ### Codegen for gRPC In order to generate the codegen files for gRPC, you should run the following command: ``` cd native yarn codegen-grpc ``` # Debugging ## React Developer Tools - For web, you can access the React Developer Tools through the Chrome extension by opening the Chrome Developer Tools and selecting the “Components” or “Profiler” tabs. This should work in both our development environment and in production. - For iOS and Android, you can access the React Developer Tools through Flipper. First start a debug build of a React Native app. Next, just open up Flipper and you should be able to see an option for “React DevTools”. Flipper communicates with the app through the Metro bundler that gets started when you run `cd native && yarn dev`. ## Redux Developer Tools - For web, you can access the Redux Developer Tools through the Chrome extension by opening the Chrome Developer Tools and selecting the “Redux” tab. This should work in both our development environment and in production, although in production you won’t be able to see Redux actions from before you opened up the Redux dev tools. - For iOS and Android, you can access the Redux Developer Tools through the Chrome extension’s Remote DevTools functionality. First, to open the Remote DevTools, right click on any webpage, go into the “Redux DevTools” menu, and select “Open Remote DevTools”. Then hit “Settings”, select “Use custom (local) server”, and configure it to connect to `localhost` on port 8043. This will connect to the `remotedev-server` instance that you started when you ran `cd native && yarn dev`. ## Debugging JavaScript - For web, you can just use your browser of choice’s dev tools. - For iOS and Android, you should use Flipper. First start a debug build of a React Native app. Next, just open up Flipper and you should be able to see an option for “Hermes Debugger (RN)”. Flipper communicates with the app through the Metro bundler that gets started when you run `cd native && yarn dev`. # Working with Phabricator ## Creating a new diff The biggest difference between GitHub PRs and Phabricator diffs is that a PR corresponds to a branch, whereas a diff corresponds to a commit. When you have a commit ready and want to submit it for code review, just run `arc diff` from within the Comm Git repo. `arc diff` will look at the most recent commit in `git log` and create a new diff for it. ## Updating a diff With GitHub PRs, updates are usually performed by adding on more commits. In contrast, in Phabricator a diff is updated by simply amending the existing commit and running `arc diff` again. When you run `arc diff`, it looks for a `Differential Revision: ` line in the commit text of the most recent commit. If Arcanist finds that line, it will assume you want to update the existing diff rather than create a new one. Other Arcanist commands such as `arc amend` (which amends commit text to match a diff on Phabricator) also look for the `Differential Revision: ` line. ## Working with a stack One of the advantages of Phabricator’s approach is that larger, multi-part changes can be split up into smaller pieces for review. These multi-part changes are usually referred to as a “stack” of diffs. When creating a diff that depends on another, you should make sure to create a dependency relationship between those two diffs, so that your reviewers can see the stack on Phabricator. The easiest way to do that is to include `Depends on D123` in the commit text of the child commit, but the dependency relationship can also be specified using the Phabricator web UI. You’ll find that mastering Git’s interactive rebase feature (`git rebase -i`) will help you a lot when working with stacks. Interactive rebases make it easy to “diff up” multiple commits at once, or to amend a specific commit in the middle of a stack in response to a review. ## Committing a diff After your diff has been accepted, you should be able to land it. To land a diff just run `arc land` from within the repository. If you have a stack of unlanded commits in your Git branch, `arc land` will attempt to land all of those diffs. If some of the diffs in your stack haven’t been accepted yet, you’ll need to create a new, separate branch that contains just the commits you want to land before running `arc land`. Note that you need commit rights to the repository in order to run `arc land`. If you don’t have commit rights, reach out to @ashoat for assistance. ## Final notes When developing, I usually just pop up three terminal windows, one for `yarn dev` in each of keyserver, web, and native. Note that it’s currently only possible to create a user account using the iOS or Android apps. The website supports logging in, but does not support account creation. Good luck, and let @ashoat know if you have any questions! diff --git a/native/android/app/CMakeLists.txt b/native/android/app/CMakeLists.txt index f5b750dd6..b7e4dcf57 100644 --- a/native/android/app/CMakeLists.txt +++ b/native/android/app/CMakeLists.txt @@ -1,229 +1,241 @@ # For more information about using CMake with Android Studio, read the # documentation: https://d.android.com/studio/projects/add-native-code.html project(comm CXX C) -set (CMAKE_CXX_STANDARD 14) +set(CMAKE_CXX_STANDARD 14) # C0103 is a naming convention, but the variable names which need to be set # are determined by the upstream project # cmake-lint: disable=C0103 # Disable line length as some paths are hard to reduce without becoming cryptic # cmake-lint: disable=C0301 # Sets the minimum version of CMake required to build the native library. -cmake_minimum_required(VERSION 3.4.1) +cmake_minimum_required(VERSION 3.18) # Creates and names a library, sets it as either STATIC # or SHARED, and provides the relative paths to its source code. # You can define multiple libraries, and CMake builds them for you. # Gradle automatically packages shared libraries with your APK. - set(PACKAGE_NAME "comm_jni_module") find_package(fbjni REQUIRED CONFIG) set(BUILD_TESTING OFF) set(HAVE_SYMBOLIZE OFF) set(WITH_GTEST OFF CACHE BOOL "Use googletest" FORCE) set(WITH_GFLAGS OFF CACHE BOOL "Use gflags" FORCE) # General set(_third_party_dir ${CMAKE_CURRENT_SOURCE_DIR}/build/third-party-ndk) set(_android_build_dir build/${CMAKE_ANDROID_ARCH_ABI}) # Protobuf set(protobuf_BUILD_TESTS OFF) # gRPC building parameters set(gRPC_BUILD_CSHARP_EXT OFF) set(gRPC_SSL_PROVIDER "package" CACHE STRING "SSL library provider") + +# gRPC client +include(FetchContent) + +FetchContent_Declare( + Corrosion + GIT_REPOSITORY https://github.com/corrosion-rs/corrosion.git + GIT_TAG v0.2.1 +) + +FetchContent_MakeAvailable(Corrosion) + # Disable unused plugins set(gRPC_BUILD_GRPC_PHP_PLUGIN OFF) set(gRPC_BUILD_GRPC_RUBY_PLUGIN OFF) set(gRPC_BUILD_GRPC_PYTHON_PLUGIN OFF) set(gRPC_BUILD_GRPC_CSHARP_PLUGIN OFF) + # We're updating parameters below for Cmake's find_OpenSSL() function set(OPENSSL_ROOT_DIR "${_third_party_dir}/openssl/openssl-${OPENSSL_VERSION}/${_android_build_dir}" ) list(APPEND CMAKE_FIND_ROOT_PATH "${OPENSSL_ROOT_DIR}") add_subdirectory(${_third_party_dir}/grpc/grpc-${GRPC_VERSION}/ ${CMAKE_CURRENT_BINARY_DIR}/grpc/ EXCLUDE_FROM_ALL ) add_subdirectory(${_third_party_dir}/glog/glog-${GLOG_VERSION}/) add_subdirectory(../../node_modules/olm ./build) set(_node_modules_dir ${CMAKE_CURRENT_SOURCE_DIR}/../../node_modules) set(_react_native_dir ${_node_modules_dir}/react-native) include_directories( ${_react_native_dir}/React ${_react_native_dir}/React/Base ${_react_native_dir}/ReactCommon ${_react_native_dir}/ReactCommon/jsi ${_react_native_dir}/ReactCommon/callinvoker ${_react_native_dir}/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/jni/ReactCommon # OpenSSL ${_third_party_dir}/openssl/openssl-${OPENSSL_VERSION}/build/${CMAKE_ANDROID_ARCH_ABI}/include # SQLCipher amalgamation ${_node_modules_dir}/@commapp/sqlcipher-amalgamation/src # SQLite ORM ../../cpp/lib/sqlite_orm # symlinked React Native headers ../headers # external libs ${_third_party_dir}/folly ${_third_party_dir}/boost/boost ${_third_party_dir}/double-conversion # comm android specific code ./src/cpp # comm native mutual code ../../cpp/CommonCpp/ ../../cpp/CommonCpp/NativeModules ../../cpp/CommonCpp/NativeModules/InternalModules ../../cpp/CommonCpp/NativeModules/PersistentStorageUtilities ../../cpp/CommonCpp/NativeModules/PersistentStorageUtilities/ThreadOperationsUtilities ../../cpp/CommonCpp/NativeModules/PersistentStorageUtilities/MessageOperationsUtilities ../../cpp/CommonCpp/NativeModules/PersistentStorageUtilities/MessageOperationsUtilities/MessageSpecs ../../cpp/CommonCpp/DatabaseManagers ../../cpp/CommonCpp/Tools ../../cpp/CommonCpp/grpc/_generated ../../cpp/CommonCpp/grpc ) # search for all cpp files in this directory file(GLOB SQLCIPHER "${_node_modules_dir}/@commapp/sqlcipher-amalgamation/src/*.c" ) file(GLOB_RECURSE COMMON_NATIVE_CODE "../../cpp/CommonCpp/**/*.cpp") file(GLOB ANDROID_NATIVE_CODE "./src/cpp/*.cpp") file(GLOB DOUBLE_CONVERSION_SOURCES "${_third_party_dir}/double-conversion/double-conversion/*.cc" ) file(GLOB GRPC_CODE "../../cpp/CommonCpp/grpc/_generated/*.cc") add_library( # Sets the name of the library. ${PACKAGE_NAME} # Sets the library as a shared library. SHARED # Provides a relative path to your source file(s). ${_react_native_dir}/ReactCommon/jsi/jsi/jsi.cpp ${_react_native_dir}/ReactAndroid/src/main/java/com/facebook/react/turbomodule/core/jni/ReactCommon/CallInvokerHolder.cpp ${_react_native_dir}/ReactCommon/react/nativemodule/core/ReactCommon/TurboModule.cpp ${_react_native_dir}/ReactCommon/react/nativemodule/core/ReactCommon/LongLivedObject.cpp ${_react_native_dir}/ReactCommon/react/nativemodule/core/ReactCommon/TurboModuleUtils.cpp # SQLCipher ${SQLCIPHER} # folly ${_third_party_dir}/folly/folly/detail/Futex.cpp ${_third_party_dir}/folly/folly/synchronization/ParkingLot.cpp ${_third_party_dir}/folly/folly/lang/SafeAssert.cpp ${_third_party_dir}/folly/folly/FileUtil.cpp ${_third_party_dir}/folly/folly/Subprocess.cpp ${_third_party_dir}/folly/folly/File.cpp ${_third_party_dir}/folly/folly/Format.cpp ${_third_party_dir}/folly/folly/Conv.cpp ${_third_party_dir}/folly/folly/io/IOBuf.cpp ${_third_party_dir}/folly/folly/memory/detail/MallocImpl.cpp ${_third_party_dir}/folly/folly/ScopeGuard.cpp ${_third_party_dir}/folly/folly/hash/SpookyHashV2.cpp ${_third_party_dir}/folly/folly/io/IOBufQueue.cpp ${_third_party_dir}/folly/folly/lang/Assume.cpp ${_third_party_dir}/folly/folly/String.cpp ${_third_party_dir}/folly/folly/portability/SysUio.cpp ${_third_party_dir}/folly/folly/net/NetOps.cpp ${_third_party_dir}/folly/folly/dynamic.cpp ${_third_party_dir}/folly/folly/json.cpp ${_third_party_dir}/folly/folly/json_pointer.cpp ${_third_party_dir}/folly/folly/Unicode.cpp # double-conversion ${DOUBLE_CONVERSION_SOURCES} ${GRPC_CODE} # comm code ${ANDROID_NATIVE_CODE} ${COMMON_NATIVE_CODE} ) add_definitions( - ## Folly + # Folly -DFOLLY_NO_CONFIG=1 -DFOLLY_HAVE_CLOCK_GETTIME=1 -DFOLLY_HAVE_MEMRCHR=1 -DFOLLY_USE_LIBCPP=1 -DFOLLY_MOBILE=1 - ## SQLCipher + # SQLCipher -DSQLITE_THREADSAFE=0 -DSQLITE_HAS_CODEC -DSQLITE_TEMP_STORE=2 -DSQLCIPHER_CRYPTO_OPENSSL ) find_library(log-lib log) add_library( # OpenSSL Crypto lib openssl-crypto STATIC IMPORTED ) set_target_properties( # OpenSSL Crypto lib openssl-crypto PROPERTIES IMPORTED_LOCATION "${_third_party_dir}/openssl/openssl-${OPENSSL_VERSION}/build/${CMAKE_ANDROID_ARCH_ABI}/lib/libcrypto.a" ) add_library( # OpenSSL SSL lib openssl-ssl STATIC IMPORTED ) set_target_properties( # OpenSSL SSL lib openssl-ssl PROPERTIES IMPORTED_LOCATION "${_third_party_dir}/openssl/openssl-${OPENSSL_VERSION}/build/${CMAKE_ANDROID_ARCH_ABI}/lib/libssl.a" ) target_link_libraries( ${PACKAGE_NAME} fbjni::fbjni android ${log-lib} glog::glog olm openssl-crypto openssl-ssl grpc++ libprotobuf ) # add a dummy library which is required by CallInvokerHolderImpl.java add_library( turbomodulejsijni # Sets the library as a shared library. SHARED # Provides a relative path to your source file(s). ./src/cpp/dummy.cpp ) diff --git a/native/android/app/build.gradle b/native/android/app/build.gradle index cb4d53317..312471ba9 100644 --- a/native/android/app/build.gradle +++ b/native/android/app/build.gradle @@ -1,608 +1,609 @@ apply plugin: "com.android.application" import com.android.build.OutputFile import de.undercouch.gradle.tasks.download.Download import app.comm.gradle.tasks.GitModules /** * The react.gradle file registers a task for each build variant (e.g. bundleDebugJsAndAssets * and bundleReleaseJsAndAssets). * These basically call `react-native bundle` with the correct arguments during the Android build * cycle. By default, bundleDebugJsAndAssets is skipped, as in debug/dev mode we prefer to load the * bundle directly from the development server. Below you can see all the possible configurations * and their defaults. If you decide to add a configuration block, make sure to add it before the * `apply from: "../../node_modules/react-native/react.gradle"` line. * * project.ext.react = [ * // the name of the generated asset file containing your JS bundle * bundleAssetName: "index.android.bundle", * * // the entry file for bundle generation. If none specified and * // "index.android.js" exists, it will be used. Otherwise "index.js" is * // default. Can be overridden with ENTRY_FILE environment variable. * entryFile: "index.android.js", * * // https://reactnative.dev/docs/performance#enable-the-ram-format * bundleCommand: "ram-bundle", * * // whether to bundle JS and assets in debug mode * bundleInDebug: false, * * // whether to bundle JS and assets in release mode * bundleInRelease: true, * * // whether to bundle JS and assets in another build variant (if configured). * // See http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Build-Variants * // The configuration property can be in the following formats * // 'bundleIn${productFlavor}${buildType}' * // 'bundleIn${buildType}' * // bundleInFreeDebug: true, * // bundleInPaidRelease: true, * // bundleInBeta: true, * * // whether to disable dev mode in custom build variants (by default only disabled in release) * // for example: to disable dev mode in the staging build type (if configured) * devDisabledInStaging: true, * // The configuration property can be in the following formats * // 'devDisabledIn${productFlavor}${buildType}' * // 'devDisabledIn${buildType}' * * // the root of your project, i.e. where "package.json" lives * root: "../../", * * // where to put the JS bundle asset in debug mode * jsBundleDirDebug: "$buildDir/intermediates/assets/debug", * * // where to put the JS bundle asset in release mode * jsBundleDirRelease: "$buildDir/intermediates/assets/release", * * // where to put drawable resources / React Native assets, e.g. the ones you use via * // require('./image.png')), in debug mode * resourcesDirDebug: "$buildDir/intermediates/res/merged/debug", * * // where to put drawable resources / React Native assets, e.g. the ones you use via * // require('./image.png')), in release mode * resourcesDirRelease: "$buildDir/intermediates/res/merged/release", * * // by default the gradle tasks are skipped if none of the JS files or assets change; this means * // that we don't look at files in android/ or ios/ to determine whether the tasks are up to * // date; if you have any other folders that you want to ignore for performance reasons (gradle * // indexes the entire tree), add them here. Alternatively, if you have JS files in android/ * // for example, you might want to remove it from here. * inputExcludes: ["android/**", "ios/**"], * * // override which node gets called and with what additional arguments * nodeExecutableAndArgs: ["node"], * * // supply additional arguments to the packager * extraPackagerArgs: [] * ] */ project.ext.react = [ enableHermes: true, // clean and rebuild if changing hermesCommand: new File(["node", "--print", "require.resolve('hermes-engine/package.json')"].execute(null, rootDir).text.trim()).getParentFile().getAbsolutePath() + "/%OS-BIN%/hermesc", cliPath: new File(["node", "--print", "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim()).getParentFile().getAbsolutePath() + "/cli.js", composeSourceMapsPath: new File(["node", "--print", "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim()).getParentFile().getAbsolutePath() + "/scripts/compose-source-maps.js", ] apply from: new File(["node", "--print", "require.resolve('react-native/package.json')"].execute(null, rootDir).text.trim(), "../react.gradle") /** * Set this to true to create two separate APKs instead of one: * - An APK that only works on ARM devices * - An APK that only works on x86 devices * The advantage is the size of the APK is reduced by about 4MB. * Upload all the APKs to the Play Store and people will download * the correct one based on the CPU architecture of their device. */ def enableSeparateBuildPerCPUArchitecture = false /** * Run Proguard to shrink the Java bytecode in release builds. */ def enableProguardInReleaseBuilds = false /** * The preferred build flavor of JavaScriptCore. * * For example, to use the international variant, you can use: * `def jscFlavor = 'org.webkit:android-jsc-intl:+'` * * The international variant includes ICU i18n library and necessary data * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that * give correct results when using with locales other than en-US. Note that * this variant is about 6MiB larger per architecture than default. */ def jscFlavor = 'org.webkit:android-jsc:+' /** * Whether to enable the Hermes VM. * * This should be set on project.ext.react and that value will be read here. If it is not set * on project.ext.react, JavaScript will not be compiled to Hermes Bytecode * and the benefits of using Hermes will therefore be sharply reduced. */ def enableHermes = project.ext.react.get("enableHermes", false) /** * Architectures to build native code for in debug. */ def nativeArchitectures = project.getProperties().get("reactNativeDebugArchitectures") def customDownloadsDir = System.getenv("REACT_NATIVE_DOWNLOADS_DIR") def dependenciesPath = System.getenv("REACT_NATIVE_DEPENDENCIES") def downloadsDir = customDownloadsDir ? new File(customDownloadsDir) : new File("$buildDir/downloads") def thirdPartyNdkDir = new File("$buildDir/third-party-ndk") // The Boost library is a very large download (>100MB). // If Boost is already present on your system, define the REACT_NATIVE_BOOST_PATH env variable // and the build will use that. def boostPath = dependenciesPath ?: System.getenv("REACT_NATIVE_BOOST_PATH") task createNativeDepsDirectories { downloadsDir.mkdirs() thirdPartyNdkDir.mkdirs() } // GRPC task downloadGrpc(dependsOn: createNativeDepsDirectories, type: Download) { src("https://github.com/grpc/grpc/archive/refs/tags/v${GRPC_VERSION}.tar.gz") onlyIfNewer(true) overwrite(false) dest(new File(downloadsDir, "grpc-${GRPC_VERSION}.tar.gz")) } task copyGrpc(dependsOn: dependenciesPath ? [] : [downloadGrpc], type: Copy) { from(tarTree(downloadGrpc.dest)) includeEmptyDirs = true into("$thirdPartyNdkDir/grpc") } def grpcDir = "${thirdPartyNdkDir}/grpc/grpc-${GRPC_VERSION}" task prepareGrpc(dependsOn: copyGrpc, type: GitModules) { gitmodulesFile(new File("${grpcDir}/.gitmodules")) outputDir(new File("${grpcDir}")) // Skip the boringSSL module as we use OpenSSL skipModules([ "third_party/boringssl-with-bazel" ]) // Needs to override/provide some module branches // for the gRPC version compatibility moduleBranch([ "third_party/cares/cares": "cares-1_13_0", "third_party/abseil-cpp": "lts_2021_03_24", "third_party/protobuf": "v3.15.8" ]) // We need to move 'zconf.h' because it modifies on the compilation stage // and makes the 'outputDir' not as UP-TO-DATE runAfter([ "mv ${grpcDir}/third_party/zlib/zconf.h ${grpcDir}/third_party/zlib/zconf.h.included" ]) } // FOLLY task downloadFolly(dependsOn: createNativeDepsDirectories, type: Download) { src("https://github.com/facebook/folly/archive/v${FOLLY_VERSION}.tar.gz") onlyIfNewer(true) overwrite(false) dest(new File(downloadsDir, "folly-${FOLLY_VERSION}.tar.gz")) } def follyFindWrapNoInt = 'return int\\(wrapNoInt\\(open, name, flags, mode\\)\\);' def follyReplaceWrapNoInt = ''' ssize_t r; do { r = open(name, flags, mode); } while (r == -1 && errno == EINTR); return r; ''' def follyFindTableSize = 'for \\(int fd = getdtablesize\\(\\) - 1' def follyReplaceTableSize = 'for (int fd = sysconf(_SC_OPEN_MAX) - 1' task prepareFolly(dependsOn: dependenciesPath ? [] : [downloadFolly], type: Copy) { inputs.properties([ 'findWrapNoInt': follyFindWrapNoInt, 'replaceWrapNoInt': follyReplaceWrapNoInt, 'findTableSize': follyFindTableSize, 'replaceTableSize': follyReplaceTableSize, ]) from(dependenciesPath ?: tarTree(downloadFolly.dest)) include("folly-${FOLLY_VERSION}/folly/**/*") eachFile { fname -> fname.path = (fname.path - "folly-${FOLLY_VERSION}/") } // Fixes problem with Folly failing to build on certain systems. See // https://github.com/facebook/react-native/issues/28298 filter { line -> line.replaceAll(follyFindWrapNoInt, follyReplaceWrapNoInt) } // fix undeclared identifier 'getdtablesize' in Subprocess.cpp // https://stackoverflow.com/questions/8225186/portable-equivalent-of-open-max/8225235#8225235 filter { line -> line.replaceAll(follyFindTableSize, follyReplaceTableSize) } includeEmptyDirs = false into("$thirdPartyNdkDir/folly") } // GLOG task downloadGlog(dependsOn: createNativeDepsDirectories, type: Download) { src("https://github.com/google/glog/archive/v${GLOG_VERSION}.tar.gz") onlyIfNewer(true) overwrite(false) dest(new File(downloadsDir, "glog-${GLOG_VERSION}.tar.gz")) } task prepareGlog(dependsOn: dependenciesPath ? [] : [downloadGlog], type: Copy) { from(dependenciesPath ?: tarTree(downloadGlog.dest)) include("glog-${GLOG_VERSION}/**/*") includeEmptyDirs = false into("$thirdPartyNdkDir/glog") } // BOOST task downloadBoost(dependsOn: createNativeDepsDirectories, type: Download) { src("https://github.com/react-native-community/boost-for-react-native/releases/download/v${BOOST_VERSION.replace("_", ".")}-0/boost_${BOOST_VERSION}.tar.gz") onlyIfNewer(true) overwrite(false) dest(new File(downloadsDir, "boost_${BOOST_VERSION}.tar.gz")) } task prepareBoost(dependsOn: boostPath ? [] : [downloadBoost]) { inputs.properties([ 'boost.version': BOOST_VERSION ]) outputs.dir("$thirdPartyNdkDir/boost/boost/") .withPropertyName('boost.output') doFirst { copy { from(boostPath ?: tarTree(resources.gzip(downloadBoost.dest))) include("boost_${BOOST_VERSION}/boost/**/*.hpp", "boost/boost/**/*.hpp") include("boost_${BOOST_VERSION}/boost/**/*.ipp", "boost/boost/**/*.ipp") include("boost_${BOOST_VERSION}/boost/**/*.h", "boost/boost/**/*.h") includeEmptyDirs = false into("$thirdPartyNdkDir/boost") } } doLast { file("$thirdPartyNdkDir/boost/boost_${BOOST_VERSION}").renameTo("$thirdPartyNdkDir/boost/boost") } } // DOUBLE-CONVERSION task downloadDoubleConversion(dependsOn: createNativeDepsDirectories, type: Download) { src("https://github.com/google/double-conversion/archive/v${DOUBLE_CONVERSION_VERSION}.tar.gz") onlyIfNewer(true) overwrite(false) dest(new File(downloadsDir, "double-conversion-${DOUBLE_CONVERSION_VERSION}.tar.gz")) } task prepareDoubleConversion(dependsOn: dependenciesPath ? [] : [downloadDoubleConversion], type: Copy) { from(dependenciesPath ?: tarTree(downloadDoubleConversion.dest)) from("src/main/jni/third-party/double-conversion/Android.mk") include("double-conversion-${DOUBLE_CONVERSION_VERSION}/src/**/*", "Android.mk") filesMatching("*/src/**/*", { fname -> fname.path = "double-conversion/${fname.name}" }) includeEmptyDirs = false into("$thirdPartyNdkDir/double-conversion") } // OPENSSL def hostSystem = System.getProperty('os.name').toLowerCase(Locale.ROOT) def hostTag = hostSystem.contains('mac') ? 'darwin-x86_64' : 'linux-x86_64' task downloadOpenSSL(dependsOn: createNativeDepsDirectories, type: Download) { src("https://www.openssl.org/source/openssl-${OPENSSL_VERSION}.tar.gz") onlyIfNewer(true) overwrite(false) dest(new File(downloadsDir, "openssl-${OPENSSL_VERSION}.tar.gz")) } task prepareOpenSSL( dependsOn: dependenciesPath ? [] : [downloadOpenSSL], type: Copy ) { from(dependenciesPath ?: tarTree(downloadOpenSSL.dest)) include("openssl-${OPENSSL_VERSION}/**/*") includeEmptyDirs = false into("${thirdPartyNdkDir}/openssl") } task prebuildOpenSSL(dependsOn: dependenciesPath ? [] : [prepareOpenSSL]) { inputs.properties([ 'openssl.version': OPENSSL_VERSION, 'openssl.abis': getBuildTypeABIs(nativeArchitectures) ]) outputs.dir("${thirdPartyNdkDir}/openssl/openssl-${OPENSSL_VERSION}/build/") .withPropertyName('openssl.output') doFirst { getBuildTypeABIs(nativeArchitectures).each { buildABI -> logger.info("Building OpenSSL library for the ${buildABI}") exec { commandLine './bash/build_openssl.sh', // OPENSSL_SUBMODULE_PATH "${thirdPartyNdkDir}/openssl/openssl-${OPENSSL_VERSION}/", // HOST_TAG hostTag, // ANDROID_ARCH_ABI "${buildABI}", // MIN_SDK_VERSION rootProject.ext.minSdkVersion, // ANDROID_NDK_HOME android.ndkDirectory.absolutePath, // PARALLEL_THREADS Runtime.getRuntime().availableProcessors() } } } } // EXTERNAL LIBS task prepareExternalLibs { dependsOn prepareGrpc dependsOn prepareFolly dependsOn prepareGlog dependsOn prepareBoost dependsOn prepareDoubleConversion dependsOn prebuildOpenSSL } // Removes the '.cxx' directory to prevent running // ninja clean when the 'clean' command is executed task removeCXX(type: Exec) { commandLine 'rm', '-rf', '.cxx' } // Bind preBuild dependencies only if not 'clean' running if (!isCleanRunning()) { afterEvaluate { preBuild.dependsOn(prepareExternalLibs) } } // Run removing CXX task before the clean execution beforeEvaluate { clean.dependsOn(removeCXX) } // Detects are we running the 'clean' commands def isCleanRunning() { gradle.startParameter.taskRequests.any { !it.args.isEmpty() && it.args.first().startsWith('clean') } } // Release keystore via macOS Keychain Access def getPassword(String keyLabel) { if (System.getenv('ANDROID_SIGNING_PASSWORD')) { return System.getenv('ANDROID_SIGNING_PASSWORD') } def stdout = new ByteArrayOutputStream() exec { commandLine 'security', 'find-generic-password', '-wl', keyLabel, '-a', System.properties['user.name'] standardOutput = stdout ignoreExitValue true } return stdout.toString().strip() } // Returns all ABIs architectures for the 'bundleRelease' // or only from 'adb devices' if running debug release. def getBuildTypeABIs(nativeArchitectures) { if (System.getenv("BUILDKITE") == "true") { return ["arm64-v8a"] } def isBundleRelease = gradle.startParameter.taskRequests.any { !it.args.isEmpty() && it.args.first().contains("bundleRelease") } if (isBundleRelease) { // All of the supported ABIs // https://developer.android.com/ndk/guides/abis.html#sa final allAbis = ["armeabi-v7a", "x86", "arm64-v8a", "x86_64"] logger.info("Using all architectures to build: ${allAbis}") return allAbis } if (nativeArchitectures) { return nativeArchitectures.split(',') } // Get current 'adb devices' architectures def commandOutput = new ByteArrayOutputStream() exec { commandLine "./bash/detect_abis.sh" standardOutput = commandOutput } final detectedAbis = commandOutput.toString("UTF-8").trim().tokenize() logger.info("Detected architectures to build: ${detectedAbis}") return detectedAbis } android { buildFeatures { prefab true } configurations { all*.exclude module: 'fbjni-java-only' } dependencies { implementation 'com.facebook.fbjni:fbjni:0.1.0' } ndkVersion rootProject.ext.ndkVersion compileSdkVersion rootProject.ext.compileSdkVersion defaultConfig { applicationId 'app.comm.android' minSdkVersion rootProject.ext.minSdkVersion targetSdkVersion rootProject.ext.targetSdkVersion versionCode 141 versionName '1.0.141' missingDimensionStrategy 'react-native-camera', 'general' multiDexEnabled true } splits { abi { reset() enable enableSeparateBuildPerCPUArchitecture universalApk false // If true, also generate a universal APK include "armeabi-v7a", "x86", "arm64-v8a", "x86_64" } } signingConfigs { debug { storeFile file('debug.keystore') storePassword 'android' keyAlias 'androiddebugkey' keyPassword 'android' } release { if (project.hasProperty('COMM_UPLOAD_STORE_FILE')) { def password = getPassword('CommAndroidKeyPassword') storeFile file(COMM_UPLOAD_STORE_FILE) storePassword password keyAlias COMM_UPLOAD_KEY_ALIAS keyPassword password } } } buildTypes { final buildABIs = getBuildTypeABIs(nativeArchitectures) release { if (project.hasProperty('COMM_UPLOAD_STORE_FILE')) { signingConfig signingConfigs.release } else { signingConfig signingConfigs.debug } minifyEnabled enableProguardInReleaseBuilds proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro" ndk { abiFilters = [] abiFilters.addAll(buildABIs) } } debug { signingConfig signingConfigs.debug ndk { abiFilters = [] abiFilters.addAll(buildABIs) } } } packagingOptions { pickFirst "**/libc++_shared.so" pickFirst "**/libfbjni.so" } defaultConfig { externalNativeBuild { cmake { arguments "-DANDROID_STL=c++_shared", "-DGLOG_VERSION=" + GLOG_VERSION, "-DOPENSSL_VERSION=" + OPENSSL_VERSION, "-DGRPC_VERSION=" + GRPC_VERSION targets "comm_jni_module", "turbomodulejsijni" } } } externalNativeBuild { cmake { path "CMakeLists.txt" + version "3.18.1" } } // applicationVariants are e.g. debug, release applicationVariants.all { variant -> variant.outputs.each { output -> // For each separate APK per architecture, set a unique version code as described here: // https://developer.android.com/studio/build/configure-apk-splits.html // Example: versionCode 1 will generate 1001 for armeabi-v7a, 1002 for x86, etc. def versionCodes = ["armeabi-v7a": 1, "x86": 2, "arm64-v8a": 3, "x86_64": 4] def abi = output.getFilter(OutputFile.ABI) if (abi != null) { // null for the universal-debug, universal-release variants output.versionCodeOverride = defaultConfig.versionCode * 1000 + versionCodes.get(abi) } } } } dependencies { implementation fileTree(dir: "libs", include: ["*.jar"]) implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.4.21" //noinspection GradleDynamicVersion implementation("com.facebook.react:react-native:+") def isGifEnabled = (findProperty('expo.gif.enabled') ?: "") == "true"; def isWebpEnabled = (findProperty('expo.webp.enabled') ?: "") == "true"; def isWebpAnimatedEnabled = (findProperty('expo.webp.animated') ?: "") == "true"; // If your app supports Android versions before Ice Cream Sandwich (API level 14) // All fresco packages should use the same version if (isGifEnabled || isWebpEnabled) { implementation 'com.facebook.fresco:fresco:2.0.0' implementation 'com.facebook.fresco:imagepipeline-okhttp3:2.0.0' } if (isGifEnabled) { // For animated gif support implementation 'com.facebook.fresco:animated-gif:2.0.0' } if (isWebpEnabled) { // For webp support implementation 'com.facebook.fresco:webpsupport:2.0.0' if (isWebpAnimatedEnabled) { // Animated webp support implementation 'com.facebook.fresco:animated-webp:2.0.0' } } implementation "androidx.swiperefreshlayout:swiperefreshlayout:1.0.0" debugImplementation("com.facebook.flipper:flipper:${FLIPPER_VERSION}") { exclude group:'com.facebook.fbjni' } debugImplementation("com.facebook.flipper:flipper-network-plugin:${FLIPPER_VERSION}") { exclude group:'com.facebook.flipper' } debugImplementation("com.facebook.flipper:flipper-fresco-plugin:${FLIPPER_VERSION}") { exclude group:'com.facebook.flipper' exclude group:'com.facebook.fresco', module:'stetho' } implementation "com.google.android.gms:play-services-base:16.1.0" implementation "com.google.firebase:firebase-core:16.0.9" implementation "com.google.firebase:firebase-messaging:18.0.0" implementation "me.leolin:ShortcutBadger:1.1.21@aar" implementation project(':reactnativekeyboardinput') implementation "androidx.multidex:multidex:2.0.1" implementation "androidx.lifecycle:lifecycle-runtime:2.2.0" implementation "androidx.lifecycle:lifecycle-process:2.2.0" implementation 'com.facebook.fresco:fresco:2.2.0' implementation 'com.facebook.fresco:animated-gif:2.2.0' implementation 'com.facebook.fresco:animated-webp:2.2.0' implementation 'com.facebook.fresco:webpsupport:2.2.0' implementation 'org.conscrypt:conscrypt-android:2.0.0' if (enableHermes) { debugImplementation files(new File(["node", "--print", "require.resolve('hermes-engine/package.json')"].execute(null, rootDir).text.trim(), "../android/hermes-debug.aar")) releaseImplementation files(new File(["node", "--print", "require.resolve('hermes-engine/package.json')"].execute(null, rootDir).text.trim(), "../android/hermes-release.aar")) } else { implementation jscFlavor } } // Run this once to be able to run the application with BUCK // puts all compile dependencies into folder libs for BUCK to use task copyDownloadableDepsToLibs(type: Copy) { from configurations.implementation into 'libs' } apply from: new File(["node", "--print", "require.resolve('@react-native-community/cli-platform-android/package.json')"].execute(null, rootDir).text.trim(), "../native_modules.gradle"); applyNativeModulesAppBuildGradle(project) apply plugin: 'com.google.gms.google-services'