# FlexisipのFirebaseを利用した拡張機能（Push Notification, FCM認証)

**URL:** https://forum.ficusonline.com/t/topic/500
**Category:** Server
**Created:** [2023 年 11 月 16 日午後 10:18 UTC](https://forum.ficusonline.com/t/topic/500 "2023-11-16T22:18:27Z")
**Posts on this page:** 9
**Page:** 1

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2023 年 11 月 16 日午後 10:18 UTC](https://forum.ficusonline.com/t/topic/500/1 "2023-11-16T22:18:27Z")

</div>

## Push Notification

相手方呼び出し時、相手方の端末がスリープモード等により呼出しリクエストに応答しないケースで、Firebaseからのプッシュ通知を利用して接続を確立。Flexisipサーバ側の設定が必要です。

* * *

**注）** 従来のFCM APIが2004年7月に新APIへと全面移行したため、この変更に伴い、FlexisipのDockerイメージもアップデートする必要があります。

> **[Firebase legacy API to HTTP v1 migration guide - XWiki](https://wiki.linphone.org/xwiki/wiki/public/view/Flexisip/Configuration/Push%20notifications/Firebase%20legacy%20API%20to%20Firebase%20v1%20migration%20guide/)**
>
> Firebase legacy API to HTTP v1 migration guide

* * *

> **[Push notifications - XWiki](https://wiki.linphone.org/xwiki/wiki/public/view/Flexisip/D.%20Specifications/Push%20notifications/)**
>
> Push notifications

**Push notification configration**

> **[Push notifications - XWiki](https://wiki.linphone.org/xwiki/wiki/public/view/Flexisip/Configuration/Push%20notifications/)**
>
> Push notifications

**Calls do not ring on Linphone client when in background**  
[https://www.3cx.com/community/threads/calls-do-not-ring-on-linphone-client-when-in-background.115782/](https://www.3cx.com/community/threads/calls-do-not-ring-on-linphone-client-when-in-background.115782/)

* * *

## Push Gateway

> **[Push Gateway - XWiki](https://wiki.linphone.org/xwiki/wiki/public/view/Flexisip/HOWTOs/Push%20Gateway/)**
>
> Push Gateway

 ![600px-Pushgateway_incoming_call](https://forum.ficusonline.com/uploads/default/original/2X/d/d312d76a6ef1fe045cc983b012c7376eaedae37b.png)

**ContactRouterInserter**

Flexisipが **SBC** ゲートウェイとして使用される場合、このモジュールは登録情報の経路を調整し、正しい送り先に着信呼び出しをルーティングできるようにします。

**SBC (Session Border Controller)** （セッション・ボーダー・コントローラ）の略で、通信ネットワークにおいてセッション（通話やデータ転送などの通信セッション）の境界で制御を行う装置やソフトウェア

> **[ContactRouteInserter - XWiki](https://wiki.linphone.org/xwiki/wiki/public/view/Flexisip/A.%20Configuration%20Reference%20Guide/master/module/ContactRouteInserter)**
>
> ContactRouteInserter

---

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2023 年 11 月 21 日午前 8:21 UTC](https://forum.ficusonline.com/t/topic/500/2 "2023-11-21T08:21:52Z")

</div>

アカウントマネージャのAPIでFirebaseによるプッシュ通知を利用する場合、アカウントマネージャを稼働しているphp-fpmコンテナ経由でflexisipサーバコンテナへコマンド送信する必要があるため、php-fpmコンテナにSSH接続などによる機能追加・PHPコードの変更などが必要になります。LaravelのフレームワークにSSHライブラリを追加することで対応できますがデバックなどに時間を要します。

このため、flexisipイメージにphp-fpmの機能を追加した新たなイメージを作成し、このイメージからflexisipサーバとphp-fpmを同時に立ち上げることにします。

> #### PHPとその機能拡張、Composerのインストールを追加

`flex-from-ubuntu-apt-repo`

```yaml
FROM ubuntu:22.04
MAINTAINER Takanobu Fuse <ficusonline@gmail.com>

ARG DEBIAN_FRONTEND=noninteractive

# Prepare dependencies
RUN apt-get update
RUN apt-get install -y nano xsdcxx gdb libmariadb3 snmp-mibs-downloader snmp snmpd iproute2 iptables wget gnupg2 \ 
    php8.1-fpm libpng-dev libfreetype-dev libjpeg-turbo8-dev libxml2-dev curl zip unzip \
    php8.1-cli php8.1-common php8.1-mysql php8.1-zip php8.1-gd php8.1-mbstring php8.1-curl php8.1-xml php8.1-xmlrpc \
    php8.1-bcmath php8.1-redis
    
RUN echo 'deb [arch=amd64] http://linphone.org/snapshots/ubuntu jammy stable' > /etc/apt/sources.list.d/belledonne.list
RUN wget https://www.linphone.org/snapshots/ubuntu/pubkey.gpg -O - | apt-key add -
RUN apt-get update && apt-get install -y bc-flexisip

# Set working directory
WORKDIR /var/www/html

# Installing composer
COPY composer_installer.sh ./
RUN chmod +x composer_installer.sh
RUN echo 'precedence ::ffff:0:0/96 100' >> /etc/gai.conf \
    && ./composer_installer.sh && mv composer.phar /usr/local/bin/composer
    
# Installing Laravel
RUN chown -R www-data:www-data /var/www/html
RUN composer global require laravel/installer \
    && ln -s /root/.config/composer/vendor/laravel/installer/bin/laravel /usr/local/bin/laravel
###### for fleisip-account-manager until the above line

# Add it to the default path
ENV PATH=$PATH:/opt/belledonne-communications/bin

WORKDIR /opt/belledonne-communications

# Generate a default configuration
RUN flexisip --dump-default all > /etc/flexisip/flexisip.conf

VOLUME /etc/opt/belledonne-communications/flexisip
VOLUME /var/opt/belledonne-communications/log/flexisip
COPY flexisip-entrypoint.sh /
COPY backtrace.gdb /
RUN chmod a+x /flexisip-entrypoint.sh

# Script to wait db before launch flexisip [Licence Apache2]
ADD https://github.com/ufoscout/docker-compose-wait/releases/download/2.2.1/wait /wait
RUN chmod +x /wait

ENTRYPOINT ["/flexisip-entrypoint.sh"]
CMD flexisip

```

> #### 起動スクリプトにphp-fpmの起動コマンド`"/etc/init.d/php8.1-fpm start"`を追加

`flexisip-entrypoint.sh`

```sh
#!/bin/bash
ulimit -c unlimited
set -- flexisip "$@"

# Wait for needed container startup
/wait || exit $?

echo "Flexisip docker params : $*"

if [[$@ == *"--server"*]]; then
  echo "--server param found, starting only one Flexisip instance"
  "$@" &
else
  echo "Server param not found, starting 3 Flexisip instances (proxy, presence, conference)"
  ( "$@" --server proxy 2>&1| tee /var/opt/belledonne-communications/log/flexisip/flexisip_proxy_stdout.log ) &
  ( "$@" --server presence 2>&1| tee /var/opt/belledonne-communications/log/flexisip/flexisip_presence_stdout.log ) &
  ( "$@" --server conference 2>&1| tee /var/opt/belledonne-communications/log/flexisip/flexisip_conference_stdout.log ) &
fi

/etc/init.d/php8.1-fpm start

wait -n

echo "At least one server crashed, stopping every sub process that is still alive"
pkill -P $$

# coredump management, used in unit tests
# we execute gdb on each coredump, with the options given in backtrace.gdb file
# we search in /root because it's the workdir set in Dockerfile and because by default our coredumps are generated by default in the working directory
if [-n "$(find /root -type f -name "core*")"]; then
	find /root -type f -name "core*" | xargs -L1 gdb flexisip -x /backtrace.gdb;
fi

```

> #### Nginxのfastcgi\_passを変更

Dockerネットワークのゲートウェイアドレス：172.17.0.1などに変更

`default.conf`

```auto
    location = /index.php {
        fastcgi_split_path_info ^(.+\.php)(/.+)$;
        fastcgi_keep_conn on;
        fastcgi_param HTTPS 'on';
        fastcgi_pass xx.xx.xx.xx:9000;
        fastcgi_index index.php;
        include fastcgi_params;
        fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
    }

```

> #### PHP-FPM設定ファイル：接続方法の変更

ListenがデフォルトでUnixソケットなので、ポートに変更します。このファイルをコンテナ起動時に読み込ませるため、下記ディレクトリから抜き出してDocker Composeファイルで読み込むように設定して下さい。

`/etc/php/8.1/fpm/pool.d/www.conf`

```auto
.....
.....

; The address on which to accept FastCGI requests.
; Valid syntaxes are:
; 'ip.add.re.ss:port' - to listen on a TCP socket to a specific IPv4 address on
; a specific port;
; '[ip:6:addr:ess]:port' - to listen on a TCP socket to a specific IPv6 address on
; a specific port;
; 'port' - to listen on a TCP socket to all addresses
; (IPv6 and IPv4-mapped) on a specific port;
; '/path/to/unix/socket' - to listen on a unix socket.
; Note: This value is mandatory.
listen = 9000
.....
.....

```

コンテナ内でphp-fpmを再起動する場合

```auto
# service php8.1-fpm restart

```

> #### アカウントマネージャ.envの変更

php-fpmコンテナのネットワークをブリッジからホストへ変更したため、アカウントマネージャの.envファイル内で指定したサービス名によるホスト指定をIPアドレスによるものに変更します。

`flexiapi/.env`

```auto
.....
.....
DB_CONNECTION=mysql
DB_HOST=172.xx.xx.xx
.....
.....
REDIS_CLIENT=phpredis # Use phpredis-sentinel and uncomment the REDIS_SENTINEL variable bellow
REDIS_HOST=172.xx.xx.xx
.....
.....

```

* * *

注）ポート9000へのアクセスがufwによって制限されていると504エラーが発生します。  
Dockerの各ブリッジネットワークからのアクセスを許可します。

```shell
$ sudo ufw allow proto tcp from 172.16.0.0/12 

```

注）nginxの設定で名前解決ができていない場合に521エラーが発生します。  
この場合、 **`docker-compose.yaml`** の **nginx** セクションに **extra\_hosts** を追加して下さい。

```auto
##### nginx
  nginx:
    container_name: nginx
    image: nginx:alpine
    .....
    .....
    extra_hosts:
      - "sip.ficusonline.com:172.19.0.1"
    .....
    .....

```

---

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2023 年 11 月 26 日午前 4:07 UTC](https://forum.ficusonline.com/t/topic/500/3 "2023-11-26T04:07:51Z")

</div>

## PostmanによるFlexisipアカウントマネージャAPIテスト

Postmanでは各種APIの動作を検証できるウェブサービスが提供されています。

[https://www.postman.com/](https://www.postman.com/)

専用デスクトップアプリのダウンロード

> **[Download Postman | Get Started for Free](https://www.postman.com/downloads/)**
>
> Try Postman for free! Join 40 million users who rely on Postman, the collaboration platform for API development. Create better APIs—faster.

### Flexisip Account Manager API

#### 1) Account Creation Request Tokens：アカウント作成リクエストトークン

このトークンは **アカウント作成トークン** を取得するために利用されます。  
JSONフォーマットにより、 **アカウント作成リクエストトークン** と認証URLが返されます。

 ![Screenshot from 2023-11-26 11-59-53](https://forum.ficusonline.com/uploads/default/original/2X/d/dc0c20a8a2d66d79a964d9cb1682909b3eb1d4de.png)

#### 2) Account Creation Tokens：アカウント作成トークン

アカウント作成トークンを取得するAPIは以下二通り用意されています。

- 上記 1) で取得したアカウントリクエストトークンを利用するAPI
- プッシュトークンを利用したAPI

---

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2023 年 12 月 8 日午後 12:06 UTC](https://forum.ficusonline.com/t/topic/500/4 "2023-12-08T12:06:32Z")

</div>

## Linphone AndroidのFCM認証について

サーバーから Firebase サービスにアクセスする場合、Firebase Authentication を使用する必要はありません。代わりに、[Admin SDK](https://firebase.google.com/docs/admin/setup?authuser=3&hl=ja) を使用します。

> **[バックエンドから Firebase サービスにアクセスする場合 - Firebase Authentication の開始方法](https://firebase.google.com/docs/auth/where-to-start?authuser=3&hl=ja#adminsdk)**
>
> アプリにログイン機能がすでに実装されていて、それを使用して Firebase バックエンド サービスで認証を行う場合は、カスタム認証を使用します。これには、次のいずれかを使用するアプリが含まれます。 | ユースケース、エクスペリエンス、アプリのアーキテクチャに基づいて、アプリに適した認証オプションを選択します。

FirebaseのFCMサービスを利用して、Android端末上でLinphoneの電話番号による登録手続きとログインが出来るようにします。FCMサービスを利用する際のポイントは、Androidアプリとウェブアプリの両者を如何に連携させるかです。

必要となる大きな作業は以下の3点です（開発用のGoogleアカウントは必須）。

1. **Firebaseでプロジェクトを登録**  
登録したプロジェクト内でAndroidアプリであるLinphoneとウェブアプリであるFlexisip Account Managerをアプリとして追加します。ややこしいキーフレーズが満載ですが、Google純正のAIチャットBardの助けを借りながら理解して下さい。Firebaseと各アプリ間で安全に通信するための認証ファイル（キーファイル）、各通信で必要となるトークン（一時的なユーザID）を理解することがポイントです。

2. **ウェブアプリのコーディング**  
Flexisip Account ManagerはLaravelのPHPフレームワークで構成されているため、PHPに対応したFirebaseの機能拡張ライブラリを追加する必要があります。この機能拡張クラスを使用してFirebaseのFCMをクライアントからのAPIリクエストに応じて送信します。

3. **Android Linphoneアプリのコーディング**  
電話番号を利用したユーザ登録やログイン時、認証コードが記述されたFCMを受信・表示させるためのコードを追加します。

The following three major tasks are required (a Google account for development is required).

1. **Register a project in Firebase**  
Add the Android app Linphone and the web app Flexisip Account Manager as apps in the project you registered. There are a lot of confusing key phrases, but please understand them with the help of Google’s AI chat Bard. The key points are to understand the authentication file (key file) for secure communication between Firebase and each app, and the token (temporary user ID) required for each communication.

2. **Coding for web app**  
Since Flexisip Account Manager is composed of the Laravel PHP framework, you need to add the Firebase feature extension library that supports PHP. Use this feature extension class to send Firebase FCM in response to API requests from clients.

3. **Coding for Android Linphone app**  
Add code to receive and display FCM containing the authentication code when registering or logging in users using a phone number.

**追加・変更ファイル一覧 : Additional or Modified Files**

1. **Firebase**  
google-service.json —\> **linphone-android/app/google-services.json**

2. **Web App**  
2-1. **Flexisip Account Manager(PHP 8.1.2)**  
flexiapi/.env

3. **Android Linphone**  
build.gradle

* * *

[https://firebase-php.readthedocs.io/en/stable/index.html](https://firebase-php.readthedocs.io/en/stable/index.html)

[https://github.com/kreait/firebase-php](https://github.com/kreait/firebase-php)

### 認証情報

[https://firebase.google.com/docs/cloud-messaging/concept-options?authuser=3&hl=ja#credentials](https://firebase.google.com/docs/cloud-messaging/concept-options?authuser=3&hl=ja#credentials)

実装する FCM 機能によっては、Firebase プロジェクトから次の認証情報の取得が必要になる場合があります。

| | |
| --- | --- |
| プロジェクト ID | FCM v1 HTTP エンドポイントへのリクエストで使用される Firebase プロジェクトの一意の識別子。この値は、[Firebase コンソールの [**設定**]](https://console.firebase.google.com/project/_/settings/general?authuser=3&hl=ja) ペインで確認できます。 |
| 登録トークン | 各クライアント アプリ インスタンスを識別する一意のトークン文字列。単一のデバイスとデバイス グループへのメッセージングに必要になります。登録トークンは非公開にしなければならないことに注意してください。 |
| 送信者 ID | Firebase プロジェクトの作成時に作成される一意の数値。Firebase コンソールの [**設定**] ペインにある [[Cloud Messaging](https://console.firebase.google.com/project/_/settings/cloudmessaging/?authuser=3&hl=ja)] タブで確認できます。送信者 ID は、クライアント アプリにメッセージを送信できる各送信者を識別するために使用されます。 |
| アクセス トークン | HTTP v1 API へのリクエストを承認する短命な OAuth 2.0 トークン。このトークンは、Firebase プロジェクトに属するサービス アカウントと関連付けられています。アクセス トークンの作成およびローテーションを行うには、[送信リクエストを承認する](https://firebase.google.com/docs/cloud-messaging/auth-server?authuser=3&hl=ja)に記されている手順に沿って操作します。 |
| サーバーキー（レガシー プロトコル用） | アプリサーバーによる Google サービスへのアクセス（以前の Firebase Cloud Messaging プロトコル経由でのメッセージの送信など）を承認するサーバーキー。サーバーキーは Firebase プロジェクトの作成時に取得します。サーバーキーを確認するには、Firebase コンソールの [**設定**] ペインにある [[クラウド メッセージング](https://console.firebase.google.com/project/_/settings/cloudmessaging/?authuser=3&hl=ja)] タブに移動します。 **重要:** クライアント コードにはサーバーキーを含めないでください。また、アプリサーバーの承認には、必ずサーバーキーのみを使用してください。Android、Apple プラットフォーム、ブラウザのキーは、FCM で拒否されます。 |

* * *

## メールアドレスまたは電話番号による認証画面切替えクラス：メソッド

電話番号を取得していないデバイスでは、メール認証のページへ誘導。

`app/src/main/java/org/linphone/activities/assistant/fragments/WelcomeFragment.kt`

```auto
class WelcomeFragment : GenericFragment<AssistantWelcomeFragmentBinding>() {
    private lateinit var viewModel: WelcomeViewModel

    override fun getLayoutId(): Int = R.layout.assistant_welcome_fragment

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)

        binding.lifecycleOwner = viewLifecycleOwner

        viewModel = ViewModelProvider(this)[WelcomeViewModel::class.java]
        binding.viewModel = viewModel

        binding.setCreateAccountClickListener {
            if (LinphoneUtils.isPushNotificationAvailable()) {
                Log.i("[Assistant] Core says push notifications are available")
                val deviceHasTelephonyFeature = coreContext.context.packageManager.hasSystemFeature(
                    PackageManager.FEATURE_TELEPHONY
                )
                if (!deviceHasTelephonyFeature) {
                    Log.i(
                        "[Assistant] Device doesn't have TELEPHONY feature, showing email based account creation"
                    )
                    navigateToEmailAccountCreation()
                } else {
                    Log.i(
                        "[Assistant] Device has TELEPHONY feature, showing phone based account creation"
                    )
                    navigateToPhoneAccountCreation()
                }
            } else {
                Log.w(
                    "[Assistant] Failed to get push notification info, showing warning instead of phone based account creation"
                )
                navigateToNoPushWarning()
            }
        }
.....
.....

```

---

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2023 年 12 月 8 日午後 3:25 UTC](https://forum.ficusonline.com/t/topic/500/5 "2023-12-08T15:25:05Z")

</div>

## Android-Studio デバイスシミュレータによるFCM送受信確認

1つのデバイスで1つのアカウントを付与することはできるが、任意の電話番号または他人の電話番号でアカウントが取得可能のため使用はNG。

**YouTube : Create Account by phone number**  
[https://youtube.com/shorts/nq6F1L5qK18?si=\_qVY-F\_FN5cJkLwb](https://youtube.com/shorts/nq6F1L5qK18?si=_qVY-F_FN5cJkLwb)

**YouTube : Login by phone number**  
[https://youtube.com/shorts/\_X\_QQHG7kr4?si=7jXSabxvcG6XAjVL](https://youtube.com/shorts/_X_QQHG7kr4?si=7jXSabxvcG6XAjVL)

#### Click Assistant Menu

 ![vlcsnap-2023-12-18-10h32m35s040](https://forum.ficusonline.com/uploads/default/original/2X/7/74dd66c53b3890941a1730c9a594ec280624c848.png)

#### Click CREATE ACCOUNT

 ![vlcsnap-2023-12-18-10h14m31s768](https://forum.ficusonline.com/uploads/default/original/2X/3/36ce6bbb42f8135417524c90ddb26e6f0ff24b39.png)

#### Input Phone Number, Then Click CREATE ACCOUNT

 ![vlcsnap-2023-12-18-10h15m11s101](https://forum.ficusonline.com/uploads/default/original/2X/a/af026d047b039cfbdf76292de9895b3f5788ccd1.png)

#### Waiting for a few second until receiving the message

 ![vlcsnap-2023-12-18-10h15m23s999](https://forum.ficusonline.com/uploads/default/original/2X/8/834c4795bfcc82ae9d4ea2820025e11bfef50c02.png)

#### Received the message from Firebase

 ![vlcsnap-2023-12-18-10h16m26s722](https://forum.ficusonline.com/uploads/default/original/2X/1/155988daea247234b2158052a53f3603c1814647.png)

#### Pull down the top indicator, and check the confirmation code (FCM Message)

 ![vlcsnap-2023-12-18-10h16m48s731](https://forum.ficusonline.com/uploads/default/original/2X/d/d25c1e595d23fb1940f5cf71d77a2e2c7064d8c7.png)

#### Input the confirmation code, then click FINISH CONFIGURATION

 ![vlcsnap-2023-12-18-10h17m21s454](https://forum.ficusonline.com/uploads/default/original/2X/e/e8f4f017b6c30414b4620c135108756098b5b526.png)

#### Finished the Account Registration

 ![vlcsnap-2023-12-18-10h17m37s928](https://forum.ficusonline.com/uploads/default/original/2X/4/4c6da91b871b1198f2c576de2d4fdbdfc60da903.png)

 ![vlcsnap-2023-12-18-10h17m47s158](https://forum.ficusonline.com/uploads/default/original/2X/2/24b0325d89706d06158202b891dfc73988d183dd.png)

 ![vlcsnap-2023-12-18-10h18m03s365](https://forum.ficusonline.com/uploads/default/original/2X/2/23250bb45f34cefc2789c40495dc55fc4db5a28a.png)

---

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2024 年 1 月 8 日午後 2:13 UTC](https://forum.ficusonline.com/t/topic/500/6 "2024-01-08T14:13:20Z")

</div>

## 参考：Firebase + OTP に関するブログ検索(Medium)

以下のMediumサイトからFirebaseのOTPに関するブログを検索。

[https://medium.com/search?q=firebase+otp](https://medium.com/search?q=firebase+otp)

* * *

KotlinによるAndroidアプリ作成の際は以下参照。

### OTP Login using Firebase

[https://proandroiddev.com/otp-login-using-firebase-hilt-jetpack-components-all-together-in-kotlin-718f7c6974aa](https://proandroiddev.com/otp-login-using-firebase-hilt-jetpack-components-all-together-in-kotlin-718f7c6974aa)

> **[GitHub - aqua30/Otp-Demo---Kotlin: A learning project which focuses on designing an...](https://github.com/aqua30/Otp-Demo---Kotlin?tab=readme-ov-file)**
>
> A learning project which focuses on designing an OTP flow and use of various components of Android efficiently

### MVVM Architecture

[https://medium.com/@onurcem.isik/introduction-to-mvvm-architecture-5c5558c3679](https://medium.com/@onurcem.isik/introduction-to-mvvm-architecture-5c5558c3679)

 ![MVVM_Architecture](https://forum.ficusonline.com/uploads/default/original/2X/b/b368b378230edeeba2227d1bb943c3603f92f96e.png)

---

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2024 年 1 月 10 日午後 12:25 UTC](https://forum.ficusonline.com/t/topic/500/7 "2024-01-10T12:25:20Z")

</div>

> **[Google Codelabs](https://codelabs.developers.google.com/?cat=Android&hl=ja)**
>
> Google for Developers Codelab は、個別指導の実践的なコーディング エクスペリエンスを提供します。ほとんどのコードラボでは、小規模なアプリを構築するプロセスや、既存のアプリに新しい機能を追加するプロセスを手順ごとに説明します。Android Wear、Google Compute Engine、ARCore、iOS の Google API など、幅広いトピックをカバーしています。

---

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2024 年 8 月 30 日午前 4:37 UTC](https://forum.ficusonline.com/t/topic/500/11 "2024-08-30T04:37:15Z")

</div>



---

<div class="post-metadata">

### Author: ![tk-fuse](https://forum.ficusonline.com/user_avatar/forum.ficusonline.com/tk-fuse/32/255_2.png) [@tk-fuse](https://forum.ficusonline.com/u/tk-fuse)
#### Post date: [2024 年 8 月 30 日午前 5:01 UTC](https://forum.ficusonline.com/t/topic/500/12 "2024-08-30T05:01:59Z")

</div>

## PushNotificationアップデート

**注）** 従来のFCM APIが2004年7月に新APIへと全面移行したため、この変更に伴い、FlexisipのDockerイメージもアップデートする必要があります。

> **[Firebase legacy API to HTTP v1 migration guide - XWiki](https://wiki.linphone.org/xwiki/wiki/public/view/Flexisip/Configuration/Push%20notifications/Firebase%20legacy%20API%20to%20Firebase%20v1%20migration%20guide/)**
>
> Firebase legacy API to HTTP v1 migration guide

`ubuntu-flexisip` の `dockerfile:flex-from-ubuntu-apt-repo` にPythonパッケージマネージャ `python3-pip` をインストールし、 `pip3` コマンドで新規パッケージ `google-auth, requests` を追加。

```auto
FROM ubuntu:22.04
MAINTAINER Takanobu Fuse <ficusonline@gmail.com>

ARG DEBIAN_FRONTEND=noninteractive

# Prepare dependencies
RUN apt-get update
RUN apt-get install -y nano xsdcxx gdb libmariadb3 snmp-mibs-downloader snmp snmpd iproute2 iptables wget gnupg2 \ 
    php8.1-fpm libpng-dev libfreetype-dev libjpeg-turbo8-dev libxml2-dev curl zip unzip \
    php8.1-cli php8.1-common php8.1-mysql php8.1-zip php8.1-gd php8.1-mbstring php8.1-curl php8.1-xml php8.1-xmlrpc \
    php8.1-bcmath php8.1-redis python3-pip
RUN pip3 install google-auth requests
.....
.....

```

ubuntu-flexisipイメージのアップデート

```auto
$ docker compose build ubntu-flexisip

```

Docker Composeの再起動

```auto
$ docker compose down
$ docker compose up -d

```

インストールしたPythonパッケージの確認

```auto
$ docker compose exec ubuntu-flexisip bash
# pip3 list
Package Version
------------------ --------
cachetools 5.5.0
certifi 2024.7.4
chardet 4.0.0
charset-normalizer 3.3.2
dbus-python 1.2.18
google-auth 2.34.0
idna 3.8
pip 22.0.2
pyasn1 0.6.0
pyasn1_modules 0.4.0
PyGObject 3.42.1
requests 2.32.3
rsa 4.9
setuptools 59.6.0
six 1.16.0
urllib3 2.2.2
wheel 0.37.1

```

* * *

Firebaseでプロジェクトの秘密キーを作成します。

 ![firebase_secet_key_json](https://forum.ficusonline.com/uploads/default/original/2X/a/a6c07cda36e37f57541c93e4ac9ddc0a57fdec1d.png)

JSONフォーマットのファイルが作成されダウンロードされます。

`project-name-firebase-adminsdk-xxxxxxxxxxxxx.json`

```ini
{
  "type": "service_account",
  "project_id": "<project_id>",
  "private_key_id": "<private_key_id>",
  "private_key": "<PEM_private_key>",
  "client_email": "<mail_address>",
  "client_id": "<client_id>",
  "auth_uri": "https://accounts.google.com/o/oauth2/auth",
  "token_uri": "https://oauth2.googleapis.com/token",
  "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
  "client_x509_cert_url": "<client_x509_cert_url>",
  "universe_domain": "googleapis.com"
}

```

このファイルをubuntu-flexisipコンテナとホスト間でシェアするため、docker-composeファイルのボリュームセクションで指定したflexisip\_confフォルダに格納します。

最後にflexisip.confファイルの[module::PushNotification]セクションで

> firebase-projects-api-keys=…

のラインをコメントアウトまたは削除し、プロジェクト番号と共にファイルパスを指定します。

> firebase-service-accounts=123456789123:/etc/flexisip/project-name-firebase-adminsdk-xxxxxxxxxxxxx.json

を追加します。

`flexisip.conf`

```ini
.....
.....

[module::PushNotification]

# Enable push notification for Android devices.
# Default: true
firebase=true

# List of pairs of <Firebase Project Number>:<Firebase Cloud Messaging
# API (Legacy) Server Key> for each Android project that supports
# push notifications.
# Default: 
#firebase-projects-api-keys=123456789123:<api_key>

# List of pairs of <Firebase Project Number>:<Path to service account
# json file> for each Android project that supports push notifications.
# Default: 
firebase-service-accounts=123456789123:/etc/flexisip/project-name-firebase-adminsdk-xxxxxxxxxxxxx.json

# Represents the time in seconds to execute the access token refresh
# operation just before the current access token expires. This parameter
# is used to control overlapping access token lifetimes.
# Default: 300
#firebase-token-expiration-anticipation-time=300

# Default interval in seconds to execute the access token refresh
# operation in the event that the access token has not been successfully
# obtained.
# Default: 60
#firebase-default-refresh-interval=60
.....
.....

```
