Skip to content

Kavita is a fast, feature rich, cross platform reading server. Built with the goal of being a full solution for all your reading needs. Setup your own server and share your reading collection with your friends and family.

2.7 KB
Raw Blame
import {
  ChangeDetectionStrategy,
  ChangeDetectorRef,
  Component, DestroyRef,
  ElementRef, inject,
  Input,
  OnInit,
  ViewChild
} from '@angular/core';
import {ToastrService} from 'ngx-toastr';
import {ConfirmService} from 'src/app/shared/confirm.service';
import {AccountService} from 'src/app/_services/account.service';
import {Clipboard} from '@angular/cdk/clipboard';
import {takeUntilDestroyed} from "@angular/core/rxjs-interop";
import { NgbTooltip } from '@ng-bootstrap/ng-bootstrap';
import { NgIf } from '@angular/common';
import {translate, TranslocoDirective} from "@ngneat/transloco";

@Component({
    selector: 'app-api-key',
    templateUrl: './api-key.component.html',
    styleUrls: ['./api-key.component.scss'],
    changeDetection: ChangeDetectionStrategy.OnPush,
    standalone: true,
    imports: [NgIf, NgbTooltip, TranslocoDirective]
})
export class ApiKeyComponent implements OnInit {

  @Input() title: string = 'API Key';
  @Input() showRefresh: boolean = true;
  @Input() transform: (val: string) => string = (val: string) => val;
  @Input() tooltipText: string = '';
  @Input() hideData = true;
  @ViewChild('apiKey') inputElem!: ElementRef;
  key: string = '';
  private readonly destroyRef = inject(DestroyRef);

  get InputType() {
    return this.hideData ? 'password' : 'text';
  }

  constructor(private confirmService: ConfirmService, private accountService: AccountService, private toastr: ToastrService, private clipboard: Clipboard,
              private readonly cdRef: ChangeDetectorRef) { }

  ngOnInit(): void {
    this.accountService.currentUser$.pipe(takeUntilDestroyed(this.destroyRef)).subscribe(user => {
      let key = '';
      if (user) {
        key = user.apiKey;
      } else {
        key = translate('api-key.no-key');
      }

      if (this.transform != undefined) {
        this.key = this.transform(key);
        this.cdRef.markForCheck();
      }
    });
  }

  async copy() {
    this.inputElem.nativeElement.select();
    this.clipboard.copy(this.inputElem.nativeElement.value);
    this.inputElem.nativeElement.setSelectionRange(0, 0);
    this.cdRef.markForCheck();
  }

  async refresh() {
    if (!await this.confirmService.confirm(translate('api-key.confirm-reset'))) {
      return;
    }
    this.accountService.resetApiKey().subscribe(newKey => {
      this.key = newKey;
      this.cdRef.markForCheck();
      this.toastr.success(translate('api-key.key-reset'));
    });
  }

  selectAll() {
    if (this.inputElem) {
      this.inputElem.nativeElement.setSelectionRange(0, this.key.length);
      this.cdRef.markForCheck();
    }
  }

  show() {
    this.inputElem.nativeElement.setAttribute('type', 'text');
    this.cdRef.markForCheck();
  }

}