All files / app/component/ext ext.component.ts

36.3% Statements 53/146
24.07% Branches 13/54
23.07% Functions 9/39
35.87% Lines 47/131

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295                                        67x 67x   67x     67x             67x 67x 67x 67x 67x 67x   67x                               67x 1x               1x     1x 1x 1x 1x 1x     1x 1x   1x 1x 1x   1x     1x 1x 1x 1x 1x 1x 1x                                                                                   2x         2x         1x       67x         67x 1x 1x         67x 1x       67x 1x 1x       67x 1x                                                                                                                                                                                                   1x                                                  
import { AsyncPipe } from '@angular/common';
import { HttpErrorResponse } from '@angular/common/http';
import {
  Component,
  forwardRef,
  HostBinding,
  Input,
  OnChanges,
  QueryList,
  SimpleChanges,
  ViewChild,
  ViewChildren
} from '@angular/core';
import { ReactiveFormsModule, UntypedFormBuilder, UntypedFormGroup } from '@angular/forms';
import { RouterLink } from '@angular/router';
import { isObject } from 'lodash-es';
import { DateTime } from 'luxon';
import { toJS } from 'mobx';
import { catchError, of, switchMap, throwError } from 'rxjs';
import { tap } from 'rxjs/operators';
import { TitleDirective } from '../../directive/title.directive';
import { extForm, ExtFormComponent } from '../../form/ext/ext.component';
import { HasChanges } from '../../guard/pending-changes.guard';
import { equalsExt, Ext, writeExt } from '../../model/ext';
import { Plugin } from '../../model/plugin';
import { Template } from '../../model/template';
import { isDeletorTag, tagDeleteNotice } from '../../mods/delete';
import { AdminService } from '../../service/admin.service';
import { ExtService } from '../../service/api/ext.service';
import { AuthzService } from '../../service/authz.service';
import { BookmarkService } from '../../service/bookmark.service';
import { EditorService } from '../../service/editor.service';
import { Store } from '../../store/store';
import { downloadTag } from '../../util/download';
import { scrollToFirstInvalid } from '../../util/form';
import { tagLink } from '../../util/format';
import { printError } from '../../util/http';
import { memo, MemoCache } from '../../util/memo';
import { hasPrefix, parentTag } from '../../util/tag';
import { ActionComponent } from '../action/action.component';
import { ConfirmActionComponent } from '../action/confirm-action/confirm-action.component';
 
@Component({
  selector: 'app-ext',
  templateUrl: './ext.component.html',
  styleUrls: ['./ext.component.scss'],
  host: { 'class': 'ext list-item' },
  imports: [
    forwardRef(() => ExtFormComponent),
    RouterLink,
    TitleDirective,
    ConfirmActionComponent,
    ReactiveFormsModule,
    AsyncPipe,
  ],
})
export class ExtComponent implements OnChanges, HasChanges {
  @HostBinding('attr.tabindex') tabIndex = 0;
 
  @ViewChildren('action')
  actionComponents?: QueryList<ActionComponent>;
 
  @Input()
  ext!: Ext;
  @Input()
  useEditPage = false;
 
  editForm!: UntypedFormGroup;
  submitted = false;
  invalid = false;
  overwritten = false;
  overwrite = true;
  icons: Template[] = [];
  template?: Template;
  plugin?: Plugin;
  editing = false;
  viewSource = false;
  @HostBinding('class.deleted')
  deleted = false;
  writeAccess = false;
  serverError: string[] = [];
 
  private overwrittenModified? = '';
 
  constructor(
    public admin: AdminService,
    public store: Store,
    private auth: AuthzService,
    private exts: ExtService,
    private editor: EditorService,
    public bookmarks: BookmarkService,
    private fb: UntypedFormBuilder,
  ) { }
 
  saveChanges() {
    return !this.editForm?.dirty;
  }
 
  init() {
    MemoCache.clear(this);
    this.submitted = false;
    this.invalid = false;
    this.overwrite = false;
    this.overwritten = false;
    this.template = this.admin.getTemplate(this.ext.tag);
    this.plugin = this.admin.getPlugin(this.ext.tag);
    this.editing = false;
    this.viewSource = false;
    this.deleted = false;
    this.writeAccess = false;
    this.serverError = [];
    this.actionComponents?.forEach(c => c.reset());
    if (this.ext) {
      this.icons = this.admin.getTemplateView(this.ext.tag);
      if (hasPrefix(this.ext.tag, 'user')) {
        this.icons.push({tag: 'user', config: { view: $localize`🧑️` }});
      }
      this.editForm = extForm(this.fb, this.ext, this.admin, true);
      this.writeAccess = this.auth.tagWriteAccess(this.qualifiedTag);
    } else {
      this.icons = [];
      this.writeAccess = false;
    }
  }
 
  ngOnChanges(changes: SimpleChanges) {
    if (changes.ext) {
      this.init();
    }
  }
 
  @HostBinding('class.upload')
  get uploadedFile() {
    return this.ext.upload;
  }
 
  @HostBinding('class.exists')
  get existsFile() {
    return this.ext.exists;
  }
 
  @ViewChild('extForm')
  set extForm(value: ExtFormComponent) {
    value?.setValue(toJS(this.ext));
  }
 
  @memo
  get qualifiedTag() {
    return this.ext.tag + this.ext.origin;
  }
 
  @memo
  get parent() {
    const p = parentTag(this.ext.tag);
    Eif (!p) return p;
    return tagLink(p, this.ext.origin, this.store.account.origin);
  }
 
  @memo
  get local() {
    return this.ext.origin === this.store.account.origin;
  }
 
  @memo
  get extLink() {
    Iif (this.admin.local.find(t => hasPrefix(this.ext.tag, t.tag))) return this.ext.tag + (this.ext.origin || '@');
    return tagLink(this.ext.tag, this.ext.origin, this.store.account.origin);
  }
 
  @memo
  get preview() {
    return this.editor.getTagPreview(this.ext.tag, this.ext.origin);
  }
 
  save() {
    this.submitted = true;
    this.editForm.markAllAsTouched();
    if (!this.editForm.valid) {
      scrollToFirstInvalid();
      return;
    }
    let ext = {
      ...this.editForm.value,
      tag: this.ext.tag, // Need to fetch because control is disabled
      modifiedString: this.overwrite ? this.overwrittenModified : this.ext.modifiedString,
    };
    const config = this.ext.config;
    ext = {
      ...this.ext,
      ...ext,
      config: {
        ...isObject(config) ? config : {},
        ...ext.config,
      },
    };
    if (this.ext.upload) {
      ext.upload = true;
      this.ext = ext;
      this.store.submit.setExt(this.ext);
    } else {
      this.exts.update(ext).pipe(
        switchMap(() => this.exts.get(this.qualifiedTag)),
        catchError((res: HttpErrorResponse) => {
          if (res.status === 400) {
            this.invalid = true;
            console.log(res.message);
            // TODO: read res.message to find which fields to delete
          }
          if (res.status === 409) {
            this.overwritten = true;
            this.exts.get(this.qualifiedTag).subscribe(x => this.overwrittenModified = x.modifiedString);
          }
          this.serverError = printError(res);
          return throwError(() => res);
        }),
      ).subscribe(ext => {
        this.editForm.reset();
        this.ext = ext;
        this.init();
      });
    }
  }
 
  upload() {
    (this.store.submit.overwrite
      ? this.exts.update({ ...this.ext, origin: this.store.account.origin })
      : this.exts.create({ ...this.ext, origin: this.store.account.origin })).pipe(
      catchError((err: HttpErrorResponse) => {
        this.serverError = printError(err);
        return throwError(() => err);
      }),
    ).subscribe(cursor => {
      this.ext.modifiedString = cursor;
      this.ext.modified = DateTime.fromISO(cursor);
      this.ext.origin = this.store.account.origin;
      this.store.submit.removeExt(this.ext);
      this.init();
    });
  }
 
  copy() {
    const copied: Ext = {
      ...this.ext,
      origin: this.store.account.origin,
    };
    this.exts.create(copied).pipe(
      catchError((err: HttpErrorResponse) => {
        if (err.status === 409) {
          return this.exts.get(this.qualifiedTag).pipe(
            switchMap(ext => {
              if (equalsExt(ext, copied) || confirm('An old version already exists. Overwrite it?')) {
                // TODO: Show diff and merge or split
                return this.exts.update(copied);
              } else {
                return throwError(() => 'Cancelled')
              }
            })
          );
        }
        this.serverError = printError(err);
        return throwError(() => err);
      }),
      switchMap(() => this.exts.get(this.ext.tag + this.store.account.origin)),
    ).subscribe(ext => {
      this.ext = ext;
      this.init();
    });
  }
 
  delete$ = () => {
    this.serverError = [];
    if (this.ext.upload) {
      this.store.submit.removeExt(this.ext);
      this.deleted = true;
      return of(null);
    } else {
      const deleteNotice = !isDeletorTag(this.ext.tag) && this.admin.getPlugin('plugin/delete')
        ? this.exts.create(tagDeleteNotice(this.ext))
        : of(null);
      return this.exts.delete(this.qualifiedTag).pipe(
        tap(() => this.deleted = true),
        switchMap(() => deleteNotice),
        catchError((err: HttpErrorResponse) => {
          this.serverError = printError(err);
          return throwError(() => err);
        }),
      );
    }
  }
 
  download() {
    downloadTag(writeExt(this.ext));
  }
}