plugin.ts 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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, GrowiPluginMeta,
  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<string>
  28. retrieveThemeHref(theme: string): Promise<string | undefined>
  29. retrieveAllPluginResourceEntries(): Promise<GrowiPluginResourceEntries>
  30. downloadNotExistPluginRepositories(): Promise<void>
  31. }
  32. export class PluginService implements IPluginService {
  33. async downloadNotExistPluginRepositories(): Promise<void> {
  34. try {
  35. // check all growi plugin documents
  36. const GrowiPlugin = mongoose.model<GrowiPlugin>('GrowiPlugin');
  37. const growiPlugins = await GrowiPlugin.find({});
  38. for await (const growiPlugin of growiPlugins) {
  39. const pluginPath = path.join(pluginStoringPath, growiPlugin.installedPath);
  40. if (fs.existsSync(pluginPath)) {
  41. // if exists repository, do nothing
  42. continue;
  43. }
  44. else {
  45. // if not exists repository, download latest plugin repository
  46. // TODO: imprv Document version and repository version possibly different.
  47. const ghUrl = new URL(growiPlugin.origin.url);
  48. const ghPathname = ghUrl.pathname;
  49. // TODO: Branch names can be specified.
  50. const ghBranch = 'main';
  51. const match = ghPathname.match(githubReposIdPattern);
  52. if (ghUrl.hostname !== 'github.com' || match == null) {
  53. throw new Error('GitHub repository URL is invalid.');
  54. }
  55. const ghOrganizationName = match[1];
  56. const ghReposName = match[2];
  57. const temporaryReposStoringPath = path.join(pluginStoringPath, ghReposName);
  58. try {
  59. // download github repository to local file system
  60. await this.downloadPluginRepository(ghOrganizationName, ghReposName, ghBranch);
  61. fs.renameSync(temporaryReposStoringPath, pluginPath);
  62. }
  63. catch (err) {
  64. // clean up
  65. if (fs.existsSync(temporaryReposStoringPath)) await fs.promises.rm(temporaryReposStoringPath, { recursive: true });
  66. if (fs.existsSync(pluginPath)) await fs.promises.rm(pluginPath, { recursive: true });
  67. logger.error(err);
  68. }
  69. continue;
  70. }
  71. }
  72. }
  73. catch (err) {
  74. logger.error(err);
  75. }
  76. }
  77. async install(origin: GrowiPluginOrigin): Promise<string> {
  78. // download
  79. const ghUrl = new URL(origin.url);
  80. const ghPathname = ghUrl.pathname;
  81. // TODO: Branch names can be specified.
  82. const ghBranch = 'main';
  83. const match = ghPathname.match(githubReposIdPattern);
  84. if (ghUrl.hostname !== 'github.com' || match == null) {
  85. throw new Error('GitHub repository URL is invalid.');
  86. }
  87. const ghOrganizationName = match[1];
  88. const ghReposName = match[2];
  89. const installedPath = `${ghOrganizationName}/${ghReposName}`;
  90. const zipFilePath = path.join(pluginStoringPath, `${ghBranch}.zip`);
  91. const unzippedFolderPath = path.join(pluginStoringPath, `${installedPath}-${ghBranch}`);
  92. const temporaryReposStoringPath = path.join(pluginStoringPath, ghReposName);
  93. const reposStoringPath = path.join(pluginStoringPath, `${installedPath}`);
  94. let plugins: GrowiPlugin<GrowiPluginMeta>[];
  95. try {
  96. // download github repository to file system's temporary path
  97. await this.downloadPluginRepository(ghOrganizationName, ghReposName, ghBranch);
  98. // detect plugins
  99. plugins = await PluginService.detectPlugins(origin, ghOrganizationName, ghReposName);
  100. // remove the old repository from the storing path
  101. if (fs.existsSync(reposStoringPath)) await fs.promises.rm(reposStoringPath, { recursive: true });
  102. // move new repository from temporary path to storing path.
  103. fs.renameSync(temporaryReposStoringPath, reposStoringPath);
  104. }
  105. catch (err) {
  106. // clean up
  107. if (fs.existsSync(zipFilePath)) await fs.promises.rm(zipFilePath);
  108. if (fs.existsSync(unzippedFolderPath)) await fs.promises.rm(unzippedFolderPath, { recursive: true });
  109. if (fs.existsSync(temporaryReposStoringPath)) await fs.promises.rm(temporaryReposStoringPath, { recursive: true });
  110. logger.error(err);
  111. throw err;
  112. }
  113. try {
  114. // delete plugin documents if these exist
  115. await this.deleteOldPluginDocument(installedPath);
  116. // save new plugins metadata
  117. await this.savePluginMetaData(plugins);
  118. return plugins[0].meta.name;
  119. }
  120. catch (err) {
  121. // clean up
  122. if (fs.existsSync(reposStoringPath)) await fs.promises.rm(reposStoringPath, { recursive: true });
  123. await this.deleteOldPluginDocument(installedPath);
  124. logger.error(err);
  125. throw err;
  126. }
  127. }
  128. private async deleteOldPluginDocument(path: string): Promise<void> {
  129. const GrowiPlugin = mongoose.model<GrowiPlugin>('GrowiPlugin');
  130. await GrowiPlugin.deleteMany({ installedPath: path });
  131. }
  132. private async downloadFile(requestUrl: string, filePath: string): Promise<void> {
  133. return new Promise<void>((resolve, rejects) => {
  134. axios({
  135. method: 'GET',
  136. url: requestUrl,
  137. responseType: 'stream',
  138. })
  139. .then((res) => {
  140. if (res.status === 200) {
  141. const file = fs.createWriteStream(filePath);
  142. res.data.pipe(file)
  143. .on('close', () => file.close())
  144. .on('finish', () => {
  145. return resolve();
  146. });
  147. }
  148. else {
  149. rejects(res.status);
  150. }
  151. }).catch((err) => {
  152. logger.error(err);
  153. // eslint-disable-next-line prefer-promise-reject-errors
  154. rejects('Filed to download file.');
  155. });
  156. });
  157. }
  158. private async unzip(zipFilePath: fs.PathLike, unzippedPath: fs.PathLike) {
  159. try {
  160. const stream = fs.createReadStream(zipFilePath);
  161. const unzipStream = stream.pipe(unzipper.Extract({ path: unzippedPath }));
  162. await streamToPromise(unzipStream);
  163. await fs.promises.rm(zipFilePath);
  164. }
  165. catch (err) {
  166. logger.error(err);
  167. throw new Error('Filed to unzip.');
  168. }
  169. }
  170. private async downloadPluginRepository(ghOrganizationName: string, ghReposName: string, ghBranch: string): Promise<void> {
  171. const requestUrl = `https://github.com/${ghOrganizationName}/${ghReposName}/archive/refs/heads/${ghBranch}.zip`;
  172. const zipFilePath = path.join(pluginStoringPath, `${ghBranch}.zip`);
  173. const unzipPath = pluginStoringPath;
  174. const unzippedFolderPath = `${unzipPath}/${ghReposName}-${ghBranch}`;
  175. const temporaryReposStoringPath = `${unzipPath}/${ghReposName}`;
  176. await this.downloadFile(requestUrl, zipFilePath);
  177. await this.unzip(zipFilePath, unzipPath);
  178. fs.renameSync(unzippedFolderPath, temporaryReposStoringPath);
  179. return;
  180. }
  181. private async savePluginMetaData(plugins: GrowiPlugin[]): Promise<void> {
  182. const GrowiPlugin = mongoose.model('GrowiPlugin');
  183. await GrowiPlugin.insertMany(plugins);
  184. }
  185. // eslint-disable-next-line @typescript-eslint/explicit-module-boundary-types, max-len
  186. private static async detectPlugins(origin: GrowiPluginOrigin, ghOrganizationName: string, ghReposName: string, parentPackageJson?: any): Promise<GrowiPlugin[]> {
  187. const packageJsonPath = path.resolve(pluginStoringPath, ghReposName, 'package.json');
  188. const packageJson = JSON.parse(readFileSync(packageJsonPath, 'utf-8'));
  189. const { growiPlugin } = packageJson;
  190. const {
  191. name: packageName, description: packageDesc, author: packageAuthor,
  192. } = parentPackageJson ?? packageJson;
  193. if (growiPlugin == null) {
  194. throw new Error('This package does not include \'growiPlugin\' section.');
  195. }
  196. // detect sub plugins for monorepo
  197. if (growiPlugin.isMonorepo && growiPlugin.packages != null) {
  198. const plugins = await Promise.all(
  199. growiPlugin.packages.map(async(subPackagePath) => {
  200. const subPackageInstalledPath = path.join(ghReposName, subPackagePath);
  201. return this.detectPlugins(origin, subPackageInstalledPath, packageJson);
  202. }),
  203. );
  204. return plugins.flat();
  205. }
  206. if (growiPlugin.types == null) {
  207. throw new Error('\'growiPlugin\' section must have a \'types\' property.');
  208. }
  209. const plugin = {
  210. isEnabled: true,
  211. installedPath: `${ghOrganizationName}/${ghReposName}`,
  212. origin,
  213. meta: {
  214. name: growiPlugin.name ?? packageName,
  215. desc: growiPlugin.desc ?? packageDesc,
  216. author: growiPlugin.author ?? packageAuthor,
  217. types: growiPlugin.types,
  218. },
  219. };
  220. // add theme metadata
  221. if (growiPlugin.types.includes(GrowiPluginResourceType.Theme)) {
  222. (plugin as GrowiPlugin<GrowiThemePluginMeta>).meta = {
  223. ...plugin.meta,
  224. themes: growiPlugin.themes,
  225. };
  226. }
  227. logger.info('Plugin detected => ', plugin);
  228. return [plugin];
  229. }
  230. async listPlugins(): Promise<GrowiPlugin[]> {
  231. return [];
  232. }
  233. /**
  234. * Delete plugin
  235. */
  236. async deletePlugin(pluginId: mongoose.Types.ObjectId): Promise<string> {
  237. const deleteFolder = (path: fs.PathLike): Promise<void> => {
  238. return fs.promises.rm(path, { recursive: true });
  239. };
  240. const GrowiPlugin = mongoose.model<GrowiPlugin>('GrowiPlugin');
  241. const growiPlugins = await GrowiPlugin.findById(pluginId);
  242. if (growiPlugins == null) {
  243. throw new Error('No plugin found for this ID.');
  244. }
  245. try {
  246. const growiPluginsPath = path.join(pluginStoringPath, growiPlugins.installedPath);
  247. await deleteFolder(growiPluginsPath);
  248. }
  249. catch (err) {
  250. logger.error(err);
  251. throw new Error('Filed to delete plugin repository.');
  252. }
  253. try {
  254. await GrowiPlugin.deleteOne({ _id: pluginId });
  255. }
  256. catch (err) {
  257. logger.error(err);
  258. throw new Error('Filed to delete plugin from GrowiPlugin documents.');
  259. }
  260. return growiPlugins.meta.name;
  261. }
  262. async retrieveThemeHref(theme: string): Promise<string | undefined> {
  263. const GrowiPlugin = mongoose.model('GrowiPlugin') as GrowiPluginModel;
  264. let matchedPlugin: GrowiPlugin | undefined;
  265. let matchedThemeMetadata: GrowiThemeMetadata | undefined;
  266. try {
  267. // retrieve plugin manifests
  268. const growiPlugins = await GrowiPlugin.findEnabledPluginsIncludingAnyTypes([GrowiPluginResourceType.Theme]) as GrowiPlugin<GrowiThemePluginMeta>[];
  269. growiPlugins
  270. .forEach(async(growiPlugin) => {
  271. const themeMetadatas = growiPlugin.meta.themes;
  272. const themeMetadata = themeMetadatas.find(t => t.name === theme);
  273. // found
  274. if (themeMetadata != null) {
  275. matchedPlugin = growiPlugin;
  276. matchedThemeMetadata = themeMetadata;
  277. }
  278. });
  279. }
  280. catch (e) {
  281. logger.error(`Could not find the theme '${theme}' from GrowiPlugin documents.`, e);
  282. }
  283. try {
  284. if (matchedPlugin != null && matchedThemeMetadata != null) {
  285. const manifest = await retrievePluginManifest(matchedPlugin);
  286. return `${PLUGINS_STATIC_DIR}/${matchedPlugin.installedPath}/dist/${manifest[matchedThemeMetadata.manifestKey].file}`;
  287. }
  288. }
  289. catch (e) {
  290. logger.error(`Could not read manifest file for the theme '${theme}'`, e);
  291. }
  292. }
  293. async retrieveAllPluginResourceEntries(): Promise<GrowiPluginResourceEntries> {
  294. const GrowiPlugin = mongoose.model('GrowiPlugin') as GrowiPluginModel;
  295. const entries: GrowiPluginResourceEntries = [];
  296. try {
  297. const growiPlugins = await GrowiPlugin.findEnabledPlugins();
  298. growiPlugins.forEach(async(growiPlugin) => {
  299. try {
  300. const { types } = growiPlugin.meta;
  301. const manifest = await retrievePluginManifest(growiPlugin);
  302. // add script
  303. if (types.includes(GrowiPluginResourceType.Script) || types.includes(GrowiPluginResourceType.Template)) {
  304. const href = `${PLUGINS_STATIC_DIR}/${growiPlugin.installedPath}/dist/${manifest['client-entry.tsx'].file}`;
  305. entries.push([growiPlugin.installedPath, href]);
  306. }
  307. // add link
  308. if (types.includes(GrowiPluginResourceType.Script) || types.includes(GrowiPluginResourceType.Style)) {
  309. const href = `${PLUGINS_STATIC_DIR}/${growiPlugin.installedPath}/dist/${manifest['client-entry.tsx'].css}`;
  310. entries.push([growiPlugin.installedPath, href]);
  311. }
  312. }
  313. catch (e) {
  314. logger.warn(e);
  315. }
  316. });
  317. }
  318. catch (e) {
  319. logger.error('Could not retrieve GrowiPlugin documents.', e);
  320. }
  321. return entries;
  322. }
  323. }