site.js 6.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189
  1. const graphHelper = require('../../helpers/graph')
  2. const _ = require('lodash')
  3. const CleanCSS = require('clean-css')
  4. const path = require('path')
  5. /* global WIKI */
  6. module.exports = {
  7. Query: {
  8. async sites () {
  9. const sites = await WIKI.models.sites.query().orderBy('hostname')
  10. return sites.map(s => ({
  11. ...s.config,
  12. id: s.id,
  13. hostname: s.hostname,
  14. isEnabled: s.isEnabled,
  15. pageExtensions: s.config.pageExtensions.join(', ')
  16. }))
  17. },
  18. async siteById (obj, args) {
  19. const site = await WIKI.models.sites.query().findById(args.id)
  20. return site ? {
  21. ...site.config,
  22. id: site.id,
  23. hostname: site.hostname,
  24. isEnabled: site.isEnabled,
  25. pageExtensions: site.config.pageExtensions.join(', ')
  26. } : null
  27. },
  28. async siteByHostname (obj, args) {
  29. let site = await WIKI.models.sites.query().where({
  30. hostname: args.hostname
  31. }).first()
  32. if (!site && !args.exact) {
  33. site = await WIKI.models.sites.query().where({
  34. hostname: '*'
  35. }).first()
  36. }
  37. return site ? {
  38. ...site.config,
  39. id: site.id,
  40. hostname: site.hostname,
  41. isEnabled: site.isEnabled,
  42. pageExtensions: site.config.pageExtensions.join(', ')
  43. } : null
  44. }
  45. },
  46. Mutation: {
  47. /**
  48. * CREATE SITE
  49. */
  50. async createSite (obj, args) {
  51. try {
  52. // -> Validate inputs
  53. if (!args.hostname || args.hostname.length < 1 || !/^(\\*)|([a-z0-9\-.:]+)$/.test(args.hostname)) {
  54. throw WIKI.ERROR(new Error('Invalid Site Hostname'), 'SiteCreateInvalidHostname')
  55. }
  56. if (!args.title || args.title.length < 1 || !/^[^<>"]+$/.test(args.title)) {
  57. throw WIKI.ERROR(new Error('Invalid Site Title'), 'SiteCreateInvalidTitle')
  58. }
  59. // -> Check for duplicate catch-all
  60. if (args.hostname === '*') {
  61. const site = await WIKI.models.sites.query().where({
  62. hostname: args.hostname
  63. }).first()
  64. if (site) {
  65. throw WIKI.ERROR(new Error('A site with a catch-all hostname already exists! Cannot have 2 catch-all hostnames.'), 'SiteCreateDuplicateCatchAll')
  66. }
  67. }
  68. // -> Create site
  69. const newSite = await WIKI.models.sites.createSite(args.hostname, {
  70. title: args.title
  71. })
  72. return {
  73. operation: graphHelper.generateSuccess('Site created successfully'),
  74. site: newSite
  75. }
  76. } catch (err) {
  77. WIKI.logger.warn(err)
  78. return graphHelper.generateError(err)
  79. }
  80. },
  81. /**
  82. * UPDATE SITE
  83. */
  84. async updateSite (obj, args) {
  85. try {
  86. // -> Load site
  87. const site = await WIKI.models.sites.query().findById(args.id)
  88. if (!site) {
  89. throw WIKI.ERROR(new Error('Invalid Site ID'), 'SiteInvalidId')
  90. }
  91. // -> Check for bad input
  92. if (_.has(args.patch, 'hostname') && _.trim(args.patch.hostname).length < 1) {
  93. throw WIKI.ERROR(new Error('Hostname is invalid.'), 'SiteInvalidHostname')
  94. }
  95. // -> Check for duplicate catch-all
  96. if (args.patch.hostname === '*' && site.hostname !== '*') {
  97. const dupSite = await WIKI.models.sites.query().where({ hostname: '*' }).first()
  98. if (dupSite) {
  99. throw WIKI.ERROR(new Error(`Site ${dupSite.config.title} with a catch-all hostname already exists! Cannot have 2 catch-all hostnames.`), 'SiteUpdateDuplicateCatchAll')
  100. }
  101. }
  102. // -> Format Code
  103. if (args.patch?.theme?.injectCSS) {
  104. args.patch.theme.injectCSS = new CleanCSS({ inline: false }).minify(args.patch.theme.injectCSS).styles
  105. }
  106. // -> Format Page Extensions
  107. if (args.patch?.pageExtensions) {
  108. args.patch.pageExtensions = args.patch.pageExtensions.split(',').map(ext => ext.trim().toLowerCase()).filter(ext => ext.length > 0)
  109. }
  110. // -> Update site
  111. await WIKI.models.sites.updateSite(args.id, {
  112. hostname: args.patch.hostname ?? site.hostname,
  113. isEnabled: args.patch.isEnabled ?? site.isEnabled,
  114. config: _.defaultsDeep(_.omit(args.patch, ['hostname', 'isEnabled']), site.config)
  115. })
  116. return {
  117. operation: graphHelper.generateSuccess('Site updated successfully')
  118. }
  119. } catch (err) {
  120. WIKI.logger.warn(err)
  121. return graphHelper.generateError(err)
  122. }
  123. },
  124. /**
  125. * DELETE SITE
  126. */
  127. async deleteSite (obj, args) {
  128. try {
  129. // -> Ensure site isn't last one
  130. const sitesCount = await WIKI.models.sites.query().count('id').first()
  131. if (sitesCount?.count && _.toNumber(sitesCount?.count) <= 1) {
  132. throw WIKI.ERROR(new Error('Cannot delete the last site. At least 1 site must exists at all times.'), 'SiteDeleteLastSite')
  133. }
  134. // -> Delete site
  135. await WIKI.models.sites.deleteSite(args.id)
  136. return {
  137. operation: graphHelper.generateSuccess('Site deleted successfully')
  138. }
  139. } catch (err) {
  140. WIKI.logger.warn(err)
  141. return graphHelper.generateError(err)
  142. }
  143. },
  144. /**
  145. * UPLOAD LOGO
  146. */
  147. async uploadSiteLogo (obj, args) {
  148. try {
  149. const { filename, mimetype, createReadStream } = await args.image
  150. WIKI.logger.info(`Processing site logo ${filename} of type ${mimetype}...`)
  151. if (!WIKI.extensions.ext.sharp.isInstalled) {
  152. throw new Error('This feature requires the Sharp extension but it is not installed.')
  153. }
  154. console.info(mimetype)
  155. const destFormat = mimetype.startsWith('image/svg') ? 'svg' : 'png'
  156. const destPath = path.resolve(
  157. process.cwd(),
  158. WIKI.config.dataPath,
  159. `assets/logo.${destFormat}`
  160. )
  161. await WIKI.extensions.ext.sharp.resize({
  162. format: destFormat,
  163. inputStream: createReadStream(),
  164. outputPath: destPath,
  165. width: 100
  166. })
  167. WIKI.logger.info('New site logo processed successfully.')
  168. return {
  169. operation: graphHelper.generateSuccess('Site logo uploaded successfully')
  170. }
  171. } catch (err) {
  172. return graphHelper.generateError(err)
  173. }
  174. },
  175. /**
  176. * UPLOAD FAVICON
  177. */
  178. async uploadSiteFavicon (obj, args) {
  179. const { filename, mimetype, createReadStream } = await args.image
  180. console.info(filename, mimetype)
  181. return {
  182. operation: graphHelper.generateSuccess('Site favicon uploaded successfully')
  183. }
  184. }
  185. }
  186. }