HEX
Server: Apache/2.4.41 (Ubuntu)
System: Linux ip-172-31-42-149 5.15.0-1084-aws #91~20.04.1-Ubuntu SMP Fri May 2 07:00:04 UTC 2025 aarch64
User: ubuntu (1000)
PHP: 7.4.33
Disabled: pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,pcntl_unshare,
Upload Files
File: /var/www/vhost/disk-apps/pwa.sports-crowd.com/src/app/services/utils.service.ts
import { TranslateService } from '@ngx-translate/core';
import { Injectable } from "@angular/core";
import { ToastController, LoadingController, AlertController, ModalController } from "@ionic/angular";
import { CurrencyPipe } from '@angular/common';
import { StorageService } from "./storage.service";
import { Router } from "@angular/router";
import { HTMLIonOverlayElement } from '@ionic/core';
import { ModalSeeDocumentPage } from "../pages/modal-see-document/modal-see-document.page";
import { Browser } from '@capacitor/browser';
import { InAppBrowser } from '@capgo/inappbrowser';
import { Capacitor } from "@capacitor/core";
import { Directory, Filesystem } from '@capacitor/filesystem';
import { Http, HttpDownloadFileResult } from '@capacitor-community/http';
import { Share } from '@capacitor/share';

@Injectable({
  providedIn: "root",
})
export class UtilsService {
  loading: any;
  toast: any;
  _HAS_LOGGED_IN: boolean = false;
  categorySession: string = 'Session';
  categoryWelcome: string = 'Welcome';
  categoryHome: string = 'Home';
  categorySettings: string = 'Settings';
  categoryShop: string = 'Shop';
  categoryApp: string = 'App';
  loadingPage: boolean = false;


  constructor(
    private storage: StorageService,
    public loadingController: LoadingController,
    public toastController: ToastController,
    public alertController: AlertController,
    public currencyPipe: CurrencyPipe,
    private router: Router,
    public modalController: ModalController,
    private translateService: TranslateService
  ) { }

  async presentLoading(message) {
    this.loading = await this.loadingController.create({
      message: message,
      spinner: "lines",
      translucent: true,
      mode: "ios",
    });
    return await this.loading.present();
  }

  async dismissLoading() {
    try {
      await this.loading.dismiss();
    } catch (e) {

    }
  }

  async presentToast(duration, color, position, message, showCloseButton: boolean = false) {
    var me = this;
    me.closeToast(me.toast);
    me.toastController.create({
      message: message,
      position: position,
      color: color,
      duration: !showCloseButton ? duration : null,
      buttons: !showCloseButton ? [] : [
        {
          text: '✓',
          handler: () => {
          }
        }
      ]
    }).then((toast) => {
      toast.present();
      toast.addEventListener("ionToastDidPresent", (obj) => {
        if (obj.target)
          obj.target.addEventListener('click', function () {
            me.closeToast(me.toast);
          });
      });
      me.toast = toast;
    });
  }

  closeToast(toast: any) {
    if (toast)
      toast.dismiss();
  }

  async presentAlertInfo(header: string, subheader?: string, message?: string) {
    const alert = await this.alertController.create({
      cssClass: "my-custom-class",
      header: header,
      subHeader: subheader,
      message: message,
      backdropDismiss: false,
      buttons: ["OK"],
    });

    await alert.present();
  }

  formatCurrency(value) {
    return this.currencyPipe.transform(value, 'USD', 'symbol', '1.0-0');
  }

  formataDate(date: string, format: string) {
    if (format == 'dd-mm-yyy') {
      date = date.slice(0, 10).split("-").reverse().join("-");
    }
    return date;
  }

  currentDate() {
    let today = new Date();
    let date = today.getFullYear() + "-" + (today.getMonth() + 1).toString().padStart(2, "0") + "-" + today.getDate().toString().padStart(2, "0");
    let time =
      (today.getHours() < 10 ? "0" + today.getHours() : today.getHours()) +
      ":" +
      (today.getMinutes() < 10 ? "0" + today.getMinutes() : today.getMinutes()) +
      ":" +
      (today.getSeconds() < 10 ? "0" + today.getSeconds() : today.getSeconds());
    let currentDate = date + " " + time;
    return currentDate;
  }

  currentDateToISOString(date) {
    return date.replace(" ", "T") + ".455-05:00";
  }

  /** valida si una fecha es valida basada con la fecha actual
   *
  */
  validateDate(date: any, type: string) {
    let currentDate = new Date();
    if (date && date != "") {
      date = date.replace("T", " ").slice(0, 19);
      let dateStart = date.slice(0, 10).split("-");
      let timeStart = date.slice(11, 19).split(":");
      let newDateValidate = new Date(
        parseInt(dateStart[0]),
        parseInt(dateStart[1]) - 1,
        parseInt(dateStart[2]),
        parseInt(timeStart[0]),
        parseInt(timeStart[1]),
        parseInt(timeStart[2])
      );
      if (newDateValidate.getTime() < currentDate.getTime() && type == "start") {
        return true;
      }
      if (newDateValidate.getTime() > currentDate.getTime() && type == "end") {
        return true;
      }
    }
    return false;
  }

  /** valida si una fecha es mayor que la otra
   * type = condicional > | <
  */
  validateDateCustom(date_one: any, date_two, type: string, days_date_one: number = 0) {
    if ((date_one && date_one != "") && (date_two && date_two != "")) {
      date_one = date_one.replace("T", " ").slice(0, 19);
      date_two = date_two.replace("T", " ").slice(0, 19);
      let dateStartOne = date_one.slice(0, 10).split("-");
      let timeStartOne = date_one.slice(11, 19).split(":");
      let dateStartTwo = date_two.slice(0, 10).split("-");
      let timeStartTwo = date_two.slice(11, 19).split(":");
      let dateValidateOne = new Date(
        parseInt(dateStartOne[0]),
        parseInt(dateStartOne[1]) - 1,
        parseInt(dateStartOne[2]) - days_date_one,
        parseInt(timeStartOne[0]),
        parseInt(timeStartOne[1]),
        parseInt(timeStartOne[2])
      );
      let dateValidateTwo = new Date(
        parseInt(dateStartTwo[0]),
        parseInt(dateStartTwo[1]) - 1,
        parseInt(dateStartTwo[2]),
        parseInt(timeStartTwo[0]),
        parseInt(timeStartTwo[1]),
        parseInt(timeStartTwo[2])
      );
      if (dateValidateOne.getTime() < dateValidateTwo.getTime() && type == "start") {
        return true;
      }
      if (dateValidateOne.getTime() > dateValidateTwo.getTime() && type == "end") {
        return true;
      }
    }
    return false;
  }

  getAccessToken() {
    return new Promise((resolve, reject) => {
      this.storage.get("token").then((token) => {
        resolve(token ? token.access_token : '');
      });
    });
  }

  sendMessage(object: any) {
    let message = 'Me gustaría solicitar los servicios de tu negocio, te he contactado desde el APP Academias Saprissa';
    let phone = object.code + object.phone;
    let textWhatsapp = "&text=" + message;
    let url = "https://api.whatsapp.com/send?phone=" + phone + textWhatsapp;

    if (Capacitor.isNativePlatform()) {
      Browser.open({ url: url });
    } else {
      window.open(url);
    }
  }

  actionClickBanner(banner: any) {
    switch (banner.type_action_id) {
      /*
      case 1: // Categoria
        this.infocategory = this.homeProvider._listCategories.find(
          (category) => category.id === parseInt(banner.value)
        );
        this.openItemCategory(this.infocategory);
        break;
        */

      case 2: // Link
        let link = banner.value;
        this.openLink(link);
        break;

      case 3: // Menu item
        this.router.navigate([banner.value]);
        break;

      default:
        break;
    }
  }

  isEmptyObject(obj: any) {
    return (obj && (Object.keys(obj).length === 0));
  }

  getWeeksDiff(startDate: any, endDate: any) {
    const msInWeek = 1000 * 60 * 60 * 24 * 7;

    return Math.floor(
      Math.abs(endDate.getTime() - startDate.getTime()) / msInWeek,
    );
  }

  omitSpecialChar(inputName, form, value) {
    if (value != '' && !/^[a-zA-Zñáéíóúü ]+$/i.test(value) && typeof value === 'string') {
      form.controls[inputName].setValue(value.replace(/[^a-zA-Z ]/g, ""));
    }
  }

  validateEmail(email) {
    var re = /\S+@\S+\.\S+/;
    return re.test(email);
  }

  closeAllAlerts() {
    const overlays = document.querySelectorAll('ion-loading');
    const overlaysArr = Array.from(overlays) as HTMLIonOverlayElement[];
    overlaysArr.forEach(o => o.dismiss());
  };

  async presentSeeDocument(title: string, url: string) {
    const modal = await this.modalController.create({
      component: ModalSeeDocumentPage,
      showBackdrop: false,
      swipeToClose: false,
      componentProps: {
        title: title,
        url: url
      },
    });
    modal.onDidDismiss().then((data) => {
    });
    return await modal.present();
  }

  timeSince(date, longFormat: boolean = false) {
    var seconds = Math.floor((new Date().getTime() - new Date(date).getTime()) / 1000);
    let textOrigin = longFormat ? 'TIMING_AGO.' : 'TIMING.';

    var interval = seconds / 31536000;
    if (interval > 2) {
      let years = Math.floor(interval);
      return this.translateService.instant(textOrigin + 'YEAR', { time: years });
    }
    interval = seconds / 2592000;
    if (interval > 2) {
      return this.translateService.instant(textOrigin + 'MONTH', { time: Math.floor(interval) })
    }
    interval = seconds / 86400;
    if (interval > 2) {
      return this.translateService.instant(textOrigin + 'DAY', { time: Math.floor(interval) })
    }
    interval = seconds / 3600;
    if (interval > 2) {
      return this.translateService.instant(textOrigin + 'HOUR', { time: Math.floor(interval) })
    }
    interval = seconds / 60;
    if (interval > 2) {
      return this.translateService.instant(textOrigin + 'MINUTE', { time: Math.floor(interval) })
    }
    return this.translateService.instant(textOrigin + 'SECOND', { time: Math.floor(interval) })
  }

  openLink(link) {
    if (!link) {
      this.presentAlertInfo(this.translateService.instant('error.alert'), '', this.translateService.instant('error.invalid_link'));
      return;
    }
    if (Capacitor.isNativePlatform()) {
      if (this.isIOS()) {
        InAppBrowser.openWebView({
          url: encodeURI(link),
          title: ''
        });
      } else {
        InAppBrowser.open({ url: link });
      }
    } else {
      window.open(link, "_blank");
    }
  }

  async downloadFromLink(link) {
    let fileName = "SportsCrowd_" + new Date().getTime() + '.pdf';
    if (this.isIOS()) {
      this.presentLoading(this.translateService.instant("all.loading"));
      const options = {
        url: link,
        filePath: fileName,
        fileDirectory: Directory.Documents,
        method: 'GET',
      };

      const response: HttpDownloadFileResult = await Http.downloadFile(options);
      if (response.path) {
        const finalPhotoUri = await Filesystem.getUri({
          directory: Directory.Documents,
          path: fileName
        });

        this.closeAllAlerts();
        Share.share({
          title: fileName,
          url: finalPhotoUri.uri
        }).then(() => {
          this.presentToast(3000, "success", "top", this.translateService.instant("FILE_DOWNLOADED"));
          this.dismissLoading();
        }).catch(e => {
        });
      }
    } else {
      this.openLink(link);
    }
  }

  isIOS(){
    return Capacitor.getPlatform() === 'ios';
  }
}