plugin.ts 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  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. if (fs.existsSync(newPath)) {
  58. // delete old directory
  59. await fs.promises.rm(newPath, { recursive: true });
  60. // delete old document
  61. const GrowiPlugin = mongoose.model<GrowiPlugin>('GrowiPlugin');
  62. await GrowiPlugin.deleteOne({ url: `https://github.com/${ghOrganizationName}/${ghReposName}` });
  63. // rename new directory
  64. fs.renameSync(oldPath, newPath);
  65. }
  66. else {
  67. fs.renameSync(oldPath, newPath);
  68. }
  69. };
  70. const downloadFile = async(requestUrl: string, filePath: string) => {
  71. return new Promise<void>((resolve, reject) => {
  72. axios({
  73. method: 'GET',
  74. url: requestUrl,
  75. responseType: 'stream',
  76. })
  77. .then((res) => {
  78. if (res.status === 200) {
  79. const file = fs.createWriteStream(filePath);
  80. res.data.pipe(file)
  81. .on('close', () => file.close())
  82. .on('finish', () => {
  83. return resolve();
  84. });
  85. }
  86. else {
  87. return reject(res.status);
  88. }
  89. }).catch((err) => {
  90. return reject(err);
  91. });
  92. });
  93. };
  94. const unzip = async(zipFilePath: fs.PathLike, unzippedPath: fs.PathLike) => {
  95. const stream = fs.createReadStream(zipFilePath);
  96. const unzipStream = stream.pipe(unzipper.Extract({ path: unzippedPath }));
  97. const deleteZipFile = (path: fs.PathLike) => fs.unlink(path, (err) => { return err });
  98. try {
  99. await streamToPromise(unzipStream);
  100. deleteZipFile(zipFilePath);
  101. }
  102. catch (err) {
  103. return err;
  104. }
  105. };
  106. try {
  107. await downloadFile(requestUrl, zipFilePath);
  108. await unzip(zipFilePath, unzippedPath);
  109. await renamePath(`${unzippedPath}/${ghReposName}-${ghBranch}`, `${unzippedPath}/${ghReposName}`);
  110. }
  111. catch (err) {
  112. logger.error(err);
  113. throw new Error(err);
  114. }
  115. return;
  116. }
  117. private async savePluginMetaData(plugins: GrowiPlugin[]): Promise<void> {
  118. const GrowiPlugin = mongoose.model('GrowiPlugin');
  119. await GrowiPlugin.insertMany(plugins);
  120. }
  121. // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types
  122. private static async detectPlugins(origin: GrowiPluginOrigin, installedPath: string, parentPackageJson?: any): Promise<GrowiPlugin[]> {
  123. const packageJsonPath = path.resolve(pluginStoringPath, installedPath, 'package.json');
  124. const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8'));
  125. const { growiPlugin } = packageJson;
  126. const {
  127. name: packageName, description: packageDesc, author: packageAuthor,
  128. } = parentPackageJson ?? packageJson;
  129. if (growiPlugin == null) {
  130. throw new Error('This package does not include \'growiPlugin\' section.');
  131. }
  132. // detect sub plugins for monorepo
  133. if (growiPlugin.isMonorepo && growiPlugin.packages != null) {
  134. const plugins = await Promise.all(
  135. growiPlugin.packages.map(async(subPackagePath) => {
  136. const subPackageInstalledPath = path.join(installedPath, subPackagePath);
  137. return this.detectPlugins(origin, subPackageInstalledPath, packageJson);
  138. }),
  139. );
  140. return plugins.flat();
  141. }
  142. if (growiPlugin.types == null) {
  143. throw new Error('\'growiPlugin\' section must have a \'types\' property.');
  144. }
  145. const plugin = {
  146. isEnabled: true,
  147. installedPath,
  148. origin,
  149. meta: {
  150. name: growiPlugin.name ?? packageName,
  151. desc: growiPlugin.desc ?? packageDesc,
  152. author: growiPlugin.author ?? packageAuthor,
  153. types: growiPlugin.types,
  154. },
  155. };
  156. // add theme metadata
  157. if (growiPlugin.types.includes(GrowiPluginResourceType.Theme)) {
  158. (plugin as GrowiPlugin<GrowiThemePluginMeta>).meta = {
  159. ...plugin.meta,
  160. themes: growiPlugin.themes,
  161. };
  162. }
  163. logger.info('Plugin detected => ', plugin);
  164. return [plugin];
  165. }
  166. async listPlugins(): Promise<GrowiPlugin[]> {
  167. return [];
  168. }
  169. async retrieveThemeHref(theme: string): Promise<string | undefined> {
  170. const GrowiPlugin = mongoose.model('GrowiPlugin') as GrowiPluginModel;
  171. let matchedPlugin: GrowiPlugin | undefined;
  172. let matchedThemeMetadata: GrowiThemeMetadata | undefined;
  173. try {
  174. // retrieve plugin manifests
  175. const growiPlugins = await GrowiPlugin.findEnabledPluginsIncludingAnyTypes([GrowiPluginResourceType.Theme]) as GrowiPlugin<GrowiThemePluginMeta>[];
  176. growiPlugins
  177. .forEach(async(growiPlugin) => {
  178. const themeMetadatas = growiPlugin.meta.themes;
  179. const themeMetadata = themeMetadatas.find(t => t.name === theme);
  180. // found
  181. if (themeMetadata != null) {
  182. matchedPlugin = growiPlugin;
  183. matchedThemeMetadata = themeMetadata;
  184. }
  185. });
  186. }
  187. catch (e) {
  188. logger.error(`Could not find the theme '${theme}' from GrowiPlugin documents.`, e);
  189. }
  190. try {
  191. if (matchedPlugin != null && matchedThemeMetadata != null) {
  192. const manifest = await retrievePluginManifest(matchedPlugin);
  193. return `${PLUGINS_STATIC_DIR}/${matchedPlugin.installedPath}/dist/${manifest[matchedThemeMetadata.manifestKey].file}`;
  194. }
  195. }
  196. catch (e) {
  197. logger.error(`Could not read manifest file for the theme '${theme}'`, e);
  198. }
  199. }
  200. async retrieveAllPluginResourceEntries(): Promise<GrowiPluginResourceEntries> {
  201. const GrowiPlugin = mongoose.model('GrowiPlugin') as GrowiPluginModel;
  202. const entries: GrowiPluginResourceEntries = [];
  203. try {
  204. const growiPlugins = await GrowiPlugin.findEnabledPlugins();
  205. growiPlugins.forEach(async(growiPlugin) => {
  206. try {
  207. const { types } = growiPlugin.meta;
  208. const manifest = await retrievePluginManifest(growiPlugin);
  209. // add script
  210. if (types.includes(GrowiPluginResourceType.Script) || types.includes(GrowiPluginResourceType.Template)) {
  211. const href = `${PLUGINS_STATIC_DIR}/${growiPlugin.installedPath}/dist/${manifest['client-entry.tsx'].file}`;
  212. entries.push([growiPlugin.installedPath, href]);
  213. }
  214. // add link
  215. if (types.includes(GrowiPluginResourceType.Script) || types.includes(GrowiPluginResourceType.Style)) {
  216. const href = `${PLUGINS_STATIC_DIR}/${growiPlugin.installedPath}/dist/${manifest['client-entry.tsx'].css}`;
  217. entries.push([growiPlugin.installedPath, href]);
  218. }
  219. }
  220. catch (e) {
  221. logger.warn(e);
  222. }
  223. });
  224. }
  225. catch (e) {
  226. logger.error('Could not retrieve GrowiPlugin documents.', e);
  227. }
  228. return entries;
  229. }
  230. }