plugin.ts 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. import fs, { readFileSync } from 'fs';
  2. import path from 'path';
  3. import { GrowiThemeMetadata, ViteManifest } from '@growi/core';
  4. // eslint-disable-next-line no-restricted-imports
  5. import axios from 'axios';
  6. import mongoose from 'mongoose';
  7. import streamToPromise from 'stream-to-promise';
  8. import unzipper from 'unzipper';
  9. import {
  10. GrowiPlugin, GrowiPluginOrigin, GrowiPluginResourceType, GrowiThemePluginMeta,
  11. } from '~/interfaces/plugin';
  12. import loggerFactory from '~/utils/logger';
  13. import { resolveFromRoot } from '~/utils/project-dir-utils';
  14. import type { GrowiPluginModel } from '../models/growi-plugin';
  15. const logger = loggerFactory('growi:plugins:plugin-utils');
  16. const pluginStoringPath = resolveFromRoot('tmp/plugins');
  17. // https://regex101.com/r/fK2rV3/1
  18. const githubReposIdPattern = new RegExp(/^\/([^/]+)\/([^/]+)$/);
  19. const PLUGINS_STATIC_DIR = '/static/plugins'; // configured by express.static
  20. export type GrowiPluginResourceEntries = [installedPath: string, href: string][];
  21. function retrievePluginManifest(growiPlugin: GrowiPlugin): ViteManifest {
  22. const manifestPath = resolveFromRoot(path.join('tmp/plugins', growiPlugin.installedPath, 'dist/manifest.json'));
  23. const manifestStr: string = readFileSync(manifestPath, 'utf-8');
  24. return JSON.parse(manifestStr);
  25. }
  26. export interface IPluginService {
  27. install(origin: GrowiPluginOrigin): Promise<void>
  28. retrieveThemeHref(theme: string): Promise<string | undefined>
  29. retrieveAllPluginResourceEntries(): Promise<GrowiPluginResourceEntries>
  30. }
  31. export class PluginService implements IPluginService {
  32. async install(origin: GrowiPluginOrigin): Promise<void> {
  33. // download
  34. const ghUrl = new URL(origin.url);
  35. const ghPathname = ghUrl.pathname;
  36. // TODO: Branch names can be specified.
  37. const ghBranch = 'main';
  38. const match = ghPathname.match(githubReposIdPattern);
  39. if (ghUrl.hostname !== 'github.com' || match == null) {
  40. throw new Error('The GitHub Repository URL is invalid.');
  41. }
  42. const ghOrganizationName = match[1];
  43. const ghReposName = match[2];
  44. const requestUrl = `https://github.com/${ghOrganizationName}/${ghReposName}/archive/refs/heads/${ghBranch}.zip`;
  45. // download github repository to local file system
  46. await this.download(requestUrl, ghOrganizationName, ghReposName, ghBranch);
  47. // save plugin metadata
  48. const installedPath = `${ghOrganizationName}/${ghReposName}`;
  49. const plugins = await PluginService.detectPlugins(origin, installedPath);
  50. await this.savePluginMetaData(plugins);
  51. return;
  52. }
  53. private async download(requestUrl: string, ghOrganizationName: string, ghReposName: string, ghBranch: string): Promise<void> {
  54. const zipFilePath = path.join(pluginStoringPath, `${ghBranch}.zip`);
  55. const unzippedPath = path.join(pluginStoringPath, ghOrganizationName);
  56. const renamePath = async(oldPath: fs.PathLike, newPath: fs.PathLike) => {
  57. fs.renameSync(oldPath, newPath);
  58. };
  59. const downloadFile = async(requestUrl: string, filePath: string) => {
  60. return new Promise<void>((resolve, reject) => {
  61. axios({
  62. method: 'GET',
  63. url: requestUrl,
  64. responseType: 'stream',
  65. })
  66. .then((res) => {
  67. if (res.status === 200) {
  68. const file = fs.createWriteStream(filePath);
  69. res.data.pipe(file)
  70. .on('close', () => file.close())
  71. .on('finish', () => {
  72. return resolve();
  73. });
  74. }
  75. else {
  76. return reject(res.status);
  77. }
  78. }).catch((err) => {
  79. return reject(err);
  80. });
  81. });
  82. };
  83. const unzip = async(zipFilePath: fs.PathLike, unzippedPath: fs.PathLike) => {
  84. const stream = fs.createReadStream(zipFilePath);
  85. const unzipStream = stream.pipe(unzipper.Extract({ path: unzippedPath }));
  86. const deleteZipFile = (path: fs.PathLike) => fs.unlink(path, (err) => { return err });
  87. try {
  88. await streamToPromise(unzipStream);
  89. deleteZipFile(zipFilePath);
  90. }
  91. catch (err) {
  92. return err;
  93. }
  94. };
  95. try {
  96. await downloadFile(requestUrl, zipFilePath);
  97. await unzip(zipFilePath, unzippedPath);
  98. await renamePath(`${unzippedPath}/${ghReposName}-${ghBranch}`, `${unzippedPath}/${ghReposName}`);
  99. }
  100. catch (err) {
  101. logger.error(err);
  102. throw new Error(err);
  103. }
  104. return;
  105. }
  106. private async savePluginMetaData(plugins: GrowiPlugin[]): Promise<void> {
  107. const GrowiPlugin = mongoose.model('GrowiPlugin');
  108. await GrowiPlugin.insertMany(plugins);
  109. }
  110. // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
  111. private static async detectPlugins(origin: GrowiPluginOrigin, installedPath: string, parentPackageJson?: any): Promise<GrowiPlugin[]> {
  112. const packageJsonPath = path.resolve(pluginStoringPath, installedPath, 'package.json');
  113. const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8'));
  114. const { growiPlugin } = packageJson;
  115. const {
  116. name: packageName, description: packageDesc, author: packageAuthor,
  117. } = parentPackageJson ?? packageJson;
  118. if (growiPlugin == null) {
  119. throw new Error('This package does not include \'growiPlugin\' section.');
  120. }
  121. // detect sub plugins for monorepo
  122. if (growiPlugin.isMonorepo && growiPlugin.packages != null) {
  123. const plugins = await Promise.all(
  124. growiPlugin.packages.map(async(subPackagePath) => {
  125. const subPackageInstalledPath = path.join(installedPath, subPackagePath);
  126. return this.detectPlugins(origin, subPackageInstalledPath, packageJson);
  127. }),
  128. );
  129. return plugins.flat();
  130. }
  131. if (growiPlugin.types == null) {
  132. throw new Error('\'growiPlugin\' section must have a \'types\' property.');
  133. }
  134. const plugin = {
  135. isEnabled: true,
  136. installedPath,
  137. origin,
  138. meta: {
  139. name: growiPlugin.name ?? packageName,
  140. desc: growiPlugin.desc ?? packageDesc,
  141. author: growiPlugin.author ?? packageAuthor,
  142. types: growiPlugin.types,
  143. },
  144. };
  145. // add theme metadata
  146. if (growiPlugin.types.includes(GrowiPluginResourceType.Theme)) {
  147. (plugin as GrowiPlugin<GrowiThemePluginMeta>).meta = {
  148. ...plugin.meta,
  149. themes: growiPlugin.themes,
  150. };
  151. }
  152. logger.info('Plugin detected => ', plugin);
  153. return [plugin];
  154. }
  155. async listPlugins(): Promise<GrowiPlugin[]> {
  156. return [];
  157. }
  158. async retrieveThemeHref(theme: string): Promise<string | undefined> {
  159. const GrowiPlugin = mongoose.model('GrowiPlugin') as GrowiPluginModel;
  160. let matchedPlugin: GrowiPlugin | undefined;
  161. let matchedThemeMetadata: GrowiThemeMetadata | undefined;
  162. try {
  163. // retrieve plugin manifests
  164. const growiPlugins = await GrowiPlugin.findEnabledPluginsIncludingAnyTypes([GrowiPluginResourceType.Theme]) as GrowiPlugin<GrowiThemePluginMeta>[];
  165. growiPlugins
  166. .forEach(async(growiPlugin) => {
  167. const themeMetadatas = growiPlugin.meta.themes;
  168. const themeMetadata = themeMetadatas.find(t => t.name === theme);
  169. // found
  170. if (themeMetadata != null) {
  171. matchedPlugin = growiPlugin;
  172. matchedThemeMetadata = themeMetadata;
  173. }
  174. });
  175. }
  176. catch (e) {
  177. logger.error(`Could not find the theme '${theme}' from GrowiPlugin documents.`, e);
  178. }
  179. try {
  180. if (matchedPlugin != null && matchedThemeMetadata != null) {
  181. const manifest = await retrievePluginManifest(matchedPlugin);
  182. return `${PLUGINS_STATIC_DIR}/${matchedPlugin.installedPath}/dist/${manifest[matchedThemeMetadata.manifestKey].file}`;
  183. }
  184. }
  185. catch (e) {
  186. logger.error(`Could not read manifest file for the theme '${theme}'`, e);
  187. }
  188. }
  189. async retrieveAllPluginResourceEntries(): Promise<GrowiPluginResourceEntries> {
  190. const GrowiPlugin = mongoose.model('GrowiPlugin') as GrowiPluginModel;
  191. const entries: GrowiPluginResourceEntries = [];
  192. try {
  193. const growiPlugins = await GrowiPlugin.findEnabledPlugins();
  194. growiPlugins.forEach(async(growiPlugin) => {
  195. try {
  196. const { types } = growiPlugin.meta;
  197. const manifest = await retrievePluginManifest(growiPlugin);
  198. // add script
  199. if (types.includes(GrowiPluginResourceType.Script) || types.includes(GrowiPluginResourceType.Template)) {
  200. const href = `${PLUGINS_STATIC_DIR}/${growiPlugin.installedPath}/dist/${manifest['client-entry.tsx'].file}`;
  201. entries.push([growiPlugin.installedPath, href]);
  202. }
  203. // add link
  204. if (types.includes(GrowiPluginResourceType.Script) || types.includes(GrowiPluginResourceType.Style)) {
  205. const href = `${PLUGINS_STATIC_DIR}/${growiPlugin.installedPath}/dist/${manifest['client-entry.tsx'].css}`;
  206. entries.push([growiPlugin.installedPath, href]);
  207. }
  208. }
  209. catch (e) {
  210. logger.warn(e);
  211. }
  212. });
  213. }
  214. catch (e) {
  215. logger.error('Could not retrieve GrowiPlugin documents.', e);
  216. }
  217. return entries;
  218. }
  219. }