All files / src/lib/pluginManager repo.ts

29.58% Statements 42/142
0% Branches 0/41
0% Functions 0/15
26.15% Lines 34/130

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 2451x 1x 1x         1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x       1x                 1x       1x   1x                         1x         1x                                                 1x                                     1x                                                 1x         1x                                                                                                                                                                             1x                                      
import fetch from "node-fetch";
import settings from "electron-settings";
import {
  isPluginRepositoryEntry,
  PluginRepositoryEntry,
  PluginRepositoryMetadata,
} from "./types";
import { Value } from "@sinclair/typebox/value";
import { checksumString } from "lib/helpers/checksum";
import { join, dirname, relative } from "path";
import l10n from "shared/lib/lang/l10n";
import { createWriteStream, remove } from "fs-extra";
import getTmp from "lib/helpers/getTmp";
import AdmZip from "adm-zip";
import rimraf from "rimraf";
import { promisify } from "util";
import confirmDeletePlugin from "lib/electron/dialog/confirmDeletePlugin";
import { removeEmptyFoldersBetweenPaths } from "lib/helpers/fs/removeEmptyFoldersBetweenPaths";
import { satisfies } from "semver";
import confirmIncompatiblePlugin from "lib/electron/dialog/confirmIncompatiblePlugin";
import { dialog } from "electron";
import confirmDeletePluginRepository from "lib/electron/dialog/confirmDeletePluginRepository";
import { guardAssetWithinProject } from "lib/helpers/assets";
import { OFFICIAL_REPO_URL } from "consts";
import { isGlobalPluginType } from "shared/lib/plugins/pluginHelpers";
import { ensureGlobalPluginsPath } from "./globalPlugins";
 
const rmdir = promisify(rimraf);
 
declare const VERSION: string;
 
export const corePluginRepository: PluginRepositoryEntry = {
  id: "core",
  name: "GB Studio",
  url: OFFICIAL_REPO_URL,
};
 
const cache: {
  value: PluginRepositoryMetadata[];
  timestamp: number;
} = {
  value: [],
  timestamp: 0,
};
const oneHour = 60 * 60 * 1000;
 
export const getUserReposList = (): PluginRepositoryEntry[] => {
  const userRepositories: PluginRepositoryEntry[] = [];
  const storedUserRepositories: unknown = settings.get("plugins:repositories");
  Iif (Array.isArray(storedUserRepositories)) {
    for (const entry of storedUserRepositories) {
      Iif (isPluginRepositoryEntry(entry)) {
        userRepositories.push(entry);
      }
    }
  }
  return userRepositories;
};
 
export const getReposList = (): PluginRepositoryEntry[] => {
  const userRepositories = getUserReposList();
  return [corePluginRepository, ...userRepositories];
};
 
export const addUserRepo = async (url: string) => {
  try {
    const userRepositories = getUserReposList();
    const data = await (await fetch(url)).json();
    const castData = Value.Cast(PluginRepositoryMetadata, data);
    const name = castData.shortName || castData.name;
    Iif (!name) {
      throw new Error('Repository "name" is missing');
    }
    const updated: PluginRepositoryEntry[] = [
      ...userRepositories.filter((entry) => {
        return entry.url !== url;
      }),
      {
        id: checksumString(url),
        name,
        url,
      },
    ];
    settings.set("plugins:repositories", updated);
  } catch (e) {
    dialog.showErrorBox(l10n("ERROR_PLUGIN_REPOSITORY_NOT_FOUND"), String(e));
  }
};
 
export const removeUserRepo = async (url: string) => {
  const userRepositories = getUserReposList();
  const repo = userRepositories.find((entry) => entry.url === url);
 
  Iif (!repo) {
    return;
  }
 
  const cancel = confirmDeletePluginRepository(repo.name, url);
  Iif (cancel) {
    return;
  }
 
  const updated = userRepositories.filter((entry) => {
    return entry.url !== url;
  });
  settings.set("plugins:repositories", updated);
};
 
export const getGlobalPluginsList = async (force?: boolean) => {
  const now = new Date().getTime();
  Iif (!force && cache.timestamp > now) {
    return cache.value;
  }
  const reposList = getReposList();
  const repos: PluginRepositoryMetadata[] = [];
  for (const repo of reposList) {
    try {
      const data = await (await fetch(repo.url)).json();
      const castData = Value.Cast(PluginRepositoryMetadata, data);
      repos.push({
        ...castData,
        id: repo.id,
        url: repo.url,
      });
    } catch (e) {
      dialog.showErrorBox(l10n("ERROR_PLUGIN_REPOSITORY_NOT_FOUND"), String(e));
    }
  }
  cache.value = repos;
  cache.timestamp = now + oneHour;
  return repos;
};
 
export const getRepoUrlById = (id: string): string | undefined => {
  const reposList = getReposList();
  return reposList.find((repo) => repo.id === id)?.url;
};
 
export const addPluginToProject = async (
  projectPath: string,
  pluginId: string,
  repoId: string
) => {
  try {
    const repoURL = getRepoUrlById(repoId);
    Iif (!repoURL) {
      throw new Error(l10n("ERROR_PLUGIN_REPOSITORY_NOT_FOUND"));
    }
    const repoRoot = dirname(repoURL);
    const repos = await getGlobalPluginsList();
    const repo = repos?.find((r) => r.id === repoId);
    Iif (!repo) {
      throw new Error(l10n("ERROR_PLUGIN_REPOSITORY_NOT_FOUND"));
    }
    const plugin = repo.plugins.find((p) => p.id === pluginId);
    Iif (!plugin) {
      throw new Error(l10n("ERROR_PLUGIN_NOT_FOUND"));
    }
 
    const pluginURL =
      plugin.filename.startsWith("http:") ||
      plugin.filename.startsWith("https:")
        ? plugin.filename
        : join(repoRoot, plugin.filename);
 
    let outputPath = "";
 
    if (isGlobalPluginType(plugin.type)) {
      const globalPluginsPath = await ensureGlobalPluginsPath();
      outputPath = join(globalPluginsPath, pluginId);
    } else {
      Iif (!projectPath) {
        dialog.showErrorBox(
          l10n("ERROR_NO_PROJECT_IS_OPEN"),
          l10n("ERROR_OPEN_A_PROJECT_TO_ADD_PLUGIN")
        );
        return;
      }
      const projectRoot = dirname(projectPath);
      outputPath = join(projectRoot, "plugins", pluginId);
      guardAssetWithinProject(outputPath, projectRoot);
    }
 
    // Remove -rc* to treat release candidates as identical
    // to releases when confirming plugins are compatible
    // (alpha and beta versions will always warn)
    const releaseVersion = VERSION.replace(/-rc.*/, "");
    Iif (plugin.gbsVersion && !satisfies(releaseVersion, plugin.gbsVersion)) {
      const cancel = confirmIncompatiblePlugin(
        releaseVersion,
        plugin.gbsVersion
      );
      Iif (cancel) {
        return;
      }
    }
 
    const res = await fetch(pluginURL);
 
    const tmpDir = getTmp();
    const tmpPluginZipPath = join(
      tmpDir,
      `${checksumString(`${repoId}::${pluginId}`)}.zip`
    );
 
    const fileStream = createWriteStream(tmpPluginZipPath);
    await new Promise((resolve, reject) => {
      res.body?.pipe(fileStream);
      res.body?.on("error", reject);
      fileStream.on("finish", resolve);
    });
 
    // Extract plugin
    const zip = new AdmZip(tmpPluginZipPath);
    zip.extractAllTo(outputPath, true);
 
    // Remove tmp files
    await remove(tmpPluginZipPath);
 
    return outputPath;
  } catch (e) {
    dialog.showErrorBox(l10n("ERROR_UNABLE_TO_INSTALL_PLUGIN"), String(e));
  }
};
 
export const removePluginFromProject = async (
  projectPath: string,
  pluginId: string
) => {
  const projectRoot = dirname(projectPath);
  const pluginsPath = join(projectRoot, "plugins");
  const outputPath = join(pluginsPath, pluginId);
  guardAssetWithinProject(outputPath, projectRoot);
 
  const cancel = confirmDeletePlugin(
    pluginId,
    relative(projectRoot, outputPath)
  );
  Iif (cancel) {
    return;
  }
  await rmdir(outputPath);
  await removeEmptyFoldersBetweenPaths(pluginsPath, dirname(outputPath));
};