Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature-in-app-upgrade-notifications #1689

Merged
merged 4 commits into from
Jun 10, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/app/features/home/home.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { CaptureTabComponent } from './capture-tab/capture-tab.component';
import { UploadingBarComponent } from './capture-tab/uploading-bar/uploading-bar.component';
import { HomePageRoutingModule } from './home-routing.module';
import { HomePage } from './home.page';
import { UpdateAppDialogComponent } from './in-app-updates/update-app-dialog/update-app-dialog.component';
import { PrefetchingDialogComponent } from './onboarding/prefetching-dialog/prefetching-dialog.component';
import { PostCaptureTabComponent } from './post-capture-tab/post-capture-tab.component';

Expand All @@ -15,6 +16,7 @@ import { PostCaptureTabComponent } from './post-capture-tab/post-capture-tab.com
CaptureTabComponent,
PostCaptureTabComponent,
PrefetchingDialogComponent,
UpdateAppDialogComponent,
UploadingBarComponent,
CaptureItemComponent,
],
Expand Down
72 changes: 72 additions & 0 deletions src/app/features/home/home.page.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { ChangeDetectorRef, Component } from '@angular/core';
import { MatDialog } from '@angular/material/dialog';
import { ActivatedRoute, Router } from '@angular/router';
import { App } from '@capacitor/app';
import { Browser } from '@capacitor/browser';
import {
ActionSheetController,
Expand All @@ -24,14 +25,17 @@ import { CaptureService, Media } from '../../shared/capture/capture.service';
import { ConfirmAlert } from '../../shared/confirm-alert/confirm-alert.service';
import { DiaBackendAssetRepository } from '../../shared/dia-backend/asset/dia-backend-asset-repository.service';
import { DiaBackendAuthService } from '../../shared/dia-backend/auth/dia-backend-auth.service';
import { DiaBackendService } from '../../shared/dia-backend/service/dia-backend-service.service';
import { DiaBackendTransactionRepository } from '../../shared/dia-backend/transaction/dia-backend-transaction-repository.service';
import { DiaBackendWalletService } from '../../shared/dia-backend/wallet/dia-backend-wallet.service';
import { ErrorService } from '../../shared/error/error.service';
import { MigrationService } from '../../shared/migration/service/migration.service';
import { OnboardingService } from '../../shared/onboarding/onboarding.service';
import { UserGuideService } from '../../shared/user-guide/user-guide.service';
import { switchTapTo, VOID$ } from '../../utils/rx-operators/rx-operators';
import { getAppDownloadLink } from '../../utils/url';
import { GoProBluetoothService } from '../settings/go-pro/services/go-pro-bluetooth.service';
import { UpdateAppDialogComponent } from './in-app-updates/update-app-dialog/update-app-dialog.component';
import { PrefetchingDialogComponent } from './onboarding/prefetching-dialog/prefetching-dialog.component';

@UntilDestroy()
Expand Down Expand Up @@ -61,6 +65,7 @@ export class HomePage {
private readonly diaBackendAuthService: DiaBackendAuthService,
private readonly diaBackendAssetRepository: DiaBackendAssetRepository,
private readonly diaBackendTransactionRepository: DiaBackendTransactionRepository,
private readonly diaBackendService: DiaBackendService,
private readonly onboardingService: OnboardingService,
private readonly router: Router,
private readonly captureService: CaptureService,
Expand All @@ -86,6 +91,7 @@ export class HomePage {
.pipe(
concatMap(isNewLogin => this.migrationService.migrate$(isNewLogin)),
catchError(() => VOID$),
switchTapTo(defer(() => this.promptAppUpdateIfAny())),
switchTapTo(defer(() => this.onboardingRedirect())),
switchTapTo(
defer(() => this.userGuideService.showUserGuidesOnHomePage())
Expand Down Expand Up @@ -138,6 +144,72 @@ export class HomePage {
await this.onboardingService.setHasPrefetchedDiaBackendAssets(true);
}

private async promptAppUpdateIfAny() {
// Not applicable to Web App
if (!this.platform.is('hybrid')) return;

const backendAppInfo = await this.diaBackendService.appInfo$().toPromise();
const appInfo = await App.getInfo();

const current = appInfo.version;
const latest = backendAppInfo.latest_app_version;

if (this.isEqualOrGreaterThanLatestVersion(current, latest)) return;

if (backendAppInfo.update_urgency === 'critical') {
this.dialog.open(UpdateAppDialogComponent, { disableClose: true });
}

if (
backendAppInfo.update_urgency === 'high' &&
(await this.diaBackendService.postponedMoreThanOneDayAgo())
) {
this.diaBackendService.setAppUpdatePromptTimestamp(Date.now());
const confirmAppUpdate = await this.showAppUpdateAlert();
if (confirmAppUpdate) await this.redirectToAppUpdatePage();
}
}

// eslint-disable-next-line class-methods-use-this
isEqualOrGreaterThanLatestVersion(
currentVersion: string,
latestVersion: string
) {
const currentVersionArray = currentVersion.split('.');
const latestVersionArray = latestVersion.split('.');

for (const index in currentVersionArray) {
if (currentVersionArray[index] > latestVersionArray[index]) {
return true;
} else if (currentVersionArray[index] < latestVersionArray[index]) {
return false;
}
}
return true;
}

private async redirectToAppUpdatePage() {
const url = getAppDownloadLink(this.platform.is.bind(this));
await Browser.open({ url });
}

private async showAppUpdateAlert() {
return this.confirmAlert.present({
header: this.translocoService.translate(
'inAppUpdate.importantUpdatesAreAvailable'
),
message: this.translocoService.translate(
'inAppUpdate.pleaseUpdateTheAppForProperFunctioning'
),
confirmButtonText: this.translocoService.translate(
'inAppUpdate.updateNow'
),
cancelButtonText: this.translocoService.translate(
'inAppUpdate.remindMeTomorrow'
),
});
}

private async showPrefetchAlert() {
return this.confirmAlert.present({
header: this.translocoService.translate('restorePhotos'),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
<ng-container *transloco="let t">
<h1 mat-dialog-title>{{ t('inAppUpdate.criticalUpdatesAreAvailable') }}</h1>

<div mat-dialog-content>
{{ t('inAppUpdate.pleaseUpdateTheAppForProperFunctioning') }}
</div>
<div mat-dialog-actions>
<button
(click)="redirectToAppUpdatePage()"
mat-button
mat-flat-button
color="warn"
cdkFocusInitial
>
{{ t('inAppUpdate.updateNow') }}
</button>
</div>
</ng-container>
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { ComponentFixture, TestBed, waitForAsync } from '@angular/core/testing';
import { SharedTestingModule } from '../../../../shared/shared-testing.module';
import { UpdateAppDialogComponent } from './update-app-dialog.component';

describe('UpdateAppDialogComponent', () => {
let component: UpdateAppDialogComponent;
let fixture: ComponentFixture<UpdateAppDialogComponent>;

beforeEach(
waitForAsync(() => {
TestBed.configureTestingModule({
declarations: [UpdateAppDialogComponent],
imports: [SharedTestingModule],
}).compileComponents();

fixture = TestBed.createComponent(UpdateAppDialogComponent);
component = fixture.componentInstance;
fixture.detectChanges();
})
);

it('should create', () => {
expect(component).toBeTruthy();
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { Component } from '@angular/core';
import { Browser } from '@capacitor/browser';
import { Platform } from '@ionic/angular';
import { getAppDownloadLink } from '../../../../utils/url';

@Component({
selector: 'app-update-app-dialog',
templateUrl: './update-app-dialog.component.html',
styleUrls: ['./update-app-dialog.component.scss'],
})
export class UpdateAppDialogComponent {
constructor(private readonly platform: Platform) {}

async redirectToAppUpdatePage() {
const url = getAppDownloadLink(this.platform.is.bind(this));
await Browser.open({ url });
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
import { TestBed } from '@angular/core/testing';
import { SharedTestingModule } from '../../shared-testing.module';
import { DiaBackendService } from './dia-backend-service.service';

describe('DiaBackendService', () => {
let service: DiaBackendService;

beforeEach(() => {
TestBed.configureTestingModule({
imports: [SharedTestingModule],
});
service = TestBed.inject(DiaBackendService);
});

it('should be created', () => {
expect(service).toBeTruthy();
});
});
66 changes: 66 additions & 0 deletions src/app/shared/dia-backend/service/dia-backend-service.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import { defer } from 'rxjs';
import { concatMap } from 'rxjs/operators';
import { calcDaysBetweenDates } from '../../../utils/date';
import { Tuple } from '../../database/table/table';
import { PreferenceManager } from '../../preference-manager/preference-manager.service';
import { DiaBackendAuthService } from '../auth/dia-backend-auth.service';
import { BASE_URL } from '../secret';

@Injectable({
providedIn: 'root',
})
export class DiaBackendService {
private readonly preferences =
this.preferenceManager.getPreferences('DiaBackendService');

constructor(
private readonly httpClient: HttpClient,
private readonly authService: DiaBackendAuthService,
private readonly preferenceManager: PreferenceManager
) {}

appInfo$() {
return defer(() => this.authService.getAuthHeaders()).pipe(
concatMap(headers =>
this.httpClient.get<DiaBackendAppInfo>(
`${BASE_URL}/api/v3/services/app-info/`,
{ headers }
)
)
);
}

async postponedMoreThanOneDayAgo() {
const timestamp = await this.getAppUpdatePromptTimestamp();

const lastPostponedTime = new Date(timestamp);
const currentTime = new Date(Date.now());

return calcDaysBetweenDates(currentTime, lastPostponedTime) > 1;
}

async getAppUpdatePromptTimestamp() {
return this.preferences.getNumber(
PrefKeys.APP_UPDATE_PROMPT_TIMESTPAMP,
0 // new Date(0) == Thu Jan 01 1970
);
}

async setAppUpdatePromptTimestamp(timestamp: number) {
return this.preferences.setNumber(
PrefKeys.APP_UPDATE_PROMPT_TIMESTPAMP,
timestamp
);
}
}

export interface DiaBackendAppInfo extends Tuple {
readonly latest_app_version: string;
readonly update_urgency: 'low' | 'high' | 'critical';
}

const enum PrefKeys {
APP_UPDATE_PROMPT_TIMESTPAMP = 'APP_UPDATE_PROMPT_TIMESTPAMP',
}
7 changes: 7 additions & 0 deletions src/app/utils/date.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export function calcDaysBetweenDates(a: Date, b: Date) {
// eslint-disable-next-line @typescript-eslint/no-magic-numbers
const millisecondsInOneDay = 1000 * 60 * 60 * 24;
const diffTime = a.getTime() - b.getTime();
const diffDays = Math.ceil(diffTime / millisecondsInOneDay);
return diffDays;
}
10 changes: 10 additions & 0 deletions src/app/utils/url.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,3 +10,13 @@ export function getAssetProfileUrl(id: string, token?: string) {
}
return `https://authmedia.net/asset-profile?cid=${id}`;
}

export function getAppDownloadLink(isPlatform: (platformName: any) => boolean) {
if (isPlatform('ios'))
return 'https://apps.apple.com/en/app/capture-app/id1536388009';

if (isPlatform('android'))
return 'https://play.google.com/store/apps/details?id=io.numbersprotocol.capturelite';

return 'https://www.numbersprotocol.io/#products';
}
7 changes: 7 additions & 0 deletions src/assets/i18n/en-us.json
Original file line number Diff line number Diff line change
Expand Up @@ -330,5 +330,12 @@
"previous": "Prev",
"next": "Next",
"okIGotIt": "Ok, I got it"
},
"inAppUpdate": {
"criticalUpdatesAreAvailable": "Critical updates are available",
"importantUpdatesAreAvailable": "Important updates are available",
"pleaseUpdateTheAppForProperFunctioning": "Please update the app for proper functioning",
"remindMeTomorrow": "REMIND ME TOMORROW",
"updateNow": "UPDATE NOW"
}
}
7 changes: 7 additions & 0 deletions src/assets/i18n/zh-tw.json
Original file line number Diff line number Diff line change
Expand Up @@ -330,5 +330,12 @@
"previous": "上一步",
"next": "下一步",
"okIGotIt": "好,我知道了"
},
"inAppUpdate": {
"criticalUpdatesAreAvailable": "重要更新可用",
"importantUpdatesAreAvailable": "重要更新可用",
"pleaseUpdateTheAppForProperFunctioning": "請更新應用程序以使其正常運行",
"remindMeTomorrow": "明天提醒我",
"updateNow": "現在更新"
}
}