All files / app/service editor.service.ts

20.5% Statements 41/200
12.17% Branches 19/156
28.2% Functions 11/39
19.04% Lines 32/168

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 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 34080x           80x     80x 80x 80x                   80x     41x 41x 41x 41x   41x                     41x                           41x                             41x                                                                                           41x                                         41x                                         41x 41x 41x 41x 41x                                                                                                                                         1x       1x   1x 1x 1x       1x       1x   1x           1x                                                                                           2x           2x                                                                  
import { Injectable } from '@angular/core';
import { UntypedFormArray, UntypedFormBuilder, UntypedFormGroup } from '@angular/forms';
import Europa from 'europa';
import { Plugin, PluginApi, PluginConverter } from 'europa-core';
import { difference, uniq } from 'lodash-es';
import { forkJoin, map, Observable, of, switchMap } from 'rxjs';
import { TagsFormComponent } from '../form/tags/tags.component';
import { Ext } from '../model/ext';
import { Store } from '../store/store';
import { getMailboxes } from '../util/editor';
import { getPath } from '../util/http';
import { access, removePrefix, setPublic } from '../util/tag';
import { AdminService } from './admin.service';
import { ExtService } from './api/ext.service';
import { ConfigService } from './config.service';
 
export type TagPreview = { name?: string,  bookmark?: string, tag: string } | Ext;
 
@Injectable({
  providedIn: 'root'
})
export class EditorService {
 
  constructor(
    private config: ConfigService,
    private admin: AdminService,
    private exts: ExtService,
    private store: Store,
  ) {
    const superscriptProvider = (api: PluginApi): Plugin => ({
      converters: {
        SUP: {
          startTag(conversion): boolean {
            conversion.output('^');
            conversion.atNoWhitespace = true;
            return true;
          },
        },
      },
    });
    const paragraphConverter: PluginConverter = {
      startTag(conversion, context): boolean {
        // @ts-ignore
        if (conversion.atParagraph || conversion.inline) return true;
        conversion.appendParagraph();
        return true;
      },
 
      endTag(conversion, context) {
        // @ts-ignore
        if (conversion.inline) return;
        conversion.appendParagraph();
      },
    };
    const paragraphProvider = (api: PluginApi): Plugin => ({
      converters: {
        ADDRESS: paragraphConverter,
        ARTICLE: paragraphConverter,
        ASIDE: paragraphConverter,
        DIV: paragraphConverter,
        FIELDSET: paragraphConverter,
        FOOTER: paragraphConverter,
        HEADER: paragraphConverter,
        MAIN: paragraphConverter,
        NAV: paragraphConverter,
        P: paragraphConverter,
        SECTION: paragraphConverter,
      },
    });
    const linkProvider = (api: PluginApi): Plugin => ({
      converters: {
        A: {
          startTag(conversion, context): boolean {
            const absolute = conversion.getOption('absolute');
            const inline = conversion.getOption('inline');
            const { element } = conversion;
            const href = element.attr('href');
            if (!href) {
              return true;
            }
 
            // Set inline flag
            // @ts-ignore
            conversion.inline = true;
 
            const title = element.attr('title');
            const url = absolute ? conversion.resolveUrl(href) : href;
            let value = title ? `${url} "${title}"` : url;
 
            if (inline) {
              value = `(${value})`;
            } else {
              const reference = conversion.addReference('link', value);
              value = `[${reference}]`;
            }
 
            context.set('value', value);
            conversion.output('[');
            conversion.atNoWhitespace = true;
 
            return true;
          },
 
          endTag(conversion, context) {
            if (context.has('value')) {
              conversion.output(`]${context.get<string>('value')}`);
 
              // Unset inline flag
              // @ts-ignore
              conversion.inline = false;
            }
          }
        }
      }
    });
    const audioProvider = (api: PluginApi): Plugin => ({
      converters: {
        AUDIO: {
          startTag(conversion): boolean {
            const { element } = conversion;
            const source = element.find('source')?.attr('src');
            if (!source) {
              return false; // No source found, skip
            }
 
            const absolute = conversion.getOption('absolute');
            const url = absolute ? conversion.resolveUrl(source) : source;
            const value = `(${url})`;
 
            conversion.output(`![]${value}`);
 
            return false;
          },
        },
      }
    });
    const videoProvider = (api: PluginApi): Plugin => ({
      converters: {
        VIDEO: {
          startTag(conversion): boolean {
            const { element } = conversion;
            const source = element.find('source')?.attr('src');
            if (!source) {
              return false; // No source found, skip
            }
 
            const absolute = conversion.getOption('absolute');
            const url = absolute ? conversion.resolveUrl(source) : source;
            const value = `(${url})`;
 
            conversion.output(`![]${value}`);
 
            return false;
          },
        },
      }
    });
    Europa.registerPlugin(superscriptProvider);
    Europa.registerPlugin(paragraphProvider);
    Europa.registerPlugin(linkProvider);
    Europa.registerPlugin(audioProvider);
    Europa.registerPlugin(videoProvider);
  }
 
  getUrlType(url: string) {
    if (url.startsWith(this.config.base)) {
      url = url.substring(this.config.base.length);
    }
    const basePath = getPath(this.config.base)!;
    if (url.startsWith(basePath)) {
      url = url.substring(basePath.length);
    }
    if (url.startsWith('/')) {
      url = url.substring(1);
    }
    return url.substring(0, url.indexOf('/'));
  }
 
  getRefUrl(url: string): string {
    if (url.startsWith('unsafe:')) url = url.substring('unsafe:'.length);
    const refPrefix = this.config.base + 'ref/';
    let ending = '';
    if (url.startsWith(refPrefix)) {
      ending = url.substring(refPrefix.length);
    } else {
      const relRefPrefix = getPath(refPrefix)!;
      if (url.startsWith(relRefPrefix)) {
        ending = url.substring(relRefPrefix.length);
      } else if (url.startsWith('/ref/')) {
        ending = url.substring('/ref/'.length);
      }
    }
    if (!ending) return url;
    if (ending.startsWith('/e/')){
      ending = ending.substring('/e/'.length);
      if (ending.indexOf('/') < 0) return decodeURIComponent(ending);
      return decodeURIComponent(ending.substring(0, ending.indexOf('/')));
    }
    return ending;
  }
 
  /**
   * Gets the query for a query URL.
   */
  getQuery(url: string): string {
    if (url.startsWith('unsafe:')) url = url.substring('unsafe:'.length);
    const tagPrefix = this.config.base + 'tag/';
    let ending = '';
    if (url.startsWith('tag:/')) {
      ending = url.substring('tag:/'.length);
    } else if (url.startsWith(tagPrefix)) {
      ending = url.substring(tagPrefix.length);
    } else {
      const relTagPrefix = getPath(tagPrefix)!;
      if (url.startsWith(relTagPrefix)) {
        ending = url.substring(relTagPrefix.length);
      } else if (url.startsWith('/tag/')) {
        ending = url.substring('/tag/'.length);
      }
    }
    if (!ending) return url;
    if (ending.indexOf('?') < 0) return ending;
    const query = ending.substring(0, ending.indexOf('?'))
    return decodeURIComponent(query);
  }
 
  /**
   * Add mailboxes for tagged users.
   */
  syncEditor(fb: UntypedFormBuilder, group: UntypedFormGroup, previousComment = '') {
    let comment = group.value.comment;
    // Store last synced comment in the form so that we can track what was already synced.
    // This will allow the user to remove a source, alt or tag without it being re-added
    // @ts-ignore
    previousComment ||= group.previousComment || '';
    // @ts-ignore
    group.previousComment = comment;
    this.syncMailboxes(fb, group, previousComment);
    group.get('comment')?.setValue(comment);
  }
 
  private syncMailboxes(fb: UntypedFormBuilder, group: UntypedFormGroup, previousComment = '') {
    const existingTags = [
      ...getMailboxes(previousComment, this.store.account.origin),
      ...(group.value.tags || []),
    ];
    const mailboxes = uniq(difference([
      ...getMailboxes(group.value.comment, this.store.account.origin)], existingTags));
    for (const t of mailboxes) {
      (group.get('tags') as UntypedFormArray).push(fb.control(t, TagsFormComponent.validators));
    }
  }
 
  getTagPreview(tag: string, defaultOrigin = '', returnDefault = true, loadTemplates = true, loadPlugins = true): Observable<{ name?: string, tag: string } | undefined> {
    return this.exts.getCachedExt(tag, defaultOrigin).pipe(
      switchMap(x => {
        const localExists = x.modified && x.origin === (defaultOrigin || this.store.account.origin);
        if (loadTemplates) {
          const templates = this.admin.getTemplates(x.tag).filter(t => t.tag);
          if (templates.length) {
            const longestMatch = templates[templates.length - 1];
            if (!localExists) {
              if (x.tag === '+user') return of({ ...x, name: (longestMatch.config?.view || longestMatch.name || longestMatch.tag) + ' / ' + $localize`⚓️ Root` });
              if (x.tag === '_user') return of({ ...x, name: (longestMatch.config?.view || longestMatch.name || longestMatch.tag) + ' / ' + $localize`🥷 Root` });
            }
            if (x.tag === longestMatch.tag) return of(longestMatch);
            const childTag = removePrefix(x.tag, longestMatch.tag.split('/').length);
            return of({ tag: x.tag, name: (longestMatch.config?.view || longestMatch.name || longestMatch.tag) + ' / ' + (x.name || childTag) });
          }
        }
        if (localExists) return of(x);
        const plugin = this.admin.getPlugin(x.tag);
        if (loadPlugins) {
          if (plugin) return of(plugin);
          const parentPlugins = this.admin.getParentPlugins(x.tag);
          if (parentPlugins.length) {
            const longestMatch = parentPlugins[parentPlugins.length - 1];
            if (x.tag === longestMatch.tag) return of(longestMatch);
            const childTag = removePrefix(x.tag, longestMatch.tag.split('/').length);
            if (longestMatch.tag === 'plugin/outbox') {
              const origin = childTag.substring(0, childTag.indexOf('/'));
              const remoteTag = childTag.substring(origin.length + 1);
              const originFormat = origin ? ' @' + origin : '';
              return this.exts.getCachedExt(remoteTag, origin).pipe(
                map(c => ({ tag: x.tag, name: (longestMatch.name || longestMatch.tag) + ' / ' + (c.name || c.tag) + originFormat })),
              );
            }
            let a = access(x.tag) || '+';
            return this.exts.getCachedExt(a + setPublic(childTag), defaultOrigin).pipe(
              map(c => ({ tag: x.tag, name: (longestMatch.config?.view || longestMatch.name || longestMatch.tag) + ' / ' + (c.name || setPublic(childTag)) })),
            );
          }
        }
        if (x.modified || returnDefault) return of(x);
        return of(undefined);
      })
    );
  }
 
  getTagsPreview(tags: string[], defaultOrigin = ''): Observable<TagPreview[]> {
    return forkJoin(tags.map( t => this.getTagPreview(t, defaultOrigin))).pipe(
      map(xs => xs.filter(x => !!x)),
    );
  }
 
  getBookmarksPreview(bookmarks: string[], defaultOrigin = ''): Observable<TagPreview[]> {
    return forkJoin(bookmarks.map(b => {
      const query = b.includes('?') ? b.substring(0, b.indexOf('?')) : b;
      return this.getQueryPreviewName(query, defaultOrigin).pipe(
        map(name => ({ name, tag: query, bookmark: b })),
      );
    })).pipe(
      map(xs => xs.filter(x => !!x)),
    ) as Observable<TagPreview[]>;
  }
 
  /** Build a display name for a query by replacing each tag token with its ext preview name. */
  getQueryPreviewName(query: string, defaultOrigin = ''): Observable<string | undefined> {
    const tokens = query.split(/([:|()])/g).filter(t => !!t);
    const ops = new Set([':', '|', '(', ')']);
    const tagIndices = tokens.reduce<number[]>((acc, t, i) => ops.has(t) ? acc : [...acc, i], []);
    if (tagIndices.length === 0) return of(undefined);
    return forkJoin(tagIndices.map(i => {
      const token = tokens[i];
      const bareTag = token.startsWith('!') ? token.substring(1) : token;
      return this.getTagPreview(bareTag, defaultOrigin).pipe(
        map(x => {
          const name = x?.name || bareTag;
          return token.startsWith('!') ? '!' + name : name;
        }),
      );
    })).pipe(
      map(names => {
        let idx = 0;
        return tokens.map(t => ops.has(t) ? t : names[idx++]).join('');
      }),
    );
  }
}