import { Injectable , Optional } from "@angular/core" ; import { SafeUrl } from "@angular/platform-browser" ; import { CloudFileService } from "../../../core/webdav/cloud-file-service.service" ; import { Child } from "../model/child" ; import { BehaviorSubject } from "rxjs" ; @ Injectable ( { providedIn : "root" , } ) export class ChildPhotoService { public static getImageFromAssets ( photoFile ) { if ( typeof photoFile !== "string" || photoFile . trim ( ) === "" ) { return ChildPhotoService . getDefaultImage ( ) ; } return ChildPhotoService . generatePhotoPath ( photoFile ) ; } param filename public static generatePhotoPath ( filename ) { return "assets/child-photos/" + filename ; } public static getDefaultImage ( ) { return "assets/child.png" ; } private basePath = "photos/" ; constructor ( @ Optional ( ) private cloudFileService ) { } param child public async getImage ( child ) { let image = await this . getImageFromCloudService ( child . entityId ) ; if ( ! image ) { image = ChildPhotoService . getImageFromAssets ( child . photo ?. path ) ; } return image ; } private async getImageFromCloudService ( entityId ) { let image ; if ( this . cloudFileService ?. isConnected ( ) ) { const imageType = [ ".png" , ".jpg" , ".jpeg" , "" ] ; for ( const ext of imageType ) { const filepath = this . basePath + entityId + ext ; try { image = await this . cloudFileService . getFile ( filepath ) ; break ; } catch ( err ) { if ( err === "File not found" ) { } else { console . warn ( "Error loading image: " , err ) ; } } } } return image ; } param child public getImageAsyncObservable ( child ) { const resultSubject = new BehaviorSubject ( ChildPhotoService . getImageFromAssets ( child . photo ?. path ) ) ; this . getImageFromCloudService ( child . entityId ) . then ( ( photo ) => { if ( photo && photo !== resultSubject . value ) { resultSubject . next ( photo ) ; } resultSubject . complete ( ) ; } ) ; return resultSubject ; } /**
     * Check if saving/uploading images is supported in the current state.
     */ public canSetImage ( ) { return this . cloudFileService ?. isConnected ( ) ; } param imageFile param childId public async setImage ( imageFile , childId ) { if ( ! this . canSetImage ( ) ) { return Promise . reject ( "CloudFileService not connected." ) ; } const fileExt = imageFile . name . substr ( imageFile . name . lastIndexOf ( "." ) ) ; return this . cloudFileService . uploadFile ( imageFile , this . basePath + childId + fileExt ) ; } }