diff --git a/.adonisjs/client/data.d.ts b/.adonisjs/client/data.d.ts
new file mode 100644
index 0000000..43bc86e
--- /dev/null
+++ b/.adonisjs/client/data.d.ts
@@ -0,0 +1,59 @@
+/**
+ * This file is automatically generated.
+ * DO NOT EDIT manually
+ */
+
+///
+import type { InferData, InferVariants } from '@adonisjs/core/types/transformers'
+import type { InferSharedProps, InferFlashData } from '@adonisjs/inertia/types'
+import type ArticleTransformer from '#transformers/article_transformer'
+import type ChannelTransformer from '#transformers/channel_transformer'
+import type DiscussionTransformer from '#transformers/discussion_transformer'
+import type NotificationTransformer from '#transformers/notification_transformer'
+import type ReplyTransformer from '#transformers/reply_transformer'
+import type ReportTransformer from '#transformers/report_transformer'
+import type TagTransformer from '#transformers/tag_transformer'
+import type ThreadTransformer from '#transformers/thread_transformer'
+import type UserTransformer from '#transformers/user_transformer'
+import type InertiaMiddleware from '#middleware/inertia_middleware'
+
+export namespace Data {
+ export type Article = InferData
+ export namespace Article {
+ export type Variants = InferVariants
+ }
+ export type Channel = InferData
+ export namespace Channel {
+ export type Variants = InferVariants
+ }
+ export type Discussion = InferData
+ export namespace Discussion {
+ export type Variants = InferVariants
+ }
+ export type Notification = InferData
+ export namespace Notification {
+ export type Variants = InferVariants
+ }
+ export type Reply = InferData
+ export namespace Reply {
+ export type Variants = InferVariants
+ }
+ export type Report = InferData
+ export namespace Report {
+ export type Variants = InferVariants
+ }
+ export type Tag = InferData
+ export namespace Tag {
+ export type Variants = InferVariants
+ }
+ export type Thread = InferData
+ export namespace Thread {
+ export type Variants = InferVariants
+ }
+ export type User = InferData
+ export namespace User {
+ export type Variants = InferVariants
+ }
+ export type SharedProps = InferSharedProps
+ export type FlashMessages = InferFlashData
+}
diff --git a/.adonisjs/client/manifest.d.ts b/.adonisjs/client/manifest.d.ts
new file mode 100644
index 0000000..f2817ea
--- /dev/null
+++ b/.adonisjs/client/manifest.d.ts
@@ -0,0 +1,11 @@
+/**
+ * This file is automatically generated.
+ * DO NOT EDIT manually
+ */
+
+///
+///
+///
+///
+///
+///
diff --git a/.adonisjs/client/registry/index.ts b/.adonisjs/client/registry/index.ts
new file mode 100644
index 0000000..0acbad5
--- /dev/null
+++ b/.adonisjs/client/registry/index.ts
@@ -0,0 +1,527 @@
+/* eslint-disable prettier/prettier */
+import type { AdonisEndpoint } from '@tuyau/core/types'
+import type { Registry } from './schema.d.ts'
+import type { ApiDefinition } from './tree.d.ts'
+
+const placeholder: any = {}
+
+const routes = {
+ 'home': {
+ methods: ["GET","HEAD"],
+ pattern: '/',
+ tokens: [{"old":"/","type":0,"val":"/","end":""}],
+ types: placeholder as Registry['home']['types'],
+ },
+ 'health': {
+ methods: ["GET","HEAD"],
+ pattern: '/up',
+ tokens: [{"old":"/up","type":0,"val":"up","end":""}],
+ types: placeholder as Registry['health']['types'],
+ },
+ 'pages.about': {
+ methods: ["GET","HEAD"],
+ pattern: '/a-propos',
+ tokens: [{"old":"/a-propos","type":0,"val":"a-propos","end":""}],
+ types: placeholder as Registry['pages.about']['types'],
+ },
+ 'pages.code_of_conduct': {
+ methods: ["GET","HEAD"],
+ pattern: '/code-de-conduite',
+ tokens: [{"old":"/code-de-conduite","type":0,"val":"code-de-conduite","end":""}],
+ types: placeholder as Registry['pages.code_of_conduct']['types'],
+ },
+ 'login': {
+ methods: ["GET","HEAD"],
+ pattern: '/login',
+ tokens: [{"old":"/login","type":0,"val":"login","end":""}],
+ types: placeholder as Registry['login']['types'],
+ },
+ 'login.store': {
+ methods: ["POST"],
+ pattern: '/login',
+ tokens: [{"old":"/login","type":0,"val":"login","end":""}],
+ types: placeholder as Registry['login.store']['types'],
+ },
+ 'register': {
+ methods: ["GET","HEAD"],
+ pattern: '/register',
+ tokens: [{"old":"/register","type":0,"val":"register","end":""}],
+ types: placeholder as Registry['register']['types'],
+ },
+ 'register.store': {
+ methods: ["POST"],
+ pattern: '/register',
+ tokens: [{"old":"/register","type":0,"val":"register","end":""}],
+ types: placeholder as Registry['register.store']['types'],
+ },
+ 'auth.github': {
+ methods: ["GET","HEAD"],
+ pattern: '/auth/github',
+ tokens: [{"old":"/auth/github","type":0,"val":"auth","end":""},{"old":"/auth/github","type":0,"val":"github","end":""}],
+ types: placeholder as Registry['auth.github']['types'],
+ },
+ 'auth.github.callback': {
+ methods: ["GET","HEAD"],
+ pattern: '/auth/github/callback',
+ tokens: [{"old":"/auth/github/callback","type":0,"val":"auth","end":""},{"old":"/auth/github/callback","type":0,"val":"github","end":""},{"old":"/auth/github/callback","type":0,"val":"callback","end":""}],
+ types: placeholder as Registry['auth.github.callback']['types'],
+ },
+ 'logout': {
+ methods: ["POST"],
+ pattern: '/logout',
+ tokens: [{"old":"/logout","type":0,"val":"logout","end":""}],
+ types: placeholder as Registry['logout']['types'],
+ },
+ 'markdown.preview': {
+ methods: ["POST"],
+ pattern: '/markdown/preview',
+ tokens: [{"old":"/markdown/preview","type":0,"val":"markdown","end":""},{"old":"/markdown/preview","type":0,"val":"preview","end":""}],
+ types: placeholder as Registry['markdown.preview']['types'],
+ },
+ 'replies.update': {
+ methods: ["PUT"],
+ pattern: '/replies/:id',
+ tokens: [{"old":"/replies/:id","type":0,"val":"replies","end":""},{"old":"/replies/:id","type":1,"val":"id","end":""}],
+ types: placeholder as Registry['replies.update']['types'],
+ },
+ 'replies.destroy': {
+ methods: ["DELETE"],
+ pattern: '/replies/:id',
+ tokens: [{"old":"/replies/:id","type":0,"val":"replies","end":""},{"old":"/replies/:id","type":1,"val":"id","end":""}],
+ types: placeholder as Registry['replies.destroy']['types'],
+ },
+ 'replies.like': {
+ methods: ["POST"],
+ pattern: '/replies/:id/like',
+ tokens: [{"old":"/replies/:id/like","type":0,"val":"replies","end":""},{"old":"/replies/:id/like","type":1,"val":"id","end":""},{"old":"/replies/:id/like","type":0,"val":"like","end":""}],
+ types: placeholder as Registry['replies.like']['types'],
+ },
+ 'seo.robots': {
+ methods: ["GET","HEAD"],
+ pattern: '/robots.txt',
+ tokens: [{"old":"/robots.txt","type":0,"val":"robots.txt","end":""}],
+ types: placeholder as Registry['seo.robots']['types'],
+ },
+ 'seo.sitemap': {
+ methods: ["GET","HEAD"],
+ pattern: '/sitemap.xml',
+ tokens: [{"old":"/sitemap.xml","type":0,"val":"sitemap.xml","end":""}],
+ types: placeholder as Registry['seo.sitemap']['types'],
+ },
+ 'seo.feed': {
+ methods: ["GET","HEAD"],
+ pattern: '/feed.xml',
+ tokens: [{"old":"/feed.xml","type":0,"val":"feed.xml","end":""}],
+ types: placeholder as Registry['seo.feed']['types'],
+ },
+ 'articles.index': {
+ methods: ["GET","HEAD"],
+ pattern: '/articles',
+ tokens: [{"old":"/articles","type":0,"val":"articles","end":""}],
+ types: placeholder as Registry['articles.index']['types'],
+ },
+ 'articles.create': {
+ methods: ["GET","HEAD"],
+ pattern: '/articles/nouveau',
+ tokens: [{"old":"/articles/nouveau","type":0,"val":"articles","end":""},{"old":"/articles/nouveau","type":0,"val":"nouveau","end":""}],
+ types: placeholder as Registry['articles.create']['types'],
+ },
+ 'articles.store': {
+ methods: ["POST"],
+ pattern: '/articles',
+ tokens: [{"old":"/articles","type":0,"val":"articles","end":""}],
+ types: placeholder as Registry['articles.store']['types'],
+ },
+ 'articles.edit': {
+ methods: ["GET","HEAD"],
+ pattern: '/articles/:slug/modifier',
+ tokens: [{"old":"/articles/:slug/modifier","type":0,"val":"articles","end":""},{"old":"/articles/:slug/modifier","type":1,"val":"slug","end":""},{"old":"/articles/:slug/modifier","type":0,"val":"modifier","end":""}],
+ types: placeholder as Registry['articles.edit']['types'],
+ },
+ 'articles.update': {
+ methods: ["PUT"],
+ pattern: '/articles/:slug',
+ tokens: [{"old":"/articles/:slug","type":0,"val":"articles","end":""},{"old":"/articles/:slug","type":1,"val":"slug","end":""}],
+ types: placeholder as Registry['articles.update']['types'],
+ },
+ 'articles.destroy': {
+ methods: ["DELETE"],
+ pattern: '/articles/:slug',
+ tokens: [{"old":"/articles/:slug","type":0,"val":"articles","end":""},{"old":"/articles/:slug","type":1,"val":"slug","end":""}],
+ types: placeholder as Registry['articles.destroy']['types'],
+ },
+ 'articles.like': {
+ methods: ["POST"],
+ pattern: '/articles/:slug/like',
+ tokens: [{"old":"/articles/:slug/like","type":0,"val":"articles","end":""},{"old":"/articles/:slug/like","type":1,"val":"slug","end":""},{"old":"/articles/:slug/like","type":0,"val":"like","end":""}],
+ types: placeholder as Registry['articles.like']['types'],
+ },
+ 'articles.publish': {
+ methods: ["POST"],
+ pattern: '/articles/:slug/publish',
+ tokens: [{"old":"/articles/:slug/publish","type":0,"val":"articles","end":""},{"old":"/articles/:slug/publish","type":1,"val":"slug","end":""},{"old":"/articles/:slug/publish","type":0,"val":"publish","end":""}],
+ types: placeholder as Registry['articles.publish']['types'],
+ },
+ 'articles.unpublish': {
+ methods: ["POST"],
+ pattern: '/articles/:slug/unpublish',
+ tokens: [{"old":"/articles/:slug/unpublish","type":0,"val":"articles","end":""},{"old":"/articles/:slug/unpublish","type":1,"val":"slug","end":""},{"old":"/articles/:slug/unpublish","type":0,"val":"unpublish","end":""}],
+ types: placeholder as Registry['articles.unpublish']['types'],
+ },
+ 'articles.feature': {
+ methods: ["POST"],
+ pattern: '/articles/:slug/feature',
+ tokens: [{"old":"/articles/:slug/feature","type":0,"val":"articles","end":""},{"old":"/articles/:slug/feature","type":1,"val":"slug","end":""},{"old":"/articles/:slug/feature","type":0,"val":"feature","end":""}],
+ types: placeholder as Registry['articles.feature']['types'],
+ },
+ 'articles.comments.store': {
+ methods: ["POST"],
+ pattern: '/articles/:slug/comments',
+ tokens: [{"old":"/articles/:slug/comments","type":0,"val":"articles","end":""},{"old":"/articles/:slug/comments","type":1,"val":"slug","end":""},{"old":"/articles/:slug/comments","type":0,"val":"comments","end":""}],
+ types: placeholder as Registry['articles.comments.store']['types'],
+ },
+ 'articles.show': {
+ methods: ["GET","HEAD"],
+ pattern: '/articles/:slug',
+ tokens: [{"old":"/articles/:slug","type":0,"val":"articles","end":""},{"old":"/articles/:slug","type":1,"val":"slug","end":""}],
+ types: placeholder as Registry['articles.show']['types'],
+ },
+ 'forum.index': {
+ methods: ["GET","HEAD"],
+ pattern: '/forum',
+ tokens: [{"old":"/forum","type":0,"val":"forum","end":""}],
+ types: placeholder as Registry['forum.index']['types'],
+ },
+ 'forum.create': {
+ methods: ["GET","HEAD"],
+ pattern: '/forum/nouveau',
+ tokens: [{"old":"/forum/nouveau","type":0,"val":"forum","end":""},{"old":"/forum/nouveau","type":0,"val":"nouveau","end":""}],
+ types: placeholder as Registry['forum.create']['types'],
+ },
+ 'forum.store': {
+ methods: ["POST"],
+ pattern: '/forum',
+ tokens: [{"old":"/forum","type":0,"val":"forum","end":""}],
+ types: placeholder as Registry['forum.store']['types'],
+ },
+ 'forum.edit': {
+ methods: ["GET","HEAD"],
+ pattern: '/forum/:slug/modifier',
+ tokens: [{"old":"/forum/:slug/modifier","type":0,"val":"forum","end":""},{"old":"/forum/:slug/modifier","type":1,"val":"slug","end":""},{"old":"/forum/:slug/modifier","type":0,"val":"modifier","end":""}],
+ types: placeholder as Registry['forum.edit']['types'],
+ },
+ 'forum.update': {
+ methods: ["PUT"],
+ pattern: '/forum/:slug',
+ tokens: [{"old":"/forum/:slug","type":0,"val":"forum","end":""},{"old":"/forum/:slug","type":1,"val":"slug","end":""}],
+ types: placeholder as Registry['forum.update']['types'],
+ },
+ 'forum.destroy': {
+ methods: ["DELETE"],
+ pattern: '/forum/:slug',
+ tokens: [{"old":"/forum/:slug","type":0,"val":"forum","end":""},{"old":"/forum/:slug","type":1,"val":"slug","end":""}],
+ types: placeholder as Registry['forum.destroy']['types'],
+ },
+ 'forum.replies.store': {
+ methods: ["POST"],
+ pattern: '/forum/:slug/replies',
+ tokens: [{"old":"/forum/:slug/replies","type":0,"val":"forum","end":""},{"old":"/forum/:slug/replies","type":1,"val":"slug","end":""},{"old":"/forum/:slug/replies","type":0,"val":"replies","end":""}],
+ types: placeholder as Registry['forum.replies.store']['types'],
+ },
+ 'forum.solution.store': {
+ methods: ["POST"],
+ pattern: '/forum/:slug/solution',
+ tokens: [{"old":"/forum/:slug/solution","type":0,"val":"forum","end":""},{"old":"/forum/:slug/solution","type":1,"val":"slug","end":""},{"old":"/forum/:slug/solution","type":0,"val":"solution","end":""}],
+ types: placeholder as Registry['forum.solution.store']['types'],
+ },
+ 'forum.solution.destroy': {
+ methods: ["DELETE"],
+ pattern: '/forum/:slug/solution',
+ tokens: [{"old":"/forum/:slug/solution","type":0,"val":"forum","end":""},{"old":"/forum/:slug/solution","type":1,"val":"slug","end":""},{"old":"/forum/:slug/solution","type":0,"val":"solution","end":""}],
+ types: placeholder as Registry['forum.solution.destroy']['types'],
+ },
+ 'forum.pin': {
+ methods: ["POST"],
+ pattern: '/forum/:slug/pin',
+ tokens: [{"old":"/forum/:slug/pin","type":0,"val":"forum","end":""},{"old":"/forum/:slug/pin","type":1,"val":"slug","end":""},{"old":"/forum/:slug/pin","type":0,"val":"pin","end":""}],
+ types: placeholder as Registry['forum.pin']['types'],
+ },
+ 'forum.lock': {
+ methods: ["POST"],
+ pattern: '/forum/:slug/lock',
+ tokens: [{"old":"/forum/:slug/lock","type":0,"val":"forum","end":""},{"old":"/forum/:slug/lock","type":1,"val":"slug","end":""},{"old":"/forum/:slug/lock","type":0,"val":"lock","end":""}],
+ types: placeholder as Registry['forum.lock']['types'],
+ },
+ 'forum.show': {
+ methods: ["GET","HEAD"],
+ pattern: '/forum/:slug',
+ tokens: [{"old":"/forum/:slug","type":0,"val":"forum","end":""},{"old":"/forum/:slug","type":1,"val":"slug","end":""}],
+ types: placeholder as Registry['forum.show']['types'],
+ },
+ 'discussions.index': {
+ methods: ["GET","HEAD"],
+ pattern: '/discussions',
+ tokens: [{"old":"/discussions","type":0,"val":"discussions","end":""}],
+ types: placeholder as Registry['discussions.index']['types'],
+ },
+ 'discussions.create': {
+ methods: ["GET","HEAD"],
+ pattern: '/discussions/nouvelle',
+ tokens: [{"old":"/discussions/nouvelle","type":0,"val":"discussions","end":""},{"old":"/discussions/nouvelle","type":0,"val":"nouvelle","end":""}],
+ types: placeholder as Registry['discussions.create']['types'],
+ },
+ 'discussions.store': {
+ methods: ["POST"],
+ pattern: '/discussions',
+ tokens: [{"old":"/discussions","type":0,"val":"discussions","end":""}],
+ types: placeholder as Registry['discussions.store']['types'],
+ },
+ 'discussions.edit': {
+ methods: ["GET","HEAD"],
+ pattern: '/discussions/:slug/modifier',
+ tokens: [{"old":"/discussions/:slug/modifier","type":0,"val":"discussions","end":""},{"old":"/discussions/:slug/modifier","type":1,"val":"slug","end":""},{"old":"/discussions/:slug/modifier","type":0,"val":"modifier","end":""}],
+ types: placeholder as Registry['discussions.edit']['types'],
+ },
+ 'discussions.update': {
+ methods: ["PUT"],
+ pattern: '/discussions/:slug',
+ tokens: [{"old":"/discussions/:slug","type":0,"val":"discussions","end":""},{"old":"/discussions/:slug","type":1,"val":"slug","end":""}],
+ types: placeholder as Registry['discussions.update']['types'],
+ },
+ 'discussions.destroy': {
+ methods: ["DELETE"],
+ pattern: '/discussions/:slug',
+ tokens: [{"old":"/discussions/:slug","type":0,"val":"discussions","end":""},{"old":"/discussions/:slug","type":1,"val":"slug","end":""}],
+ types: placeholder as Registry['discussions.destroy']['types'],
+ },
+ 'discussions.replies.store': {
+ methods: ["POST"],
+ pattern: '/discussions/:slug/replies',
+ tokens: [{"old":"/discussions/:slug/replies","type":0,"val":"discussions","end":""},{"old":"/discussions/:slug/replies","type":1,"val":"slug","end":""},{"old":"/discussions/:slug/replies","type":0,"val":"replies","end":""}],
+ types: placeholder as Registry['discussions.replies.store']['types'],
+ },
+ 'discussions.pin': {
+ methods: ["POST"],
+ pattern: '/discussions/:slug/pin',
+ tokens: [{"old":"/discussions/:slug/pin","type":0,"val":"discussions","end":""},{"old":"/discussions/:slug/pin","type":1,"val":"slug","end":""},{"old":"/discussions/:slug/pin","type":0,"val":"pin","end":""}],
+ types: placeholder as Registry['discussions.pin']['types'],
+ },
+ 'discussions.lock': {
+ methods: ["POST"],
+ pattern: '/discussions/:slug/lock',
+ tokens: [{"old":"/discussions/:slug/lock","type":0,"val":"discussions","end":""},{"old":"/discussions/:slug/lock","type":1,"val":"slug","end":""},{"old":"/discussions/:slug/lock","type":0,"val":"lock","end":""}],
+ types: placeholder as Registry['discussions.lock']['types'],
+ },
+ 'discussions.show': {
+ methods: ["GET","HEAD"],
+ pattern: '/discussions/:slug',
+ tokens: [{"old":"/discussions/:slug","type":0,"val":"discussions","end":""},{"old":"/discussions/:slug","type":1,"val":"slug","end":""}],
+ types: placeholder as Registry['discussions.show']['types'],
+ },
+ 'search': {
+ methods: ["GET","HEAD"],
+ pattern: '/recherche',
+ tokens: [{"old":"/recherche","type":0,"val":"recherche","end":""}],
+ types: placeholder as Registry['search']['types'],
+ },
+ 'notifications.index': {
+ methods: ["GET","HEAD"],
+ pattern: '/notifications',
+ tokens: [{"old":"/notifications","type":0,"val":"notifications","end":""}],
+ types: placeholder as Registry['notifications.index']['types'],
+ },
+ 'notifications.read_all': {
+ methods: ["POST"],
+ pattern: '/notifications/read-all',
+ tokens: [{"old":"/notifications/read-all","type":0,"val":"notifications","end":""},{"old":"/notifications/read-all","type":0,"val":"read-all","end":""}],
+ types: placeholder as Registry['notifications.read_all']['types'],
+ },
+ 'notifications.read': {
+ methods: ["POST"],
+ pattern: '/notifications/:id/read',
+ tokens: [{"old":"/notifications/:id/read","type":0,"val":"notifications","end":""},{"old":"/notifications/:id/read","type":1,"val":"id","end":""},{"old":"/notifications/:id/read","type":0,"val":"read","end":""}],
+ types: placeholder as Registry['notifications.read']['types'],
+ },
+ 'notifications.show': {
+ methods: ["GET","HEAD"],
+ pattern: '/notifications/:id',
+ tokens: [{"old":"/notifications/:id","type":0,"val":"notifications","end":""},{"old":"/notifications/:id","type":1,"val":"id","end":""}],
+ types: placeholder as Registry['notifications.show']['types'],
+ },
+ 'reports.store': {
+ methods: ["POST"],
+ pattern: '/signalements',
+ tokens: [{"old":"/signalements","type":0,"val":"signalements","end":""}],
+ types: placeholder as Registry['reports.store']['types'],
+ },
+ 'members.index': {
+ methods: ["GET","HEAD"],
+ pattern: '/membres',
+ tokens: [{"old":"/membres","type":0,"val":"membres","end":""}],
+ types: placeholder as Registry['members.index']['types'],
+ },
+ 'dashboard': {
+ methods: ["GET","HEAD"],
+ pattern: '/dashboard',
+ tokens: [{"old":"/dashboard","type":0,"val":"dashboard","end":""}],
+ types: placeholder as Registry['dashboard']['types'],
+ },
+ 'settings.profile': {
+ methods: ["GET","HEAD"],
+ pattern: '/settings',
+ tokens: [{"old":"/settings","type":0,"val":"settings","end":""}],
+ types: placeholder as Registry['settings.profile']['types'],
+ },
+ 'settings.profile.update': {
+ methods: ["PUT"],
+ pattern: '/settings',
+ tokens: [{"old":"/settings","type":0,"val":"settings","end":""}],
+ types: placeholder as Registry['settings.profile.update']['types'],
+ },
+ 'settings.password': {
+ methods: ["GET","HEAD"],
+ pattern: '/settings/password',
+ tokens: [{"old":"/settings/password","type":0,"val":"settings","end":""},{"old":"/settings/password","type":0,"val":"password","end":""}],
+ types: placeholder as Registry['settings.password']['types'],
+ },
+ 'settings.password.update': {
+ methods: ["PUT"],
+ pattern: '/settings/password',
+ tokens: [{"old":"/settings/password","type":0,"val":"settings","end":""},{"old":"/settings/password","type":0,"val":"password","end":""}],
+ types: placeholder as Registry['settings.password.update']['types'],
+ },
+ 'settings.account': {
+ methods: ["GET","HEAD"],
+ pattern: '/settings/account',
+ tokens: [{"old":"/settings/account","type":0,"val":"settings","end":""},{"old":"/settings/account","type":0,"val":"account","end":""}],
+ types: placeholder as Registry['settings.account']['types'],
+ },
+ 'settings.account.destroy': {
+ methods: ["DELETE"],
+ pattern: '/settings/account',
+ tokens: [{"old":"/settings/account","type":0,"val":"settings","end":""},{"old":"/settings/account","type":0,"val":"account","end":""}],
+ types: placeholder as Registry['settings.account.destroy']['types'],
+ },
+ 'profile.show': {
+ methods: ["GET","HEAD"],
+ pattern: '/:username',
+ tokens: [{"old":"/:username","type":1,"val":"username","end":""}],
+ types: placeholder as Registry['profile.show']['types'],
+ },
+ 'admin.index': {
+ methods: ["GET","HEAD"],
+ pattern: '/admin',
+ tokens: [{"old":"/admin","type":0,"val":"admin","end":""}],
+ types: placeholder as Registry['admin.index']['types'],
+ },
+ 'admin.reports.index': {
+ methods: ["GET","HEAD"],
+ pattern: '/admin/signalements',
+ tokens: [{"old":"/admin/signalements","type":0,"val":"admin","end":""},{"old":"/admin/signalements","type":0,"val":"signalements","end":""}],
+ types: placeholder as Registry['admin.reports.index']['types'],
+ },
+ 'admin.reports.resolve': {
+ methods: ["POST"],
+ pattern: '/admin/signalements/:target/:id/traiter',
+ tokens: [{"old":"/admin/signalements/:target/:id/traiter","type":0,"val":"admin","end":""},{"old":"/admin/signalements/:target/:id/traiter","type":0,"val":"signalements","end":""},{"old":"/admin/signalements/:target/:id/traiter","type":1,"val":"target","end":""},{"old":"/admin/signalements/:target/:id/traiter","type":1,"val":"id","end":""},{"old":"/admin/signalements/:target/:id/traiter","type":0,"val":"traiter","end":""}],
+ types: placeholder as Registry['admin.reports.resolve']['types'],
+ },
+ 'admin.reports.dismiss': {
+ methods: ["POST"],
+ pattern: '/admin/signalements/:target/:id/ignorer',
+ tokens: [{"old":"/admin/signalements/:target/:id/ignorer","type":0,"val":"admin","end":""},{"old":"/admin/signalements/:target/:id/ignorer","type":0,"val":"signalements","end":""},{"old":"/admin/signalements/:target/:id/ignorer","type":1,"val":"target","end":""},{"old":"/admin/signalements/:target/:id/ignorer","type":1,"val":"id","end":""},{"old":"/admin/signalements/:target/:id/ignorer","type":0,"val":"ignorer","end":""}],
+ types: placeholder as Registry['admin.reports.dismiss']['types'],
+ },
+ 'admin.reports.destroy': {
+ methods: ["DELETE"],
+ pattern: '/admin/signalements/:target/:id/contenu',
+ tokens: [{"old":"/admin/signalements/:target/:id/contenu","type":0,"val":"admin","end":""},{"old":"/admin/signalements/:target/:id/contenu","type":0,"val":"signalements","end":""},{"old":"/admin/signalements/:target/:id/contenu","type":1,"val":"target","end":""},{"old":"/admin/signalements/:target/:id/contenu","type":1,"val":"id","end":""},{"old":"/admin/signalements/:target/:id/contenu","type":0,"val":"contenu","end":""}],
+ types: placeholder as Registry['admin.reports.destroy']['types'],
+ },
+ 'admin.members.index': {
+ methods: ["GET","HEAD"],
+ pattern: '/admin/membres',
+ tokens: [{"old":"/admin/membres","type":0,"val":"admin","end":""},{"old":"/admin/membres","type":0,"val":"membres","end":""}],
+ types: placeholder as Registry['admin.members.index']['types'],
+ },
+ 'admin.members.role': {
+ methods: ["PUT"],
+ pattern: '/admin/membres/:id/role',
+ tokens: [{"old":"/admin/membres/:id/role","type":0,"val":"admin","end":""},{"old":"/admin/membres/:id/role","type":0,"val":"membres","end":""},{"old":"/admin/membres/:id/role","type":1,"val":"id","end":""},{"old":"/admin/membres/:id/role","type":0,"val":"role","end":""}],
+ types: placeholder as Registry['admin.members.role']['types'],
+ },
+ 'admin.members.ban': {
+ methods: ["POST"],
+ pattern: '/admin/membres/:id/ban',
+ tokens: [{"old":"/admin/membres/:id/ban","type":0,"val":"admin","end":""},{"old":"/admin/membres/:id/ban","type":0,"val":"membres","end":""},{"old":"/admin/membres/:id/ban","type":1,"val":"id","end":""},{"old":"/admin/membres/:id/ban","type":0,"val":"ban","end":""}],
+ types: placeholder as Registry['admin.members.ban']['types'],
+ },
+ 'admin.members.unban': {
+ methods: ["DELETE"],
+ pattern: '/admin/membres/:id/ban',
+ tokens: [{"old":"/admin/membres/:id/ban","type":0,"val":"admin","end":""},{"old":"/admin/membres/:id/ban","type":0,"val":"membres","end":""},{"old":"/admin/membres/:id/ban","type":1,"val":"id","end":""},{"old":"/admin/membres/:id/ban","type":0,"val":"ban","end":""}],
+ types: placeholder as Registry['admin.members.unban']['types'],
+ },
+ 'admin.tags.index': {
+ methods: ["GET","HEAD"],
+ pattern: '/admin/tags',
+ tokens: [{"old":"/admin/tags","type":0,"val":"admin","end":""},{"old":"/admin/tags","type":0,"val":"tags","end":""}],
+ types: placeholder as Registry['admin.tags.index']['types'],
+ },
+ 'admin.tags.store': {
+ methods: ["POST"],
+ pattern: '/admin/tags',
+ tokens: [{"old":"/admin/tags","type":0,"val":"admin","end":""},{"old":"/admin/tags","type":0,"val":"tags","end":""}],
+ types: placeholder as Registry['admin.tags.store']['types'],
+ },
+ 'admin.tags.update': {
+ methods: ["PUT"],
+ pattern: '/admin/tags/:id',
+ tokens: [{"old":"/admin/tags/:id","type":0,"val":"admin","end":""},{"old":"/admin/tags/:id","type":0,"val":"tags","end":""},{"old":"/admin/tags/:id","type":1,"val":"id","end":""}],
+ types: placeholder as Registry['admin.tags.update']['types'],
+ },
+ 'admin.tags.destroy': {
+ methods: ["DELETE"],
+ pattern: '/admin/tags/:id',
+ tokens: [{"old":"/admin/tags/:id","type":0,"val":"admin","end":""},{"old":"/admin/tags/:id","type":0,"val":"tags","end":""},{"old":"/admin/tags/:id","type":1,"val":"id","end":""}],
+ types: placeholder as Registry['admin.tags.destroy']['types'],
+ },
+ 'admin.channels.index': {
+ methods: ["GET","HEAD"],
+ pattern: '/admin/canaux',
+ tokens: [{"old":"/admin/canaux","type":0,"val":"admin","end":""},{"old":"/admin/canaux","type":0,"val":"canaux","end":""}],
+ types: placeholder as Registry['admin.channels.index']['types'],
+ },
+ 'admin.channels.store': {
+ methods: ["POST"],
+ pattern: '/admin/canaux',
+ tokens: [{"old":"/admin/canaux","type":0,"val":"admin","end":""},{"old":"/admin/canaux","type":0,"val":"canaux","end":""}],
+ types: placeholder as Registry['admin.channels.store']['types'],
+ },
+ 'admin.channels.update': {
+ methods: ["PUT"],
+ pattern: '/admin/canaux/:id',
+ tokens: [{"old":"/admin/canaux/:id","type":0,"val":"admin","end":""},{"old":"/admin/canaux/:id","type":0,"val":"canaux","end":""},{"old":"/admin/canaux/:id","type":1,"val":"id","end":""}],
+ types: placeholder as Registry['admin.channels.update']['types'],
+ },
+ 'admin.channels.destroy': {
+ methods: ["DELETE"],
+ pattern: '/admin/canaux/:id',
+ tokens: [{"old":"/admin/canaux/:id","type":0,"val":"admin","end":""},{"old":"/admin/canaux/:id","type":0,"val":"canaux","end":""},{"old":"/admin/canaux/:id","type":1,"val":"id","end":""}],
+ types: placeholder as Registry['admin.channels.destroy']['types'],
+ },
+} as const satisfies Record
+
+export { routes }
+
+export const registry = {
+ routes,
+ $tree: {} as ApiDefinition,
+}
+
+declare module '@tuyau/core/types' {
+ export interface UserRegistry {
+ routes: typeof routes
+ $tree: ApiDefinition
+ }
+}
diff --git a/.adonisjs/client/registry/schema.d.ts b/.adonisjs/client/registry/schema.d.ts
new file mode 100644
index 0000000..a1c8243
--- /dev/null
+++ b/.adonisjs/client/registry/schema.d.ts
@@ -0,0 +1,1018 @@
+/* eslint-disable prettier/prettier */
+///
+
+import type { ExtractBody, ExtractErrorResponse, ExtractQuery, ExtractQueryForGet, ExtractResponse } from '@tuyau/core/types'
+import type { InferInput, SimpleError } from '@vinejs/vine/types'
+
+export type ParamValue = string | number | bigint | boolean
+
+export interface Registry {
+ 'home': {
+ methods: ["GET","HEAD"]
+ pattern: '/'
+ types: {
+ body: {}
+ paramsTuple: []
+ params: {}
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'health': {
+ methods: ["GET","HEAD"]
+ pattern: '/up'
+ types: {
+ body: {}
+ paramsTuple: []
+ params: {}
+ query: {}
+ response: unknown
+ errorResponse: unknown
+ }
+ }
+ 'pages.about': {
+ methods: ["GET","HEAD"]
+ pattern: '/a-propos'
+ types: {
+ body: {}
+ paramsTuple: []
+ params: {}
+ query: {}
+ response: unknown
+ errorResponse: unknown
+ }
+ }
+ 'pages.code_of_conduct': {
+ methods: ["GET","HEAD"]
+ pattern: '/code-de-conduite'
+ types: {
+ body: {}
+ paramsTuple: []
+ params: {}
+ query: {}
+ response: unknown
+ errorResponse: unknown
+ }
+ }
+ 'login': {
+ methods: ["GET","HEAD"]
+ pattern: '/login'
+ types: {
+ body: {}
+ paramsTuple: []
+ params: {}
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'login.store': {
+ methods: ["POST"]
+ pattern: '/login'
+ types: {
+ body: ExtractBody>
+ paramsTuple: []
+ params: {}
+ query: ExtractQuery>
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>> | { status: 422; response: { errors: SimpleError[] } }
+ }
+ }
+ 'register': {
+ methods: ["GET","HEAD"]
+ pattern: '/register'
+ types: {
+ body: {}
+ paramsTuple: []
+ params: {}
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'register.store': {
+ methods: ["POST"]
+ pattern: '/register'
+ types: {
+ body: ExtractBody>
+ paramsTuple: []
+ params: {}
+ query: ExtractQuery>
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>> | { status: 422; response: { errors: SimpleError[] } }
+ }
+ }
+ 'auth.github': {
+ methods: ["GET","HEAD"]
+ pattern: '/auth/github'
+ types: {
+ body: {}
+ paramsTuple: []
+ params: {}
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'auth.github.callback': {
+ methods: ["GET","HEAD"]
+ pattern: '/auth/github/callback'
+ types: {
+ body: {}
+ paramsTuple: []
+ params: {}
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'logout': {
+ methods: ["POST"]
+ pattern: '/logout'
+ types: {
+ body: {}
+ paramsTuple: []
+ params: {}
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'markdown.preview': {
+ methods: ["POST"]
+ pattern: '/markdown/preview'
+ types: {
+ body: {}
+ paramsTuple: []
+ params: {}
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'replies.update': {
+ methods: ["PUT"]
+ pattern: '/replies/:id'
+ types: {
+ body: ExtractBody>
+ paramsTuple: [ParamValue]
+ params: { id: ParamValue }
+ query: ExtractQuery>
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>> | { status: 422; response: { errors: SimpleError[] } }
+ }
+ }
+ 'replies.destroy': {
+ methods: ["DELETE"]
+ pattern: '/replies/:id'
+ types: {
+ body: {}
+ paramsTuple: [ParamValue]
+ params: { id: ParamValue }
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'replies.like': {
+ methods: ["POST"]
+ pattern: '/replies/:id/like'
+ types: {
+ body: {}
+ paramsTuple: [ParamValue]
+ params: { id: ParamValue }
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'seo.robots': {
+ methods: ["GET","HEAD"]
+ pattern: '/robots.txt'
+ types: {
+ body: {}
+ paramsTuple: []
+ params: {}
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'seo.sitemap': {
+ methods: ["GET","HEAD"]
+ pattern: '/sitemap.xml'
+ types: {
+ body: {}
+ paramsTuple: []
+ params: {}
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'seo.feed': {
+ methods: ["GET","HEAD"]
+ pattern: '/feed.xml'
+ types: {
+ body: {}
+ paramsTuple: []
+ params: {}
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'articles.index': {
+ methods: ["GET","HEAD"]
+ pattern: '/articles'
+ types: {
+ body: {}
+ paramsTuple: []
+ params: {}
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'articles.create': {
+ methods: ["GET","HEAD"]
+ pattern: '/articles/nouveau'
+ types: {
+ body: {}
+ paramsTuple: []
+ params: {}
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'articles.store': {
+ methods: ["POST"]
+ pattern: '/articles'
+ types: {
+ body: ExtractBody>
+ paramsTuple: []
+ params: {}
+ query: ExtractQuery>
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>> | { status: 422; response: { errors: SimpleError[] } }
+ }
+ }
+ 'articles.edit': {
+ methods: ["GET","HEAD"]
+ pattern: '/articles/:slug/modifier'
+ types: {
+ body: {}
+ paramsTuple: [ParamValue]
+ params: { slug: ParamValue }
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'articles.update': {
+ methods: ["PUT"]
+ pattern: '/articles/:slug'
+ types: {
+ body: ExtractBody>
+ paramsTuple: [ParamValue]
+ params: { slug: ParamValue }
+ query: ExtractQuery>
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>> | { status: 422; response: { errors: SimpleError[] } }
+ }
+ }
+ 'articles.destroy': {
+ methods: ["DELETE"]
+ pattern: '/articles/:slug'
+ types: {
+ body: {}
+ paramsTuple: [ParamValue]
+ params: { slug: ParamValue }
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'articles.like': {
+ methods: ["POST"]
+ pattern: '/articles/:slug/like'
+ types: {
+ body: {}
+ paramsTuple: [ParamValue]
+ params: { slug: ParamValue }
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'articles.publish': {
+ methods: ["POST"]
+ pattern: '/articles/:slug/publish'
+ types: {
+ body: {}
+ paramsTuple: [ParamValue]
+ params: { slug: ParamValue }
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'articles.unpublish': {
+ methods: ["POST"]
+ pattern: '/articles/:slug/unpublish'
+ types: {
+ body: {}
+ paramsTuple: [ParamValue]
+ params: { slug: ParamValue }
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'articles.feature': {
+ methods: ["POST"]
+ pattern: '/articles/:slug/feature'
+ types: {
+ body: {}
+ paramsTuple: [ParamValue]
+ params: { slug: ParamValue }
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'articles.comments.store': {
+ methods: ["POST"]
+ pattern: '/articles/:slug/comments'
+ types: {
+ body: ExtractBody>
+ paramsTuple: [ParamValue]
+ params: { slug: ParamValue }
+ query: ExtractQuery>
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>> | { status: 422; response: { errors: SimpleError[] } }
+ }
+ }
+ 'articles.show': {
+ methods: ["GET","HEAD"]
+ pattern: '/articles/:slug'
+ types: {
+ body: {}
+ paramsTuple: [ParamValue]
+ params: { slug: ParamValue }
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'forum.index': {
+ methods: ["GET","HEAD"]
+ pattern: '/forum'
+ types: {
+ body: {}
+ paramsTuple: []
+ params: {}
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'forum.create': {
+ methods: ["GET","HEAD"]
+ pattern: '/forum/nouveau'
+ types: {
+ body: {}
+ paramsTuple: []
+ params: {}
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'forum.store': {
+ methods: ["POST"]
+ pattern: '/forum'
+ types: {
+ body: ExtractBody>
+ paramsTuple: []
+ params: {}
+ query: ExtractQuery>
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>> | { status: 422; response: { errors: SimpleError[] } }
+ }
+ }
+ 'forum.edit': {
+ methods: ["GET","HEAD"]
+ pattern: '/forum/:slug/modifier'
+ types: {
+ body: {}
+ paramsTuple: [ParamValue]
+ params: { slug: ParamValue }
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'forum.update': {
+ methods: ["PUT"]
+ pattern: '/forum/:slug'
+ types: {
+ body: ExtractBody>
+ paramsTuple: [ParamValue]
+ params: { slug: ParamValue }
+ query: ExtractQuery>
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>> | { status: 422; response: { errors: SimpleError[] } }
+ }
+ }
+ 'forum.destroy': {
+ methods: ["DELETE"]
+ pattern: '/forum/:slug'
+ types: {
+ body: {}
+ paramsTuple: [ParamValue]
+ params: { slug: ParamValue }
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'forum.replies.store': {
+ methods: ["POST"]
+ pattern: '/forum/:slug/replies'
+ types: {
+ body: ExtractBody>
+ paramsTuple: [ParamValue]
+ params: { slug: ParamValue }
+ query: ExtractQuery>
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>> | { status: 422; response: { errors: SimpleError[] } }
+ }
+ }
+ 'forum.solution.store': {
+ methods: ["POST"]
+ pattern: '/forum/:slug/solution'
+ types: {
+ body: ExtractBody>
+ paramsTuple: [ParamValue]
+ params: { slug: ParamValue }
+ query: ExtractQuery>
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>> | { status: 422; response: { errors: SimpleError[] } }
+ }
+ }
+ 'forum.solution.destroy': {
+ methods: ["DELETE"]
+ pattern: '/forum/:slug/solution'
+ types: {
+ body: {}
+ paramsTuple: [ParamValue]
+ params: { slug: ParamValue }
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'forum.pin': {
+ methods: ["POST"]
+ pattern: '/forum/:slug/pin'
+ types: {
+ body: {}
+ paramsTuple: [ParamValue]
+ params: { slug: ParamValue }
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'forum.lock': {
+ methods: ["POST"]
+ pattern: '/forum/:slug/lock'
+ types: {
+ body: {}
+ paramsTuple: [ParamValue]
+ params: { slug: ParamValue }
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'forum.show': {
+ methods: ["GET","HEAD"]
+ pattern: '/forum/:slug'
+ types: {
+ body: {}
+ paramsTuple: [ParamValue]
+ params: { slug: ParamValue }
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'discussions.index': {
+ methods: ["GET","HEAD"]
+ pattern: '/discussions'
+ types: {
+ body: {}
+ paramsTuple: []
+ params: {}
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'discussions.create': {
+ methods: ["GET","HEAD"]
+ pattern: '/discussions/nouvelle'
+ types: {
+ body: {}
+ paramsTuple: []
+ params: {}
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'discussions.store': {
+ methods: ["POST"]
+ pattern: '/discussions'
+ types: {
+ body: ExtractBody>
+ paramsTuple: []
+ params: {}
+ query: ExtractQuery>
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>> | { status: 422; response: { errors: SimpleError[] } }
+ }
+ }
+ 'discussions.edit': {
+ methods: ["GET","HEAD"]
+ pattern: '/discussions/:slug/modifier'
+ types: {
+ body: {}
+ paramsTuple: [ParamValue]
+ params: { slug: ParamValue }
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'discussions.update': {
+ methods: ["PUT"]
+ pattern: '/discussions/:slug'
+ types: {
+ body: ExtractBody>
+ paramsTuple: [ParamValue]
+ params: { slug: ParamValue }
+ query: ExtractQuery>
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>> | { status: 422; response: { errors: SimpleError[] } }
+ }
+ }
+ 'discussions.destroy': {
+ methods: ["DELETE"]
+ pattern: '/discussions/:slug'
+ types: {
+ body: {}
+ paramsTuple: [ParamValue]
+ params: { slug: ParamValue }
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'discussions.replies.store': {
+ methods: ["POST"]
+ pattern: '/discussions/:slug/replies'
+ types: {
+ body: ExtractBody>
+ paramsTuple: [ParamValue]
+ params: { slug: ParamValue }
+ query: ExtractQuery>
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>> | { status: 422; response: { errors: SimpleError[] } }
+ }
+ }
+ 'discussions.pin': {
+ methods: ["POST"]
+ pattern: '/discussions/:slug/pin'
+ types: {
+ body: {}
+ paramsTuple: [ParamValue]
+ params: { slug: ParamValue }
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'discussions.lock': {
+ methods: ["POST"]
+ pattern: '/discussions/:slug/lock'
+ types: {
+ body: {}
+ paramsTuple: [ParamValue]
+ params: { slug: ParamValue }
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'discussions.show': {
+ methods: ["GET","HEAD"]
+ pattern: '/discussions/:slug'
+ types: {
+ body: {}
+ paramsTuple: [ParamValue]
+ params: { slug: ParamValue }
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'search': {
+ methods: ["GET","HEAD"]
+ pattern: '/recherche'
+ types: {
+ body: {}
+ paramsTuple: []
+ params: {}
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'notifications.index': {
+ methods: ["GET","HEAD"]
+ pattern: '/notifications'
+ types: {
+ body: {}
+ paramsTuple: []
+ params: {}
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'notifications.read_all': {
+ methods: ["POST"]
+ pattern: '/notifications/read-all'
+ types: {
+ body: {}
+ paramsTuple: []
+ params: {}
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'notifications.read': {
+ methods: ["POST"]
+ pattern: '/notifications/:id/read'
+ types: {
+ body: {}
+ paramsTuple: [ParamValue]
+ params: { id: ParamValue }
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'notifications.show': {
+ methods: ["GET","HEAD"]
+ pattern: '/notifications/:id'
+ types: {
+ body: {}
+ paramsTuple: [ParamValue]
+ params: { id: ParamValue }
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'reports.store': {
+ methods: ["POST"]
+ pattern: '/signalements'
+ types: {
+ body: ExtractBody>
+ paramsTuple: []
+ params: {}
+ query: ExtractQuery>
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>> | { status: 422; response: { errors: SimpleError[] } }
+ }
+ }
+ 'members.index': {
+ methods: ["GET","HEAD"]
+ pattern: '/membres'
+ types: {
+ body: {}
+ paramsTuple: []
+ params: {}
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'dashboard': {
+ methods: ["GET","HEAD"]
+ pattern: '/dashboard'
+ types: {
+ body: {}
+ paramsTuple: []
+ params: {}
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'settings.profile': {
+ methods: ["GET","HEAD"]
+ pattern: '/settings'
+ types: {
+ body: {}
+ paramsTuple: []
+ params: {}
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'settings.profile.update': {
+ methods: ["PUT"]
+ pattern: '/settings'
+ types: {
+ body: ExtractBody>
+ paramsTuple: []
+ params: {}
+ query: ExtractQuery>
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>> | { status: 422; response: { errors: SimpleError[] } }
+ }
+ }
+ 'settings.password': {
+ methods: ["GET","HEAD"]
+ pattern: '/settings/password'
+ types: {
+ body: {}
+ paramsTuple: []
+ params: {}
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'settings.password.update': {
+ methods: ["PUT"]
+ pattern: '/settings/password'
+ types: {
+ body: ExtractBody>
+ paramsTuple: []
+ params: {}
+ query: ExtractQuery>
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>> | { status: 422; response: { errors: SimpleError[] } }
+ }
+ }
+ 'settings.account': {
+ methods: ["GET","HEAD"]
+ pattern: '/settings/account'
+ types: {
+ body: {}
+ paramsTuple: []
+ params: {}
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'settings.account.destroy': {
+ methods: ["DELETE"]
+ pattern: '/settings/account'
+ types: {
+ body: ExtractBody>
+ paramsTuple: []
+ params: {}
+ query: ExtractQuery>
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>> | { status: 422; response: { errors: SimpleError[] } }
+ }
+ }
+ 'profile.show': {
+ methods: ["GET","HEAD"]
+ pattern: '/:username'
+ types: {
+ body: {}
+ paramsTuple: [ParamValue]
+ params: { username: ParamValue }
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'admin.index': {
+ methods: ["GET","HEAD"]
+ pattern: '/admin'
+ types: {
+ body: {}
+ paramsTuple: []
+ params: {}
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'admin.reports.index': {
+ methods: ["GET","HEAD"]
+ pattern: '/admin/signalements'
+ types: {
+ body: {}
+ paramsTuple: []
+ params: {}
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'admin.reports.resolve': {
+ methods: ["POST"]
+ pattern: '/admin/signalements/:target/:id/traiter'
+ types: {
+ body: {}
+ paramsTuple: [ParamValue, ParamValue]
+ params: { target: ParamValue; id: ParamValue }
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'admin.reports.dismiss': {
+ methods: ["POST"]
+ pattern: '/admin/signalements/:target/:id/ignorer'
+ types: {
+ body: {}
+ paramsTuple: [ParamValue, ParamValue]
+ params: { target: ParamValue; id: ParamValue }
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'admin.reports.destroy': {
+ methods: ["DELETE"]
+ pattern: '/admin/signalements/:target/:id/contenu'
+ types: {
+ body: {}
+ paramsTuple: [ParamValue, ParamValue]
+ params: { target: ParamValue; id: ParamValue }
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'admin.members.index': {
+ methods: ["GET","HEAD"]
+ pattern: '/admin/membres'
+ types: {
+ body: {}
+ paramsTuple: []
+ params: {}
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'admin.members.role': {
+ methods: ["PUT"]
+ pattern: '/admin/membres/:id/role'
+ types: {
+ body: ExtractBody>
+ paramsTuple: [ParamValue]
+ params: { id: ParamValue }
+ query: ExtractQuery>
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>> | { status: 422; response: { errors: SimpleError[] } }
+ }
+ }
+ 'admin.members.ban': {
+ methods: ["POST"]
+ pattern: '/admin/membres/:id/ban'
+ types: {
+ body: {}
+ paramsTuple: [ParamValue]
+ params: { id: ParamValue }
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'admin.members.unban': {
+ methods: ["DELETE"]
+ pattern: '/admin/membres/:id/ban'
+ types: {
+ body: {}
+ paramsTuple: [ParamValue]
+ params: { id: ParamValue }
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'admin.tags.index': {
+ methods: ["GET","HEAD"]
+ pattern: '/admin/tags'
+ types: {
+ body: {}
+ paramsTuple: []
+ params: {}
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'admin.tags.store': {
+ methods: ["POST"]
+ pattern: '/admin/tags'
+ types: {
+ body: ExtractBody>
+ paramsTuple: []
+ params: {}
+ query: ExtractQuery>
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>> | { status: 422; response: { errors: SimpleError[] } }
+ }
+ }
+ 'admin.tags.update': {
+ methods: ["PUT"]
+ pattern: '/admin/tags/:id'
+ types: {
+ body: ExtractBody>
+ paramsTuple: [ParamValue]
+ params: { id: ParamValue }
+ query: ExtractQuery>
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>> | { status: 422; response: { errors: SimpleError[] } }
+ }
+ }
+ 'admin.tags.destroy': {
+ methods: ["DELETE"]
+ pattern: '/admin/tags/:id'
+ types: {
+ body: {}
+ paramsTuple: [ParamValue]
+ params: { id: ParamValue }
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'admin.channels.index': {
+ methods: ["GET","HEAD"]
+ pattern: '/admin/canaux'
+ types: {
+ body: {}
+ paramsTuple: []
+ params: {}
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+ 'admin.channels.store': {
+ methods: ["POST"]
+ pattern: '/admin/canaux'
+ types: {
+ body: ExtractBody>
+ paramsTuple: []
+ params: {}
+ query: ExtractQuery>
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>> | { status: 422; response: { errors: SimpleError[] } }
+ }
+ }
+ 'admin.channels.update': {
+ methods: ["PUT"]
+ pattern: '/admin/canaux/:id'
+ types: {
+ body: ExtractBody>
+ paramsTuple: [ParamValue]
+ params: { id: ParamValue }
+ query: ExtractQuery>
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>> | { status: 422; response: { errors: SimpleError[] } }
+ }
+ }
+ 'admin.channels.destroy': {
+ methods: ["DELETE"]
+ pattern: '/admin/canaux/:id'
+ types: {
+ body: {}
+ paramsTuple: [ParamValue]
+ params: { id: ParamValue }
+ query: {}
+ response: ExtractResponse>>
+ errorResponse: ExtractErrorResponse>>
+ }
+ }
+}
diff --git a/.adonisjs/client/registry/tree.d.ts b/.adonisjs/client/registry/tree.d.ts
new file mode 100644
index 0000000..5f14d6c
--- /dev/null
+++ b/.adonisjs/client/registry/tree.d.ts
@@ -0,0 +1,139 @@
+/* eslint-disable prettier/prettier */
+import type { routes } from './index.ts'
+
+export interface ApiDefinition {
+ home: typeof routes['home']
+ health: typeof routes['health']
+ pages: {
+ about: typeof routes['pages.about']
+ codeOfConduct: typeof routes['pages.code_of_conduct']
+ }
+ login: typeof routes['login'] & {
+ store: typeof routes['login.store']
+ }
+ register: typeof routes['register'] & {
+ store: typeof routes['register.store']
+ }
+ auth: {
+ github: typeof routes['auth.github'] & {
+ callback: typeof routes['auth.github.callback']
+ }
+ }
+ logout: typeof routes['logout']
+ markdown: {
+ preview: typeof routes['markdown.preview']
+ }
+ replies: {
+ update: typeof routes['replies.update']
+ destroy: typeof routes['replies.destroy']
+ like: typeof routes['replies.like']
+ }
+ seo: {
+ robots: typeof routes['seo.robots']
+ sitemap: typeof routes['seo.sitemap']
+ feed: typeof routes['seo.feed']
+ }
+ articles: {
+ index: typeof routes['articles.index']
+ create: typeof routes['articles.create']
+ store: typeof routes['articles.store']
+ edit: typeof routes['articles.edit']
+ update: typeof routes['articles.update']
+ destroy: typeof routes['articles.destroy']
+ like: typeof routes['articles.like']
+ publish: typeof routes['articles.publish']
+ unpublish: typeof routes['articles.unpublish']
+ feature: typeof routes['articles.feature']
+ comments: {
+ store: typeof routes['articles.comments.store']
+ }
+ show: typeof routes['articles.show']
+ }
+ forum: {
+ index: typeof routes['forum.index']
+ create: typeof routes['forum.create']
+ store: typeof routes['forum.store']
+ edit: typeof routes['forum.edit']
+ update: typeof routes['forum.update']
+ destroy: typeof routes['forum.destroy']
+ replies: {
+ store: typeof routes['forum.replies.store']
+ }
+ solution: {
+ store: typeof routes['forum.solution.store']
+ destroy: typeof routes['forum.solution.destroy']
+ }
+ pin: typeof routes['forum.pin']
+ lock: typeof routes['forum.lock']
+ show: typeof routes['forum.show']
+ }
+ discussions: {
+ index: typeof routes['discussions.index']
+ create: typeof routes['discussions.create']
+ store: typeof routes['discussions.store']
+ edit: typeof routes['discussions.edit']
+ update: typeof routes['discussions.update']
+ destroy: typeof routes['discussions.destroy']
+ replies: {
+ store: typeof routes['discussions.replies.store']
+ }
+ pin: typeof routes['discussions.pin']
+ lock: typeof routes['discussions.lock']
+ show: typeof routes['discussions.show']
+ }
+ search: typeof routes['search']
+ notifications: {
+ index: typeof routes['notifications.index']
+ readAll: typeof routes['notifications.read_all']
+ read: typeof routes['notifications.read']
+ show: typeof routes['notifications.show']
+ }
+ reports: {
+ store: typeof routes['reports.store']
+ }
+ members: {
+ index: typeof routes['members.index']
+ }
+ dashboard: typeof routes['dashboard']
+ settings: {
+ profile: typeof routes['settings.profile'] & {
+ update: typeof routes['settings.profile.update']
+ }
+ password: typeof routes['settings.password'] & {
+ update: typeof routes['settings.password.update']
+ }
+ account: typeof routes['settings.account'] & {
+ destroy: typeof routes['settings.account.destroy']
+ }
+ }
+ profile: {
+ show: typeof routes['profile.show']
+ }
+ admin: {
+ index: typeof routes['admin.index']
+ reports: {
+ index: typeof routes['admin.reports.index']
+ resolve: typeof routes['admin.reports.resolve']
+ dismiss: typeof routes['admin.reports.dismiss']
+ destroy: typeof routes['admin.reports.destroy']
+ }
+ members: {
+ index: typeof routes['admin.members.index']
+ role: typeof routes['admin.members.role']
+ ban: typeof routes['admin.members.ban']
+ unban: typeof routes['admin.members.unban']
+ }
+ tags: {
+ index: typeof routes['admin.tags.index']
+ store: typeof routes['admin.tags.store']
+ update: typeof routes['admin.tags.update']
+ destroy: typeof routes['admin.tags.destroy']
+ }
+ channels: {
+ index: typeof routes['admin.channels.index']
+ store: typeof routes['admin.channels.store']
+ update: typeof routes['admin.channels.update']
+ destroy: typeof routes['admin.channels.destroy']
+ }
+ }
+}
diff --git a/.adonisjs/server/controllers.ts b/.adonisjs/server/controllers.ts
new file mode 100644
index 0000000..5fb12f0
--- /dev/null
+++ b/.adonisjs/server/controllers.ts
@@ -0,0 +1,37 @@
+/**
+ * This file is automatically generated.
+ * DO NOT EDIT manually
+ */
+
+export const controllers = {
+ admin: {
+ Channels: () => import('#controllers/admin/channels_controller'),
+ Members: () => import('#controllers/admin/members_controller'),
+ Overview: () => import('#controllers/admin/overview_controller'),
+ Reports: () => import('#controllers/admin/reports_controller'),
+ Tags: () => import('#controllers/admin/tags_controller'),
+ },
+ ArticleActions: () => import('#controllers/article_actions_controller'),
+ ArticleComments: () => import('#controllers/article_comments_controller'),
+ Articles: () => import('#controllers/articles_controller'),
+ auth: {
+ Github: () => import('#controllers/auth/github_controller'),
+ Login: () => import('#controllers/auth/login_controller'),
+ Register: () => import('#controllers/auth/register_controller'),
+ },
+ Dashboard: () => import('#controllers/dashboard_controller'),
+ DiscussionActions: () => import('#controllers/discussion_actions_controller'),
+ Discussions: () => import('#controllers/discussions_controller'),
+ Home: () => import('#controllers/home_controller'),
+ Markdown: () => import('#controllers/markdown_controller'),
+ Members: () => import('#controllers/members_controller'),
+ Notifications: () => import('#controllers/notifications_controller'),
+ Profile: () => import('#controllers/profile_controller'),
+ Replies: () => import('#controllers/replies_controller'),
+ Reports: () => import('#controllers/reports_controller'),
+ Search: () => import('#controllers/search_controller'),
+ Seo: () => import('#controllers/seo_controller'),
+ Settings: () => import('#controllers/settings_controller'),
+ ThreadActions: () => import('#controllers/thread_actions_controller'),
+ Threads: () => import('#controllers/threads_controller'),
+}
diff --git a/.adonisjs/server/events.ts b/.adonisjs/server/events.ts
new file mode 100644
index 0000000..a74e59b
--- /dev/null
+++ b/.adonisjs/server/events.ts
@@ -0,0 +1,6 @@
+/**
+ * This file is automatically generated.
+ * DO NOT EDIT manually
+ */
+
+export const events = {}
diff --git a/.adonisjs/server/listeners.ts b/.adonisjs/server/listeners.ts
new file mode 100644
index 0000000..05f35f8
--- /dev/null
+++ b/.adonisjs/server/listeners.ts
@@ -0,0 +1,6 @@
+/**
+ * This file is automatically generated.
+ * DO NOT EDIT manually
+ */
+
+export const listeners = {}
diff --git a/.adonisjs/server/pages.d.ts b/.adonisjs/server/pages.d.ts
new file mode 100644
index 0000000..a219e86
--- /dev/null
+++ b/.adonisjs/server/pages.d.ts
@@ -0,0 +1,48 @@
+import '@adonisjs/inertia/types'
+
+import type React from 'react'
+import type { Prettify } from '@adonisjs/core/types/common'
+
+type ExtractProps =
+ T extends React.FC
+ ? Prettify>
+ : T extends React.Component
+ ? Prettify>
+ : never
+
+declare module '@adonisjs/inertia/types' {
+ export interface InertiaPages {
+ 'admin/channels': ExtractProps<(typeof import('../../inertia/pages/admin/channels.tsx'))['default']>
+ 'admin/index': ExtractProps<(typeof import('../../inertia/pages/admin/index.tsx'))['default']>
+ 'admin/members': ExtractProps<(typeof import('../../inertia/pages/admin/members.tsx'))['default']>
+ 'admin/reports': ExtractProps<(typeof import('../../inertia/pages/admin/reports.tsx'))['default']>
+ 'admin/tags': ExtractProps<(typeof import('../../inertia/pages/admin/tags.tsx'))['default']>
+ 'articles/[slug]': ExtractProps<(typeof import('../../inertia/pages/articles/[slug].tsx'))['default']>
+ 'articles/create': ExtractProps<(typeof import('../../inertia/pages/articles/create.tsx'))['default']>
+ 'articles/edit': ExtractProps<(typeof import('../../inertia/pages/articles/edit.tsx'))['default']>
+ 'articles/index': ExtractProps<(typeof import('../../inertia/pages/articles/index.tsx'))['default']>
+ 'auth/login': ExtractProps<(typeof import('../../inertia/pages/auth/login.tsx'))['default']>
+ 'auth/register': ExtractProps<(typeof import('../../inertia/pages/auth/register.tsx'))['default']>
+ 'dashboard/index': ExtractProps<(typeof import('../../inertia/pages/dashboard/index.tsx'))['default']>
+ 'discussions/create': ExtractProps<(typeof import('../../inertia/pages/discussions/create.tsx'))['default']>
+ 'discussions/edit': ExtractProps<(typeof import('../../inertia/pages/discussions/edit.tsx'))['default']>
+ 'discussions/index': ExtractProps<(typeof import('../../inertia/pages/discussions/index.tsx'))['default']>
+ 'discussions/show': ExtractProps<(typeof import('../../inertia/pages/discussions/show.tsx'))['default']>
+ 'errors/not_found': ExtractProps<(typeof import('../../inertia/pages/errors/not_found.tsx'))['default']>
+ 'errors/server_error': ExtractProps<(typeof import('../../inertia/pages/errors/server_error.tsx'))['default']>
+ 'forum/create': ExtractProps<(typeof import('../../inertia/pages/forum/create.tsx'))['default']>
+ 'forum/edit': ExtractProps<(typeof import('../../inertia/pages/forum/edit.tsx'))['default']>
+ 'forum/index': ExtractProps<(typeof import('../../inertia/pages/forum/index.tsx'))['default']>
+ 'forum/show': ExtractProps<(typeof import('../../inertia/pages/forum/show.tsx'))['default']>
+ 'home': ExtractProps<(typeof import('../../inertia/pages/home.tsx'))['default']>
+ 'members/index': ExtractProps<(typeof import('../../inertia/pages/members/index.tsx'))['default']>
+ 'notifications/index': ExtractProps<(typeof import('../../inertia/pages/notifications/index.tsx'))['default']>
+ 'pages/about': ExtractProps<(typeof import('../../inertia/pages/pages/about.tsx'))['default']>
+ 'pages/code_of_conduct': ExtractProps<(typeof import('../../inertia/pages/pages/code_of_conduct.tsx'))['default']>
+ 'profile/show': ExtractProps<(typeof import('../../inertia/pages/profile/show.tsx'))['default']>
+ 'search/index': ExtractProps<(typeof import('../../inertia/pages/search/index.tsx'))['default']>
+ 'settings/account': ExtractProps<(typeof import('../../inertia/pages/settings/account.tsx'))['default']>
+ 'settings/password': ExtractProps<(typeof import('../../inertia/pages/settings/password.tsx'))['default']>
+ 'settings/profile': ExtractProps<(typeof import('../../inertia/pages/settings/profile.tsx'))['default']>
+ }
+}
diff --git a/.adonisjs/server/routes.d.ts b/.adonisjs/server/routes.d.ts
new file mode 100644
index 0000000..64a76af
--- /dev/null
+++ b/.adonisjs/server/routes.d.ts
@@ -0,0 +1,226 @@
+import '@adonisjs/core/types/http'
+
+type ParamValue = string | number | bigint | boolean
+
+export type ScannedRoutes = {
+ ALL: {
+ 'home': { paramsTuple?: []; params?: {} }
+ 'health': { paramsTuple?: []; params?: {} }
+ 'pages.about': { paramsTuple?: []; params?: {} }
+ 'pages.code_of_conduct': { paramsTuple?: []; params?: {} }
+ 'login': { paramsTuple?: []; params?: {} }
+ 'login.store': { paramsTuple?: []; params?: {} }
+ 'register': { paramsTuple?: []; params?: {} }
+ 'register.store': { paramsTuple?: []; params?: {} }
+ 'auth.github': { paramsTuple?: []; params?: {} }
+ 'auth.github.callback': { paramsTuple?: []; params?: {} }
+ 'logout': { paramsTuple?: []; params?: {} }
+ 'markdown.preview': { paramsTuple?: []; params?: {} }
+ 'replies.update': { paramsTuple: [ParamValue]; params: {'id': ParamValue} }
+ 'replies.destroy': { paramsTuple: [ParamValue]; params: {'id': ParamValue} }
+ 'replies.like': { paramsTuple: [ParamValue]; params: {'id': ParamValue} }
+ 'seo.robots': { paramsTuple?: []; params?: {} }
+ 'seo.sitemap': { paramsTuple?: []; params?: {} }
+ 'seo.feed': { paramsTuple?: []; params?: {} }
+ 'articles.index': { paramsTuple?: []; params?: {} }
+ 'articles.create': { paramsTuple?: []; params?: {} }
+ 'articles.store': { paramsTuple?: []; params?: {} }
+ 'articles.edit': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'articles.update': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'articles.destroy': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'articles.like': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'articles.publish': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'articles.unpublish': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'articles.feature': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'articles.comments.store': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'articles.show': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'forum.index': { paramsTuple?: []; params?: {} }
+ 'forum.create': { paramsTuple?: []; params?: {} }
+ 'forum.store': { paramsTuple?: []; params?: {} }
+ 'forum.edit': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'forum.update': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'forum.destroy': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'forum.replies.store': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'forum.solution.store': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'forum.solution.destroy': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'forum.pin': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'forum.lock': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'forum.show': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'discussions.index': { paramsTuple?: []; params?: {} }
+ 'discussions.create': { paramsTuple?: []; params?: {} }
+ 'discussions.store': { paramsTuple?: []; params?: {} }
+ 'discussions.edit': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'discussions.update': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'discussions.destroy': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'discussions.replies.store': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'discussions.pin': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'discussions.lock': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'discussions.show': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'search': { paramsTuple?: []; params?: {} }
+ 'notifications.index': { paramsTuple?: []; params?: {} }
+ 'notifications.read_all': { paramsTuple?: []; params?: {} }
+ 'notifications.read': { paramsTuple: [ParamValue]; params: {'id': ParamValue} }
+ 'notifications.show': { paramsTuple: [ParamValue]; params: {'id': ParamValue} }
+ 'reports.store': { paramsTuple?: []; params?: {} }
+ 'members.index': { paramsTuple?: []; params?: {} }
+ 'dashboard': { paramsTuple?: []; params?: {} }
+ 'settings.profile': { paramsTuple?: []; params?: {} }
+ 'settings.profile.update': { paramsTuple?: []; params?: {} }
+ 'settings.password': { paramsTuple?: []; params?: {} }
+ 'settings.password.update': { paramsTuple?: []; params?: {} }
+ 'settings.account': { paramsTuple?: []; params?: {} }
+ 'settings.account.destroy': { paramsTuple?: []; params?: {} }
+ 'profile.show': { paramsTuple: [ParamValue]; params: {'username': ParamValue} }
+ 'admin.index': { paramsTuple?: []; params?: {} }
+ 'admin.reports.index': { paramsTuple?: []; params?: {} }
+ 'admin.reports.resolve': { paramsTuple: [ParamValue,ParamValue]; params: {'target': ParamValue,'id': ParamValue} }
+ 'admin.reports.dismiss': { paramsTuple: [ParamValue,ParamValue]; params: {'target': ParamValue,'id': ParamValue} }
+ 'admin.reports.destroy': { paramsTuple: [ParamValue,ParamValue]; params: {'target': ParamValue,'id': ParamValue} }
+ 'admin.members.index': { paramsTuple?: []; params?: {} }
+ 'admin.members.role': { paramsTuple: [ParamValue]; params: {'id': ParamValue} }
+ 'admin.members.ban': { paramsTuple: [ParamValue]; params: {'id': ParamValue} }
+ 'admin.members.unban': { paramsTuple: [ParamValue]; params: {'id': ParamValue} }
+ 'admin.tags.index': { paramsTuple?: []; params?: {} }
+ 'admin.tags.store': { paramsTuple?: []; params?: {} }
+ 'admin.tags.update': { paramsTuple: [ParamValue]; params: {'id': ParamValue} }
+ 'admin.tags.destroy': { paramsTuple: [ParamValue]; params: {'id': ParamValue} }
+ 'admin.channels.index': { paramsTuple?: []; params?: {} }
+ 'admin.channels.store': { paramsTuple?: []; params?: {} }
+ 'admin.channels.update': { paramsTuple: [ParamValue]; params: {'id': ParamValue} }
+ 'admin.channels.destroy': { paramsTuple: [ParamValue]; params: {'id': ParamValue} }
+ }
+ GET: {
+ 'home': { paramsTuple?: []; params?: {} }
+ 'health': { paramsTuple?: []; params?: {} }
+ 'pages.about': { paramsTuple?: []; params?: {} }
+ 'pages.code_of_conduct': { paramsTuple?: []; params?: {} }
+ 'login': { paramsTuple?: []; params?: {} }
+ 'register': { paramsTuple?: []; params?: {} }
+ 'auth.github': { paramsTuple?: []; params?: {} }
+ 'auth.github.callback': { paramsTuple?: []; params?: {} }
+ 'seo.robots': { paramsTuple?: []; params?: {} }
+ 'seo.sitemap': { paramsTuple?: []; params?: {} }
+ 'seo.feed': { paramsTuple?: []; params?: {} }
+ 'articles.index': { paramsTuple?: []; params?: {} }
+ 'articles.create': { paramsTuple?: []; params?: {} }
+ 'articles.edit': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'articles.show': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'forum.index': { paramsTuple?: []; params?: {} }
+ 'forum.create': { paramsTuple?: []; params?: {} }
+ 'forum.edit': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'forum.show': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'discussions.index': { paramsTuple?: []; params?: {} }
+ 'discussions.create': { paramsTuple?: []; params?: {} }
+ 'discussions.edit': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'discussions.show': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'search': { paramsTuple?: []; params?: {} }
+ 'notifications.index': { paramsTuple?: []; params?: {} }
+ 'notifications.show': { paramsTuple: [ParamValue]; params: {'id': ParamValue} }
+ 'members.index': { paramsTuple?: []; params?: {} }
+ 'dashboard': { paramsTuple?: []; params?: {} }
+ 'settings.profile': { paramsTuple?: []; params?: {} }
+ 'settings.password': { paramsTuple?: []; params?: {} }
+ 'settings.account': { paramsTuple?: []; params?: {} }
+ 'profile.show': { paramsTuple: [ParamValue]; params: {'username': ParamValue} }
+ 'admin.index': { paramsTuple?: []; params?: {} }
+ 'admin.reports.index': { paramsTuple?: []; params?: {} }
+ 'admin.members.index': { paramsTuple?: []; params?: {} }
+ 'admin.tags.index': { paramsTuple?: []; params?: {} }
+ 'admin.channels.index': { paramsTuple?: []; params?: {} }
+ }
+ HEAD: {
+ 'home': { paramsTuple?: []; params?: {} }
+ 'health': { paramsTuple?: []; params?: {} }
+ 'pages.about': { paramsTuple?: []; params?: {} }
+ 'pages.code_of_conduct': { paramsTuple?: []; params?: {} }
+ 'login': { paramsTuple?: []; params?: {} }
+ 'register': { paramsTuple?: []; params?: {} }
+ 'auth.github': { paramsTuple?: []; params?: {} }
+ 'auth.github.callback': { paramsTuple?: []; params?: {} }
+ 'seo.robots': { paramsTuple?: []; params?: {} }
+ 'seo.sitemap': { paramsTuple?: []; params?: {} }
+ 'seo.feed': { paramsTuple?: []; params?: {} }
+ 'articles.index': { paramsTuple?: []; params?: {} }
+ 'articles.create': { paramsTuple?: []; params?: {} }
+ 'articles.edit': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'articles.show': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'forum.index': { paramsTuple?: []; params?: {} }
+ 'forum.create': { paramsTuple?: []; params?: {} }
+ 'forum.edit': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'forum.show': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'discussions.index': { paramsTuple?: []; params?: {} }
+ 'discussions.create': { paramsTuple?: []; params?: {} }
+ 'discussions.edit': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'discussions.show': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'search': { paramsTuple?: []; params?: {} }
+ 'notifications.index': { paramsTuple?: []; params?: {} }
+ 'notifications.show': { paramsTuple: [ParamValue]; params: {'id': ParamValue} }
+ 'members.index': { paramsTuple?: []; params?: {} }
+ 'dashboard': { paramsTuple?: []; params?: {} }
+ 'settings.profile': { paramsTuple?: []; params?: {} }
+ 'settings.password': { paramsTuple?: []; params?: {} }
+ 'settings.account': { paramsTuple?: []; params?: {} }
+ 'profile.show': { paramsTuple: [ParamValue]; params: {'username': ParamValue} }
+ 'admin.index': { paramsTuple?: []; params?: {} }
+ 'admin.reports.index': { paramsTuple?: []; params?: {} }
+ 'admin.members.index': { paramsTuple?: []; params?: {} }
+ 'admin.tags.index': { paramsTuple?: []; params?: {} }
+ 'admin.channels.index': { paramsTuple?: []; params?: {} }
+ }
+ POST: {
+ 'login.store': { paramsTuple?: []; params?: {} }
+ 'register.store': { paramsTuple?: []; params?: {} }
+ 'logout': { paramsTuple?: []; params?: {} }
+ 'markdown.preview': { paramsTuple?: []; params?: {} }
+ 'replies.like': { paramsTuple: [ParamValue]; params: {'id': ParamValue} }
+ 'articles.store': { paramsTuple?: []; params?: {} }
+ 'articles.like': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'articles.publish': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'articles.unpublish': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'articles.feature': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'articles.comments.store': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'forum.store': { paramsTuple?: []; params?: {} }
+ 'forum.replies.store': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'forum.solution.store': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'forum.pin': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'forum.lock': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'discussions.store': { paramsTuple?: []; params?: {} }
+ 'discussions.replies.store': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'discussions.pin': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'discussions.lock': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'notifications.read_all': { paramsTuple?: []; params?: {} }
+ 'notifications.read': { paramsTuple: [ParamValue]; params: {'id': ParamValue} }
+ 'reports.store': { paramsTuple?: []; params?: {} }
+ 'admin.reports.resolve': { paramsTuple: [ParamValue,ParamValue]; params: {'target': ParamValue,'id': ParamValue} }
+ 'admin.reports.dismiss': { paramsTuple: [ParamValue,ParamValue]; params: {'target': ParamValue,'id': ParamValue} }
+ 'admin.members.ban': { paramsTuple: [ParamValue]; params: {'id': ParamValue} }
+ 'admin.tags.store': { paramsTuple?: []; params?: {} }
+ 'admin.channels.store': { paramsTuple?: []; params?: {} }
+ }
+ PUT: {
+ 'replies.update': { paramsTuple: [ParamValue]; params: {'id': ParamValue} }
+ 'articles.update': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'forum.update': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'discussions.update': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'settings.profile.update': { paramsTuple?: []; params?: {} }
+ 'settings.password.update': { paramsTuple?: []; params?: {} }
+ 'admin.members.role': { paramsTuple: [ParamValue]; params: {'id': ParamValue} }
+ 'admin.tags.update': { paramsTuple: [ParamValue]; params: {'id': ParamValue} }
+ 'admin.channels.update': { paramsTuple: [ParamValue]; params: {'id': ParamValue} }
+ }
+ DELETE: {
+ 'replies.destroy': { paramsTuple: [ParamValue]; params: {'id': ParamValue} }
+ 'articles.destroy': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'forum.destroy': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'forum.solution.destroy': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'discussions.destroy': { paramsTuple: [ParamValue]; params: {'slug': ParamValue} }
+ 'settings.account.destroy': { paramsTuple?: []; params?: {} }
+ 'admin.reports.destroy': { paramsTuple: [ParamValue,ParamValue]; params: {'target': ParamValue,'id': ParamValue} }
+ 'admin.members.unban': { paramsTuple: [ParamValue]; params: {'id': ParamValue} }
+ 'admin.tags.destroy': { paramsTuple: [ParamValue]; params: {'id': ParamValue} }
+ 'admin.channels.destroy': { paramsTuple: [ParamValue]; params: {'id': ParamValue} }
+ }
+}
+declare module '@adonisjs/core/types/http' {
+ export interface RoutesList extends ScannedRoutes {}
+}
\ No newline at end of file
diff --git a/.dockerignore b/.dockerignore
new file mode 100644
index 0000000..6f3cc9d
--- /dev/null
+++ b/.dockerignore
@@ -0,0 +1,12 @@
+node_modules
+build
+tmp
+.git
+.github
+.env
+.env.*
+!.env.example
+npm-debug.log
+.DS_Store
+.vscode
+.idea
diff --git a/.env.example b/.env.example
index 25b1a45..fe0f0ce 100644
--- a/.env.example
+++ b/.env.example
@@ -1,15 +1,28 @@
+# Node
TZ=UTC
PORT=3333
HOST=localhost
+NODE_ENV=development
+
+# App
LOG_LEVEL=info
APP_KEY=
-NODE_ENV=development
+APP_URL=http://${HOST}:${PORT}
+
+# Session
SESSION_DRIVER=cookie
+
+# Database (PostgreSQL)
DB_HOST=127.0.0.1
-DB_PORT=3306
-DB_USER=root
-DB_PASSWORD=root
-DB_DATABASE=app
+DB_PORT=5432
+DB_USER=jscm
+DB_PASSWORD=jscm
+DB_DATABASE=jscm
+
+# Rate limiting
+LIMITER_STORE=database
+
+# GitHub OAuth — https://github.com/settings/developers
+# Callback URL: ${APP_URL}/auth/github/callback
GITHUB_CLIENT_ID=
GITHUB_CLIENT_SECRET=
-GITHUB_CALLBACK_URL=
\ No newline at end of file
diff --git a/.env.test b/.env.test
new file mode 100644
index 0000000..837fd45
--- /dev/null
+++ b/.env.test
@@ -0,0 +1,5 @@
+NODE_ENV=test
+SESSION_DRIVER=memory
+LIMITER_STORE=memory
+DB_DATABASE=jscm_test
+APP_URL=http://localhost:3333
diff --git a/.github/workflows/deploy-staging.yml b/.github/workflows/deploy-staging.yml
new file mode 100644
index 0000000..7d19db6
--- /dev/null
+++ b/.github/workflows/deploy-staging.yml
@@ -0,0 +1,77 @@
+name: CI & staging deploy
+
+on:
+ push:
+ pull_request:
+ workflow_dispatch:
+
+concurrency:
+ group: ${{ github.workflow }}-${{ github.ref }}
+ cancel-in-progress: ${{ github.ref != 'refs/heads/staging' }}
+
+jobs:
+ check:
+ name: Typecheck, tests & build
+ runs-on: ubuntu-latest
+ services:
+ postgres:
+ image: postgres:18-alpine
+ env:
+ POSTGRES_USER: jscm
+ POSTGRES_PASSWORD: jscm
+ POSTGRES_DB: jscm_test
+ ports: ['5432:5432']
+ options: >-
+ --health-cmd "pg_isready -U jscm -d jscm_test"
+ --health-interval 5s
+ --health-timeout 5s
+ --health-retries 20
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: 24
+ cache: npm
+ - run: npm ci
+ - name: Prepare environment
+ run: |
+ cp .env.example .env
+ sed -i "s/^APP_KEY=.*/APP_KEY=$(openssl rand -hex 32)/" .env
+ - run: npm run typecheck
+ - run: node ace test
+ - run: node ace build
+
+ deploy:
+ name: Deploy to staging.javascript.cm
+ needs: check
+ if: github.event_name == 'push' && github.ref == 'refs/heads/staging'
+ runs-on: ubuntu-latest
+ concurrency:
+ group: staging-deploy
+ cancel-in-progress: false
+ environment:
+ name: staging
+ url: https://staging.javascript.cm
+ steps:
+ - name: Check deploy secrets
+ id: secrets
+ env:
+ HOST: ${{ secrets.STAGING_HOST }}
+ run: |
+ if [ -z "$HOST" ]; then
+ echo "::warning title=Deploy skipped::STAGING_SSH_KEY, STAGING_KNOWN_HOSTS, STAGING_HOST and STAGING_SSH_USER secrets are not configured."
+ echo "ready=false" >> "$GITHUB_OUTPUT"
+ else
+ echo "ready=true" >> "$GITHUB_OUTPUT"
+ fi
+ - name: Configure SSH
+ if: steps.secrets.outputs.ready == 'true'
+ run: |
+ install -m 700 -d ~/.ssh
+ echo "${{ secrets.STAGING_SSH_KEY }}" > ~/.ssh/deploy_key
+ chmod 600 ~/.ssh/deploy_key
+ echo "${{ secrets.STAGING_KNOWN_HOSTS }}" > ~/.ssh/known_hosts
+ # The key is restricted server-side (forced command): it can only run the deploy script.
+ - name: Deploy
+ if: steps.secrets.outputs.ready == 'true'
+ run: ssh -i ~/.ssh/deploy_key ${{ secrets.STAGING_SSH_USER }}@${{ secrets.STAGING_HOST }} deploy
diff --git a/.gitignore b/.gitignore
index 4e9b445..dd7579a 100644
--- a/.gitignore
+++ b/.gitignore
@@ -1,7 +1,8 @@
# Dependencies and AdonisJS build
node_modules
build
-tmp
+tmp/*
+!tmp/.gitkeep
# Secrets
.env
diff --git a/.prettierignore b/.prettierignore
new file mode 100644
index 0000000..2614418
--- /dev/null
+++ b/.prettierignore
@@ -0,0 +1,6 @@
+.adonisjs
+node_modules
+build
+
+# Generated
+database/schema.ts
diff --git a/Dockerfile b/Dockerfile
new file mode 100644
index 0000000..58bab20
--- /dev/null
+++ b/Dockerfile
@@ -0,0 +1,43 @@
+# syntax=docker/dockerfile:1.7
+
+# ---------------------------------------------------------------------------
+# javascript.cm — production image
+# ---------------------------------------------------------------------------
+FROM node:24-bookworm-slim AS base
+WORKDIR /app
+ENV CI=true \
+ npm_config_fund=false \
+ npm_config_audit=false \
+ npm_config_update_notifier=false
+
+# All dependencies (build tooling included)
+FROM base AS deps
+COPY package.json package-lock.json ./
+RUN --mount=type=cache,target=/root/.npm npm ci
+
+# Production dependencies only
+FROM base AS production-deps
+COPY package.json package-lock.json ./
+RUN --mount=type=cache,target=/root/.npm npm ci --omit=dev
+
+# Compile TypeScript + Vite client and SSR bundles into ./build
+FROM deps AS build
+COPY . .
+RUN node ace build
+
+# Runtime
+FROM base AS runtime
+ENV NODE_ENV=production \
+ HOST=0.0.0.0 \
+ PORT=3333 \
+ LOG_LEVEL=info
+COPY --from=production-deps --chown=node:node /app/node_modules ./node_modules
+COPY --from=build --chown=node:node /app/build ./
+COPY --chown=node:node docker/entrypoint.sh /usr/local/bin/entrypoint.sh
+RUN chmod +x /usr/local/bin/entrypoint.sh && mkdir -p tmp && chown node:node tmp
+USER node
+EXPOSE 3333
+HEALTHCHECK --interval=30s --timeout=5s --start-period=40s --retries=3 \
+ CMD node -e "fetch('http://127.0.0.1:3333/up').then(r=>process.exit(r.ok?0:1)).catch(()=>process.exit(1))"
+ENTRYPOINT ["/usr/local/bin/entrypoint.sh"]
+CMD ["node", "bin/server.js"]
diff --git a/README.md b/README.md
index dff0775..31f3cf6 100644
--- a/README.md
+++ b/README.md
@@ -1,96 +1,94 @@
-# JavaScript.cm
+# javascript.cm
-This repository contains the source code for the [javascript.cm](https://javascript.cm) website ( javascript community in Cameroon ), inspired by [laravel.cm](https://laravel.cm). Laravel Cameroon is the largest community of PHP & Laravel developers residing in Cameroon.
+Le site de **JavaScript Cameroun**, la communauté des développeurs JavaScript du 237 : articles, forum d’entraide (questions / solutions acceptées), discussions, profils et annuaire des membres.
-## Server Requirements
+Staging :
-The following dependencies are required to start the installation:
+## Stack
-- Node.js >= 22.0.0
-- npm or yarn
-- PostgreSQL or MySQL
+| Couche | Outils |
+| --------------- | -------------------------------------------------------------------------------------------------------------- |
+| Backend | [AdonisJS 7](https://adonisjs.com) (TypeScript), Lucid ORM, VineJS, sessions + remember-me, rate limiting |
+| Frontend | [Inertia 3](https://inertiajs.com) + React 19 (rendu serveur / SSR), [Tailwind CSS 4](https://tailwindcss.com) |
+| Base de données | PostgreSQL 18 |
+| Contenu | Markdown (GFM) rendu côté serveur, nettoyé (`rehype-sanitize`) et coloré par [Shiki](https://shiki.style) |
+| Déploiement | Docker Compose derrière [Caddy](https://caddyserver.com) (HTTPS automatique) |
-## Installation
+## Démarrer en local
-1. Clone this repo:
-
-```bash
-git clone https://github.com/bleriotnoguia/javascript.cm.git
-```
-
-2. Install dependencies:
+Prérequis : **Node.js ≥ 24**, Docker (ou un PostgreSQL local).
```bash
+git clone https://github.com/javascriptcm/javascript.cm.git
+cd javascript.cm
npm install
-```
-or
+# PostgreSQL de développement
+docker run -d --name jscm-pg -p 5455:5432 \
+ -e POSTGRES_USER=jscm -e POSTGRES_PASSWORD=jscm -e POSTGRES_DB=jscm postgres:18-alpine
-```bash
-yarn install
+cp .env.example .env # puis DB_PORT=5455
+node ace generate:key # remplit APP_KEY
+node ace migration:run
+node ace db:seed # canaux, tags + contenu de démonstration en développement
+npm run dev # http://localhost:3333
```
-3. Configure your database in `.env`:
+Donner un rôle à un membre : `node ace user:promote --role=admin|moderator|member`.
-```env
-DB_CONNECTION=mysql
-MYSQL_HOST=localhost
-MYSQL_PORT=3306
-MYSQL_USER=root
-MYSQL_PASSWORD=
-MYSQL_DB_NAME=javascript_cm
-```
+### Connexion GitHub (optionnelle)
-4. Run migrations:
+Créez une OAuth App sur avec comme callback `${APP_URL}/auth/github/callback`, puis renseignez `GITHUB_CLIENT_ID` et `GITHUB_CLIENT_SECRET`. Sans ces variables, le bouton « Continuer avec GitHub » est simplement masqué.
-```bash
-node ace migration:run
-```
+## Commandes utiles
-5. Start the development server:
+| Commande | Rôle |
+| ------------------------ | -------------------------------------------------------------------------------- |
+| `npm run dev` | Serveur de développement (HMR) |
+| `npm run typecheck` | Vérification TypeScript (backend + frontend) |
+| `node ace test` | Tests (Japa) |
+| `node ace build` | Build de production dans `build/` |
+| `node ace codegen` | Régénère les types partagés (`.adonisjs/`) |
+| `node ace migration:run` | Applique les migrations (le schéma TypeScript `database/schema.ts` est régénéré) |
-```bash
-node ace serve --watch
-```
+## Organisation du code
-## Features
+```
+app/
+ controllers/ contrôleurs HTTP (auth, articles, forum, discussions, membres, admin…)
+ models/ modèles Lucid (étendent les classes générées dans database/schema.ts)
+ transformers/ sérialisation typée vers Inertia (types Data.* côté React)
+ services/ markdown, slugs, réponses, OAuth GitHub…
+ validators/ schémas VineJS (messages en français : start/validator.ts)
+inertia/
+ pages/ une page React par écran
+ components/ui/ design system (boutons, champs, menus, éditeur Markdown…)
+ css/app.css tokens de design (clair / sombre) et utilitaires
+start/routes/ routes par domaine (articles, forum, discussions, membres, admin)
+deploy/ Caddyfile et script de déploiement
+```
-- [x] User Authentication
-- [x] GitHub Authentication
-- [ ] Twitter Integration
-- [ ] Article Management
-- [ ] Forum
-- [ ] Discussions
-- [ ] Admin Dashboard
-- [ ] Telegram Notifications
+### Design
-## Available Commands
+Direction artistique : _un journal technique imprimé de la scène JavaScript camerounaise_. Papier chaud et encre carbone, le jaune JavaScript comme unique signal (surligneur, survols, focus), filets fins, Bricolage Grotesque + JetBrains Mono, thèmes clair et sombre. Toutes les couleurs passent par les tokens de `inertia/css/app.css`.
-| Command | Description |
-| ----------------------------- | ------------------------ |
-| `node ace serve --watch` | Start development server |
-| `node ace build` | Build for production |
-| `node ace test` | Run tests |
-| `node ace migration:run` | Run database migrations |
-| `node ace migration:rollback` | Rollback migrations |
+## Déploiement
-## Stack / Resources
+Le serveur exécute `docker-compose.yml` (application + PostgreSQL) ; Caddy, installé sur l’hôte, termine le TLS et relaie vers `127.0.0.1:3333` (`deploy/Caddyfile`).
-- [AdonisJS](https://adonisjs.com/)
-- [React.js](https://react.dev/)
-- [Inertia.js](https://inertiajs.com/)
-- [TailwindCSS](https://tailwindcss.com/)
-- [MySQL](https://www.mysql.com/)
-- [Lucid ORM](https://lucid.adonisjs.com/)
+- Chaque push sur la branche `staging` lance le workflow GitHub Actions _Staging_ : typecheck + build, puis déploiement par SSH. La clé utilisée est restreinte côté serveur à une seule commande (`deploy/deploy.sh`).
+- Au démarrage, le conteneur applique les migrations et les seeders idempotents. Le contenu de démonstration (membres et publications fictifs) n’est inséré en production que si `SEED_DEMO=true`.
+- Déploiement manuel sur le serveur : `./deploy/deploy.sh staging`.
+- Sauvegardes : `deploy/backup.sh` (dump PostgreSQL compressé, rotation 14 jours dans `~/backups/jscm`) est lancé chaque nuit par le timer systemd `jscm-backup` (`deploy/jscm-backup.{service,timer}`). Restauration : `docker compose exec -T db pg_restore -U -d --clean --if-exists < fichier.dump`.
-## Contributing
+## Contribuer
-Please read the contribution guide before creating an issue or sending a pull request.
+Les issues et pull requests sont les bienvenues. Ouvrez une issue pour discuter d’une fonctionnalité avant de vous lancer, gardez les PR ciblées, et vérifiez `npm run typecheck` et `node ace test` avant de pousser.
-## Security Vulnerabilities
+## Sécurité
-If you discover a security vulnerability in the application, please send an email to [support@javascript.cm](mailto:support@javascript.cm).
+Pour signaler une vulnérabilité, écrivez à [support@javascript.cm](mailto:support@javascript.cm) plutôt que d’ouvrir une issue publique.
-## License
+## Licence
-The MIT License. Please see the License file for more information.
+MIT. Inspiré par [Laravel Cameroun](https://laravel.cm).
diff --git a/ace.js b/ace.js
index e04fbe0..0eefd20 100644
--- a/ace.js
+++ b/ace.js
@@ -17,9 +17,9 @@
*/
/**
- * Register hook to process TypeScript files using ts-node-maintained
+ * Register hook to process TypeScript files using @poppinss/ts-exec
*/
-import 'ts-node-maintained/register/esm'
+import '@poppinss/ts-exec'
/**
* Import ace console entrypoint
diff --git a/adonisrc.ts b/adonisrc.ts
index 5235734..243457b 100644
--- a/adonisrc.ts
+++ b/adonisrc.ts
@@ -1,6 +1,21 @@
+import { indexPages } from '@adonisjs/inertia'
+import { indexEntities } from '@adonisjs/core/generators'
import { defineConfig } from '@adonisjs/core/app'
+import { generateRegistry } from '@tuyau/core/hooks'
export default defineConfig({
+ /*
+ |--------------------------------------------------------------------------
+ | Experimental flags
+ |--------------------------------------------------------------------------
+ |
+ | The following features will be enabled by default in the next major release
+ | of AdonisJS. You can opt into them today to avoid any breaking changes
+ | during upgrade.
+ |
+ */
+ experimental: {},
+
/*
|--------------------------------------------------------------------------
| Commands
@@ -10,7 +25,12 @@ export default defineConfig({
| will be scanned automatically from the "./commands" directory.
|
*/
- commands: [() => import('@adonisjs/core/commands'), () => import('@adonisjs/lucid/commands')],
+ commands: [
+ () => import('@adonisjs/core/commands'),
+ () => import('@adonisjs/lucid/commands'),
+ () => import('@adonisjs/session/commands'),
+ () => import('@adonisjs/inertia/commands'),
+ ],
/*
|--------------------------------------------------------------------------
@@ -34,11 +54,12 @@ export default defineConfig({
() => import('@adonisjs/vite/vite_provider'),
() => import('@adonisjs/shield/shield_provider'),
() => import('@adonisjs/static/static_provider'),
- () => import('@adonisjs/cors/cors_provider'),
() => import('@adonisjs/lucid/database_provider'),
- () => import('@adonisjs/auth/auth_provider'),
+ () => import('@adonisjs/cors/cors_provider'),
() => import('@adonisjs/inertia/inertia_provider'),
- () => import('@adonisjs/ally/ally_provider'),
+ () => import('@adonisjs/auth/auth_provider'),
+ () => import('@adonisjs/limiter/limiter_provider'),
+ () => import('#providers/api_provider'),
],
/*
@@ -49,7 +70,11 @@ export default defineConfig({
| List of modules to import before starting the application.
|
*/
- preloads: [() => import('#start/routes'), () => import('#start/kernel')],
+ preloads: [
+ () => import('#start/routes'),
+ () => import('#start/kernel'),
+ () => import('#start/validator'),
+ ],
/*
|--------------------------------------------------------------------------
@@ -63,12 +88,12 @@ export default defineConfig({
tests: {
suites: [
{
- files: ['tests/unit/**/*.spec(.ts|.js)'],
+ files: ['tests/unit/**/*.spec.{ts,js}'],
name: 'unit',
timeout: 2000,
},
{
- files: ['tests/functional/**/*.spec(.ts|.js)'],
+ files: ['tests/functional/**/*.spec.{ts,js}'],
name: 'functional',
timeout: 30000,
},
@@ -96,8 +121,14 @@ export default defineConfig({
},
],
- assetsBundler: false,
hooks: {
- onBuildStarting: [() => import('@adonisjs/vite/build_hook')],
+ init: [
+ indexEntities({
+ transformers: { enabled: true, withSharedProps: true },
+ }),
+ indexPages({ framework: 'react' }),
+ generateRegistry(),
+ ],
+ buildStarting: [() => import('@adonisjs/vite/build_hook')],
},
})
diff --git a/app/controllers/admin/channels_controller.ts b/app/controllers/admin/channels_controller.ts
new file mode 100644
index 0000000..33e19d6
--- /dev/null
+++ b/app/controllers/admin/channels_controller.ts
@@ -0,0 +1,77 @@
+import type { HttpContext } from '@adonisjs/core/http'
+import Channel from '#models/channel'
+import ChannelTransformer from '#transformers/channel_transformer'
+import { channelValidator } from '#validators/admin_validator'
+import { uniqueSlug } from '#services/slug'
+
+export default class AdminChannelsController {
+ /**
+ * GET /admin/canaux
+ */
+ async index({ inertia }: HttpContext) {
+ const channels = await Channel.query()
+ .withCount('threads')
+ .orderBy('position', 'asc')
+ .orderBy('name', 'asc')
+
+ return inertia.render('admin/channels', {
+ // ChannelTransformer has no "position": extend its public shape.
+ channels: channels.map((channel) => ({
+ ...new ChannelTransformer(channel).toObject(),
+ position: channel.position,
+ })),
+ nextPosition: channels.reduce((max, channel) => Math.max(max, channel.position), 0) + 1,
+ })
+ }
+
+ /**
+ * POST /admin/canaux
+ */
+ async store({ request, response, session }: HttpContext) {
+ const data = await request.validateUsing(channelValidator, { meta: {} })
+ const channel = await Channel.create({
+ name: data.name,
+ slug: data.slug ?? (await uniqueSlug('channels', data.name)),
+ description: data.description,
+ position: data.position,
+ })
+ session.flash('success', `Canal « ${channel.name} » créé.`)
+ return response.redirect().toPath('/admin/canaux')
+ }
+
+ /**
+ * PUT /admin/canaux/:id
+ */
+ async update({ params, request, response, session }: HttpContext) {
+ const channel = await Channel.findOrFail(params.id)
+ const data = await request.validateUsing(channelValidator, { meta: { id: channel.id } })
+ channel.merge({
+ name: data.name,
+ slug: data.slug ?? channel.slug,
+ description: data.description,
+ position: data.position,
+ })
+ await channel.save()
+ session.flash('success', `Canal « ${channel.name} » mis à jour.`)
+ return response.redirect().toPath('/admin/canaux')
+ }
+
+ /**
+ * DELETE /admin/canaux/:id — refused while questions live in the channel
+ * (the foreign key would delete them with it).
+ */
+ async destroy({ params, response, session }: HttpContext) {
+ const channel = await Channel.query().where('id', params.id).withCount('threads').firstOrFail()
+ const threads = Number(channel.$extras.threads_count ?? 0)
+ if (threads > 0) {
+ session.flash(
+ 'error',
+ `Le canal « ${channel.name} » contient ${threads} question${threads > 1 ? 's' : ''} : déplacez-les avant de le supprimer.`
+ )
+ return response.redirect().toPath('/admin/canaux')
+ }
+ await channel.delete()
+ session.flash('success', `Canal « ${channel.name} » supprimé.`)
+ return response.redirect().toPath('/admin/canaux')
+ }
+}
diff --git a/app/controllers/admin/members_controller.ts b/app/controllers/admin/members_controller.ts
new file mode 100644
index 0000000..0c4236a
--- /dev/null
+++ b/app/controllers/admin/members_controller.ts
@@ -0,0 +1,155 @@
+import type { HttpContext } from '@adonisjs/core/http'
+import { DateTime } from 'luxon'
+import db from '@adonisjs/lucid/services/db'
+import User from '#models/user'
+import UserTransformer from '#transformers/user_transformer'
+import { roleValidator } from '#validators/admin_validator'
+import { MEMBER_COUNTERS, likePattern } from '#controllers/members_controller'
+
+const FILTERS = ['tous', 'equipe', 'suspendus'] as const
+type Filter = (typeof FILTERS)[number]
+
+const RANK = { member: 0, moderator: 1, admin: 2 } as const
+
+export default class AdminMembersController {
+ /**
+ * GET /admin/membres — search, filter, moderate.
+ */
+ async index({ request, inertia, auth }: HttpContext) {
+ const viewer = auth.getUserOrFail()
+ const q = String(request.input('q') ?? '')
+ .trim()
+ .slice(0, 80)
+ const requested = request.input('filtre')
+ const filter: Filter = FILTERS.includes(requested) ? requested : 'tous'
+ const page = Math.max(1, Number.parseInt(request.input('page', '1'), 10) || 1)
+
+ const query = User.query()
+ .select('users.*')
+ .select(db.raw(`${MEMBER_COUNTERS.articles} as articles_count`))
+ .select(db.raw(`${MEMBER_COUNTERS.threads} as threads_count`))
+ .select(db.raw(`${MEMBER_COUNTERS.replies} as replies_count`))
+
+ if (q) {
+ const pattern = likePattern(q.replace(/^@/, ''))
+ query.where((builder) => {
+ builder.whereILike('users.username', pattern).orWhereILike('users.name', pattern)
+ // Only admins may look members up by e-mail.
+ if (viewer.isAdmin) builder.orWhereILike('users.email', pattern)
+ })
+ }
+ if (filter === 'equipe') query.whereIn('role', ['admin', 'moderator'])
+ if (filter === 'suspendus') query.whereNotNull('banned_at')
+
+ const [paginator, counts] = await Promise.all([
+ query.orderBy('users.created_at', 'desc').orderBy('users.id', 'desc').paginate(page, 30),
+ db
+ .rawQuery(
+ `select
+ (select count(*) from users) as tous,
+ (select count(*) from users where role in ('admin', 'moderator')) as equipe,
+ (select count(*) from users where banned_at is not null) as suspendus`
+ )
+ .then((result) => result.rows[0]),
+ ])
+
+ const items = paginator.all()
+ const meta = paginator.getMeta()
+
+ return inertia.render('admin/members', {
+ members: viewer.isAdmin
+ ? UserTransformer.paginate(items, meta).useVariant('forAdmin')
+ : UserTransformer.paginate(items, meta).useVariant('forModeration'),
+ filters: { q, filter },
+ counts: {
+ tous: Number(counts.tous),
+ equipe: Number(counts.equipe),
+ suspendus: Number(counts.suspendus),
+ },
+ })
+ }
+
+ /**
+ * PUT /admin/membres/:id/role — admins only (see routes).
+ */
+ async updateRole({ params, request, auth, response, session }: HttpContext) {
+ const viewer = auth.getUserOrFail()
+ const member = await User.findOrFail(params.id)
+ const { role } = await request.validateUsing(roleValidator)
+
+ if (member.id === viewer.id) {
+ session.flash('error', 'Vous ne pouvez pas modifier votre propre rôle.')
+ return response.redirect().back()
+ }
+ if (member.isBanned && role !== 'member') {
+ session.flash('error', 'Réactivez ce compte avant de lui confier un rôle.')
+ return response.redirect().back()
+ }
+
+ member.role = role
+ await member.save()
+
+ const labels = { member: 'membre', moderator: 'modérateur', admin: 'administrateur' }
+ session.flash('success', `@${member.username} est désormais ${labels[role]}.`)
+ return response.redirect().back()
+ }
+
+ /**
+ * POST /admin/membres/:id/ban — suspend an account.
+ */
+ async ban({ params, auth, response, session }: HttpContext) {
+ const viewer = auth.getUserOrFail()
+ const member = await User.findOrFail(params.id)
+
+ const refusal = this.cannotModerate(viewer, member)
+ if (refusal) {
+ session.flash('error', refusal)
+ return response.redirect().back()
+ }
+ if (member.isBanned) {
+ session.flash('error', `@${member.username} est déjà suspendu.`)
+ return response.redirect().back()
+ }
+
+ member.bannedAt = DateTime.now()
+ await member.save()
+ // Close the "remember me" sessions; the auth middleware does the rest.
+ await db.from('remember_me_tokens').where('tokenable_id', member.id).delete()
+
+ session.flash('success', `Le compte @${member.username} est suspendu.`)
+ return response.redirect().back()
+ }
+
+ /**
+ * DELETE /admin/membres/:id/ban — lift a suspension.
+ */
+ async unban({ params, auth, response, session }: HttpContext) {
+ const viewer = auth.getUserOrFail()
+ const member = await User.findOrFail(params.id)
+
+ const refusal = this.cannotModerate(viewer, member)
+ if (refusal) {
+ session.flash('error', refusal)
+ return response.redirect().back()
+ }
+
+ member.bannedAt = null
+ await member.save()
+ session.flash('success', `Le compte @${member.username} est réactivé.`)
+ return response.redirect().back()
+ }
+
+ /**
+ * Nobody moderates themselves; staff can only act on lower ranks
+ * (moderators cannot touch the staff, admins cannot ban admins).
+ */
+ private cannotModerate(viewer: User, member: User): string | null {
+ if (viewer.id === member.id) return 'Vous ne pouvez pas suspendre votre propre compte.'
+ if (RANK[member.role] >= RANK[viewer.role]) {
+ return viewer.isAdmin
+ ? 'Retirez d’abord son rôle d’administrateur à ce compte.'
+ : 'Seul un administrateur peut suspendre un membre de l’équipe.'
+ }
+ return null
+ }
+}
diff --git a/app/controllers/admin/overview_controller.ts b/app/controllers/admin/overview_controller.ts
new file mode 100644
index 0000000..99ac6c4
--- /dev/null
+++ b/app/controllers/admin/overview_controller.ts
@@ -0,0 +1,88 @@
+import type { HttpContext } from '@adonisjs/core/http'
+import db from '@adonisjs/lucid/services/db'
+import User from '#models/user'
+import Article from '#models/article'
+import Thread from '#models/thread'
+import Discussion from '#models/discussion'
+import UserTransformer from '#transformers/user_transformer'
+import ArticleTransformer from '#transformers/article_transformer'
+import ThreadTransformer from '#transformers/thread_transformer'
+import DiscussionTransformer from '#transformers/discussion_transformer'
+import { MEMBER_COUNTERS } from '#controllers/members_controller'
+
+export default class OverviewController {
+ /**
+ * GET /admin — community vital signs and the latest arrivals.
+ */
+ async index({ inertia, auth }: HttpContext) {
+ const [counts, members, articles, threads, discussions] = await Promise.all([
+ db
+ .rawQuery(
+ `select
+ (select count(*) from users where banned_at is null) as members,
+ (select count(*) from users where banned_at is not null) as banned,
+ (select count(*) from users where role in ('admin', 'moderator')) as staff,
+ (select count(*) from users where created_at > now() - interval '7 days') as signups_week,
+ (select count(*) from articles where published_at is not null and published_at <= now()) as articles,
+ (select count(*) from articles where published_at is null or published_at > now()) as drafts,
+ (select count(*) from threads) as threads,
+ (select count(*) from threads where solution_reply_id is null) as unsolved,
+ (select count(*) from discussions) as discussions,
+ (select count(*) from replies) as replies,
+ (select count(*) from tags) as tags,
+ (select count(*) from channels) as channels,
+ (select count(*) from reports where status = 'open') as reports_open,
+ (select count(*) from (
+ select 1 from reports where status = 'open' group by target_type, target_id
+ ) as queue) as reports_queue`
+ )
+ .then((result) => result.rows[0]),
+ User.query()
+ .select('users.*')
+ .select(db.raw(`${MEMBER_COUNTERS.articles} as articles_count`))
+ .select(db.raw(`${MEMBER_COUNTERS.threads} as threads_count`))
+ .select(db.raw(`${MEMBER_COUNTERS.replies} as replies_count`))
+ .orderBy('created_at', 'desc')
+ .limit(8),
+ Article.query()
+ .withScopes((s) => s.published())
+ .preload('author')
+ .withCount('likes')
+ .withCount('comments')
+ .orderBy('published_at', 'desc')
+ .limit(6),
+ Thread.query().preload('author').preload('channel').orderBy('created_at', 'desc').limit(6),
+ Discussion.query().preload('author').orderBy('created_at', 'desc').limit(6),
+ ])
+
+ const stats = Object.fromEntries(
+ Object.entries(counts as Record).map(([key, value]) => [key, Number(value)])
+ ) as Record<
+ | 'members'
+ | 'banned'
+ | 'staff'
+ | 'signups_week'
+ | 'articles'
+ | 'drafts'
+ | 'threads'
+ | 'unsolved'
+ | 'discussions'
+ | 'replies'
+ | 'tags'
+ | 'channels'
+ | 'reports_open'
+ | 'reports_queue',
+ number
+ >
+
+ return inertia.render('admin/index', {
+ stats,
+ members: auth.user!.isAdmin
+ ? UserTransformer.transform(members).useVariant('forAdmin')
+ : UserTransformer.transform(members).useVariant('forModeration'),
+ articles: ArticleTransformer.transform(articles),
+ threads: ThreadTransformer.transform(threads),
+ discussions: DiscussionTransformer.transform(discussions),
+ })
+ }
+}
diff --git a/app/controllers/admin/reports_controller.ts b/app/controllers/admin/reports_controller.ts
new file mode 100644
index 0000000..15aa9c8
--- /dev/null
+++ b/app/controllers/admin/reports_controller.ts
@@ -0,0 +1,436 @@
+import type { HttpContext } from '@adonisjs/core/http'
+import { DateTime } from 'luxon'
+import db from '@adonisjs/lucid/services/db'
+import type { DatabaseQueryBuilderContract } from '@adonisjs/lucid/types/querybuilder'
+import Report from '#models/report'
+import Article from '#models/article'
+import Thread from '#models/thread'
+import Discussion from '#models/discussion'
+import Reply from '#models/reply'
+import User from '#models/user'
+import ReportTransformer, { type ReportQueueTarget } from '#transformers/report_transformer'
+import { deleteReply } from '#services/reply_service'
+import { plainExcerpt } from '#services/markdown'
+import { THREAD_REPLIES_PER_PAGE } from '#controllers/threads_controller'
+import { DISCUSSION_REPLIES_PER_PAGE } from '#controllers/discussions_controller'
+import { REPORT_TARGETS, type ReportTarget } from '#validators/report_validator'
+
+const TABS = { ouverts: 'open', traites: 'resolved', ignores: 'dismissed' } as const
+type Tab = keyof typeof TABS
+type Status = (typeof TABS)[Tab]
+
+const PER_PAGE = 20
+
+/**
+ * Column of "replies" pointing at each kind of parent.
+ */
+const REPLY_PARENT_COLUMNS = {
+ article: 'article_id',
+ thread: 'thread_id',
+ discussion: 'discussion_id',
+} as const
+
+type Row = { type: ReportTarget; id: number }
+
+/**
+ * Same rule as User.canManageContent, from an already loaded owner (the
+ * queue lists up to 20 rows: no query per row).
+ */
+function canManage(viewer: User, owner: User | null) {
+ if (!owner) return viewer.isAdmin
+ if (viewer.id === owner.id || viewer.isAdmin) return true
+ return viewer.isModerator && owner.role === 'member'
+}
+
+/**
+ * Restrict a query on "reports" to the reports of one content.
+ */
+function ofTarget(query: DatabaseQueryBuilderContract, type: ReportTarget, id: number) {
+ return query.where('target_type', type).where('target_id', id)
+}
+
+/**
+ * Number of rows (distinct contents) per status, for the tabs.
+ */
+export async function reportQueueCounts(): Promise> {
+ const result = await db.rawQuery(
+ `select status, count(*) as total from (
+ select status from reports group by status, target_type, target_id
+ ) as grouped group by status`
+ )
+ const counts: Record = { open: 0, resolved: 0, dismissed: 0 }
+ for (const row of result.rows as { status: Status; total: string }[]) {
+ counts[row.status] = Number(row.total)
+ }
+ return counts
+}
+
+/**
+ * The moderation queue: what members reported, grouped by content. Reports
+ * outlive their content (deleted from the queue or elsewhere): such rows
+ * are shown from the snapshot taken when the report was filed.
+ */
+export default class AdminReportsController {
+ /**
+ * GET /admin/signalements?statut=ouverts|traites|ignores
+ */
+ async index({ request, inertia, auth }: HttpContext) {
+ const viewer = auth.getUserOrFail()
+ const requested = String(request.input('statut') ?? '')
+ const tab: Tab = Object.hasOwn(TABS, requested) ? (requested as Tab) : 'ouverts'
+ const status = TABS[tab]
+ const page = Math.max(1, Number.parseInt(request.input('page', '1'), 10) || 1)
+
+ const groups = db
+ .from('reports')
+ .select('target_type', 'target_id')
+ .select(db.raw('max(created_at) as last_reported_at'))
+ .where('status', status)
+ .groupBy('target_type', 'target_id')
+ if (status === 'open') {
+ groups.orderBy('last_reported_at', 'desc')
+ } else {
+ groups.orderByRaw('max(resolved_at) desc nulls last').orderBy('last_reported_at', 'desc')
+ }
+ groups.orderByRaw('max(id) desc')
+
+ const [paginator, counts] = await Promise.all([
+ groups.paginate(page, PER_PAGE),
+ reportQueueCounts(),
+ ])
+ const rows: Row[] = (paginator.all() as { target_type: ReportTarget; target_id: number }[]).map(
+ (row) => ({ type: row.target_type, id: Number(row.target_id) })
+ )
+
+ const ids: Record = {
+ article: [],
+ thread: [],
+ discussion: [],
+ reply: [],
+ }
+ for (const row of rows) ids[row.type].push(row.id)
+
+ const [reports, articles, threads, discussions, replies] = rows.length
+ ? await Promise.all([
+ Report.query()
+ .where('status', status)
+ .where((query) => {
+ for (const type of REPORT_TARGETS) {
+ if (!ids[type].length) continue
+ query.orWhere((sub) =>
+ sub.where('target_type', type).whereIn('target_id', ids[type])
+ )
+ }
+ })
+ .preload('reporter')
+ .preload('resolvedBy')
+ .orderBy('created_at', 'desc')
+ .orderBy('id', 'desc'),
+ Article.query()
+ .select('id', 'user_id', 'title', 'slug', 'published_at')
+ .whereIn('id', ids.article)
+ .preload('author'),
+ Thread.query()
+ .select('id', 'user_id', 'title', 'slug')
+ .whereIn('id', ids.thread)
+ .preload('author'),
+ Discussion.query()
+ .select('id', 'user_id', 'title', 'slug')
+ .whereIn('id', ids.discussion)
+ .preload('author'),
+ Reply.query()
+ .select('replies.*')
+ // Position among its siblings, to link to the right page of a long thread.
+ .select(
+ db.raw(
+ `(select count(*) from replies as siblings
+ where (siblings.thread_id = replies.thread_id or siblings.discussion_id = replies.discussion_id)
+ and siblings.id < replies.id) as position`
+ )
+ )
+ .whereIn('id', ids.reply)
+ .preload('author')
+ .preload('thread', (query) => query.select('id', 'title', 'slug'))
+ .preload('discussion', (query) => query.select('id', 'title', 'slug'))
+ .preload('article', (query) => query.select('id', 'title', 'slug', 'published_at')),
+ ])
+ : [[], [], [], [], []]
+
+ const grouped = rows
+ .map((row) => ({
+ row,
+ reports: reports.filter(
+ (report) => report.targetType === row.type && report.targetId === row.id
+ ),
+ live: describe(row, { articles, threads, discussions, replies }),
+ }))
+ .filter((item) => item.reports.length)
+
+ // Owners of deleted contents, from the snapshots.
+ const missingOwnerIds = grouped
+ .filter((item) => !item.live)
+ .map((item) => item.reports.find((report) => report.targetOwnerId)?.targetOwnerId)
+ .filter((id): id is number => typeof id === 'number')
+ const owners = missingOwnerIds.length
+ ? await User.query().whereIn('id', [...new Set(missingOwnerIds)])
+ : []
+
+ const leads = grouped.map(({ row, reports: group, live }) => {
+ const content = live ?? snapshot(row, group, owners)
+ const [lead] = group
+ lead.$extras.queue = {
+ target: content.target,
+ owner: content.owner,
+ reports: group,
+ canDelete: !content.target.deleted && canManage(viewer, content.owner),
+ }
+ return lead
+ })
+
+ return inertia.render('admin/reports', {
+ rows: ReportTransformer.paginate(leads, paginator.getMeta()).useVariant('forQueue').depth(3),
+ tab,
+ counts: {
+ ouverts: counts.open,
+ traites: counts.resolved,
+ ignores: counts.dismissed,
+ },
+ })
+ }
+
+ /**
+ * POST /admin/signalements/:target/:id/ignorer — the content stays online.
+ */
+ async dismiss(ctx: HttpContext) {
+ return this.close(ctx, 'dismissed')
+ }
+
+ /**
+ * POST /admin/signalements/:target/:id/traiter — handled another way
+ * (content edited, author contacted…), or the content is already gone.
+ */
+ async resolve(ctx: HttpContext) {
+ return this.close(ctx, 'resolved')
+ }
+
+ /**
+ * DELETE /admin/signalements/:target/:id/contenu — remove the reported
+ * content. Staff ranks apply: moderators cannot delete the staff's content.
+ * Its reports stay, marked as resolved (with those of its replies, which
+ * go with it).
+ */
+ async destroyContent({ params, auth, response, session }: HttpContext) {
+ const viewer = auth.getUserOrFail()
+ const type = params.target as ReportTarget
+ const id = Number(params.id)
+
+ const open = await this.openReportsCount(type, id)
+ if (!open) {
+ session.flash('error', 'Ces signalements ont déjà été traités.')
+ return response.redirect().back()
+ }
+
+ const content = await this.findContent(type, id)
+ if (!content) {
+ session.flash(
+ 'error',
+ 'Ce contenu a déjà été supprimé : marquez plutôt le signalement comme traité.'
+ )
+ return response.redirect().back()
+ }
+ if (!(await viewer.canManageContent(content.userId))) {
+ session.flash(
+ 'error',
+ 'Seul un administrateur peut supprimer le contenu d’un membre de l’équipe.'
+ )
+ return response.redirect().back()
+ }
+
+ // Record the decision, then delete (the reports keep their target
+ // identity and snapshot: ON DELETE SET NULL). Replies go through the
+ // reply service so the thread / discussion counters stay right.
+ const closed = await this.closeReports(type, id, 'resolved', viewer, { withReplies: true })
+ try {
+ if (content instanceof Reply) {
+ await deleteReply(content)
+ } else {
+ await content.delete()
+ }
+ } catch (error) {
+ await db
+ .from('reports')
+ .whereIn('id', closed)
+ .update({ status: 'open', resolved_by_id: null, resolved_at: null })
+ throw error
+ }
+
+ const label = closed.length > 1 ? `${closed.length} signalements clos` : 'signalement clos'
+ session.flash('success', `Contenu supprimé, ${label}.`)
+ return response.redirect().back()
+ }
+
+ private async close({ params, auth, response, session }: HttpContext, status: Status) {
+ const viewer = auth.getUserOrFail()
+ const closed = await this.closeReports(
+ params.target as ReportTarget,
+ Number(params.id),
+ status,
+ viewer
+ )
+ if (!closed.length) {
+ session.flash('error', 'Ces signalements ont déjà été traités.')
+ return response.redirect().back()
+ }
+ session.flash(
+ 'success',
+ status === 'dismissed'
+ ? 'Signalement ignoré : le contenu reste en ligne.'
+ : 'Signalement marqué comme traité.'
+ )
+ return response.redirect().back()
+ }
+
+ /**
+ * Close every open report of a content (and, when it is deleted, of its
+ * replies). Returns the ids of the reports closed.
+ */
+ private async closeReports(
+ type: ReportTarget,
+ id: number,
+ status: Status,
+ viewer: User,
+ options: { withReplies?: boolean } = {}
+ ): Promise {
+ const now = DateTime.now().toSQL()
+ const rows: { id: number }[] = await db
+ .from('reports')
+ .where('status', 'open')
+ .where((query) => {
+ query.where((sub) => ofTarget(sub, type, id))
+ if (options.withReplies && type !== 'reply') {
+ query.orWhere((sub) =>
+ sub
+ .where('target_type', 'reply')
+ .whereIn(
+ 'target_id',
+ db.from('replies').select('id').where(REPLY_PARENT_COLUMNS[type], id)
+ )
+ )
+ }
+ })
+ .update({ status, resolved_by_id: viewer.id, resolved_at: now, updated_at: now }, ['id'])
+ return rows.map((row) => row.id)
+ }
+
+ private async openReportsCount(type: ReportTarget, id: number) {
+ const [row] = await ofTarget(db.from('reports'), type, id)
+ .where('status', 'open')
+ .count('* as total')
+ return Number(row?.total ?? 0)
+ }
+
+ private async findContent(type: ReportTarget, id: number) {
+ switch (type) {
+ case 'article':
+ return Article.find(id)
+ case 'thread':
+ return Thread.find(id)
+ case 'discussion':
+ return Discussion.find(id)
+ case 'reply':
+ return Reply.find(id)
+ }
+ }
+}
+
+type Described = { target: ReportQueueTarget; owner: User | null }
+
+/**
+ * A deleted content, as the reports remember it: label (title, or the
+ * parent's title for a reply) and owner. No link.
+ */
+function snapshot(row: Row, reports: Report[], owners: User[]): Described {
+ const label = reports.find((report) => report.targetLabel)?.targetLabel ?? null
+ const ownerId = reports.find((report) => report.targetOwnerId)?.targetOwnerId ?? null
+ const isReply = row.type === 'reply'
+ return {
+ target: {
+ type: row.type,
+ id: row.id,
+ title: isReply ? '' : (label ?? ''),
+ parent: isReply && label ? { type: null, title: label } : null,
+ href: null,
+ isDraft: false,
+ deleted: true,
+ },
+ owner: owners.find((owner) => owner.id === ownerId) ?? null,
+ }
+}
+
+/**
+ * Title, link and owner of a reported content that still exists.
+ */
+function describe(
+ row: Row,
+ loaded: { articles: Article[]; threads: Thread[]; discussions: Discussion[]; replies: Reply[] }
+): Described | null {
+ const base = { type: row.type, id: row.id, parent: null, isDraft: false, deleted: false }
+ switch (row.type) {
+ case 'article': {
+ const article = loaded.articles.find((item) => item.id === row.id)
+ if (!article) return null
+ return {
+ target: {
+ ...base,
+ title: article.title,
+ href: `/articles/${article.slug}`,
+ isDraft: !article.isPublished,
+ },
+ owner: article.author ?? null,
+ }
+ }
+ case 'thread': {
+ const thread = loaded.threads.find((item) => item.id === row.id)
+ if (!thread) return null
+ return {
+ target: { ...base, title: thread.title, href: `/forum/${thread.slug}` },
+ owner: thread.author ?? null,
+ }
+ }
+ case 'discussion': {
+ const discussion = loaded.discussions.find((item) => item.id === row.id)
+ if (!discussion) return null
+ return {
+ target: { ...base, title: discussion.title, href: `/discussions/${discussion.slug}` },
+ owner: discussion.author ?? null,
+ }
+ }
+ case 'reply': {
+ const reply = loaded.replies.find((item) => item.id === row.id)
+ if (!reply) return null
+ const position = Number(reply.$extras.position ?? 0)
+ const anchor = `#reponse-${reply.id}`
+ const excerpt = plainExcerpt(reply.body, 280) || 'Réponse composée uniquement de code.'
+ let parent: ReportQueueTarget['parent'] = null
+ let href = anchor
+ let isDraft = false
+ if (reply.thread) {
+ const page = Math.floor(position / THREAD_REPLIES_PER_PAGE) + 1
+ parent = { type: 'thread', title: reply.thread.title }
+ href = `/forum/${reply.thread.slug}${page > 1 ? `?page=${page}` : ''}${anchor}`
+ } else if (reply.discussion) {
+ const page = Math.floor(position / DISCUSSION_REPLIES_PER_PAGE) + 1
+ parent = { type: 'discussion', title: reply.discussion.title }
+ href = `/discussions/${reply.discussion.slug}${page > 1 ? `?page=${page}` : ''}${anchor}`
+ } else if (reply.article) {
+ parent = { type: 'article', title: reply.article.title }
+ href = `/articles/${reply.article.slug}${anchor}`
+ isDraft = !reply.article.isPublished
+ }
+ return {
+ target: { ...base, title: excerpt, parent, href, isDraft },
+ owner: reply.author ?? null,
+ }
+ }
+ }
+}
diff --git a/app/controllers/admin/tags_controller.ts b/app/controllers/admin/tags_controller.ts
new file mode 100644
index 0000000..af5820f
--- /dev/null
+++ b/app/controllers/admin/tags_controller.ts
@@ -0,0 +1,61 @@
+import type { HttpContext } from '@adonisjs/core/http'
+import Tag from '#models/tag'
+import TagTransformer from '#transformers/tag_transformer'
+import { tagValidator } from '#validators/admin_validator'
+import { uniqueSlug } from '#services/slug'
+
+export default class AdminTagsController {
+ /**
+ * GET /admin/tags
+ */
+ async index({ inertia }: HttpContext) {
+ const tags = await Tag.query().withCount('articles').withCount('discussions')
+ // French alphabetical order ("Événements" next to "DevOps", not after "Vue").
+ tags.sort((a, b) => a.name.localeCompare(b.name, 'fr', { sensitivity: 'base' }))
+
+ return inertia.render('admin/tags', {
+ tags: TagTransformer.transform(tags),
+ })
+ }
+
+ /**
+ * POST /admin/tags
+ */
+ async store({ request, response, session }: HttpContext) {
+ const data = await request.validateUsing(tagValidator, { meta: {} })
+ const tag = await Tag.create({
+ name: data.name,
+ slug: data.slug ?? (await uniqueSlug('tags', data.name)),
+ description: data.description,
+ })
+ session.flash('success', `Tag « ${tag.name} » créé.`)
+ return response.redirect().toPath('/admin/tags')
+ }
+
+ /**
+ * PUT /admin/tags/:id — the slug only changes when edited explicitly
+ * (it appears in public URLs such as /articles?tag=…).
+ */
+ async update({ params, request, response, session }: HttpContext) {
+ const tag = await Tag.findOrFail(params.id)
+ const data = await request.validateUsing(tagValidator, { meta: { id: tag.id } })
+ tag.merge({
+ name: data.name,
+ slug: data.slug ?? tag.slug,
+ description: data.description,
+ })
+ await tag.save()
+ session.flash('success', `Tag « ${tag.name} » mis à jour.`)
+ return response.redirect().toPath('/admin/tags')
+ }
+
+ /**
+ * DELETE /admin/tags/:id — content keeps existing, only the label goes.
+ */
+ async destroy({ params, response, session }: HttpContext) {
+ const tag = await Tag.findOrFail(params.id)
+ await tag.delete()
+ session.flash('success', `Tag « ${tag.name} » supprimé.`)
+ return response.redirect().toPath('/admin/tags')
+ }
+}
diff --git a/app/controllers/article_actions_controller.ts b/app/controllers/article_actions_controller.ts
new file mode 100644
index 0000000..67461eb
--- /dev/null
+++ b/app/controllers/article_actions_controller.ts
@@ -0,0 +1,116 @@
+import type { HttpContext } from '@adonisjs/core/http'
+import { DateTime } from 'luxon'
+import { errors as lucidErrors } from '@adonisjs/lucid'
+import Article from '#models/article'
+import Like from '#models/like'
+import type User from '#models/user'
+
+/**
+ * Load an article the user may manage (owner or moderator). Drafts of
+ * other people stay invisible (404); published articles get a flash error.
+ */
+async function managedArticle(slug: string, user: User) {
+ const article = await Article.findByOrFail('slug', slug)
+ if (await user.canManageContent(article.userId)) return { article, allowed: true as const }
+ if (!article.isPublished) throw new lucidErrors.E_ROW_NOT_FOUND()
+ return { article, allowed: false as const }
+}
+
+/**
+ * One-click actions on an article: like, publish / unpublish, feature.
+ */
+export default class ArticleActionsController {
+ /**
+ * POST /articles/:slug/like — toggle the viewer's like.
+ */
+ async like({ params, auth, response, session }: HttpContext) {
+ const user = auth.user!
+ const article = await Article.query()
+ .where('slug', params.slug)
+ .withScopes((scopes) => scopes.published())
+ .firstOrFail()
+
+ if (article.userId === user.id) {
+ session.flash('error', 'Vous ne pouvez pas aimer votre propre article.')
+ return response.redirect().back()
+ }
+
+ const existing = await Like.query()
+ .where('user_id', user.id)
+ .where('article_id', article.id)
+ .first()
+ if (existing) {
+ await existing.delete()
+ } else {
+ try {
+ await Like.create({ userId: user.id, articleId: article.id })
+ } catch (error) {
+ // Double click: the unique (user_id, article_id) index already holds it.
+ if ((error as { code?: string }).code !== '23505') throw error
+ }
+ }
+ return response.redirect().back()
+ }
+
+ /**
+ * POST /articles/:slug/publish — publish a draft right away.
+ */
+ async publish({ params, auth, response, session }: HttpContext) {
+ const { article, allowed } = await managedArticle(params.slug, auth.user!)
+ if (!allowed || article.userId !== auth.user!.id) {
+ session.flash('error', 'Seul l’auteur de cet article peut le publier.')
+ return response.redirect().back()
+ }
+
+ if (!article.isPublished) {
+ article.publishedAt = DateTime.now()
+ await article.save()
+ session.flash('success', 'Article publié. Merci pour ce partage !')
+ }
+ return response.redirect().toPath(`/articles/${article.slug}`)
+ }
+
+ /**
+ * POST /articles/:slug/unpublish — back to draft (and off the front page).
+ */
+ async unpublish({ params, auth, response, session }: HttpContext) {
+ const { article, allowed } = await managedArticle(params.slug, auth.user!)
+ if (!allowed) {
+ session.flash('error', 'Seul l’auteur de cet article peut le dépublier.')
+ return response.redirect().back()
+ }
+
+ if (article.publishedAt) {
+ article.publishedAt = null
+ article.featuredAt = null
+ await article.save()
+ }
+ session.flash('success', 'Article repassé en brouillon : il n’est plus visible publiquement.')
+ return response.redirect().back()
+ }
+
+ /**
+ * POST /articles/:slug/feature — moderators toggle "à la une".
+ */
+ async feature({ params, auth, response, session }: HttpContext) {
+ const user = auth.user!
+ if (!user.isModerator) {
+ session.flash('error', 'Action réservée à l’équipe de modération.')
+ return response.redirect().back()
+ }
+
+ const article = await Article.findByOrFail('slug', params.slug)
+ if (!article.isPublished) {
+ session.flash('error', 'Publiez l’article avant de le mettre à la une.')
+ return response.redirect().back()
+ }
+
+ // Query update: featuring is editorial, not a content change (keeps updated_at).
+ const featuring = article.featuredAt === null
+ await Article.query()
+ .where('id', article.id)
+ .update({ featured_at: featuring ? DateTime.now().toSQL() : null })
+ session.flash('success', featuring ? 'Article mis à la une.' : 'Article retiré de la une.')
+ return response.redirect().back()
+ }
+}
diff --git a/app/controllers/article_comments_controller.ts b/app/controllers/article_comments_controller.ts
new file mode 100644
index 0000000..1122106
--- /dev/null
+++ b/app/controllers/article_comments_controller.ts
@@ -0,0 +1,26 @@
+import type { HttpContext } from '@adonisjs/core/http'
+import Article from '#models/article'
+import { replyValidator } from '#validators/reply_validator'
+import { createReply } from '#services/reply_service'
+
+/**
+ * Comments on articles are replies (edit / delete / like go through the
+ * shared /replies routes). Only published articles accept comments.
+ */
+export default class ArticleCommentsController {
+ /**
+ * POST /articles/:slug/comments
+ */
+ async store({ params, request, auth, response, session }: HttpContext) {
+ const article = await Article.query()
+ .where('slug', params.slug)
+ .withScopes((scopes) => scopes.published())
+ .firstOrFail()
+
+ const { body } = await request.validateUsing(replyValidator)
+ const reply = await createReply({ type: 'article', id: article.id }, auth.user!, body)
+
+ session.flash('success', 'Commentaire publié.')
+ return response.redirect().toPath(`/articles/${article.slug}#reponse-${reply.id}`)
+ }
+}
diff --git a/app/controllers/articles_controller.ts b/app/controllers/articles_controller.ts
index 7a5d845..6c4fe40 100644
--- a/app/controllers/articles_controller.ts
+++ b/app/controllers/articles_controller.ts
@@ -1,48 +1,360 @@
-import { HttpContext } from '@adonisjs/core/http'
-import { articleValidator } from '#validators/article_validator'
-import Article from '#models/article'
+import { markSubjectRead } from '#services/notifications'
+import type { HttpContext } from '@adonisjs/core/http'
import { DateTime } from 'luxon'
+import db from '@adonisjs/lucid/services/db'
+import { errors as lucidErrors } from '@adonisjs/lucid'
+import Article from '#models/article'
+import Tag from '#models/tag'
+import Like from '#models/like'
+import Reply from '#models/reply'
+import type User from '#models/user'
+import ArticleTransformer from '#transformers/article_transformer'
+import TagTransformer from '#transformers/tag_transformer'
+import UserTransformer from '#transformers/user_transformer'
+import ReplyTransformer from '#transformers/reply_transformer'
+import { articleValidator } from '#validators/article_validator'
+import { plainExcerpt, readingMinutes, renderMarkdown } from '#services/markdown'
+import { uniqueSlug } from '#services/slug'
+import { withReplyMeta } from '#services/reply_service'
+
+const PER_PAGE = 15
+const SEEN_SESSION_KEY = 'articles_seen'
+
+type ArticleSort = 'recents' | 'populaires'
+type ArticlePayload = Awaited>
+
+/**
+ * Escape LIKE wildcards so a search for "100%" stays literal.
+ */
+function likePattern(term: string) {
+ return `%${term.replace(/[\\%_]/g, (char) => `\\${char}`)}%`
+}
+
+/**
+ * Excerpt generated from the body when the author leaves it blank
+ * (headings are skipped: they read badly once flattened into a sentence).
+ */
+function autoExcerpt(body: string) {
+ return plainExcerpt(body.replace(/^#{1,6}\s.*$/gm, ''))
+}
+
+/**
+ * Copy validated form data onto the model: rendered HTML, reading time,
+ * and an excerpt generated from the body when the author left it blank.
+ */
+async function fillArticle(article: Article, data: ArticlePayload) {
+ article.title = data.title
+ article.body = data.body
+ article.bodyHtml = await renderMarkdown(data.body)
+ article.readingMinutes = readingMinutes(data.body)
+ article.excerpt = data.excerpt ?? autoExcerpt(data.body)
+ article.coverUrl = data.coverUrl ?? null
+}
+
+/**
+ * Only keep tag ids that exist (unknown ids are silently dropped).
+ */
+async function existingTagIds(ids: number[] | undefined) {
+ if (!ids?.length) return []
+ const tags = await Tag.query()
+ .whereIn('id', [...new Set(ids)])
+ .select('id')
+ return tags.map((tag) => tag.id)
+}
+
+async function saveWithTags(article: Article, tagIds: number[]) {
+ await db.transaction(async (trx) => {
+ article.useTransaction(trx)
+ await article.save()
+ await article.related('tags').sync(tagIds, true, trx)
+ })
+}
+
+/**
+ * "À lire ensuite": up to 3 published articles sharing the most tags with
+ * "article", completed with the latest ones.
+ */
+async function relatedArticles(article: Article) {
+ const base = () =>
+ Article.query()
+ .withScopes((scopes) => scopes.published())
+ .whereNot('id', article.id)
+ .preload('author')
+ .preload('tags')
+
+ const tagIds = article.tags.map((tag) => tag.id)
+ let related: Article[] = []
+ if (tagIds.length) {
+ related = await base()
+ .whereHas('tags', (query) => query.whereIn('tags.id', tagIds))
+ .orderByRaw(
+ `(select count(*) from article_tag where article_tag.article_id = articles.id and article_tag.tag_id in (${tagIds.map(() => '?').join(', ')})) desc`,
+ tagIds
+ )
+ .orderBy('published_at', 'desc')
+ .limit(3)
+ }
+ if (related.length < 3) {
+ const latest = await base()
+ .whereNotIn(
+ 'id',
+ related.map((item) => item.id)
+ )
+ .orderBy('published_at', 'desc')
+ .limit(3 - related.length)
+ related = [...related, ...latest]
+ }
+ return related
+}
+
+/**
+ * Drafts (unpublished or scheduled) only exist for their author and the
+ * moderators; everyone else gets a 404.
+ */
+function assertVisible(article: Article, viewer: User | undefined) {
+ if (article.isPublished) return
+ if (viewer && viewer.canSeeDraftsOf(article.userId)) return
+ throw new lucidErrors.E_ROW_NOT_FOUND()
+}
export default class ArticlesController {
+ /**
+ * GET /articles — published articles, filters: ?tag= ?q= ?sort= ?page=
+ */
async index({ inertia, request }: HttpContext) {
- const page = request.input('page', 1)
- const articles = await Article.query()
+ const qs = request.qs()
+ const page = Math.max(1, Number.parseInt(String(qs.page ?? '1'), 10) || 1)
+ const search = typeof qs.q === 'string' ? qs.q.trim().slice(0, 100) : ''
+ const sort: ArticleSort = qs.sort === 'populaires' ? 'populaires' : 'recents'
+ const tagSlug = typeof qs.tag === 'string' ? qs.tag.trim().toLowerCase().slice(0, 60) : ''
+ const unfiltered = !tagSlug && !search && sort === 'recents'
+
+ const [tags, featured] = await Promise.all([
+ Tag.query()
+ .withCount('articles', (query) => {
+ query
+ .whereNotNull('articles.published_at')
+ .where('articles.published_at', '<=', DateTime.now().toSQL()!)
+ })
+ .orderBy('name', 'asc'),
+ unfiltered
+ ? Article.query()
+ .withScopes((scopes) => scopes.published())
+ .whereNotNull('featured_at')
+ .preload('author')
+ .preload('tags')
+ .withCount('likes')
+ .withCount('comments')
+ .orderBy('featured_at', 'desc')
+ .first()
+ : null,
+ ])
+
+ const query = Article.query()
+ .withScopes((scopes) => scopes.published())
.preload('author')
- .where('is_published', true)
- .orderBy('published_at', 'desc')
- .paginate(page, 10)
+ .preload('tags')
+ .withCount('likes')
+ .withCount('comments')
+
+ if (featured) query.whereNot('articles.id', featured.id)
+ if (tagSlug) query.whereHas('tags', (tagQuery) => tagQuery.where('tags.slug', tagSlug))
+ if (search) {
+ const pattern = likePattern(search)
+ query.where((where) => where.whereILike('title', pattern).orWhereILike('excerpt', pattern))
+ }
+ if (sort === 'populaires') {
+ query.orderBy('likes_count', 'desc').orderBy('views_count', 'desc')
+ }
+ query.orderBy('published_at', 'desc').orderBy('id', 'desc')
+
+ const paginator = await query.paginate(page, PER_PAGE)
+ const indexedTags = tags
+ .filter((tag) => Number(tag.$extras.articles_count) > 0)
+ .sort((a, b) => Number(b.$extras.articles_count) - Number(a.$extras.articles_count))
+ const activeTag = tagSlug ? (tags.find((tag) => tag.slug === tagSlug) ?? null) : null
return inertia.render('articles/index', {
- articles: articles.toJSON(),
+ articles: ArticleTransformer.paginate(paginator.all(), paginator.getMeta()),
+ featured: featured ? ArticleTransformer.transform(featured) : null,
+ total: paginator.total + (featured ? 1 : 0),
+ tags: TagTransformer.transform(indexedTags),
+ activeTag: activeTag ? TagTransformer.transform(activeTag) : null,
+ filters: { q: search, sort, tag: tagSlug || null },
})
}
+ /**
+ * GET /articles/:slug
+ */
+ async show({ params, inertia, auth, session }: HttpContext) {
+ const viewer = auth.user
+ const article = await Article.query()
+ .where('slug', params.slug)
+ .preload('author')
+ .preload('tags', (query) => query.orderBy('name', 'asc'))
+ .withCount('likes')
+ .withCount('comments')
+ .firstOrFail()
+
+ assertVisible(article, viewer)
+ if (viewer) await markSubjectRead(viewer.id, { articleId: article.id })
+
+ /**
+ * Count one view per session (likes and comments redirect back here),
+ * never the author's own visits, never drafts.
+ */
+ if (article.isPublished && viewer?.id !== article.userId) {
+ const seen = session.get(SEEN_SESSION_KEY, []) as number[]
+ if (!seen.includes(article.id)) {
+ await Article.query().where('id', article.id).increment('views_count', 1)
+ article.viewsCount += 1
+ session.put(SEEN_SESSION_KEY, [...seen.slice(-29), article.id])
+ }
+ }
+
+ // withReplyMeta is a query modifier (Lucid's .apply() runs scopes instead).
+ const commentsQuery = Reply.query().where('article_id', article.id)
+ withReplyMeta(viewer)(commentsQuery)
+
+ const [comments, related, liked, authorTotals] = await Promise.all([
+ commentsQuery,
+ relatedArticles(article),
+ viewer
+ ? Like.query().where('article_id', article.id).where('user_id', viewer.id).first()
+ : null,
+ db
+ .from('articles')
+ .where('user_id', article.userId)
+ .whereNotNull('published_at')
+ .where('published_at', '<=', DateTime.now().toSQL()!)
+ .count('* as total')
+ .first(),
+ ])
+
+ return inertia.render('articles/[slug]', {
+ article: ArticleTransformer.transform(article).useVariant('forDetail'),
+ author: UserTransformer.transform(article.author).useVariant('forProfile'),
+ authorArticlesCount: Number(authorTotals?.total ?? 0),
+ comments: ReplyTransformer.transform(comments),
+ related: ArticleTransformer.transform(related),
+ likedByMe: Boolean(liked),
+ canManage: Boolean(viewer && (await viewer.canManageContent(article.userId))),
+ })
+ }
+
+ /**
+ * GET /articles/nouveau
+ */
async create({ inertia }: HttpContext) {
- return inertia.render('articles/create')
+ const tags = await Tag.query().orderBy('id', 'asc')
+ return inertia.render('articles/create', { tags: TagTransformer.transform(tags) })
}
- async store({ request, auth, response }: HttpContext) {
- const data = await articleValidator.validate(request.all())
+ /**
+ * POST /articles
+ */
+ async store({ request, auth, response, session }: HttpContext) {
+ const user = auth.user!
+ const data = await request.validateUsing(articleValidator)
+
const article = new Article()
+ article.userId = user.id
+ article.slug = await uniqueSlug('articles', data.title)
+ await fillArticle(article, data)
+ if (data.publish) article.publishedAt = DateTime.now()
- article.title = data.title
- article.content = data.content
- article.excerpt = data.excerpt
- article.isPublished = data.isPublished || false
- article.authorId = auth.user!.id
- if (data.isPublished) {
+ await saveWithTags(article, await existingTagIds(data.tags))
+
+ session.flash(
+ 'success',
+ data.publish
+ ? 'Article publié. Merci pour ce partage !'
+ : 'Brouillon enregistré. Il n’est visible que par vous.'
+ )
+ return response.redirect().toPath(`/articles/${article.slug}`)
+ }
+
+ /**
+ * GET /articles/:slug/modifier
+ */
+ async edit({ params, inertia, auth, response, session }: HttpContext) {
+ const user = auth.user!
+ const article = await Article.query().where('slug', params.slug).preload('tags').firstOrFail()
+ assertVisible(article, user)
+ if (!(await user.canManageContent(article.userId))) {
+ session.flash('error', 'Seul l’auteur de cet article peut le modifier.')
+ return response.redirect().toPath(`/articles/${article.slug}`)
+ }
+
+ const tags = await Tag.query().orderBy('id', 'asc')
+ return inertia.render('articles/edit', {
+ article: ArticleTransformer.transform(article).useVariant('forEdit'),
+ excerptIsAuto: article.excerpt === autoExcerpt(article.body),
+ tags: TagTransformer.transform(tags),
+ })
+ }
+
+ /**
+ * PUT /articles/:slug
+ */
+ async update({ params, request, auth, response, session }: HttpContext) {
+ const user = auth.user!
+ const article = await Article.findByOrFail('slug', params.slug)
+ assertVisible(article, user)
+ if (!(await user.canManageContent(article.userId))) {
+ session.flash('error', 'Seul l’auteur de cet article peut le modifier.')
+ return response.redirect().toPath(`/articles/${article.slug}`)
+ }
+
+ const data = await request.validateUsing(articleValidator)
+ const wasPublic = article.isPublished
+
+ /**
+ * The URL only follows the title while nobody can have seen or shared
+ * it: never published (and never viewed, since views are only counted
+ * on published articles).
+ */
+ const everPublic = wasPublic || article.viewsCount > 0
+ if (data.title !== article.title && !everPublic) {
+ article.slug = await uniqueSlug('articles', data.title, article.id)
+ }
+
+ await fillArticle(article, data)
+ if (data.publish && !wasPublic) {
article.publishedAt = DateTime.now()
+ } else if (!data.publish && article.publishedAt) {
+ article.publishedAt = null
+ article.featuredAt = null
}
- await article.generateSlug()
- await article.save()
+ await saveWithTags(article, await existingTagIds(data.tags))
- return response.redirect().toRoute('articles.show', { slug: article.slug })
+ let message = 'Brouillon enregistré.'
+ if (data.publish)
+ message = wasPublic
+ ? 'Modifications enregistrées.'
+ : 'Article publié. Merci pour ce partage !'
+ else if (wasPublic)
+ message = 'Article repassé en brouillon : il n’est plus visible publiquement.'
+ session.flash('success', message)
+ return response.redirect().toPath(`/articles/${article.slug}`)
}
- async show({ inertia, params }: HttpContext) {
- const article = await Article.query().where('slug', params.slug).preload('author').firstOrFail()
+ /**
+ * DELETE /articles/:slug — comments, likes and tag links cascade.
+ */
+ async destroy({ params, auth, response, session }: HttpContext) {
+ const user = auth.user!
+ const article = await Article.findByOrFail('slug', params.slug)
+ assertVisible(article, user)
+ if (!(await user.canManageContent(article.userId))) {
+ session.flash('error', 'Vous ne pouvez pas supprimer cet article.')
+ return response.redirect().toPath(`/articles/${article.slug}`)
+ }
- return inertia.render('articles/[slug]', { article })
+ await article.delete()
+ session.flash('success', 'Article supprimé.')
+ return response.redirect().toPath('/articles')
}
}
diff --git a/app/controllers/auth/github_controller.ts b/app/controllers/auth/github_controller.ts
index 4a4d0bc..bf34366 100644
--- a/app/controllers/auth/github_controller.ts
+++ b/app/controllers/auth/github_controller.ts
@@ -1,62 +1,104 @@
-import { HttpContext } from '@adonisjs/core/http'
+import { SESSION_VERSION_KEY } from '#middleware/silent_auth_middleware'
+import { DateTime } from 'luxon'
+import string from '@adonisjs/core/helpers/string'
+import type { HttpContext } from '@adonisjs/core/http'
import User from '#models/user'
-import type { GithubDriver } from '@adonisjs/ally/drivers/github'
+import GithubOAuth from '#services/github_oauth'
+import { githubEnabled } from '#config/ally'
+import { RESERVED_USERNAMES } from '#validators/register_validator'
export default class GithubController {
- async redirect({ ally }: HttpContext) {
- return (ally.use('github') as GithubDriver).redirect()
+ async redirect(ctx: HttpContext) {
+ if (!githubEnabled()) {
+ ctx.session.flash('error', 'La connexion avec GitHub n’est pas encore activée.')
+ return ctx.response.redirect().toRoute('login')
+ }
+ return ctx.response.redirect(new GithubOAuth(ctx).redirectUrl())
}
- async callback({ ally, auth, response }: HttpContext) {
- const github = ally.use('github') as GithubDriver
+ async callback(ctx: HttpContext) {
+ const { auth, response, session } = ctx
+ if (!githubEnabled()) return response.redirect().toRoute('login')
- /**
- * User has explicitly cancelled the login flow
- */
- if (github.accessDenied()) {
+ const profile = await new GithubOAuth(ctx).user().catch(() => null)
+ if (!profile) {
+ session.flash('error', 'Connexion GitHub annulée ou expirée. Réessayez.')
return response.redirect().toRoute('login')
}
- /**
- * OAuth state verification failed. This happens when the
- * CSRF cookie gets expired or request is forged
- */
- if (github.stateMisMatch()) {
- return response.redirect().toRoute('login')
+ let user = await User.findBy('githubId', profile.id)
+
+ if (!user && profile.email) {
+ // Link the GitHub account to an existing account with the same e-mail.
+ const existing = await User.findBy('email', profile.email.toLowerCase())
+ if (existing && !existing.emailVerifiedAt) {
+ // Local e-mails are not verified: auto-linking would let anyone who
+ // registered with someone else's address capture their GitHub login.
+ session.flash(
+ 'error',
+ 'Un compte existe déjà avec cette adresse e-mail. Connectez-vous avec votre mot de passe.'
+ )
+ return response.redirect().toRoute('login')
+ }
+ if (existing) {
+ existing.githubId = profile.id
+ existing.githubUsername = profile.login
+ existing.avatarUrl = existing.avatarUrl ?? profile.avatarUrl
+ await existing.save()
+ user = existing
+ }
}
- /**
- * GitHub responded with some error
- */
- if (github.hasError()) {
+ if (!user) {
+ if (!profile.email) {
+ session.flash(
+ 'error',
+ 'Votre compte GitHub n’expose aucune adresse e-mail vérifiée. Créez un compte avec votre e-mail.'
+ )
+ return response.redirect().toRoute('register')
+ }
+ user = await User.create({
+ githubId: profile.id,
+ githubUsername: profile.login,
+ username: await this.availableUsername(profile.login),
+ name: profile.name,
+ email: profile.email.toLowerCase(),
+ avatarUrl: profile.avatarUrl,
+ bio: profile.bio?.slice(0, 280) ?? null,
+ location: profile.location?.slice(0, 100) ?? null,
+ websiteUrl:
+ profile.blog && /^https?:\/\//.test(profile.blog) ? profile.blog.slice(0, 255) : null,
+ twitterUsername: profile.twitterUsername,
+ password: null,
+ role: 'member',
+ // GitHub only returns verified addresses.
+ emailVerifiedAt: DateTime.now(),
+ })
+ session.flash('success', `Bienvenue dans la communauté, ${user.displayName} !`)
+ } else {
+ session.flash('success', `Bon retour, ${user.displayName} !`)
+ }
+
+ if (user.isBanned) {
+ session.flash('error', 'Ce compte a été suspendu.')
return response.redirect().toRoute('login')
}
- /**
- * Get user details from GitHub
- */
- const githubUser = await github.user()
-
- /**
- * Find or create user by GitHub ID
- */
- const user = await User.firstOrCreate(
- {
- githubId: githubUser.id,
- },
- {
- username: githubUser.nickName,
- name: githubUser.name,
- email: githubUser.email!,
- avatar: githubUser.avatarUrl,
- githubId: githubUser.id,
- }
- )
+ await auth.use('web').login(user, true)
+ session.put(SESSION_VERSION_KEY, user.sessionVersion)
+ return response.redirect().toPath('/dashboard')
+ }
- /**
- * Login user using the web guard
- */
- await auth.use('web').login(user)
- return response.redirect().toRoute('dashboard')
+ private async availableUsername(login: string) {
+ const base =
+ login
+ .toLowerCase()
+ .replace(/[^a-z0-9_-]/g, '')
+ .slice(0, 24) || 'membre'
+ let candidate = RESERVED_USERNAMES.includes(base) ? `${base}-dev` : base
+ while (await User.findBy('username', candidate)) {
+ candidate = `${base}-${string.random(4).toLowerCase()}`
+ }
+ return candidate
}
}
diff --git a/app/controllers/auth/login_controller.ts b/app/controllers/auth/login_controller.ts
index 4778558..cceaf15 100644
--- a/app/controllers/auth/login_controller.ts
+++ b/app/controllers/auth/login_controller.ts
@@ -1,39 +1,45 @@
-import { loginValidator } from '#validators/login_validator'
-import { HttpContext } from '@adonisjs/core/http'
+import { SESSION_VERSION_KEY } from '#middleware/silent_auth_middleware'
import User from '#models/user'
-import { errors } from '@adonisjs/auth'
+import { loginValidator } from '#validators/login_validator'
+import type { HttpContext } from '@adonisjs/core/http'
+import { safeRedirectPath } from '#services/safe_redirect'
export default class LoginController {
- async show({ inertia }: HttpContext) {
- return inertia.render('auth/login')
+ async show({ inertia, request }: HttpContext) {
+ return inertia.render('auth/login', {
+ redirect: safeRedirectPath(request.input('redirect'), ''),
+ })
}
- async login({ request, auth, response, session }: HttpContext) {
- try {
- // Validate the request data
- const data = await loginValidator.validate(request.all())
-
- // Attempt to verify credentials
- const user = await User.verifyCredentials(data.email, data.password)
-
- // Login the user
- await auth.use('web').login(user, data.remember)
+ async store({ request, auth, response, session }: HttpContext) {
+ const { login, password, remember } = await request.validateUsing(loginValidator)
- return response.redirect().toRoute('dashboard')
- } catch (error) {
- if (error instanceof errors.E_INVALID_CREDENTIALS) {
- session.flash('errors', { form: 'Invalid credentials' })
- return response.redirect().back()
- }
+ let user: User
+ try {
+ user = await User.verifyCredentials(login.toLowerCase(), password)
+ } catch {
+ session.flashExcept(['password'])
+ session.flash('inputErrorsBag', { login: ['Identifiants incorrects.'] })
+ return response.redirect().back()
+ }
- // Handle other errors
- session.flash('errors', { form: 'An error occurred during login' })
+ if (user.isBanned) {
+ session.flash(
+ 'error',
+ 'Ce compte a été suspendu. Contactez l’équipe si vous pensez à une erreur.'
+ )
return response.redirect().back()
}
+
+ await auth.use('web').login(user, Boolean(remember))
+ session.put(SESSION_VERSION_KEY, user.sessionVersion)
+ session.flash('success', `Bon retour, ${user.displayName} !`)
+ return response.redirect().toPath(safeRedirectPath(request.input('redirect')))
}
- async logout({ auth, response }: HttpContext) {
+ async destroy({ auth, response, session }: HttpContext) {
await auth.use('web').logout()
- return response.redirect().toRoute('login')
+ session.flash('success', 'Vous êtes déconnecté. À bientôt !')
+ return response.redirect().toRoute('home')
}
}
diff --git a/app/controllers/auth/register_controller.ts b/app/controllers/auth/register_controller.ts
index f6d4857..e2ac813 100644
--- a/app/controllers/auth/register_controller.ts
+++ b/app/controllers/auth/register_controller.ts
@@ -1,18 +1,20 @@
-import { HttpContext } from '@adonisjs/core/http'
+import { SESSION_VERSION_KEY } from '#middleware/silent_auth_middleware'
import User from '#models/user'
import { registerValidator } from '#validators/register_validator'
+import type { HttpContext } from '@adonisjs/core/http'
export default class RegisterController {
async show({ inertia }: HttpContext) {
- return inertia.render('auth/register')
+ return inertia.render('auth/register', {})
}
- async store({ request, auth, response }: HttpContext) {
- const data = await registerValidator.validate(request.all())
+ async store({ request, response, auth, session }: HttpContext) {
+ const { name, username, email, password } = await request.validateUsing(registerValidator)
+ const user = await User.create({ name, username, email, password, role: 'member' })
- const user = await User.create(data)
await auth.use('web').login(user)
-
- return response.redirect().toRoute('dashboard')
+ session.put(SESSION_VERSION_KEY, user.sessionVersion)
+ session.flash('success', `Bienvenue dans la communauté, ${user.displayName} !`)
+ return response.redirect().toPath('/dashboard')
}
}
diff --git a/app/controllers/dashboard_controller.ts b/app/controllers/dashboard_controller.ts
new file mode 100644
index 0000000..91f1d38
--- /dev/null
+++ b/app/controllers/dashboard_controller.ts
@@ -0,0 +1,94 @@
+import type { HttpContext } from '@adonisjs/core/http'
+import db from '@adonisjs/lucid/services/db'
+import Article from '#models/article'
+import Thread from '#models/thread'
+import Discussion from '#models/discussion'
+import Reply from '#models/reply'
+import ArticleTransformer from '#transformers/article_transformer'
+import ThreadTransformer from '#transformers/thread_transformer'
+import DiscussionTransformer from '#transformers/discussion_transformer'
+import { replySummary, withReplyParents } from '#controllers/profile_controller'
+
+export default class DashboardController {
+ /**
+ * GET /dashboard — the signed-in member's workspace.
+ */
+ async index({ auth, inertia }: HttpContext) {
+ const user = auth.getUserOrFail()
+
+ const [statsRow, articles, threads, discussions, activity] = await Promise.all([
+ db
+ .rawQuery(
+ `select
+ (select count(*) from articles where user_id = :id and published_at is not null and published_at <= now()) as published,
+ (select count(*) from articles where user_id = :id and (published_at is null or published_at > now())) as drafts,
+ (select coalesce(sum(views_count), 0) from articles where user_id = :id) as views,
+ (select count(*) from threads where user_id = :id) as questions,
+ (select count(*) from threads where user_id = :id and solution_reply_id is null) as unsolved,
+ (select count(*) from discussions where user_id = :id) as discussions,
+ (select count(*) from replies where user_id = :id) as replies,
+ (select count(*) from likes l join articles a on a.id = l.article_id where a.user_id = :id)
+ + (select count(*) from likes l join replies r on r.id = l.reply_id where r.user_id = :id) as likes`,
+ { id: user.id }
+ )
+ .then((result) => result.rows[0]),
+
+ // Drafts first, then the latest publications.
+ Article.query()
+ .where('user_id', user.id)
+ .preload('tags')
+ .withCount('likes')
+ .withCount('comments')
+ .orderByRaw('(published_at is null or published_at > now()) desc')
+ .orderByRaw('coalesce(published_at, updated_at, created_at) desc')
+ .limit(8),
+
+ // Questions still waiting for a solution come first.
+ Thread.query()
+ .where('user_id', user.id)
+ .preload('channel')
+ .orderByRaw('(solution_reply_id is null) desc')
+ .orderBy('last_activity_at', 'desc')
+ .limit(6),
+
+ Discussion.query()
+ .where('user_id', user.id)
+ .preload('tags')
+ .orderBy('last_activity_at', 'desc')
+ .limit(5),
+
+ // Latest replies written by others on my threads, discussions and articles.
+ withReplyParents(Reply.query())
+ .preload('author')
+ .whereNot('user_id', user.id)
+ .where((query) => {
+ query
+ .whereIn('thread_id', db.from('threads').select('id').where('user_id', user.id))
+ .orWhereIn(
+ 'discussion_id',
+ db.from('discussions').select('id').where('user_id', user.id)
+ )
+ .orWhereIn('article_id', db.from('articles').select('id').where('user_id', user.id))
+ })
+ .orderBy('created_at', 'desc')
+ .limit(10),
+ ])
+
+ return inertia.render('dashboard/index', {
+ stats: {
+ published: Number(statsRow.published),
+ drafts: Number(statsRow.drafts),
+ views: Number(statsRow.views),
+ questions: Number(statsRow.questions),
+ unsolved: Number(statsRow.unsolved),
+ discussions: Number(statsRow.discussions),
+ replies: Number(statsRow.replies),
+ likes: Number(statsRow.likes),
+ },
+ articles: ArticleTransformer.transform(articles),
+ threads: ThreadTransformer.transform(threads),
+ discussions: DiscussionTransformer.transform(discussions),
+ activity: activity.map((reply) => replySummary(reply, { withAuthor: true })),
+ })
+ }
+}
diff --git a/app/controllers/discussion_actions_controller.ts b/app/controllers/discussion_actions_controller.ts
new file mode 100644
index 0000000..2c06a43
--- /dev/null
+++ b/app/controllers/discussion_actions_controller.ts
@@ -0,0 +1,81 @@
+import type { HttpContext } from '@adonisjs/core/http'
+import db from '@adonisjs/lucid/services/db'
+import Discussion from '#models/discussion'
+import { replyValidator } from '#validators/reply_validator'
+import { createReply } from '#services/reply_service'
+import { DISCUSSION_REPLIES_PER_PAGE } from '#controllers/discussions_controller'
+
+/**
+ * Replying to a discussion and moderation toggles (pin / lock).
+ */
+export default class DiscussionActionsController {
+ /**
+ * POST /discussions/:slug/replies
+ */
+ async reply({ params, request, auth, response, session }: HttpContext) {
+ const user = auth.user!
+ const discussion = await Discussion.findByOrFail('slug', params.slug)
+ if (discussion.isLocked && !user.isModerator) {
+ session.flash(
+ 'error',
+ 'Cette discussion est verrouillée : elle n’accepte plus de nouvelles réponses.'
+ )
+ return response.redirect().toPath(`/discussions/${discussion.slug}`)
+ }
+
+ const { body } = await request.validateUsing(replyValidator)
+ const reply = await createReply({ type: 'discussion', id: discussion.id }, user, body)
+
+ const total = discussion.repliesCount + 1
+ const page =
+ total > DISCUSSION_REPLIES_PER_PAGE ? Math.ceil(total / DISCUSSION_REPLIES_PER_PAGE) : 1
+ session.flash('success', 'Réponse publiée.')
+ return response
+ .redirect()
+ .toPath(
+ `/discussions/${discussion.slug}${page > 1 ? `?page=${page}` : ''}#reponse-${reply.id}`
+ )
+ }
+
+ /**
+ * POST /discussions/:slug/pin — moderators only, toggles.
+ */
+ async togglePin({ params, auth, response, session }: HttpContext) {
+ const discussion = await Discussion.findByOrFail('slug', params.slug)
+ if (!auth.user!.isModerator) {
+ session.flash('error', 'Action réservée aux modérateurs.')
+ return response.redirect().back()
+ }
+ const pinned = discussion.pinnedAt === null
+ await db
+ .from('discussions')
+ .where('id', discussion.id)
+ .update({ pinned_at: pinned ? new Date() : null })
+ session.flash(
+ 'success',
+ pinned ? 'Discussion épinglée en tête de liste.' : 'Discussion désépinglée.'
+ )
+ return response.redirect().back()
+ }
+
+ /**
+ * POST /discussions/:slug/lock — moderators only, toggles.
+ */
+ async toggleLock({ params, auth, response, session }: HttpContext) {
+ const discussion = await Discussion.findByOrFail('slug', params.slug)
+ if (!auth.user!.isModerator) {
+ session.flash('error', 'Action réservée aux modérateurs.')
+ return response.redirect().back()
+ }
+ const locked = discussion.lockedAt === null
+ await db
+ .from('discussions')
+ .where('id', discussion.id)
+ .update({ locked_at: locked ? new Date() : null })
+ session.flash(
+ 'success',
+ locked ? 'Discussion verrouillée : plus de nouvelles réponses.' : 'Discussion déverrouillée.'
+ )
+ return response.redirect().back()
+ }
+}
diff --git a/app/controllers/discussions_controller.ts b/app/controllers/discussions_controller.ts
new file mode 100644
index 0000000..2da155b
--- /dev/null
+++ b/app/controllers/discussions_controller.ts
@@ -0,0 +1,363 @@
+import { markSubjectRead } from '#services/notifications'
+import type { HttpContext } from '@adonisjs/core/http'
+import { DateTime } from 'luxon'
+import db from '@adonisjs/lucid/services/db'
+import { errors as lucidErrors } from '@adonisjs/lucid'
+import Discussion from '#models/discussion'
+import Tag from '#models/tag'
+import Reply from '#models/reply'
+import User from '#models/user'
+import DiscussionTransformer from '#transformers/discussion_transformer'
+import TagTransformer from '#transformers/tag_transformer'
+import ReplyTransformer from '#transformers/reply_transformer'
+import UserTransformer from '#transformers/user_transformer'
+import { discussionValidator } from '#validators/discussion_validator'
+import { renderMarkdown } from '#services/markdown'
+import { uniqueSlug } from '#services/slug'
+import { withReplyMeta } from '#services/reply_service'
+
+const PER_PAGE = 20
+export const DISCUSSION_REPLIES_PER_PAGE = 50
+
+const SORTS = ['recentes', 'populaires', 'sans-reponse'] as const
+type Sort = (typeof SORTS)[number]
+
+function likePattern(term: string) {
+ return `%${term.replace(/[\\%_]/g, (char) => `\\${char}`)}%`
+}
+
+function toPage(value: unknown) {
+ const page = Number.parseInt(String(value ?? '1'), 10)
+ return Number.isFinite(page) && page > 0 ? page : 1
+}
+
+/**
+ * One view per visitor session (see ThreadsController).
+ */
+function isFirstView(session: HttpContext['session'], key: string) {
+ const seen: string[] = session.get('seen_content', [])
+ if (seen.includes(key)) return false
+ session.put('seen_content', [...seen.slice(-39), key])
+ return true
+}
+
+function byName(tags: Tag[]) {
+ return tags.sort((a, b) => a.name.localeCompare(b.name, 'fr', { sensitivity: 'base' }))
+}
+
+/**
+ * Attach the latest repliers (max 4, author excluded) and the number of
+ * distinct participants to each discussion, in two queries for the page.
+ */
+async function attachParticipants(discussions: Discussion[]) {
+ if (!discussions.length) return
+ const rows: { discussion_id: number; user_id: number }[] = await db
+ .from('replies')
+ .select('discussion_id', 'user_id')
+ .max('created_at as last_at')
+ .whereIn(
+ 'discussion_id',
+ discussions.map((d) => d.id)
+ )
+ .groupBy('discussion_id', 'user_id')
+ .orderBy('last_at', 'desc')
+
+ const authors = new Map(discussions.map((d) => [d.id, d.userId]))
+ const latest = new Map()
+ const counts = new Map()
+ for (const row of rows) {
+ const discussionId = Number(row.discussion_id)
+ const userId = Number(row.user_id)
+ if (userId === authors.get(discussionId)) continue
+ counts.set(discussionId, (counts.get(discussionId) ?? 0) + 1)
+ const list = latest.get(discussionId) ?? []
+ if (list.length < 4) list.push(userId)
+ latest.set(discussionId, list)
+ }
+
+ const userIds = [...new Set([...latest.values()].flat())]
+ const users = userIds.length ? await User.query().whereIn('id', userIds) : []
+ const byId = new Map(users.map((u) => [u.id, u]))
+
+ for (const discussion of discussions) {
+ discussion.$extras.participants = (latest.get(discussion.id) ?? [])
+ .map((id) => byId.get(id))
+ .filter(Boolean)
+ // + 1: the author opened the conversation.
+ discussion.$extras.participants_count = (counts.get(discussion.id) ?? 0) + 1
+ }
+}
+
+export default class DiscussionsController {
+ /**
+ * GET /discussions — tag index, sort, search.
+ */
+ async index({ request, inertia }: HttpContext) {
+ const qs = request.qs()
+ const q = typeof qs.q === 'string' ? qs.q.trim().slice(0, 120) : ''
+ const sort: Sort = SORTS.includes(qs.sort) ? qs.sort : 'recentes'
+ const page = toPage(qs.page)
+
+ // Most discussed first, then alphabetical with a French collation
+ // (« Événements » sorts with the E, not after « Vue »).
+ const allTags = await Tag.query().withCount('discussions')
+ const tags = allTags.sort(
+ (a, b) =>
+ Number(b.$extras.discussions_count) - Number(a.$extras.discussions_count) ||
+ a.name.localeCompare(b.name, 'fr', { sensitivity: 'base' })
+ )
+
+ let tag: Tag | null = null
+ if (typeof qs.tag === 'string' && qs.tag !== '') {
+ tag = tags.find((t) => t.slug === qs.tag) ?? null
+ if (!tag) throw new lucidErrors.E_ROW_NOT_FOUND(Tag)
+ }
+
+ const query = Discussion.query().preload('author').preload('tags')
+ if (tag) {
+ const tagId = tag.id
+ query.whereIn('id', (sub) =>
+ sub.from('discussion_tag').select('discussion_id').where('tag_id', tagId)
+ )
+ }
+ if (q) {
+ const pattern = likePattern(q)
+ query.where((sub) => sub.whereILike('title', pattern).orWhereILike('body', pattern))
+ }
+
+ if (sort === 'populaires') {
+ query
+ .orderBy('replies_count', 'desc')
+ .orderBy('views_count', 'desc')
+ .orderBy('last_activity_at', 'desc')
+ } else if (sort === 'sans-reponse') {
+ query.where('replies_count', 0).orderBy('created_at', 'desc')
+ } else {
+ query.orderByRaw('pinned_at desc nulls last').orderBy('last_activity_at', 'desc')
+ }
+ query.orderBy('id', 'desc')
+
+ const [discussions, totals] = await Promise.all([
+ query.paginate(page, PER_PAGE),
+ db
+ .rawQuery(
+ `select
+ (select count(*) from discussions)::int as discussions,
+ (select count(*) from replies where discussion_id is not null and created_at > now() - interval '30 days')::int as replies_month,
+ (select count(distinct user_id) from replies where discussion_id is not null)::int as voices`
+ )
+ .then(
+ (result) =>
+ result.rows[0] as { discussions: number; replies_month: number; voices: number }
+ ),
+ ])
+ await attachParticipants(discussions.all())
+
+ return inertia.render('discussions/index', {
+ discussions: DiscussionTransformer.paginate(
+ discussions.all(),
+ discussions.getMeta()
+ ).useVariant('forList'),
+ tags: TagTransformer.transform(tags),
+ filters: { tag: tag?.slug ?? null, sort, q },
+ stats: {
+ discussions: Number(totals.discussions),
+ repliesThisMonth: Number(totals.replies_month),
+ voices: Number(totals.voices),
+ },
+ })
+ }
+
+ /**
+ * GET /discussions/nouvelle
+ */
+ async create({ request, inertia }: HttpContext) {
+ const tags = byName(await Tag.query())
+ const preselected = tags.find((t) => t.slug === request.qs().tag)
+ return inertia.render('discussions/create', {
+ tags: TagTransformer.transform(tags),
+ defaultTagIds: preselected ? [preselected.id] : [],
+ })
+ }
+
+ /**
+ * POST /discussions
+ */
+ async store({ request, auth, response, session }: HttpContext) {
+ const data = await request.validateUsing(discussionValidator)
+ const discussion = new Discussion()
+ discussion.userId = auth.user!.id
+ discussion.title = data.title
+ discussion.body = data.body
+ discussion.bodyHtml = await renderMarkdown(data.body)
+ discussion.slug = await uniqueSlug('discussions', data.title)
+ discussion.lastActivityAt = DateTime.now()
+
+ await db.transaction(async (trx) => {
+ discussion.useTransaction(trx)
+ await discussion.save()
+ await discussion.related('tags').sync(data.tags ?? [])
+ })
+
+ session.flash('success', 'Discussion lancée. À vous la parole !')
+ return response.redirect().toPath(`/discussions/${discussion.slug}`)
+ }
+
+ /**
+ * GET /discussions/:slug
+ */
+ async show({ params, request, auth, inertia, session }: HttpContext) {
+ const viewer = auth.user ?? null
+ const discussion = await Discussion.query()
+ .where('slug', params.slug)
+ .preload('author')
+ .preload('tags')
+ .firstOrFail()
+
+ if (viewer) await markSubjectRead(viewer.id, { discussionId: discussion.id })
+
+ if (viewer?.id !== discussion.userId && isFirstView(session, `d${discussion.id}`)) {
+ await db.from('discussions').where('id', discussion.id).increment('views_count', 1)
+ discussion.viewsCount += 1
+ }
+
+ const repliesQuery = Reply.query().where('discussion_id', discussion.id)
+ withReplyMeta(viewer)(repliesQuery)
+ repliesQuery.orderBy('id', 'asc')
+
+ let replies: Reply[]
+ let repliesMeta: {
+ total: number
+ perPage: number
+ currentPage: number
+ lastPage: number
+ } | null = null
+ if (discussion.repliesCount > DISCUSSION_REPLIES_PER_PAGE) {
+ const paginator = await repliesQuery.paginate(
+ toPage(request.qs().page),
+ DISCUSSION_REPLIES_PER_PAGE
+ )
+ replies = paginator.all()
+ const meta = paginator.getMeta()
+ repliesMeta = {
+ total: Number(meta.total),
+ perPage: Number(meta.perPage),
+ currentPage: Number(meta.currentPage),
+ lastPage: Number(meta.lastPage),
+ }
+ } else {
+ replies = await repliesQuery
+ }
+
+ const tagIds = discussion.tags.map((t) => t.id)
+ const relatedQuery = Discussion.query().whereNot('id', discussion.id).preload('author')
+ if (tagIds.length) {
+ relatedQuery.whereIn('id', (sub) =>
+ sub.from('discussion_tag').select('discussion_id').whereIn('tag_id', tagIds)
+ )
+ }
+
+ const [participantRows, tagRelated] = await Promise.all([
+ db
+ .from('replies')
+ .select('user_id')
+ .count('* as replies')
+ .min('created_at as first_at')
+ .where('discussion_id', discussion.id)
+ .groupBy('user_id')
+ .orderBy('first_at', 'asc'),
+ relatedQuery.orderBy('last_activity_at', 'desc').limit(5),
+ ])
+
+ // Nothing shares a tag yet: fall back to the latest conversations.
+ const related = tagRelated.length
+ ? tagRelated
+ : await Discussion.query()
+ .whereNot('id', discussion.id)
+ .preload('author')
+ .orderBy('last_activity_at', 'desc')
+ .limit(5)
+
+ // The author opens the conversation: first in the participants strip.
+ const participantIds: number[] = [
+ discussion.userId,
+ ...participantRows.map((row) => Number(row.user_id)).filter((id) => id !== discussion.userId),
+ ]
+ const others =
+ participantIds.length > 1 ? await User.query().whereIn('id', participantIds.slice(1, 16)) : []
+ const participants = [discussion.author, ...others].sort(
+ (a, b) => participantIds.indexOf(a.id) - participantIds.indexOf(b.id)
+ )
+
+ return inertia.render('discussions/show', {
+ discussion: DiscussionTransformer.transform(discussion).useVariant('forDetail'),
+ replies: ReplyTransformer.transform(replies),
+ repliesMeta,
+ participants: UserTransformer.transform(participants),
+ participantsCount: participantIds.length,
+ related: DiscussionTransformer.transform(related),
+ relatedByTags: tagRelated.length > 0,
+ can: {
+ manage: Boolean(viewer && (await viewer.canManageContent(discussion.userId))),
+ moderate: Boolean(viewer?.isModerator),
+ },
+ })
+ }
+
+ /**
+ * GET /discussions/:slug/modifier
+ */
+ async edit({ params, auth, inertia, response, session }: HttpContext) {
+ const discussion = await Discussion.query()
+ .where('slug', params.slug)
+ .preload('tags')
+ .firstOrFail()
+ if (!(await auth.user!.canManageContent(discussion.userId))) {
+ session.flash('error', 'Vous ne pouvez pas modifier cette discussion.')
+ return response.redirect().toPath(`/discussions/${discussion.slug}`)
+ }
+ const tags = byName(await Tag.query())
+ return inertia.render('discussions/edit', {
+ discussion: DiscussionTransformer.transform(discussion).useVariant('forEdit'),
+ tags: TagTransformer.transform(tags),
+ })
+ }
+
+ /**
+ * PUT /discussions/:slug — the slug never changes.
+ */
+ async update({ params, request, auth, response, session }: HttpContext) {
+ const discussion = await Discussion.findByOrFail('slug', params.slug)
+ if (!(await auth.user!.canManageContent(discussion.userId))) {
+ session.flash('error', 'Vous ne pouvez pas modifier cette discussion.')
+ return response.redirect().toPath(`/discussions/${discussion.slug}`)
+ }
+ const data = await request.validateUsing(discussionValidator)
+ discussion.title = data.title
+ discussion.body = data.body
+ discussion.bodyHtml = await renderMarkdown(data.body)
+
+ await db.transaction(async (trx) => {
+ discussion.useTransaction(trx)
+ await discussion.save()
+ await discussion.related('tags').sync(data.tags ?? [])
+ })
+
+ session.flash('success', 'Discussion mise à jour.')
+ return response.redirect().toPath(`/discussions/${discussion.slug}`)
+ }
+
+ /**
+ * DELETE /discussions/:slug
+ */
+ async destroy({ params, auth, response, session }: HttpContext) {
+ const discussion = await Discussion.findByOrFail('slug', params.slug)
+ if (!(await auth.user!.canManageContent(discussion.userId))) {
+ session.flash('error', 'Vous ne pouvez pas supprimer cette discussion.')
+ return response.redirect().toPath(`/discussions/${discussion.slug}`)
+ }
+ await discussion.delete()
+ session.flash('success', 'La discussion a été supprimée.')
+ return response.redirect().toPath('/discussions')
+ }
+}
diff --git a/app/controllers/home_controller.ts b/app/controllers/home_controller.ts
index b170eeb..cba213c 100644
--- a/app/controllers/home_controller.ts
+++ b/app/controllers/home_controller.ts
@@ -1,18 +1,62 @@
-import { HttpContext } from '@adonisjs/core/http'
+import type { HttpContext } from '@adonisjs/core/http'
+import db from '@adonisjs/lucid/services/db'
import Article from '#models/article'
+import Thread from '#models/thread'
+import Discussion from '#models/discussion'
+import User from '#models/user'
+import ArticleTransformer from '#transformers/article_transformer'
+import ThreadTransformer from '#transformers/thread_transformer'
+import DiscussionTransformer from '#transformers/discussion_transformer'
+import UserTransformer from '#transformers/user_transformer'
export default class HomeController {
async index({ inertia }: HttpContext) {
- const articles = await Article.query().where('is_published', true).preload('author')
+ const [articles, threads, discussions, members, counts] = await Promise.all([
+ Article.query()
+ .withScopes((s) => s.published())
+ .preload('author')
+ .preload('tags')
+ .withCount('likes')
+ .withCount('comments')
+ .orderByRaw('featured_at desc nulls last')
+ .orderBy('published_at', 'desc')
+ .limit(5),
+ Thread.query()
+ .preload('author')
+ .preload('channel')
+ .orderBy('last_activity_at', 'desc')
+ .limit(6),
+ Discussion.query()
+ .preload('author')
+ .preload('tags')
+ .orderBy('last_activity_at', 'desc')
+ .limit(4),
+ User.query().whereNull('banned_at').orderBy('created_at', 'desc').limit(12),
+ db
+ .rawQuery(
+ `select
+ (select count(*) from users where banned_at is null) as members,
+ (select count(*) from articles where published_at is not null and published_at <= now()) as articles,
+ (select count(*) from threads) as threads,
+ (select count(*) from threads where solution_reply_id is not null) as solved,
+ (select count(*) from replies) as replies`
+ )
+ .then((result) => result.rows[0]),
+ ])
+ const threadsCount = Number(counts.threads)
return inertia.render('home', {
stats: {
- members: 600,
- developers: 50,
- participation: 25,
- githubStars: 10,
+ members: Number(counts.members),
+ articles: Number(counts.articles),
+ threads: threadsCount,
+ replies: Number(counts.replies),
+ solvedRate: threadsCount ? Math.round((Number(counts.solved) / threadsCount) * 100) : 0,
},
- articles: articles,
+ articles: ArticleTransformer.transform(articles),
+ threads: ThreadTransformer.transform(threads),
+ discussions: DiscussionTransformer.transform(discussions),
+ members: UserTransformer.transform(members),
})
}
}
diff --git a/app/controllers/markdown_controller.ts b/app/controllers/markdown_controller.ts
new file mode 100644
index 0000000..80d3ba2
--- /dev/null
+++ b/app/controllers/markdown_controller.ts
@@ -0,0 +1,14 @@
+import vine from '@vinejs/vine'
+import type { HttpContext } from '@adonisjs/core/http'
+import { renderMarkdown } from '#services/markdown'
+
+const previewValidator = vine.create({
+ body: vine.string().maxLength(60_000),
+})
+
+export default class MarkdownController {
+ async preview({ request }: HttpContext) {
+ const { body } = await request.validateUsing(previewValidator)
+ return { html: await renderMarkdown(body) }
+ }
+}
diff --git a/app/controllers/members_controller.ts b/app/controllers/members_controller.ts
new file mode 100644
index 0000000..17290d9
--- /dev/null
+++ b/app/controllers/members_controller.ts
@@ -0,0 +1,72 @@
+import type { HttpContext } from '@adonisjs/core/http'
+import db from '@adonisjs/lucid/services/db'
+import User from '#models/user'
+import UserTransformer from '#transformers/user_transformer'
+
+/**
+ * Per-member counters as correlated subqueries (one round trip, no N+1).
+ */
+export const MEMBER_COUNTERS = {
+ articles: `(select count(*) from articles where articles.user_id = users.id and articles.published_at is not null and articles.published_at <= now())`,
+ threads: `(select count(*) from threads where threads.user_id = users.id)`,
+ replies: `(select count(*) from replies where replies.user_id = users.id)`,
+}
+
+/**
+ * Escape LIKE wildcards typed by the visitor ("100%" must not match everything).
+ */
+export function likePattern(value: string) {
+ return `%${value.replace(/[\\%_]/g, (char) => `\\${char}`)}%`
+}
+
+export default class MembersController {
+ /**
+ * GET /membres — searchable directory of the community.
+ */
+ async index({ request, inertia }: HttpContext) {
+ const q = String(request.input('q') ?? '')
+ .trim()
+ .slice(0, 60)
+ const sort: 'recents' | 'actifs' = request.input('sort') === 'actifs' ? 'actifs' : 'recents'
+ const page = Math.max(1, Number.parseInt(request.input('page', '1'), 10) || 1)
+
+ const query = User.query()
+ .whereNull('banned_at')
+ .select('users.*')
+ .select(db.raw(`${MEMBER_COUNTERS.articles} as articles_count`))
+ .select(db.raw(`${MEMBER_COUNTERS.threads} as threads_count`))
+ .select(db.raw(`${MEMBER_COUNTERS.replies} as replies_count`))
+
+ if (q) {
+ const pattern = likePattern(q.replace(/^@/, ''))
+ query.where((builder) => {
+ builder.whereILike('users.username', pattern).orWhereILike('users.name', pattern)
+ })
+ }
+
+ if (sort === 'actifs') {
+ query.orderByRaw(
+ `(${MEMBER_COUNTERS.articles} + ${MEMBER_COUNTERS.threads} + ${MEMBER_COUNTERS.replies}) desc`
+ )
+ }
+ query.orderBy('users.created_at', 'desc').orderBy('users.id', 'desc')
+
+ const [paginator, total] = await Promise.all([
+ query.paginate(page, 30),
+ db
+ .from('users')
+ .whereNull('banned_at')
+ .count('* as total')
+ .first()
+ .then((row) => Number(row?.total ?? 0)),
+ ])
+
+ return inertia.render('members/index', {
+ members: UserTransformer.paginate(paginator.all(), paginator.getMeta()).useVariant(
+ 'forDirectory'
+ ),
+ filters: { q, sort },
+ totalMembers: total,
+ })
+ }
+}
diff --git a/app/controllers/notifications_controller.ts b/app/controllers/notifications_controller.ts
new file mode 100644
index 0000000..c32cba9
--- /dev/null
+++ b/app/controllers/notifications_controller.ts
@@ -0,0 +1,210 @@
+import type { HttpContext } from '@adonisjs/core/http'
+import { DateTime } from 'luxon'
+import db from '@adonisjs/lucid/services/db'
+import Notification from '#models/notification'
+import NotificationTransformer from '#transformers/notification_transformer'
+import { withReplyCounts } from '#services/notifications'
+import { THREAD_REPLIES_PER_PAGE } from '#controllers/threads_controller'
+import { DISCUSSION_REPLIES_PER_PAGE } from '#controllers/discussions_controller'
+
+const PER_PAGE = 30
+
+const FILTERS = ['toutes', 'non-lues'] as const
+type Filter = (typeof FILTERS)[number]
+
+function toPage(value: unknown) {
+ const page = Number.parseInt(String(value ?? '1'), 10)
+ return Number.isFinite(page) && page > 0 ? page : 1
+}
+
+/**
+ * The page of a paginated thread / discussion that shows a given reply
+ * (replies are listed by id, see ThreadsController#show).
+ */
+async function replyPage(
+ column: 'thread_id' | 'discussion_id',
+ parentId: number,
+ replyId: number,
+ repliesCount: number,
+ perPage: number
+) {
+ if (repliesCount <= perPage) return 1
+ const [{ n }] = await db
+ .from('replies')
+ .where(column, parentId)
+ .where('id', '<', replyId)
+ .count('* as n')
+ return Math.floor(Number(n) / perPage) + 1
+}
+
+/**
+ * Where a notification leads: the exact reply, on the right page.
+ */
+async function targetOf(notification: Notification) {
+ const anchor = notification.replyId ? `#reponse-${notification.replyId}` : ''
+
+ if (notification.threadId !== null) {
+ const thread = await db
+ .from('threads')
+ .select('slug', 'replies_count')
+ .where('id', notification.threadId)
+ .first()
+ if (!thread) return null
+ const page = notification.replyId
+ ? await replyPage(
+ 'thread_id',
+ notification.threadId,
+ notification.replyId,
+ Number(thread.replies_count),
+ THREAD_REPLIES_PER_PAGE
+ )
+ : 1
+ return `/forum/${thread.slug}${page > 1 ? `?page=${page}` : ''}${anchor}`
+ }
+
+ if (notification.discussionId !== null) {
+ const discussion = await db
+ .from('discussions')
+ .select('slug', 'replies_count')
+ .where('id', notification.discussionId)
+ .first()
+ if (!discussion) return null
+ const page = notification.replyId
+ ? await replyPage(
+ 'discussion_id',
+ notification.discussionId,
+ notification.replyId,
+ Number(discussion.replies_count),
+ DISCUSSION_REPLIES_PER_PAGE
+ )
+ : 1
+ return `/discussions/${discussion.slug}${page > 1 ? `?page=${page}` : ''}${anchor}`
+ }
+
+ if (notification.articleId !== null) {
+ const article = await db
+ .from('articles')
+ .select('slug')
+ .where('id', notification.articleId)
+ .first()
+ return article ? `/articles/${article.slug}${anchor}` : null
+ }
+
+ return null
+}
+
+/**
+ * The signed-in member's notification center. Every action is scoped to
+ * the owner: someone else's notification is a 404.
+ */
+export default class NotificationsController {
+ /**
+ * GET /notifications — grouped by recency, "Toutes" / "Non lues".
+ */
+ async index({ auth, request, inertia }: HttpContext) {
+ const user = auth.getUserOrFail()
+ const requested = request.input('filtre')
+ const filter: Filter = FILTERS.includes(requested) ? requested : 'toutes'
+ const page = toPage(request.input('page'))
+
+ const query = Notification.query()
+ .where('user_id', user.id)
+ .preload('actor')
+ .preload('thread', (q) => q.select('id', 'slug', 'title', 'user_id'))
+ .preload('discussion', (q) => q.select('id', 'slug', 'title', 'user_id'))
+ .preload('article', (q) => q.select('id', 'slug', 'title', 'user_id'))
+ // plainExcerpt() only reads the first characters of the body.
+ .preload('reply', (q) => q.select('id', db.raw('left(body, 1200) as body')))
+ .orderBy('created_at', 'desc')
+ .orderBy('id', 'desc')
+ if (filter === 'non-lues') query.whereNull('read_at')
+
+ const [paginator, counts] = await Promise.all([
+ query.paginate(page, PER_PAGE),
+ db
+ .from('notifications')
+ .where('user_id', user.id)
+ .select(
+ db.raw('count(*)::int as total'),
+ db.raw('count(*) filter (where read_at is null)::int as unread')
+ )
+ .first(),
+ ])
+ await withReplyCounts(paginator.all())
+
+ return inertia.render('notifications/index', {
+ notifications: NotificationTransformer.paginate(paginator.all(), paginator.getMeta()),
+ filter,
+ counts: {
+ toutes: Number(counts?.total ?? 0),
+ nonLues: Number(counts?.unread ?? 0),
+ },
+ })
+ }
+
+ /**
+ * GET /notifications/:id — mark as read, then go to the reply.
+ *
+ * From an Inertia visit, a 409 + X-Inertia-Redirect makes the client visit
+ * the target itself, so the "#reponse-…" fragment survives (an XHR
+ * following a 302 would drop it). A plain request gets a regular redirect.
+ */
+ async show({ params, auth, request, response, session }: HttpContext) {
+ const user = auth.getUserOrFail()
+ const notification = await Notification.query()
+ .where('id', params.id)
+ .where('user_id', user.id)
+ .firstOrFail()
+
+ if (notification.readAt === null) {
+ notification.readAt = DateTime.now()
+ await notification.save()
+ }
+
+ const target = await targetOf(notification)
+ if (!target) {
+ session.flash('error', 'Ce contenu n’est plus disponible.')
+ return response.redirect().toPath('/notifications')
+ }
+
+ if (request.header('x-inertia')) {
+ response.header('X-Inertia-Redirect', target)
+ return response.status(409).send('')
+ }
+ return response.redirect().toPath(target)
+ }
+
+ /**
+ * POST /notifications/:id/read
+ */
+ async read({ params, auth, response }: HttpContext) {
+ const user = auth.getUserOrFail()
+ const notification = await Notification.query()
+ .where('id', params.id)
+ .where('user_id', user.id)
+ .firstOrFail()
+
+ if (notification.readAt === null) {
+ notification.readAt = DateTime.now()
+ await notification.save()
+ }
+ return response.redirect().back()
+ }
+
+ /**
+ * POST /notifications/read-all
+ */
+ async readAll({ auth, response, session }: HttpContext) {
+ const user = auth.getUserOrFail()
+ const updated = await db
+ .from('notifications')
+ .where('user_id', user.id)
+ .whereNull('read_at')
+ .update({ read_at: new Date() })
+
+ if (Number(updated)) {
+ session.flash('success', 'Toutes vos notifications sont marquées comme lues.')
+ }
+ return response.redirect().back()
+ }
+}
diff --git a/app/controllers/profile_controller.ts b/app/controllers/profile_controller.ts
index 451b7d4..a18d761 100644
--- a/app/controllers/profile_controller.ts
+++ b/app/controllers/profile_controller.ts
@@ -1,21 +1,199 @@
-import { HttpContext } from '@adonisjs/core/http'
+import type { HttpContext } from '@adonisjs/core/http'
+import db from '@adonisjs/lucid/services/db'
import User from '#models/user'
import Article from '#models/article'
+import Thread from '#models/thread'
+import Discussion from '#models/discussion'
+import Reply from '#models/reply'
+import ArticleTransformer from '#transformers/article_transformer'
+import ThreadTransformer from '#transformers/thread_transformer'
+import DiscussionTransformer from '#transformers/discussion_transformer'
+import UserTransformer from '#transformers/user_transformer'
+import { plainExcerpt } from '#services/markdown'
+import type { ModelQueryBuilderContract } from '@adonisjs/lucid/types/model'
+
+export const PROFILE_TABS = ['articles', 'questions', 'discussions', 'reponses'] as const
+export type ProfileTab = (typeof PROFILE_TABS)[number]
+
+const PER_PAGE = 15
+
+/**
+ * Compact representation of a reply, with the title and URL of the page
+ * it belongs to (thread, discussion or article). Relations "thread",
+ * "discussion" and "article" must be preloaded (id, slug, title), plus
+ * "author" when `withAuthor` is set.
+ */
+export function replySummary(reply: Reply, { withAuthor = false } = {}) {
+ const parent = reply.thread
+ ? { type: 'thread' as const, title: reply.thread.title, url: `/forum/${reply.thread.slug}` }
+ : reply.discussion
+ ? {
+ type: 'discussion' as const,
+ title: reply.discussion.title,
+ url: `/discussions/${reply.discussion.slug}`,
+ }
+ : reply.article
+ ? {
+ type: 'article' as const,
+ title: reply.article.title,
+ url: `/articles/${reply.article.slug}`,
+ }
+ : null
+
+ return {
+ id: reply.id,
+ excerpt: plainExcerpt(reply.body, 220),
+ createdAt: reply.createdAt.toISO()!,
+ likesCount: Number(reply.$extras.likes_count ?? 0),
+ isSolution: Boolean(reply.thread && reply.thread.solutionReplyId === reply.id),
+ parent: parent ? { ...parent, anchor: `${parent.url}#reponse-${reply.id}` } : null,
+ author: withAuthor && reply.author ? new UserTransformer(reply.author).toObject() : null,
+ }
+}
+
+export type ReplySummary = ReturnType
+
+/**
+ * Query modifier: the parents a reply summary needs (only light columns).
+ */
+export function withReplyParents(query: ModelQueryBuilderContract) {
+ return (
+ query
+ // Comments on articles that went back to draft must not leak their title.
+ .where((q) =>
+ q
+ .whereNull('replies.article_id')
+ .orWhereIn(
+ 'replies.article_id',
+ db
+ .from('articles')
+ .select('id')
+ .whereNotNull('published_at')
+ .where('published_at', '<=', db.raw('now()'))
+ )
+ )
+ .preload('thread', (q) => q.select('id', 'slug', 'title', 'solution_reply_id'))
+ .preload('discussion', (q) => q.select('id', 'slug', 'title'))
+ .preload('article', (q) => q.select('id', 'slug', 'title'))
+ )
+}
export default class ProfileController {
- async show({ params, inertia }: HttpContext) {
- const user = await User.findByOrFail('username', params.username.replace('@', ''))
- const articles = await Article.query()
- .where('author_id', user.id)
- .where('is_published', true)
- .orderBy('created_at', 'desc')
- .preload('author')
+ /**
+ * Public profile: /@username (see start/routes/members.ts).
+ */
+ async show({ params, request, inertia, auth }: HttpContext) {
+ const viewer = auth.user
+ const username = String(params.username).toLowerCase()
+
+ // Banned members disappear from the site, except for the staff.
+ const profile = await User.query()
+ .whereRaw('lower(username) = ?', [username])
+ .if(!viewer?.isModerator, (q) => q.whereNull('banned_at'))
+ .firstOrFail()
+
+ const statsRow = await db
+ .rawQuery(
+ `select
+ (select count(*) from articles where user_id = :id and published_at is not null and published_at <= now()) as articles,
+ (select count(*) from threads where user_id = :id) as questions,
+ (select count(*) from discussions where user_id = :id) as discussions,
+ (select count(*) from replies where user_id = :id) as replies,
+ (select count(*) from threads t join replies r on r.id = t.solution_reply_id where r.user_id = :id) as solutions,
+ (select count(*) from likes l join articles a on a.id = l.article_id where a.user_id = :id)
+ + (select count(*) from likes l join replies r on r.id = l.reply_id where r.user_id = :id) as likes`,
+ { id: profile.id }
+ )
+ .then((result) => result.rows[0])
+
+ const stats = {
+ articles: Number(statsRow.articles),
+ questions: Number(statsRow.questions),
+ discussions: Number(statsRow.discussions),
+ replies: Number(statsRow.replies),
+ solutions: Number(statsRow.solutions),
+ likes: Number(statsRow.likes),
+ }
+
+ const counts: Record = {
+ articles: stats.articles,
+ questions: stats.questions,
+ discussions: stats.discussions,
+ reponses: stats.replies,
+ }
+
+ // Explicit tab from the URL, otherwise the first one with content.
+ const requested = request.input('tab')
+ const tab: ProfileTab = PROFILE_TABS.includes(requested)
+ ? requested
+ : (PROFILE_TABS.find((name) => counts[name] > 0) ?? 'articles')
+ const page = Math.max(1, Number.parseInt(request.input('page', '1'), 10) || 1)
+
+ const tabData = await this.tabData(profile, tab, page)
return inertia.render('profile/show', {
- profile: {
- ...user.serialize(),
- articles: articles,
- },
+ profile: UserTransformer.transform(profile).useVariant('forProfile'),
+ banned: profile.isBanned,
+ isOwner: viewer?.id === profile.id,
+ stats,
+ tab,
+ ...tabData,
})
}
+
+ private async tabData(profile: User, tab: ProfileTab, page: number) {
+ const empty = { articles: null, threads: null, discussions: null, replies: null }
+
+ if (tab === 'articles') {
+ const paginator = await Article.query()
+ .where('user_id', profile.id)
+ .withScopes((s) => s.published())
+ .preload('author')
+ .preload('tags')
+ .withCount('likes')
+ .withCount('comments')
+ .orderBy('published_at', 'desc')
+ .paginate(page, PER_PAGE)
+ return {
+ ...empty,
+ articles: ArticleTransformer.paginate(paginator.all(), paginator.getMeta()),
+ }
+ }
+
+ if (tab === 'questions') {
+ const paginator = await Thread.query()
+ .where('user_id', profile.id)
+ .preload('author')
+ .preload('channel')
+ .orderBy('created_at', 'desc')
+ .paginate(page, PER_PAGE)
+ return { ...empty, threads: ThreadTransformer.paginate(paginator.all(), paginator.getMeta()) }
+ }
+
+ if (tab === 'discussions') {
+ const paginator = await Discussion.query()
+ .where('user_id', profile.id)
+ .preload('author')
+ .preload('tags')
+ .orderBy('created_at', 'desc')
+ .paginate(page, PER_PAGE)
+ return {
+ ...empty,
+ discussions: DiscussionTransformer.paginate(paginator.all(), paginator.getMeta()),
+ }
+ }
+
+ const paginator = await withReplyParents(Reply.query())
+ .where('user_id', profile.id)
+ .withCount('likes')
+ .orderBy('created_at', 'desc')
+ .paginate(page, PER_PAGE)
+ return {
+ ...empty,
+ replies: {
+ data: paginator.all().map((reply) => replySummary(reply)),
+ metadata: paginator.getMeta(),
+ },
+ }
+ }
}
diff --git a/app/controllers/replies_controller.ts b/app/controllers/replies_controller.ts
new file mode 100644
index 0000000..e3b97bb
--- /dev/null
+++ b/app/controllers/replies_controller.ts
@@ -0,0 +1,57 @@
+import type { HttpContext } from '@adonisjs/core/http'
+import Reply from '#models/reply'
+import Like from '#models/like'
+import { replyValidator } from '#validators/reply_validator'
+import { deleteReply, replyLocation, updateReply } from '#services/reply_service'
+
+/**
+ * Edit / delete / like any reply (forum, discussion or article comment).
+ * Creation lives with each parent (threads, discussions, articles).
+ */
+export default class RepliesController {
+ async update({ params, request, auth, response, session }: HttpContext) {
+ const reply = await Reply.findOrFail(params.id)
+ if (!(await auth.user!.canManageContent(reply.userId))) {
+ session.flash('error', 'Vous ne pouvez pas modifier cette réponse.')
+ return response.redirect().back()
+ }
+ const { body } = await request.validateUsing(replyValidator)
+ await updateReply(reply, body)
+ session.flash('success', 'Réponse mise à jour.')
+ return response.redirect().toPath(`${await replyLocation(reply)}#reponse-${reply.id}`)
+ }
+
+ async destroy({ params, auth, response, session }: HttpContext) {
+ const reply = await Reply.findOrFail(params.id)
+ if (!(await auth.user!.canManageContent(reply.userId))) {
+ session.flash('error', 'Vous ne pouvez pas supprimer cette réponse.')
+ return response.redirect().back()
+ }
+ const location = await replyLocation(reply)
+ await deleteReply(reply)
+ session.flash('success', 'Réponse supprimée.')
+ return response.redirect().toPath(location)
+ }
+
+ /**
+ * Toggle the viewer's like on a reply.
+ */
+ async like({ params, auth, response }: HttpContext) {
+ const reply = await Reply.findOrFail(params.id)
+ const existing = await Like.query()
+ .where('user_id', auth.user!.id)
+ .where('reply_id', reply.id)
+ .first()
+ if (existing) {
+ await existing.delete()
+ } else if (reply.userId !== auth.user!.id) {
+ try {
+ await Like.create({ userId: auth.user!.id, replyId: reply.id })
+ } catch (error) {
+ // Double click: the unique (user_id, reply_id) index already holds it.
+ if ((error as { code?: string }).code !== '23505') throw error
+ }
+ }
+ return response.redirect().back()
+ }
+}
diff --git a/app/controllers/reports_controller.ts b/app/controllers/reports_controller.ts
new file mode 100644
index 0000000..ebf73e8
--- /dev/null
+++ b/app/controllers/reports_controller.ts
@@ -0,0 +1,121 @@
+import type { HttpContext } from '@adonisjs/core/http'
+import { errors as lucidErrors } from '@adonisjs/lucid'
+import db from '@adonisjs/lucid/services/db'
+import Report from '#models/report'
+import Article from '#models/article'
+import Thread from '#models/thread'
+import Discussion from '#models/discussion'
+import Reply from '#models/reply'
+import type User from '#models/user'
+import { reportValidator, type ReportTarget } from '#validators/report_validator'
+
+const TARGET_ATTRIBUTE = {
+ article: 'articleId',
+ thread: 'threadId',
+ discussion: 'discussionId',
+ reply: 'replyId',
+} as const satisfies Record
+
+/**
+ * Drafts stay invisible to everyone but their author and the staff.
+ */
+function assertArticleVisible(article: Article, viewer: User) {
+ if (article.isPublished || viewer.canSeeDraftsOf(article.userId)) return
+ throw new lucidErrors.E_ROW_NOT_FOUND()
+}
+
+/**
+ * Owner and label (title, or the parent's title for a reply) of a piece of
+ * content the viewer is allowed to see. Missing or invisible content
+ * (someone else's draft, or a comment on it) is a 404.
+ */
+async function visibleTarget(
+ target: ReportTarget,
+ id: number,
+ viewer: User
+): Promise<{ ownerId: number; label: string | null }> {
+ switch (target) {
+ case 'article': {
+ const article = await Article.findOrFail(id)
+ assertArticleVisible(article, viewer)
+ return { ownerId: article.userId, label: article.title }
+ }
+ case 'thread': {
+ const thread = await Thread.findOrFail(id)
+ return { ownerId: thread.userId, label: thread.title }
+ }
+ case 'discussion': {
+ const discussion = await Discussion.findOrFail(id)
+ return { ownerId: discussion.userId, label: discussion.title }
+ }
+ case 'reply': {
+ const reply = await Reply.query()
+ .where('id', id)
+ .preload('thread', (query) => query.select('id', 'title'))
+ .preload('discussion', (query) => query.select('id', 'title'))
+ .preload('article', (query) => query.select('id', 'title', 'user_id', 'published_at'))
+ .firstOrFail()
+ if (reply.article) assertArticleVisible(reply.article, viewer)
+ const parent = reply.thread ?? reply.discussion ?? reply.article
+ return { ownerId: reply.userId, label: parent?.title ?? null }
+ }
+ }
+}
+
+/**
+ * The partial unique index "reports_open_unique" refused a second open
+ * report of the same member on the same content.
+ */
+function isDuplicateOpenReport(error: unknown) {
+ const { code, constraint } = error as { code?: string; constraint?: string }
+ return code === '23505' && constraint === 'reports_open_unique'
+}
+
+/**
+ * Members flag content for the moderators ("Signaler").
+ */
+export default class ReportsController {
+ /**
+ * POST /signalements { target, id, reason, details? }
+ */
+ async store({ request, auth, response, session }: HttpContext) {
+ const user = auth.getUserOrFail()
+ const { target, id, reason, details } = await request.validateUsing(reportValidator)
+
+ const { ownerId, label } = await visibleTarget(target, id, user)
+ if (ownerId === user.id) {
+ session.flash('error', 'Vous ne pouvez pas signaler votre propre contenu.')
+ return response.redirect().back()
+ }
+
+ const report = new Report()
+ report.reporterId = user.id
+ report.targetType = target
+ report.targetId = id
+ report[TARGET_ATTRIBUTE[target]] = id
+ report.targetLabel = label ? label.slice(0, 200) : null
+ report.targetOwnerId = ownerId
+ report.reason = reason
+ report.details = details ?? null
+ report.status = 'open'
+
+ // One open report per member and content, enforced by the database (no
+ // race between two clicks). The savepoint keeps an outer transaction usable.
+ try {
+ await db.transaction(async (trx) => {
+ report.useTransaction(trx)
+ await report.save()
+ })
+ } catch (error) {
+ if (!isDuplicateOpenReport(error)) throw error
+ session.flash(
+ 'success',
+ 'Vous avez déjà signalé ce contenu : l’équipe de modération l’a bien dans sa file.'
+ )
+ return response.redirect().back()
+ }
+
+ session.flash('success', 'Merci, l’équipe de modération va examiner ce contenu.')
+ return response.redirect().back()
+ }
+}
diff --git a/app/controllers/search_controller.ts b/app/controllers/search_controller.ts
new file mode 100644
index 0000000..bbda9ec
--- /dev/null
+++ b/app/controllers/search_controller.ts
@@ -0,0 +1,267 @@
+import type { HttpContext } from '@adonisjs/core/http'
+import { DateTime } from 'luxon'
+import db from '@adonisjs/lucid/services/db'
+import Article from '#models/article'
+import Thread from '#models/thread'
+import Discussion from '#models/discussion'
+import Tag from '#models/tag'
+import Channel from '#models/channel'
+import ArticleTransformer from '#transformers/article_transformer'
+import ThreadTransformer from '#transformers/thread_transformer'
+import DiscussionTransformer from '#transformers/discussion_transformer'
+import TagTransformer from '#transformers/tag_transformer'
+import ChannelTransformer from '#transformers/channel_transformer'
+import { searchMessages, searchValidator } from '#validators/search_validator'
+import {
+ SEARCH_SECTIONS,
+ SEARCH_TYPES,
+ countAll,
+ exactQuery,
+ findHits,
+ prefixQuery,
+ type SearchCounts,
+ type SearchHit,
+ type SearchSection,
+ type SearchType,
+} from '#services/search'
+
+/** Results per page on a filtered tab. */
+const PER_PAGE = 15
+/** Results per section on the "tout" tab. */
+const PREVIEW = 4
+
+type Status = 'landing' | 'invalid' | 'throttled' | 'results' | 'empty'
+
+type Meta = { total: number; perPage: number; currentPage: number; lastPage: number }
+
+function toPage(value: unknown) {
+ const page = Number.parseInt(String(value ?? '1'), 10)
+ return Number.isFinite(page) && page > 0 ? Math.min(page, 1000) : 1
+}
+
+function meta(total: number, perPage: number, currentPage: number): Meta {
+ return { total, perPage, currentPage, lastPage: Math.max(1, Math.ceil(total / perPage)) }
+}
+
+/**
+ * Lucid returns "whereIn" rows in any order: restore the ranking.
+ */
+function inRankOrder(hits: SearchHit[], rows: T[]) {
+ const byId = new Map(rows.map((row) => [row.id, row]))
+ return hits.map((hit) => byId.get(hit.id)).filter((row): row is T => Boolean(row))
+}
+
+const loaders = {
+ articles: (ids: number[]) =>
+ Article.query().whereIn('id', ids).preload('author').preload('tags').withCount('comments'),
+ questions: (ids: number[]) =>
+ Thread.query().whereIn('id', ids).preload('author').preload('channel'),
+ discussions: (ids: number[]) =>
+ Discussion.query().whereIn('id', ids).preload('author').preload('tags'),
+}
+
+/**
+ * Popular topics and forum channels, offered on the landing state and
+ * when nothing matches.
+ */
+async function suggestions() {
+ const [tags, channels] = await Promise.all([
+ Tag.query().withCount('articles', (query) => {
+ query
+ .whereNotNull('articles.published_at')
+ .where('articles.published_at', '<=', DateTime.now().toSQL()!)
+ }),
+ Channel.query().withCount('threads').orderBy('position', 'asc'),
+ ])
+ const popular = tags
+ .filter((tag) => Number(tag.$extras.articles_count) > 0)
+ .sort((a, b) => Number(b.$extras.articles_count) - Number(a.$extras.articles_count))
+ .slice(0, 12)
+ return {
+ popularTags: TagTransformer.transform(popular),
+ channels: ChannelTransformer.transform(channels),
+ }
+}
+
+/**
+ * Size of the searchable index (landing state), same visibility rules.
+ */
+async function indexSize(): Promise {
+ const visibleAuthor = (table: string) =>
+ `not exists (select 1 from users where users.id = ${table}.user_id and users.banned_at is not null)`
+ const result = await db.rawQuery(
+ `select
+ (select count(*) from articles where published_at is not null and published_at <= now() and ${visibleAuthor('articles')}) as articles,
+ (select count(*) from threads where ${visibleAuthor('threads')}) as questions,
+ (select count(*) from discussions where ${visibleAuthor('discussions')}) as discussions`
+ )
+ const row = result.rows[0] ?? {}
+ return {
+ articles: Number(row.articles ?? 0),
+ questions: Number(row.questions ?? 0),
+ discussions: Number(row.discussions ?? 0),
+ }
+}
+
+const sum = (counts: SearchCounts) => counts.articles + counts.questions + counts.discussions
+
+export default class SearchController {
+ /**
+ * GET /recherche?q=&type=tout|articles|questions|discussions&page=
+ */
+ async index(ctx: HttpContext) {
+ const qs = ctx.request.qs()
+ const rawQ = typeof qs.q === 'string' ? qs.q.trim() : ''
+ const type: SearchType = SEARCH_TYPES.includes(qs.type) ? qs.type : 'tout'
+
+ if (!rawQ) return this.landing(ctx, { type })
+
+ const [error, input] = await searchValidator.tryValidate(
+ { q: rawQ, type, page: toPage(qs.page) },
+ { messagesProvider: searchMessages }
+ )
+ if (error) {
+ return this.landing(ctx, {
+ type,
+ q: rawQ.slice(0, 100),
+ status: 'invalid',
+ error: error.messages[0]?.message ?? 'Recherche invalide.',
+ })
+ }
+
+ const q = input.q
+ const page = input.page ?? 1
+
+ // Exact (websearch) query first; prefixes ("clos" → closures) only
+ // when it finds nothing at all.
+ let query = exactQuery(q)
+ let counts = await countAll(query)
+ if (sum(counts) === 0) {
+ const fallback = prefixQuery(q)
+ if (fallback) {
+ const fallbackCounts = await countAll(fallback)
+ if (sum(fallbackCounts) > 0) {
+ query = fallback
+ counts = fallbackCounts
+ }
+ }
+ }
+
+ if (sum(counts) === 0) {
+ return ctx.inertia.render('search/index', {
+ ...this.emptyProps(type, q),
+ status: 'empty',
+ counts,
+ ...(await suggestions()),
+ })
+ }
+
+ const filtered = type !== 'tout'
+ const perPage = filtered ? PER_PAGE : PREVIEW
+ const currentPage = filtered ? page : 1
+ const sections = SEARCH_SECTIONS.filter((section) =>
+ filtered ? section === type : counts[section] > 0
+ )
+
+ const results = await Promise.all(
+ sections.map(async (section) => {
+ const hits = counts[section]
+ ? await findHits(section, query, { limit: perPage, offset: (currentPage - 1) * perPage })
+ : []
+ const ids = hits.map((hit) => hit.id)
+ const rows = ids.length ? await loaders[section](ids) : []
+ return { section, hits, rows: inRankOrder(hits, rows as { id: number }[]) }
+ })
+ )
+
+ const highlights: Record = {}
+ for (const { section, hits } of results) {
+ for (const hit of hits) {
+ highlights[`${section}:${hit.id}`] = {
+ titleHtml: hit.titleHtml,
+ snippetHtml: hit.snippetHtml,
+ }
+ }
+ }
+
+ const pick = (section: SearchSection) => results.find((result) => result.section === section)
+ const sectionMeta = (section: SearchSection) => meta(counts[section], perPage, currentPage)
+ const articles = pick('articles')
+ const questions = pick('questions')
+ const discussions = pick('discussions')
+
+ return ctx.inertia.render('search/index', {
+ ...this.emptyProps(type, q),
+ status: 'results',
+ mode: query.mode,
+ counts,
+ highlights,
+ articles: articles
+ ? ArticleTransformer.paginate(articles.rows as Article[], sectionMeta('articles'))
+ : null,
+ questions: questions
+ ? ThreadTransformer.paginate(questions.rows as Thread[], sectionMeta('questions'))
+ : null,
+ discussions: discussions
+ ? DiscussionTransformer.paginate(
+ discussions.rows as Discussion[],
+ sectionMeta('discussions')
+ )
+ : null,
+ })
+ }
+
+ /**
+ * Rendered by the search limiter (start/routes/search.ts) for Inertia
+ * visits instead of a bare "429" text response. No database query.
+ */
+ async throttled(ctx: HttpContext, message: string) {
+ const qs = ctx.request.qs()
+ const type: SearchType = SEARCH_TYPES.includes(qs.type) ? qs.type : 'tout'
+ const q = typeof qs.q === 'string' ? qs.q.trim().slice(0, 100) : ''
+ const page = await ctx.inertia.render('search/index', {
+ ...this.emptyProps(type, q),
+ status: 'throttled',
+ error: message,
+ })
+ // Called from an exception handler: the return value is not sent.
+ ctx.response.status(429).send(page)
+ }
+
+ private emptyProps(type: SearchType, q: string) {
+ return {
+ q,
+ type,
+ status: 'landing' as Status,
+ error: null as string | null,
+ mode: null,
+ counts: null as SearchCounts | null,
+ index: null as SearchCounts | null,
+ highlights: {},
+ articles: null,
+ questions: null,
+ discussions: null,
+ popularTags: null,
+ channels: null,
+ }
+ }
+
+ private async landing(
+ ctx: HttpContext,
+ options: {
+ type: SearchType
+ q?: string
+ status?: Status
+ error?: string
+ }
+ ) {
+ const [hints, index] = await Promise.all([suggestions(), indexSize()])
+ return ctx.inertia.render('search/index', {
+ ...this.emptyProps(options.type, options.q ?? ''),
+ status: options.status ?? 'landing',
+ error: options.error ?? null,
+ index,
+ ...hints,
+ })
+ }
+}
diff --git a/app/controllers/seo_controller.ts b/app/controllers/seo_controller.ts
new file mode 100644
index 0000000..2e4de28
--- /dev/null
+++ b/app/controllers/seo_controller.ts
@@ -0,0 +1,121 @@
+import type { HttpContext } from '@adonisjs/core/http'
+import env from '#start/env'
+import Article from '#models/article'
+import Thread from '#models/thread'
+import Discussion from '#models/discussion'
+import User from '#models/user'
+
+const PRODUCTION_HOST = 'javascript.cm'
+
+function escapeXml(value: string) {
+ return value
+ .replace(/&/g, '&')
+ .replace(//g, '>')
+ .replace(/"/g, '"')
+ .replace(/'/g, ''')
+}
+
+export default class SeoController {
+ /**
+ * Only the production host is indexable: staging and previews are not.
+ */
+ async robots({ response }: HttpContext) {
+ const appUrl = new URL(env.get('APP_URL'))
+ response.header('Content-Type', 'text/plain; charset=utf-8')
+
+ if (appUrl.hostname !== PRODUCTION_HOST) {
+ return 'User-agent: *\nDisallow: /\n'
+ }
+
+ return [
+ 'User-agent: *',
+ 'Allow: /',
+ 'Disallow: /dashboard',
+ 'Disallow: /settings',
+ 'Disallow: /admin',
+ '',
+ `Sitemap: ${appUrl.origin}/sitemap.xml`,
+ '',
+ ].join('\n')
+ }
+
+ async sitemap({ response }: HttpContext) {
+ const base = env.get('APP_URL')
+ const [articles, threads, discussions, users] = await Promise.all([
+ Article.query()
+ .withScopes((s) => s.published())
+ .select('slug', 'updated_at', 'published_at'),
+ Thread.query().select('slug', 'last_activity_at'),
+ Discussion.query().select('slug', 'last_activity_at'),
+ User.query().whereNull('banned_at').select('username', 'updated_at'),
+ ])
+
+ const urls: { loc: string; lastmod?: string; priority?: string }[] = [
+ { loc: '/', priority: '1.0' },
+ { loc: '/articles', priority: '0.9' },
+ { loc: '/forum', priority: '0.9' },
+ { loc: '/discussions', priority: '0.8' },
+ { loc: '/membres', priority: '0.5' },
+ ...articles.map((a) => ({
+ loc: `/articles/${a.slug}`,
+ lastmod: (a.updatedAt ?? a.publishedAt)?.toISODate() ?? undefined,
+ priority: '0.8',
+ })),
+ ...threads.map((t) => ({
+ loc: `/forum/${t.slug}`,
+ lastmod: t.lastActivityAt.toISODate() ?? undefined,
+ })),
+ ...discussions.map((d) => ({
+ loc: `/discussions/${d.slug}`,
+ lastmod: d.lastActivityAt.toISODate() ?? undefined,
+ })),
+ ...users.map((u) => ({ loc: `/@${u.username}`, priority: '0.3' })),
+ ]
+
+ const body = urls
+ .map(
+ (u) =>
+ `${escapeXml(base + u.loc)}${u.lastmod ? `${u.lastmod}` : ''}${u.priority ? `${u.priority}` : ''}`
+ )
+ .join('')
+
+ response.header('Content-Type', 'application/xml; charset=utf-8')
+ return `${body}`
+ }
+
+ async feed({ response }: HttpContext) {
+ const base = env.get('APP_URL')
+ const articles = await Article.query()
+ .withScopes((s) => s.published())
+ .preload('author')
+ .orderBy('published_at', 'desc')
+ .limit(30)
+
+ const items = articles
+ .map(
+ (a) => `-
+ ${escapeXml(a.title)}
+ ${escapeXml(`${base}/articles/${a.slug}`)}
+ ${escapeXml(`${base}/articles/${a.slug}`)}
+ ${a.publishedAt!.toRFC2822()}
+ ${escapeXml(a.author.displayName)}
+ ${escapeXml(a.excerpt ?? '')}
+
`
+ )
+ .join('\n')
+
+ response.header('Content-Type', 'application/rss+xml; charset=utf-8')
+ return `
+
+
+ JavaScript Cameroun — Articles
+ ${escapeXml(base)}
+
+ Les articles de la communauté des développeurs JavaScript du Cameroun.
+ fr
+${items}
+
+`
+ }
+}
diff --git a/app/controllers/settings_controller.ts b/app/controllers/settings_controller.ts
new file mode 100644
index 0000000..5ee14c0
--- /dev/null
+++ b/app/controllers/settings_controller.ts
@@ -0,0 +1,218 @@
+import { SESSION_VERSION_KEY } from '#middleware/silent_auth_middleware'
+import type { HttpContext } from '@adonisjs/core/http'
+import hash from '@adonisjs/core/services/hash'
+import db from '@adonisjs/lucid/services/db'
+import {
+ deleteAccountValidator,
+ normalizeHandle,
+ passwordSettingsValidator,
+ profileSettingsValidator,
+} from '#validators/settings_validator'
+
+/**
+ * Account settings of the signed-in member (profile, password, deletion).
+ * The forms read the current values from the shared `user` prop.
+ */
+export default class SettingsController {
+ async profile({ inertia }: HttpContext) {
+ return inertia.render('settings/profile', {})
+ }
+
+ async updateProfile({ request, auth, response, session }: HttpContext) {
+ const user = auth.getUserOrFail()
+ const input = request.only([
+ 'name',
+ 'username',
+ 'email',
+ 'bio',
+ 'location',
+ 'websiteUrl',
+ 'avatarUrl',
+ 'githubUsername',
+ 'twitterUsername',
+ 'linkedinUsername',
+ ])
+
+ const data = await profileSettingsValidator.validate(
+ {
+ ...input,
+ githubUsername: normalizeHandle(input.githubUsername, 'github'),
+ twitterUsername: normalizeHandle(input.twitterUsername, 'twitter'),
+ linkedinUsername: normalizeHandle(input.linkedinUsername, 'linkedin'),
+ },
+ { meta: { userId: user.id } }
+ )
+
+ const usernameChanged = data.username !== user.username
+ if (data.email !== user.email) {
+ // A new address is unverified until proven otherwise (GitHub sign-in
+ // only links accounts whose e-mail is verified).
+ user.emailVerifiedAt = null
+ }
+ user.merge({
+ name: data.name,
+ username: data.username,
+ email: data.email,
+ bio: data.bio,
+ location: data.location,
+ websiteUrl: data.websiteUrl,
+ avatarUrl: data.avatarUrl,
+ githubUsername: data.githubUsername,
+ twitterUsername: data.twitterUsername,
+ linkedinUsername: data.linkedinUsername,
+ })
+ await user.save()
+
+ session.flash(
+ 'success',
+ usernameChanged
+ ? `Profil mis à jour. Votre nouvelle adresse : javascript.cm/@${user.username}`
+ : 'Profil mis à jour.'
+ )
+ return response.redirect().toPath('/settings')
+ }
+
+ async password({ inertia }: HttpContext) {
+ return inertia.render('settings/password', {})
+ }
+
+ async updatePassword({ request, auth, response, session }: HttpContext) {
+ const user = auth.getUserOrFail()
+ const { currentPassword, password } = await request.validateUsing(passwordSettingsValidator)
+
+ if (user.password !== null) {
+ const valid = currentPassword ? await hash.verify(user.password, currentPassword) : false
+ if (!valid) {
+ session.flashExcept(['currentPassword', 'password', 'passwordConfirmation'])
+ session.flash('inputErrorsBag', {
+ currentPassword: [
+ currentPassword
+ ? 'Mot de passe actuel incorrect.'
+ : 'Saisissez votre mot de passe actuel.',
+ ],
+ })
+ return response.redirect().back()
+ }
+ }
+
+ const hadPassword = user.password !== null
+ user.password = password // hashed by the AuthFinder mixin
+ user.sessionVersion = user.sessionVersion + 1
+ await user.save()
+
+ // Sign out the other devices: their sessions carry the previous version
+ // (see SilentAuthMiddleware) and their "remember me" tokens are revoked.
+ await db.from('remember_me_tokens').where('tokenable_id', user.id).delete()
+ session.put(SESSION_VERSION_KEY, user.sessionVersion)
+
+ session.flash(
+ 'success',
+ hadPassword
+ ? 'Mot de passe modifié.'
+ : 'Mot de passe défini : vous pouvez aussi vous connecter avec votre e-mail.'
+ )
+ return response.redirect().toPath('/settings/password')
+ }
+
+ async account({ inertia, auth }: HttpContext) {
+ const user = auth.getUserOrFail()
+ const counts = await db
+ .rawQuery(
+ `select
+ (select count(*) from articles where user_id = :id) as articles,
+ (select count(*) from threads where user_id = :id) as threads,
+ (select count(*) from discussions where user_id = :id) as discussions,
+ (select count(*) from replies where user_id = :id) as replies`,
+ { id: user.id }
+ )
+ .then((result) => result.rows[0])
+
+ return inertia.render('settings/account', {
+ githubLinked: user.githubId !== null,
+ content: {
+ articles: Number(counts.articles),
+ threads: Number(counts.threads),
+ discussions: Number(counts.discussions),
+ replies: Number(counts.replies),
+ },
+ })
+ }
+
+ async destroyAccount({ request, auth, response, session }: HttpContext) {
+ const user = auth.getUserOrFail()
+ const { confirmation } = await request.validateUsing(deleteAccountValidator)
+
+ if (confirmation.replace(/^@/, '').toLowerCase() !== user.username.toLowerCase()) {
+ session.flash('inputErrorsBag', {
+ confirmation: ['Saisissez exactement votre nom d’utilisateur pour confirmer.'],
+ })
+ return response.redirect().back()
+ }
+
+ if (user.isAdmin) {
+ const admins = await db
+ .from('users')
+ .where('role', 'admin')
+ .whereNull('banned_at')
+ .count('* as total')
+ .first()
+ if (Number(admins?.total ?? 0) <= 1) {
+ session.flash(
+ 'error',
+ 'Vous êtes le dernier administrateur : nommez un autre administrateur avant de supprimer votre compte.'
+ )
+ return response.redirect().back()
+ }
+ }
+
+ await db.transaction(async (trx) => {
+ // Threads and discussions of other members lose this member's replies
+ // through the cascade: keep their counters right.
+ const threadRows = await trx
+ .from('replies')
+ .select('thread_id')
+ .where('user_id', user.id)
+ .whereNotNull('thread_id')
+ const discussionRows = await trx
+ .from('replies')
+ .select('discussion_id')
+ .where('user_id', user.id)
+ .whereNotNull('discussion_id')
+ const touchedThreads = [...new Set(threadRows.map((row) => row.thread_id as number))]
+ const touchedDiscussions = [
+ ...new Set(discussionRows.map((row) => row.discussion_id as number)),
+ ]
+
+ user.useTransaction(trx)
+ await user.delete()
+
+ if (touchedThreads.length) {
+ await trx
+ .from('threads')
+ .whereIn('id', touchedThreads)
+ .update({
+ replies_count: trx.raw(
+ '(select count(*) from replies where replies.thread_id = threads.id)'
+ ),
+ })
+ }
+ if (touchedDiscussions.length) {
+ await trx
+ .from('discussions')
+ .whereIn('id', touchedDiscussions)
+ .update({
+ replies_count: trx.raw(
+ '(select count(*) from replies where replies.discussion_id = discussions.id)'
+ ),
+ })
+ }
+ })
+
+ await auth.use('web').logout()
+ session.flash(
+ 'success',
+ 'Votre compte a été supprimé. Merci d’avoir fait partie de la communauté.'
+ )
+ return response.redirect().toPath('/')
+ }
+}
diff --git a/app/controllers/thread_actions_controller.ts b/app/controllers/thread_actions_controller.ts
new file mode 100644
index 0000000..f741087
--- /dev/null
+++ b/app/controllers/thread_actions_controller.ts
@@ -0,0 +1,122 @@
+import type { HttpContext } from '@adonisjs/core/http'
+import db from '@adonisjs/lucid/services/db'
+import Thread from '#models/thread'
+import Reply from '#models/reply'
+import { replyValidator } from '#validators/reply_validator'
+import { solutionValidator } from '#validators/thread_validator'
+import { createReply } from '#services/reply_service'
+import { notifySolution } from '#services/notifications'
+import { THREAD_REPLIES_PER_PAGE } from '#controllers/threads_controller'
+
+/**
+ * Everything that happens *on* a forum thread: replying, accepting a
+ * solution, and moderation toggles (pin / lock).
+ */
+export default class ThreadActionsController {
+ /**
+ * POST /forum/:slug/replies
+ */
+ async reply({ params, request, auth, response, session }: HttpContext) {
+ const user = auth.user!
+ const thread = await Thread.findByOrFail('slug', params.slug)
+ if (thread.isLocked && !user.isModerator) {
+ session.flash('error', 'Ce sujet est verrouillé : il n’accepte plus de nouvelles réponses.')
+ return response.redirect().toPath(`/forum/${thread.slug}`)
+ }
+
+ const { body } = await request.validateUsing(replyValidator)
+ const reply = await createReply({ type: 'thread', id: thread.id }, user, body)
+
+ const total = thread.repliesCount + 1
+ const page = total > THREAD_REPLIES_PER_PAGE ? Math.ceil(total / THREAD_REPLIES_PER_PAGE) : 1
+ session.flash('success', 'Réponse publiée. Merci pour votre aide !')
+ return response
+ .redirect()
+ .toPath(`/forum/${thread.slug}${page > 1 ? `?page=${page}` : ''}#reponse-${reply.id}`)
+ }
+
+ /**
+ * POST /forum/:slug/solution { replyId } — thread author or moderators,
+ * on a reply of this thread written by someone else.
+ */
+ async markSolution({ params, request, auth, response, session }: HttpContext) {
+ const thread = await Thread.findByOrFail('slug', params.slug)
+ if (!(await auth.user!.canManageContent(thread.userId))) {
+ session.flash('error', 'Seul l’auteur de la question peut choisir la solution.')
+ return response.redirect().back()
+ }
+
+ const { replyId } = await request.validateUsing(solutionValidator)
+ const reply = await Reply.query().where('id', replyId).where('thread_id', thread.id).first()
+ if (!reply) {
+ session.flash('error', 'Cette réponse n’appartient pas à cette question.')
+ return response.redirect().back()
+ }
+ if (reply.userId === thread.userId) {
+ session.flash('error', 'La solution doit venir d’une réponse d’un autre membre.')
+ return response.redirect().back()
+ }
+
+ // Plain update: accepting an answer is not an edit of the question.
+ await db.from('threads').where('id', thread.id).update({ solution_reply_id: reply.id })
+ await notifySolution(thread.id, reply, auth.user!.id)
+ session.flash('success', 'Réponse marquée comme solution.')
+ return response.redirect().back()
+ }
+
+ /**
+ * DELETE /forum/:slug/solution
+ */
+ async unmarkSolution({ params, auth, response, session }: HttpContext) {
+ const thread = await Thread.findByOrFail('slug', params.slug)
+ if (!(await auth.user!.canManageContent(thread.userId))) {
+ session.flash('error', 'Seul l’auteur de la question peut retirer la solution.')
+ return response.redirect().back()
+ }
+ await db.from('threads').where('id', thread.id).update({ solution_reply_id: null })
+ session.flash('success', 'La solution a été retirée. La question est de nouveau ouverte.')
+ return response.redirect().back()
+ }
+
+ /**
+ * POST /forum/:slug/pin — moderators only, toggles.
+ */
+ async togglePin({ params, auth, response, session }: HttpContext) {
+ const thread = await Thread.findByOrFail('slug', params.slug)
+ if (!auth.user!.isModerator) {
+ session.flash('error', 'Action réservée aux modérateurs.')
+ return response.redirect().back()
+ }
+ const pinned = thread.pinnedAt === null
+ await db
+ .from('threads')
+ .where('id', thread.id)
+ .update({ pinned_at: pinned ? new Date() : null })
+ session.flash(
+ 'success',
+ pinned ? 'Question épinglée en haut du forum.' : 'Question désépinglée.'
+ )
+ return response.redirect().back()
+ }
+
+ /**
+ * POST /forum/:slug/lock — moderators only, toggles.
+ */
+ async toggleLock({ params, auth, response, session }: HttpContext) {
+ const thread = await Thread.findByOrFail('slug', params.slug)
+ if (!auth.user!.isModerator) {
+ session.flash('error', 'Action réservée aux modérateurs.')
+ return response.redirect().back()
+ }
+ const locked = thread.lockedAt === null
+ await db
+ .from('threads')
+ .where('id', thread.id)
+ .update({ locked_at: locked ? new Date() : null })
+ session.flash(
+ 'success',
+ locked ? 'Sujet verrouillé : plus de nouvelles réponses.' : 'Sujet déverrouillé.'
+ )
+ return response.redirect().back()
+ }
+}
diff --git a/app/controllers/threads_controller.ts b/app/controllers/threads_controller.ts
new file mode 100644
index 0000000..20260d5
--- /dev/null
+++ b/app/controllers/threads_controller.ts
@@ -0,0 +1,304 @@
+import { markSubjectRead } from '#services/notifications'
+import type { HttpContext } from '@adonisjs/core/http'
+import { DateTime } from 'luxon'
+import db from '@adonisjs/lucid/services/db'
+import { errors as lucidErrors } from '@adonisjs/lucid'
+import type { ModelQueryBuilderContract } from '@adonisjs/lucid/types/model'
+import Thread from '#models/thread'
+import Channel from '#models/channel'
+import Reply from '#models/reply'
+import User from '#models/user'
+import ThreadTransformer from '#transformers/thread_transformer'
+import ChannelTransformer from '#transformers/channel_transformer'
+import ReplyTransformer from '#transformers/reply_transformer'
+import UserTransformer from '#transformers/user_transformer'
+import { threadValidator } from '#validators/thread_validator'
+import { plainExcerpt, renderMarkdown } from '#services/markdown'
+import { uniqueSlug } from '#services/slug'
+import { withReplyMeta } from '#services/reply_service'
+
+const PER_PAGE = 20
+export const THREAD_REPLIES_PER_PAGE = 50
+
+const FILTERS = ['sans-reponse', 'non-resolues', 'resolues'] as const
+type Filter = (typeof FILTERS)[number]
+
+/**
+ * "%term%" for ILIKE, with the LIKE wildcards of the term escaped.
+ */
+function likePattern(term: string) {
+ return `%${term.replace(/[\\%_]/g, (char) => `\\${char}`)}%`
+}
+
+function toPage(value: unknown) {
+ const page = Number.parseInt(String(value ?? '1'), 10)
+ return Number.isFinite(page) && page > 0 ? page : 1
+}
+
+/**
+ * Count one view per visitor session (replying, accepting a solution or
+ * reloading the page must not inflate the counter).
+ */
+function isFirstView(session: HttpContext['session'], key: string) {
+ const seen: string[] = session.get('seen_content', [])
+ if (seen.includes(key)) return false
+ session.put('seen_content', [...seen.slice(-39), key])
+ return true
+}
+
+export default class ThreadsController {
+ /**
+ * GET /forum — channel index, status filters, search.
+ */
+ async index({ request, inertia }: HttpContext) {
+ const qs = request.qs()
+ const q = typeof qs.q === 'string' ? qs.q.trim().slice(0, 120) : ''
+ const filter: Filter | null = FILTERS.includes(qs.filter) ? qs.filter : null
+ const page = toPage(qs.page)
+
+ const channels = await Channel.query().withCount('threads').orderBy('position', 'asc')
+
+ let channel: Channel | null = null
+ if (typeof qs.channel === 'string' && qs.channel !== '') {
+ channel = channels.find((c) => c.slug === qs.channel) ?? null
+ if (!channel) throw new lucidErrors.E_ROW_NOT_FOUND(Channel)
+ }
+
+ // The current selection (channel + search), shared by the list and the stats.
+ const selection = (query: ModelQueryBuilderContract) => {
+ if (channel) query.where('channel_id', channel.id)
+ if (q) {
+ const pattern = likePattern(q)
+ query.where((sub) => sub.whereILike('title', pattern).orWhereILike('body', pattern))
+ }
+ return query
+ }
+
+ const listQuery = selection(Thread.query().preload('author').preload('channel'))
+ if (filter === 'sans-reponse') listQuery.where('replies_count', 0)
+ if (filter === 'non-resolues') listQuery.whereNull('solution_reply_id')
+ if (filter === 'resolues') listQuery.whereNotNull('solution_reply_id')
+
+ const [threads, statsRows] = await Promise.all([
+ listQuery
+ .orderByRaw('pinned_at desc nulls last')
+ .orderBy('last_activity_at', 'desc')
+ .orderBy('id', 'desc')
+ .paginate(page, PER_PAGE),
+ selection(Thread.query())
+ .select(
+ db.raw('count(*)::int as total'),
+ db.raw('count(*) filter (where solution_reply_id is not null)::int as solved'),
+ db.raw('count(*) filter (where replies_count = 0)::int as unanswered')
+ )
+ .pojo<{ total: number; solved: number; unanswered: number }>(),
+ ])
+
+ const total = Number(statsRows[0]?.total ?? 0)
+ const solved = Number(statsRows[0]?.solved ?? 0)
+ const unanswered = Number(statsRows[0]?.unanswered ?? 0)
+
+ return inertia.render('forum/index', {
+ threads: ThreadTransformer.paginate(threads.all(), threads.getMeta()).useVariant('forList'),
+ channels: ChannelTransformer.transform(channels),
+ filters: { channel: channel?.slug ?? null, filter, q },
+ stats: {
+ total,
+ solved,
+ unanswered,
+ unsolved: total - solved,
+ solvedRate: total ? Math.round((solved / total) * 100) : 0,
+ allThreads: channels.reduce((sum, c) => sum + Number(c.$extras.threads_count ?? 0), 0),
+ },
+ })
+ }
+
+ /**
+ * GET /forum/nouveau
+ */
+ async create({ request, inertia }: HttpContext) {
+ const channels = await Channel.query().orderBy('position', 'asc')
+ const preselected = channels.find((c) => c.slug === request.qs().channel)
+ return inertia.render('forum/create', {
+ channels: ChannelTransformer.transform(channels),
+ defaultChannelId: preselected?.id ?? null,
+ })
+ }
+
+ /**
+ * POST /forum
+ */
+ async store({ request, auth, response, session }: HttpContext) {
+ const data = await request.validateUsing(threadValidator)
+ const thread = new Thread()
+ thread.userId = auth.user!.id
+ thread.channelId = data.channelId
+ thread.title = data.title
+ thread.body = data.body
+ thread.bodyHtml = await renderMarkdown(data.body)
+ thread.slug = await uniqueSlug('threads', data.title)
+ thread.lastActivityAt = DateTime.now()
+ await thread.save()
+
+ session.flash('success', 'Votre question est publiée. La communauté va pouvoir vous répondre.')
+ return response.redirect().toPath(`/forum/${thread.slug}`)
+ }
+
+ /**
+ * GET /forum/:slug
+ */
+ async show({ params, request, auth, inertia, session }: HttpContext) {
+ const viewer = auth.user ?? null
+ const thread = await Thread.query()
+ .where('slug', params.slug)
+ .preload('author')
+ .preload('channel')
+ .firstOrFail()
+
+ if (viewer) await markSubjectRead(viewer.id, { threadId: thread.id })
+
+ if (viewer?.id !== thread.userId && isFirstView(session, `t${thread.id}`)) {
+ await db.from('threads').where('id', thread.id).increment('views_count', 1)
+ thread.viewsCount += 1
+ }
+
+ // Replies: everything on one page, unless the thread is very long.
+ const repliesQuery = Reply.query().where('thread_id', thread.id)
+ withReplyMeta(viewer)(repliesQuery)
+ repliesQuery.orderBy('id', 'asc')
+
+ const paginated = thread.repliesCount > THREAD_REPLIES_PER_PAGE
+ let replies: Reply[]
+ let repliesMeta: {
+ total: number
+ perPage: number
+ currentPage: number
+ lastPage: number
+ } | null = null
+ if (paginated) {
+ const paginator = await repliesQuery.paginate(
+ toPage(request.qs().page),
+ THREAD_REPLIES_PER_PAGE
+ )
+ replies = paginator.all()
+ const meta = paginator.getMeta()
+ repliesMeta = {
+ total: Number(meta.total),
+ perPage: Number(meta.perPage),
+ currentPage: Number(meta.currentPage),
+ lastPage: Number(meta.lastPage),
+ }
+ } else {
+ replies = await repliesQuery
+ }
+
+ // The accepted answer may live on another page of replies.
+ let solution: Reply | null = null
+ let solutionHref: string | null = null
+ if (thread.solutionReplyId) {
+ solution =
+ replies.find((reply) => reply.id === thread.solutionReplyId) ??
+ (await Reply.query().where('id', thread.solutionReplyId).preload('author').first())
+ if (solution) {
+ let solutionPage = 1
+ if (paginated) {
+ const [{ n }] = await db
+ .from('replies')
+ .where('thread_id', thread.id)
+ .where('id', '<', solution.id)
+ .count('* as n')
+ solutionPage = Math.floor(Number(n) / THREAD_REPLIES_PER_PAGE) + 1
+ }
+ solutionHref = `${solutionPage > 1 ? `?page=${solutionPage}` : ''}#reponse-${solution.id}`
+ }
+ }
+
+ const [participantRows, similar] = await Promise.all([
+ db
+ .from('replies')
+ .select('user_id')
+ .min('created_at as first_at')
+ .where('thread_id', thread.id)
+ .groupBy('user_id')
+ .orderBy('first_at', 'asc'),
+ Thread.query()
+ .where('channel_id', thread.channelId)
+ .whereNot('id', thread.id)
+ .orderByRaw('solution_reply_id is null')
+ .orderBy('last_activity_at', 'desc')
+ .limit(5),
+ ])
+
+ const participantIds: number[] = participantRows.map((row) => Number(row.user_id))
+ const participantUsers = participantIds.length
+ ? await User.query().whereIn('id', participantIds.slice(0, 16))
+ : []
+ participantUsers.sort((a, b) => participantIds.indexOf(a.id) - participantIds.indexOf(b.id))
+
+ return inertia.render('forum/show', {
+ thread: ThreadTransformer.transform(thread).useVariant('forDetail'),
+ replies: ReplyTransformer.transform(replies),
+ repliesMeta,
+ solution: solution ? ReplyTransformer.transform(solution) : null,
+ solutionExcerpt: solution ? plainExcerpt(solution.body, 260) : null,
+ solutionHref,
+ participants: UserTransformer.transform(participantUsers),
+ participantsCount: participantIds.length,
+ similar: ThreadTransformer.transform(similar),
+ can: {
+ manage: Boolean(viewer && (await viewer.canManageContent(thread.userId))),
+ moderate: Boolean(viewer?.isModerator),
+ },
+ })
+ }
+
+ /**
+ * GET /forum/:slug/modifier
+ */
+ async edit({ params, auth, inertia, response, session }: HttpContext) {
+ const thread = await Thread.query().where('slug', params.slug).preload('channel').firstOrFail()
+ if (!(await auth.user!.canManageContent(thread.userId))) {
+ session.flash('error', 'Vous ne pouvez pas modifier cette question.')
+ return response.redirect().toPath(`/forum/${thread.slug}`)
+ }
+ const channels = await Channel.query().orderBy('position', 'asc')
+ return inertia.render('forum/edit', {
+ thread: ThreadTransformer.transform(thread).useVariant('forEdit'),
+ channels: ChannelTransformer.transform(channels),
+ })
+ }
+
+ /**
+ * PUT /forum/:slug — the slug never changes (links stay valid).
+ */
+ async update({ params, request, auth, response, session }: HttpContext) {
+ const thread = await Thread.findByOrFail('slug', params.slug)
+ if (!(await auth.user!.canManageContent(thread.userId))) {
+ session.flash('error', 'Vous ne pouvez pas modifier cette question.')
+ return response.redirect().toPath(`/forum/${thread.slug}`)
+ }
+ const data = await request.validateUsing(threadValidator)
+ thread.title = data.title
+ thread.channelId = data.channelId
+ thread.body = data.body
+ thread.bodyHtml = await renderMarkdown(data.body)
+ await thread.save()
+
+ session.flash('success', 'Question mise à jour.')
+ return response.redirect().toPath(`/forum/${thread.slug}`)
+ }
+
+ /**
+ * DELETE /forum/:slug — replies go with it (FK cascade).
+ */
+ async destroy({ params, auth, response, session }: HttpContext) {
+ const thread = await Thread.findByOrFail('slug', params.slug)
+ if (!(await auth.user!.canManageContent(thread.userId))) {
+ session.flash('error', 'Vous ne pouvez pas supprimer cette question.')
+ return response.redirect().toPath(`/forum/${thread.slug}`)
+ }
+ await thread.delete()
+ session.flash('success', 'La question a été supprimée.')
+ return response.redirect().toPath('/forum')
+ }
+}
diff --git a/app/exceptions/handler.ts b/app/exceptions/handler.ts
index 0ab9d3b..75d7d9e 100644
--- a/app/exceptions/handler.ts
+++ b/app/exceptions/handler.ts
@@ -1,5 +1,5 @@
import app from '@adonisjs/core/services/app'
-import { HttpContext, ExceptionHandler } from '@adonisjs/core/http'
+import { type HttpContext, ExceptionHandler } from '@adonisjs/core/http'
import type { StatusPageRange, StatusPageRenderer } from '@adonisjs/core/types/http'
export default class HttpExceptionHandler extends ExceptionHandler {
@@ -21,8 +21,8 @@ export default class HttpExceptionHandler extends ExceptionHandler {
* to return the HTML contents to send as a response.
*/
protected statusPages: Record = {
- '404': (error, { inertia }) => inertia.render('errors/not_found', { error }),
- '500..599': (error, { inertia }) => inertia.render('errors/server_error', { error }),
+ '404': (_, { inertia }) => inertia.render('errors/not_found', {}),
+ '500..599': (_, { inertia }) => inertia.render('errors/server_error', {}),
}
/**
diff --git a/app/exceptions/markdown_too_complex_exception.ts b/app/exceptions/markdown_too_complex_exception.ts
new file mode 100644
index 0000000..0e3e65d
--- /dev/null
+++ b/app/exceptions/markdown_too_complex_exception.ts
@@ -0,0 +1,22 @@
+import { Exception } from '@adonisjs/core/exceptions'
+import type { HttpContext } from '@adonisjs/core/http'
+
+/**
+ * Raised when markdown takes too long to render (pathological input).
+ * Sends the member back to the form with an explanation instead of a 500.
+ */
+export default class MarkdownTooComplexException extends Exception {
+ static status = 422
+ static code = 'E_MARKDOWN_TOO_COMPLEX'
+ static message =
+ 'Ce contenu est trop complexe à mettre en forme. Simplifiez la mise en forme (gras, italique, liens imbriqués) puis réessayez.'
+
+ async handle(error: this, ctx: HttpContext) {
+ if (ctx.request.accepts(['html', 'json']) === 'json' && !ctx.request.header('x-inertia')) {
+ return ctx.response.status(error.status).send({ message: error.message })
+ }
+ ctx.session.flashExcept(['password', 'passwordConfirmation'])
+ ctx.session.flash('error', error.message)
+ return ctx.response.redirect().back()
+ }
+}
diff --git a/app/middleware/auth_middleware.ts b/app/middleware/auth_middleware.ts
index f5a2ba3..75eb64e 100644
--- a/app/middleware/auth_middleware.ts
+++ b/app/middleware/auth_middleware.ts
@@ -4,12 +4,10 @@ import type { Authenticators } from '@adonisjs/auth/types'
/**
* Auth middleware is used authenticate HTTP requests and deny
- * access to unauthenticated users.
+ * access to unauthenticated users. GET requests are sent back to the
+ * page they asked for after login.
*/
export default class AuthMiddleware {
- /**
- * The URL to redirect to, when authentication fails
- */
redirectTo = '/login'
async handle(
@@ -19,7 +17,19 @@ export default class AuthMiddleware {
guards?: (keyof Authenticators)[]
} = {}
) {
- await ctx.auth.authenticateUsing(options.guards, { loginRoute: this.redirectTo })
+ const loginRoute =
+ ctx.request.method() === 'GET'
+ ? `${this.redirectTo}?redirect=${encodeURIComponent(ctx.request.url(true))}`
+ : this.redirectTo
+
+ await ctx.auth.authenticateUsing(options.guards, { loginRoute })
+
+ if (ctx.auth.user?.bannedAt) {
+ await ctx.auth.use('web').logout()
+ ctx.session.flash('error', 'Ce compte a été suspendu.')
+ return ctx.response.redirect(this.redirectTo)
+ }
+
return next()
}
}
diff --git a/app/middleware/container_bindings_middleware.ts b/app/middleware/container_bindings_middleware.ts
index bbe5a07..8f5322b 100644
--- a/app/middleware/container_bindings_middleware.ts
+++ b/app/middleware/container_bindings_middleware.ts
@@ -1,6 +1,6 @@
import { Logger } from '@adonisjs/core/logger'
import { HttpContext } from '@adonisjs/core/http'
-import { NextFn } from '@adonisjs/core/types/http'
+import { type NextFn } from '@adonisjs/core/types/http'
/**
* The container bindings middleware binds classes to their request
@@ -13,6 +13,7 @@ export default class ContainerBindingsMiddleware {
handle(ctx: HttpContext, next: NextFn) {
ctx.containerResolver.bindValue(HttpContext, ctx)
ctx.containerResolver.bindValue(Logger, ctx.logger)
+
return next()
}
}
diff --git a/app/middleware/guest_middleware.ts b/app/middleware/guest_middleware.ts
index 15b2ddc..d032760 100644
--- a/app/middleware/guest_middleware.ts
+++ b/app/middleware/guest_middleware.ts
@@ -22,9 +22,11 @@ export default class GuestMiddleware {
) {
for (let guard of options.guards || [ctx.auth.defaultGuard]) {
if (await ctx.auth.use(guard).check()) {
+ ctx.session.reflash()
return ctx.response.redirect(this.redirectTo, true)
}
}
+
return next()
}
}
diff --git a/app/middleware/inertia_middleware.ts b/app/middleware/inertia_middleware.ts
new file mode 100644
index 0000000..c8bdb26
--- /dev/null
+++ b/app/middleware/inertia_middleware.ts
@@ -0,0 +1,88 @@
+import type { HttpContext } from '@adonisjs/core/http'
+import type { NextFn } from '@adonisjs/core/types/http'
+import UserTransformer from '#transformers/user_transformer'
+import BaseInertiaMiddleware from '@adonisjs/inertia/inertia_middleware'
+import { githubEnabled } from '#config/ally'
+import env from '#start/env'
+import db from '@adonisjs/lucid/services/db'
+import { reportQueueCounts } from '#controllers/admin/reports_controller'
+
+export type ThemePreference = 'light' | 'dark' | 'system'
+
+export default class InertiaMiddleware extends BaseInertiaMiddleware {
+ async share(ctx: HttpContext) {
+ /**
+ * The share method is called everytime an Inertia page is rendered. In
+ * certain cases, a page may get rendered before the session middleware
+ * or the auth middleware are executed. For example: During a 404 request.
+ *
+ * In that case, we must always assume that HttpContext is not fully hydrated
+ * with all the properties
+ */
+ const { auth, request } = ctx as Partial
+
+ const cookie = request?.plainCookie('app_theme', { encoded: false })
+ const theme: ThemePreference = cookie === 'light' || cookie === 'dark' ? cookie : 'system'
+
+ let unreadNotifications = 0
+ if (auth?.user) {
+ const [row] = await db
+ .from('notifications')
+ .where('user_id', auth.user.id)
+ .whereNull('read_at')
+ .count('* as total')
+ unreadNotifications = Number(row?.total ?? 0)
+ }
+
+ // Moderation queue badge (staff only: no query for regular members).
+ let reportQueueCount = 0
+ if (auth?.user?.isModerator) {
+ const counts = await reportQueueCounts()
+ reportQueueCount = counts.open
+ }
+
+ /**
+ * Data shared with all Inertia pages. Make sure you are using
+ * transformers for rich data-types like Models.
+ */
+ return {
+ errors: ctx.inertia.always(this.getValidationErrors(ctx)),
+ user: ctx.inertia.always(
+ auth?.user ? UserTransformer.transform(auth.user).useVariant('forSession') : undefined
+ ),
+ preferences: ctx.inertia.always({ theme }),
+ features: ctx.inertia.always({ github: githubEnabled() }),
+ site: ctx.inertia.always({ url: env.get('APP_URL') }),
+ unreadNotifications: ctx.inertia.always(unreadNotifications),
+ reportQueueCount: ctx.inertia.always(reportQueueCount),
+ }
+ }
+
+ flash(ctx: HttpContext) {
+ /**
+ * Flash messages travel in the dedicated `flash` field of the page
+ * object instead of props, and the client strips them from history
+ * state so they never reappear when navigating back.
+ */
+ const { session } = ctx as Partial