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/pages/home-sc/home-sc.page.ts
import { PublicationClubService } from './../../services/publication-club.service';
import { DataPolicyService } from './../../services/data-policy.service';
import { AnalyticsService } from './../../services/analytics.service';
import { HttpClient } from "@angular/common/http";
import { Component, OnInit, ViewChild, ElementRef } from "@angular/core";
import { DomSanitizer, SafeResourceUrl } from "@angular/platform-browser";
import { NavigationStart, Router } from "@angular/router";
import { CartService } from "../../services/cart.service";
import { CommsService } from "../../services/comms.service";
import { HomeService } from "../../services/home.service";
import { OrderService } from "../../services/order.service";
import { StorageService } from "../../services/storage.service";
import { UserService } from "../../services/user.service";
import { CityService } from "../../services/city.service";
import { LealService } from '../../services/leal.service';
import { UtilsService } from "../../services/utils.service";
import { ParameterService } from "../../services/parameter.service";
import { LocationStrategy } from "@angular/common";
import { SectionService } from "../../services/section.service";
import { TranslateService } from "@ngx-translate/core";
import { TermService } from "../../services/term.service";
import { IonContent } from '@ionic/angular';
import { NotificationService } from '../../services/notification.service';
import { OfflineTicketingService } from 'src/app/services/ticketing/offline-ticketing.service';

@Component({
  selector: "app-home-sc",
  templateUrl: "./home-sc.page.html",
  styleUrls: ["./home-sc.page.scss"],
})
export class HomeScPage implements OnInit {
  @ViewChild("parent") private parentRef: ElementRef<HTMLElement>;
  @ViewChild(IonContent) content: IonContent;
  public statisticUrlOnly: SafeResourceUrl;
  public statisticUrlStanding: SafeResourceUrl;

  loading: boolean = false;
  messageText: any;
  infocategory: any;
  arr: any = [];
  news: any;
  targetUrl: string = "https://dimoficial.com/feed/eclectica104_rss";
  videos: any;
  youtubeLink1: any;
  vidUrl: SafeResourceUrl;
  instagram: any;
  userInfo: any = {};
  photoInstagram: any;
  coins: number;
  imageList: any;
  parameters: any = {};
  banners: any = [];
  time: number;
  dataSections: any = [];
  allDataSections: any = [];
  notificationsCount: number;
  notificationsNotViewedCount: number;
  buttonBackground: any;
  photoClub: any = [];

  slideOpts = {
    initialSlide: 0,
    speed: 400,
    autoplay: {
      delay: 5000,
    },
  };
  slideOptsTickets = {
    initialSlide: 0,
    speed: 600,
    autoplay: {
      delay: 6000,
    },
    slidesPerView: 1,
    coverflowEffect: {
      rotate: 50,
      stretch: 0,
      depth: 100,
      modifier: 1,
      slideShadows: true,
    },
    on: {
      beforeInit() {
        const swiper = this;

        swiper.classNames.push(
          `${swiper.params.containerModifierClass}coverflow`
        );
        swiper.classNames.push(`${swiper.params.containerModifierClass}3d`);

        swiper.params.watchSlidesProgress = true;
        swiper.originalParams.watchSlidesProgress = true;
      },
      setTranslate() {
        const swiper = this;
        const {
          width: swiperWidth,
          height: swiperHeight,
          slides,
          $wrapperEl,
          slidesSizesGrid,
          $,
        } = swiper;
        const params = swiper.params.coverflowEffect;
        const isHorizontal = swiper.isHorizontal();
        const transform$$1 = swiper.translate;
        const center = isHorizontal
          ? -transform$$1 + swiperWidth / 2
          : -transform$$1 + swiperHeight / 2;
        const rotate = isHorizontal ? params.rotate : -params.rotate;
        const translate = params.depth;
        // Each slide offset from center
        for (let i = 0, length = slides.length; i < length; i += 1) {
          const $slideEl = slides.eq(i);
          const slideSize = slidesSizesGrid[i];
          const slideOffset = $slideEl[0].swiperSlideOffset;
          const offsetMultiplier =
            ((center - slideOffset - slideSize / 2) / slideSize) *
            params.modifier;

          let rotateY = isHorizontal ? rotate * offsetMultiplier : 0;
          let rotateX = isHorizontal ? 0 : rotate * offsetMultiplier;
          // var rotateZ = 0
          let translateZ = -translate * Math.abs(offsetMultiplier);

          let translateY = isHorizontal ? 0 : params.stretch * offsetMultiplier;
          let translateX = isHorizontal ? params.stretch * offsetMultiplier : 0;

          // Fix for ultra small values
          if (Math.abs(translateX) < 0.001) translateX = 0;
          if (Math.abs(translateY) < 0.001) translateY = 0;
          if (Math.abs(translateZ) < 0.001) translateZ = 0;
          if (Math.abs(rotateY) < 0.001) rotateY = 0;
          if (Math.abs(rotateX) < 0.001) rotateX = 0;

          const slideTransform = `translate3d(${translateX}px,${translateY}px,${translateZ}px)  rotateX(${rotateX}deg) rotateY(${rotateY}deg)`;

          $slideEl.transform(slideTransform);
          $slideEl[0].style.zIndex =
            -Math.abs(Math.round(offsetMultiplier)) + 1;
          if (params.slideShadows) {
            // Set shadows
            let $shadowBeforeEl = isHorizontal
              ? $slideEl.find(".swiper-slide-shadow-left")
              : $slideEl.find(".swiper-slide-shadow-top");
            let $shadowAfterEl = isHorizontal
              ? $slideEl.find(".swiper-slide-shadow-right")
              : $slideEl.find(".swiper-slide-shadow-bottom");
            if ($shadowBeforeEl.length === 0) {
              $shadowBeforeEl = swiper.$(
                `<div class="swiper-slide-shadow-${isHorizontal ? "left" : "top"
                }"></div>`
              );
              $slideEl.append($shadowBeforeEl);
            }
            if ($shadowAfterEl.length === 0) {
              $shadowAfterEl = swiper.$(
                `<div class="swiper-slide-shadow-${isHorizontal ? "right" : "bottom"
                }"></div>`
              );
              $slideEl.append($shadowAfterEl);
            }
            if ($shadowBeforeEl.length)
              $shadowBeforeEl[0].style.opacity =
                offsetMultiplier > 0 ? offsetMultiplier : 0;
            if ($shadowAfterEl.length)
              $shadowAfterEl[0].style.opacity =
                -offsetMultiplier > 0 ? -offsetMultiplier : 0;
          }
        }

        // Set correct perspective for IE10
        if (
          swiper.support.pointerEvents ||
          swiper.support.prefixedPointerEvents
        ) {
          const ws = $wrapperEl[0].style;
          ws.perspectiveOrigin = `${center}px 50%`;
        }
      },
      setTransition(duration) {
        const swiper = this;
        swiper.slides
          .transition(duration)
          .find(
            ".swiper-slide-shadow-top, .swiper-slide-shadow-right, .swiper-slide-shadow-bottom, .swiper-slide-shadow-left"
          )
          .transition(duration);
      },
    },
  };

  constructor(
    private router: Router,
    private dom: DomSanitizer,
    public homeProvider: HomeService,
    public cityProvider: CityService,
    public http: HttpClient,
    public userProvider: UserService,
    public cartProvider: CartService,
    public orderProvider: OrderService,
    private storage: StorageService,
    private commsService: CommsService,
    private lealService: LealService,
    public location: LocationStrategy,
    public utilsService: UtilsService,
    public parameterService: ParameterService,
    public sectionService: SectionService,
    public translateService: TranslateService,
    public termProvider: TermService,
    private analyticsService: AnalyticsService,
    private publicationClubService: PublicationClubService,
    private dataPolicyService: DataPolicyService,
    private notificationService: NotificationService,
    private offlineTicketingService: OfflineTicketingService
  ) {
    router.events.subscribe((event: NavigationStart) => {
      if ((event.navigationTrigger === 'popstate' || event.navigationTrigger === 'imperative') && event.url && event.url == '/app/tabs/home') {
        this.parameterService.startApp(false);
        let sectionName = this.sectionService.sectionName;
        this.getNotifications();
        setTimeout(() => {
          if (sectionName) {
            this.goToSection(sectionName, "");
          }
        }, 600);
      }
    });
  }

  ngOnInit() {
    this.loadInit();
    if (!this.homeProvider._activateNewsLink)
      this.loadXML();
  }

  loadInit(time = 0) {
    this.time = new Date().getTime();
    this.getStatisticsUrl();
    setTimeout(() => {
      return new Promise((resolve, reject) => {
        this.utilsService.presentLoading(this.translateService.instant("all.loading")).then(() => {
          Promise.all([
            this.parameterService.getParameters().then((resp: any) => {
              this.parameters = resp.parameters;
            }),
            this.userProvider.getInfoUser().then((user: any) => {
              this.userInfo = user;
              this.analyticsService.setUserId(user.id);
              if (!this.userProvider.isRestrictedUser()) {
                this.getNotifications();
                this.termProvider.validateTerms();
                this.dataPolicyService.validate();
              }
            }),
            this.commsService.getPopups('home'),
            this.commsService.getBanners('home').then((banners) => {
              this.banners = banners;
            }),
            this.parameterService.startApp(false),
            this.getSectionHome(),
            // this.loadCoins(),
            this.homeProvider.getForms(),
            this.homeProvider.getTeamData(),
            // this.homeProvider.infoCategories(),
            // this.homeProvider.infoCategoriesBusiness(),
            // this.homeProvider.infoDirectoryBusiness(),
            this.userProvider.updateLastSession(),
            this.getInstagram(2),
            this.getYoutube(2),
            this.userProvider.savePlayerOnesignal(),
            this.offlineTicketingService.saveData()
          ]).then(() => {
            this.utilsService.closeAllAlerts();
            this.utilsService.loadingPage = false;
            resolve(false);
          }).catch((error) => {
            this.utilsService.closeAllAlerts();
            this.utilsService.loadingPage = false;
            console.log('Error loadInit HomeSc', error);
            reject(error);
          });
        });
      });
    }, time);
  }

  getPublications() {
    if (this.checkAttributeValue('Contenido')) {
      this.publicationClubService.get().then((items) => {
        this.photoClub = items;
      })
    }
  }

  actionClickBanner(banner) {
    this.analyticsService.logEvent('Banner Click: ' + banner.name, 'Banner', 'click', banner);
    return this.homeProvider.openAction(banner.type_action_id, banner.value, banner.target);
  }

  loadXML() {
    this.http
      .get(this.targetUrl, {
        responseType: "text",
      })
      .subscribe((data) => {
        let xmlDOM = new DOMParser().parseFromString(data, "text/xml");
        this.news = this.xmlToJson(xmlDOM);
        for (let k in this.news.rss.channel.item) {
          let item = this.news.rss.channel.item[k];
          let dt = item.pubDate;
          let publicationDate =
            dt.substring(0, 4) +
            "/" +
            dt.substring(4, 6) +
            "/" +
            dt.substring(6, 8) +
            "  " +
            dt.substring(8, 10) +
            ":" +
            dt.substring(10, 12) +
            ":" +
            dt.substring(12, 14);
          let weeks = this.utilsService.getWeeksDiff(new Date(publicationDate), new Date());
          this.arr.push({
            imgUrl: item.imgUrl,
            category: item.category,
            title: item.title,
            publicationDate,
            new: weeks == 0
          });
        }
      });
  }

  xmlToJson(xml) {
    // Create the return object
    let obj = {};

    if (xml.nodeType == 1) {
      // element
      // do attributes
      if (xml.attributes.length > 0) {
        obj["@attributes"] = {};
        for (let j = 0; j < xml.attributes.length; j++) {
          let attribute = xml.attributes.item(j);
          obj["@attributes"][attribute.nodeName] = attribute.nodeValue;
        }
      }
    } else if (xml.nodeType == 3) {
      // text
      obj = xml.nodeValue;
    }

    // do children
    // If all text nodes inside, get concatenated text from them.
    let textNodes = [].slice.call(xml.childNodes).filter(function (node) {
      return node.nodeType === 3;
    });
    if (xml.hasChildNodes() && xml.childNodes.length === textNodes.length) {
      obj = [].slice.call(xml.childNodes).reduce(function (text, node) {
        return text + node.nodeValue;
      }, "");
    } else if (xml.hasChildNodes()) {
      for (let i = 0; i < xml.childNodes.length; i++) {
        let item = xml.childNodes.item(i);
        let nodeName = item.nodeName;
        if (typeof obj[nodeName] == "undefined") {
          obj[nodeName] = this.xmlToJson(item);
        } else {
          if (typeof obj[nodeName].push == "undefined") {
            let old = obj[nodeName];
            obj[nodeName] = [];
            obj[nodeName].push(old);
          }
          obj[nodeName].push(this.xmlToJson(item));
        }
      }
    }
    return obj;
  }

  launchStorie(link) {
    this.utilsService.openLink(link);
  }

  launchVideo(link) {
    this.utilsService.openLink(link);
  }

  getYoutube(showYoutube: number) {
    this.storage.get("token").then(async (token) => {
      if (token) {
        (await this.commsService.getYoutube(token.access_token, showYoutube)).subscribe(
          (resp: any) => {
            let videos = resp;
            for (let i = 0; i < videos.length; ++i) {
              videos[i].link = 'https://www.youtube-nocookie.com/embed/' + videos[i].code;
              videos[i].sanitizedSource = this.sanitizer(videos[i].link);
            }
            this.videos = videos;
          },
          (error) => {
            console.log("error GetYoutube", error);
          }
        );
      }
    });
  }

  getInstagram(showInstagram) {
    this.storage.get("token").then(async (token) => {
      if (token) {
        (await this.commsService.getInstagram(token.access_token, showInstagram)).subscribe(
          (resp: any) => {
            this.photoInstagram = Object.values(resp);
            for (let i = 0; i < this.photoInstagram.length; ++i) {
              this.photoInstagram[i].link = this.photoInstagram[i].link.split('?')[0] + 'embed';
              this.photoInstagram[i].sanitizedSource = this.sanitizer(this.photoInstagram[i].link);
            }
            this.instagram = this.photoInstagram;
          },
          (error) => {
            console.log("error GetInstagram", error);
          }
        );
      }
    });
  }

  goToStatistics() {
    this.analyticsService.logEvent('Statistics Click', this.utilsService.categoryHome);
    this.router.navigate(["/app/tabs/home/statistics"]);
  }

  goToCoins() {
    this.router.navigate(["/app/tabs/home/coins"]);
  }

  goToNotifications() {
    this.router.navigate(["/notification"]);
  }

  goToBookcase() {
    this.router.navigate(["/app/tabs/bookcase"]);
  }

  goToSocial() {
    this.analyticsService.logEvent('Social Click', this.utilsService.categoryHome);
    this.router.navigate(["/app/tabs/home/social"]);
  }

  goToNews() {
    this.analyticsService.logEvent('News Click', this.utilsService.categoryHome);
    this.router.navigate(["/app/tabs/home/news"]);
  }

  goToNewsLink() {
    this.analyticsService.logEvent('News Link Click', this.utilsService.categoryHome);
    let link = this.homeProvider._urlNewsLink;
    this.utilsService.openLink(link);
  }

  sanitizer(vidUrl: string) {
    return this.dom.bypassSecurityTrustResourceUrl(vidUrl);
  }

  doRefresh(event) {
    setTimeout(() => {
      this.loadInit(100);
      if (!this.homeProvider._activateNewsLink)
        this.loadXML();
      event.target.complete();
    }, 500);
  }

  loadCoins() {
    this.storage.get("infoUser").then((infoUser) => {
      if (infoUser) {
        this.storage.get("token").then(async (token) => {
          if (token) {
            (await this.lealService.login(token.access_token)).subscribe(
              async (resp) => {
                (await this.lealService.coins(token.access_token, infoUser.coin_uid ? infoUser.coin_uid : 0)).subscribe(
                  (resp) => {
                    this.coins = (resp['external_coins'] ? parseInt(resp['external_coins']) : 0)
                      + (resp['credit_coins'] ? parseInt(resp['credit_coins']) : 0); parseInt(resp['external_coins']) + parseInt(resp['credit_coins']);
                  },
                  (error) => {
                    console.log("Error coins", error);
                  }
                );
              }
            );
          }
        });
      }
    });
  }

  goToPlayers() {
    this.analyticsService.logEvent('Players Click', this.utilsService.categoryHome);
    this.router.navigate(["/app/tabs/home/player"]);
  }

  async getStatisticsUrl() {
    let baseUrl = (await this.cityProvider.getAdminUrl());
    this.statisticUrlOnly = this.sanitizer(baseUrl + '/statistics/showData/only?_dc=' + this.time);
    this.statisticUrlStanding = this.sanitizer(baseUrl + '/statistics/showData/standing?_dc=' + this.time);
  }

  goToClubContent() {
    this.analyticsService.logEvent('Club Content Click', this.utilsService.categoryHome);
    this.router.navigate(["/club-content"]);
  }

  getStatisticsUrlOnly(): SafeResourceUrl {
    return this.statisticUrlOnly;
  }

  getStatisticsUrlStanding(): SafeResourceUrl {
    return this.statisticUrlStanding;
  }

  async getNotifications() {
    this.notificationsNotViewedCount = 0;
    let viewedNotificationsCount = localStorage.getItem('viewedNotificationsCount') ?? 0;
    (await this.notificationService.getNotificationsCount()).subscribe((resp: any) => {
      this.notificationsCount = resp;
      this.notificationsNotViewedCount = this.notificationsCount - Number(viewedNotificationsCount);
    });
  }

  goToSection(sectionName: string, url: string, link: any = null) {
    let section: any = this.dataSections.find(function (item: any) { return item.name == sectionName; });
    if (section) {
      this.sectionService.sectionName = '';
      this.analyticsService.logEvent(sectionName + ' Click', this.utilsService.categoryHome);
      if (!link) {
        this.router.navigate([url]);
      } else if (link.includes('&iframe')) {
        link = link.split('&iframe')[0];
        if (url.includes('browser')) {
          this.utilsService.openLink(link);
        } else {
          this.homeProvider._urlIframe = link;
          this.router.navigate(['/website/' + sectionName]);
        }
      } else {
        this.utilsService.openLink(link);
      }
    }
  }

  getButtonBackgroundColor(background) {
    if (background) {
      return {
        "background": "linear-gradient(135deg, " + background + " 50%, black 150%)"
      };
    }
  }

  getTextAndIconColor(color) {
    if (color) {
      return {
        "color": "" + color + ""
      };
    }
  }

  getBase64Data() {
    const data = `{
      “countryCode”: “+57”,
      “phoneNumber”: "${this.userInfo.phone}",
      “email”: "${this.userInfo.email}",
      “username”: "${this.userInfo.document}",
      “country”: “Colombia”,
      “dob”: "${this.userInfo.user_info.dob}"
    }`;
    const base64EncodedData = Buffer.from(data).toString('base64');
    return base64EncodedData;
  }

  async getSectionHome() {
    let sectionArray = [];
    let nameSection = [];
    var oDivElement = null;
    var oDivElementDelete = null;
    const children = this.parentRef.nativeElement;
    var parentElement = this.parentRef.nativeElement;
    var divImgElement = [];

    // Obtengo los label de los children
    children.childNodes.forEach(function check(child: any) {
      if (child.id) {
        child.style.display = 'none';
      }
      if (child.nodeType === Node.TEXT_NODE) {
        nameSection.push(child.nodeValue.trim());
      }
      child.childNodes.forEach(check);
    });
    nameSection.join(' ');

    // Obtengo las sesiones que estan en el panel
    await this.sectionService.getSections().then((resp: any) => {
      sectionArray = resp.data.sort((a, b) => a.button_order - b.button_order).filter(function (item: any) { return item.enable_section_on_home == 1 || item.enable_section_on_home == 0 });
      this.allDataSections = resp.data;
      this.dataSections = resp.data.sort((a: any, b: any) => a.button_order - b.button_order).filter(function (item: any) { return item.enable_on_home });
      this.getPublications();
    });

    // Filtramos si existe las sesiones en la app y panel
    const sessionFilter = sectionArray.filter((elem) => {
      return nameSection.some((ele) => {
        return ele === elem.name;
      });
    }).reverse();

    if (sessionFilter) {
      var firstChild;
      for (var i = 0; i < sessionFilter.length; i++) {
        if (sessionFilter[i].name && sessionFilter[i].enable_section_on_home == 1) {
          //Funcion que busca el child
          oDivElement = await this.getParentFromLabel(sessionFilter[i].name);
          if (sessionFilter[i].link_section_home) {
            divImgElement = oDivElement.querySelectorAll('img');
            if (divImgElement.length > 0) {
              divImgElement[0].src = sessionFilter[i].link_section_home;
            }
          }
          oDivElement.style.display = '';
          oDivElement.firstChild.value = [];
          if (i == sessionFilter.length - 1) {
            firstChild = oDivElement.firstChild;
          }
          parentElement.insertBefore(oDivElement, parentElement.firstChild);
        } else {
          oDivElementDelete = await this.getParentFromLabel(sessionFilter[i].name);
          oDivElementDelete.style.display = 'none';
        }
      }
      if (firstChild) {
        firstChild.value = ['first'];
      }
    }
  }

  async getParentFromLabel(labelName) {
    var parentElement = this.parentRef.nativeElement;
    let nameSection = [];
    var oDivElement = null;
    parentElement.childNodes.forEach(function check(child) {
      if (child.nodeType === Node.TEXT_NODE) {
        nameSection.push(child.nodeValue.trim());
        if (labelName === child.nodeValue.trim()) {
          oDivElement = child.parentElement.parentElement.parentElement.parentElement.parentElement;
        }
      }
      child.childNodes.forEach(check);
    });
    return oDivElement;
  }

  scrollTo(y) {
    setTimeout(() => {
      this.content.scrollToPoint(0, (y.screenY), 500);
    }, 200);
  }

  checkAttributeValue(value: string): boolean {
    return this.allDataSections.some(obj => obj.name.includes(value));
  }
}