All files / app/service action.service.ts

9.65% Statements 14/145
5% Branches 5/100
1.88% Functions 1/53
8% Lines 10/125

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 27672x               72x   72x 72x                 72x     21x 21x 21x 21x 21x                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                
import { Injectable } from '@angular/core';
import { debounce, isArray, without } from 'lodash-es';
import { DateTime } from 'luxon';
import { runInAction } from 'mobx';
import { catchError, concat, last, merge, Observable, of, Subscription, switchMap, throwError } from 'rxjs';
import { tap } from 'rxjs/operators';
import { PluginApi } from '../model/plugin';
import { Ref } from '../model/ref';
import { Action, EmitAction, emitModels } from '../model/tag';
import { Store } from '../store/store';
import { merge3 } from '../util/diff';
import { hasTag } from '../util/tag';
import { ExtService } from './api/ext.service';
import { RefService } from './api/ref.service';
import { StompService } from './api/stomp.service';
import { TaggingService } from './api/tagging.service';
 
@Injectable({
  providedIn: 'root'
})
export class ActionService {
 
  constructor(
    private refs: RefService,
    private exts: ExtService,
    private tags: TaggingService,
    private store: Store,
    private stomp: StompService,
  ) { }
 
  wrap(ref?: Ref): PluginApi {
    let o: Subscription | undefined = undefined;
    return {
      comment: debounce((comment: string) => {
        if (!ref) throw 'Error: No ref to save';
        o?.unsubscribe();
        o = this.comment$(comment, ref).subscribe();
      }, 500),
      event: (event: string) => {
        this.event(event, ref);
      },
      emit: (a: EmitAction) => {
        this.emit(a, ref);
      },
      tag: (tag: string) => {
        if (!ref) throw 'Error: No ref to tag';
        this.tag(tag, ref);
      },
      respond: (response: string, clear?: string[]) => {
        if (!ref) throw 'Error: No ref to respond to';
        this.respond(response, clear || [], ref);
      },
      watch: (delimiter?: string) => {
        if (!ref) throw 'Error: No ref to respond to';
        return this.watch(ref, delimiter);
      },
      append: () => {
        if (!ref) throw 'Error: No ref to respond to';
        return this.append(ref);
      }
    }
  }
 
  apply$(actions: Action | Action[], ref: Ref, repost?: Ref) {
    if (!isArray(actions)) actions = [actions];
    const updates: Observable<any>[] = [];
    for (const a of actions) {
      if ('tag' in a) {
        updates.push(this.tag$(a.tag, ref));
      }
      if ('response' in a) {
        updates.push(this.respond$(a.response, a.clear || [], ref));
      }
      if ('event' in a) {
        updates.push(this.event$(a.event, ref, repost));
      }
      if ('emit' in a) {
        updates.push(this.emit$(a, ref));
      }
    }
    if (!updates.length) return of(null);
    return this.store.eventBus.runAndReload$(concat(...updates).pipe(last()), ref);
  }
 
  event(event: string, ref?: Ref, repost?: Ref) {
    this.store.eventBus.fire(event, ref, repost);
    this.store.eventBus.reset();
  }
 
  event$(event: string, ref?: Ref, repost?: Ref) {
    this.store.eventBus.fire(event, ref, repost);
    this.store.eventBus.reset();
    return of(null);
  }
 
  emit(a: EmitAction, ref?: Ref) {
    this.emit$(a, ref).subscribe();
  }
 
  emit$(a: EmitAction, ref?: Ref) {
    const models = emitModels(a, ref, this.store.account.localTag);
    const uploads = [
      ...models.ref.map(ref => this.refs.create(ref)),
      ...models.ext.map(ext => this.exts.create(ext)),
    ];
    return concat(...uploads).pipe(last());
  }
 
  comment(comment: string, ref: Ref) {
    this.store.eventBus.runAndRefresh(this.comment$(comment, ref), ref);
  }
 
  comment$(comment: string, ref: Ref) {
    return this.refs.patch(ref.url, this.store.account.origin, ref.modifiedString!, [{
      op: 'add',
      path: '/comment',
      value: comment,
    }]).pipe(
      catchError(err => {
        if (err.status === 409) {
          return this.refs.get(ref.url, this.store.account.origin).pipe(
            switchMap(ref => this.refs.patch(ref.url, this.store.account.origin, ref.modifiedString!, [{
              op: 'add',
              path: '/comment',
              value: comment,
            }])),
          );
        }
        return throwError(() => err);
      }),
      tap(cursor => runInAction(() => {
        ref.comment = comment;
        ref.modifiedString = cursor;
        ref.modified = DateTime.fromISO(cursor);
      })),
    );
  }
 
  tag(tag: string, ref: Ref) {
    this.store.eventBus.runAndReload(this.tag$(tag, ref), ref);
  }
 
  tag$(tag: string, ref: Ref) {
    const patch = (hasTag(tag, ref) ? '-' : '') + tag;
    return this.tags.create(patch, ref.url, this.store.account.origin);
  }
 
  respond(response: string, clear: string[], ref: Ref) {
    this.store.eventBus.runAndRefresh(this.respond$(response, clear, ref), ref);
  }
 
  respond$(response: string, clear: string[], ref: Ref) {
    if (ref.metadata?.userUrls?.includes(response)) {
      ref.metadata ||= {};
      ref.metadata.userUrls ||= [];
      ref.metadata.userUrls = without(ref.metadata.userUrls, response);
      return this.tags.deleteResponse(response, ref.url);
    } else {
      const tags = [
        ...clear.map(t => '-' + t),
        response,
      ];
      ref.metadata ||= {};
      ref.metadata.userUrls ||= [];
      ref.metadata.userUrls.push(response);
      ref.metadata.userUrls = without(ref.metadata.userUrls, ...clear);
      return this.tags.respond(tags, ref.url);
    }
  }
 
  watch(ref: Ref, delimiter = '\n') {
    let cursor = ref.origin === this.store.account.origin ? ref.modifiedString! : '';
    let baseComment = ref.comment || '';
    const inner = {
      ref$: merge(...this.store.origins.list.map(origin => this.stomp.watchRef(ref.url, origin).pipe(
        tap(u => {
          if (u.origin === this.store.account.origin) cursor = u.modifiedString!;
          baseComment = u.comment || '';
        }),
      ))),
      comment$: (comment: string): Observable<string> => {
        if (!cursor) {
          return this.refs.get(ref.url, this.store.account.origin).pipe(
            tap(ref => {
              cursor = ref.modifiedString!;
              baseComment = ref.comment || '';
            }),
            switchMap(ref => inner.comment$(comment)),
          );
        }
        return this.refs.patch(ref.url, this.store.account.origin, cursor, [{
          op: 'add',
          path: '/comment',
          value: comment,
        }]).pipe(
          tap(c => {
            cursor = c;
            baseComment = comment;
          }),
          catchError(err => {
            if (err.status === 409) {
              // Fetch the current version from server
              return this.refs.get(ref.url, this.store.account.origin).pipe(
                switchMap(remote => {
                  const { result, conflict } = merge3(comment, baseComment, remote.comment || '', delimiter);
                  cursor = remote.modifiedString!;
                  baseComment = remote.comment || '';
                  if (conflict) return throwError(() => ({ conflict }));
                  return inner.comment$(result || '');
                }),
              );
            }
            return throwError(() => err);
          }),
        );
      },
    };
    return inner;
  }
 
  append(ref: Ref) {
    let cursor = ref.origin === this.store.account.origin ? ref.modifiedString! : '';
    let comment = ref.comment || '';
    const inner = {
      updates$: merge(...this.store.origins.list.map(origin => this.stomp.watchRef(ref.url, origin).pipe(
        tap(u => {
          if (u.origin === this.store.account.origin) cursor = u.modifiedString!;
        }),
        switchMap(u => {
          if (comment.startsWith(u?.comment || '')) return of()
          if (!u.comment?.startsWith(comment)) {
            comment = u.comment || '';
            throw u;
          }
          const moves = u.comment.substring(comment.length).split('\n').map(m => m.trim()).filter(m => !!m);
          comment = comment ? `${comment}  \n${moves.join('  \n')}` : moves.join('  \n');
          return moves;
        })
      ))),
      append$: (value: string): Observable<string> => {
        if (!cursor) {
          return this.refs.get(ref.url, this.store.account.origin).pipe(
            tap(ref => cursor = ref.modifiedString!),
            switchMap(ref => inner.append$(value)),
          );
        }
        comment = comment ? `${comment}  \n${value}` : value;
        return this.refs.patch(ref.url, this.store.account.origin, cursor, [{
          op: 'add',
          path: '/comment',
          value: comment,
        }]).pipe(
          tap(c => cursor = c),
        );
      },
      reset$: (value: string[]): Observable<string> => {
        if (!cursor) {
          return this.refs.get(ref.url, this.store.account.origin).pipe(
            tap(ref => cursor = ref.modifiedString!),
            switchMap(ref => inner.reset$(value)),
          );
        }
        comment = value.join('  \n');
        return this.refs.patch(ref.url, this.store.account.origin, cursor, [{
          op: 'add',
          path: '/comment',
          value: comment,
        }]).pipe(
          tap(c => cursor = c),
        );
      },
    };
    return inner;
  }
}