site.js 6.1 KB

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