create-nextjs-cms 0.7.0 → 0.7.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (184) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +71 -71
  3. package/dist/helpers/utils.js +16 -16
  4. package/dist/lib/section-creators.js +166 -166
  5. package/package.json +3 -3
  6. package/templates/default/.eslintrc.json +5 -5
  7. package/templates/default/.prettierignore +7 -7
  8. package/templates/default/.prettierrc.json +27 -27
  9. package/templates/default/CHANGELOG.md +140 -140
  10. package/templates/default/_gitignore +57 -57
  11. package/templates/default/app/(auth)/auth/login/LoginPage.tsx +192 -192
  12. package/templates/default/app/(auth)/auth/login/page.tsx +11 -11
  13. package/templates/default/app/(auth)/auth-locale-provider.tsx +34 -34
  14. package/templates/default/app/(auth)/layout.tsx +81 -81
  15. package/templates/default/app/(rootLayout)/(plugins)/[...slug]/page.tsx +40 -40
  16. package/templates/default/app/(rootLayout)/(plugins)/[...slug]/plugin-server-registry.ts +22 -22
  17. package/templates/default/app/(rootLayout)/admins/page.tsx +10 -10
  18. package/templates/default/app/(rootLayout)/browse/[section]/[page]/page.tsx +22 -22
  19. package/templates/default/app/(rootLayout)/categorized/[section]/page.tsx +15 -15
  20. package/templates/default/app/(rootLayout)/dashboard/page.tsx +63 -63
  21. package/templates/default/app/(rootLayout)/dashboard-new/page.tsx +7 -7
  22. package/templates/default/app/(rootLayout)/edit/[section]/[itemId]/page.tsx +17 -17
  23. package/templates/default/app/(rootLayout)/layout.tsx +81 -81
  24. package/templates/default/app/(rootLayout)/loading.tsx +10 -10
  25. package/templates/default/app/(rootLayout)/log/page.tsx +7 -7
  26. package/templates/default/app/(rootLayout)/new/[section]/page.tsx +15 -15
  27. package/templates/default/app/(rootLayout)/section/[section]/page.tsx +16 -16
  28. package/templates/default/app/(rootLayout)/settings/page.tsx +13 -13
  29. package/templates/default/app/_trpc/client.ts +3 -3
  30. package/templates/default/app/api/auth/csrf/route.ts +25 -25
  31. package/templates/default/app/api/auth/refresh/route.ts +10 -10
  32. package/templates/default/app/api/auth/session/route.ts +20 -20
  33. package/templates/default/app/api/editor/photo/route.ts +49 -49
  34. package/templates/default/app/api/photo/route.ts +27 -27
  35. package/templates/default/app/api/submit/section/item/[slug]/route.ts +66 -66
  36. package/templates/default/app/api/submit/section/item/route.ts +56 -56
  37. package/templates/default/app/api/submit/section/simple/route.ts +57 -57
  38. package/templates/default/app/api/trpc/[trpc]/route.ts +33 -33
  39. package/templates/default/app/api/video/route.ts +174 -174
  40. package/templates/default/app/globals.css +219 -219
  41. package/templates/default/app/providers.tsx +152 -152
  42. package/templates/default/cms.config.ts +49 -52
  43. package/templates/default/components/AdminCard.tsx +166 -166
  44. package/templates/default/components/AdminEditPage.tsx +124 -124
  45. package/templates/default/components/AdminPrivilegeCard.tsx +185 -185
  46. package/templates/default/components/AdminsPage.tsx +43 -43
  47. package/templates/default/components/AnalyticsPage.tsx +128 -128
  48. package/templates/default/components/BarChartBox.tsx +42 -42
  49. package/templates/default/components/BrowsePage.tsx +106 -106
  50. package/templates/default/components/CategorizedSectionPage.tsx +31 -31
  51. package/templates/default/components/CategoryDeleteConfirmPage.tsx +130 -130
  52. package/templates/default/components/CategorySectionSelectInput.tsx +140 -140
  53. package/templates/default/components/ConditionalFields.tsx +49 -49
  54. package/templates/default/components/ContainerBox.tsx +24 -24
  55. package/templates/default/components/DashboardNewPage.tsx +253 -253
  56. package/templates/default/components/DashboardPage.tsx +188 -188
  57. package/templates/default/components/DashboardPageAlt.tsx +45 -45
  58. package/templates/default/components/DefaultNavItems.tsx +3 -3
  59. package/templates/default/components/Dropzone.tsx +154 -154
  60. package/templates/default/components/EmailCard.tsx +138 -138
  61. package/templates/default/components/EmailPasswordForm.tsx +85 -85
  62. package/templates/default/components/EmailQuotaForm.tsx +73 -73
  63. package/templates/default/components/EmailsPage.tsx +49 -49
  64. package/templates/default/components/ErrorComponent.tsx +16 -16
  65. package/templates/default/components/GalleryPhoto.tsx +93 -93
  66. package/templates/default/components/InfoCard.tsx +93 -93
  67. package/templates/default/components/ItemEditPage.tsx +214 -214
  68. package/templates/default/components/Layout.tsx +84 -84
  69. package/templates/default/components/LoadingSpinners.tsx +67 -67
  70. package/templates/default/components/LogPage.tsx +107 -107
  71. package/templates/default/components/Modal.tsx +166 -166
  72. package/templates/default/components/Navbar.tsx +258 -258
  73. package/templates/default/components/NewAdminForm.tsx +173 -173
  74. package/templates/default/components/NewEmailForm.tsx +132 -132
  75. package/templates/default/components/NewPage.tsx +205 -205
  76. package/templates/default/components/NewVariantComponent.tsx +229 -229
  77. package/templates/default/components/PhotoGallery.tsx +35 -35
  78. package/templates/default/components/PieChartBox.tsx +101 -101
  79. package/templates/default/components/ProgressBar.tsx +48 -48
  80. package/templates/default/components/ProtectedDocument.tsx +78 -78
  81. package/templates/default/components/ProtectedImage.tsx +143 -143
  82. package/templates/default/components/ProtectedVideo.tsx +76 -76
  83. package/templates/default/components/SectionItemCard.tsx +144 -144
  84. package/templates/default/components/SectionItemStatusBadge.tsx +17 -17
  85. package/templates/default/components/SectionPage.tsx +125 -125
  86. package/templates/default/components/SelectBox.tsx +98 -98
  87. package/templates/default/components/SelectInputButtons.tsx +125 -125
  88. package/templates/default/components/SettingsPage.tsx +232 -232
  89. package/templates/default/components/Sidebar.tsx +201 -201
  90. package/templates/default/components/SidebarDropdownItem.tsx +80 -80
  91. package/templates/default/components/SidebarItem.tsx +20 -20
  92. package/templates/default/components/ThemeProvider.tsx +8 -8
  93. package/templates/default/components/TooltipComponent.tsx +27 -27
  94. package/templates/default/components/VariantCard.tsx +124 -124
  95. package/templates/default/components/VariantEditPage.tsx +230 -230
  96. package/templates/default/components/analytics/BounceRate.tsx +70 -70
  97. package/templates/default/components/analytics/LivePageViews.tsx +55 -55
  98. package/templates/default/components/analytics/LiveUsersCount.tsx +33 -33
  99. package/templates/default/components/analytics/MonthlyPageViews.tsx +42 -42
  100. package/templates/default/components/analytics/TopCountries.tsx +52 -52
  101. package/templates/default/components/analytics/TopDevices.tsx +46 -46
  102. package/templates/default/components/analytics/TopMediums.tsx +58 -58
  103. package/templates/default/components/analytics/TopSources.tsx +45 -45
  104. package/templates/default/components/analytics/TotalPageViews.tsx +41 -41
  105. package/templates/default/components/analytics/TotalSessions.tsx +41 -41
  106. package/templates/default/components/analytics/TotalUniqueUsers.tsx +41 -41
  107. package/templates/default/components/custom/RightHomeRoomVariantCard.tsx +138 -138
  108. package/templates/default/components/dndKit/Draggable.tsx +21 -21
  109. package/templates/default/components/dndKit/Droppable.tsx +20 -20
  110. package/templates/default/components/dndKit/SortableItem.tsx +18 -18
  111. package/templates/default/components/form/DateRangeFormInput.tsx +57 -57
  112. package/templates/default/components/form/Form.tsx +317 -317
  113. package/templates/default/components/form/FormInputElement.tsx +70 -70
  114. package/templates/default/components/form/FormInputs.tsx +112 -112
  115. package/templates/default/components/form/helpers/_section-hot-reload.js +1 -1
  116. package/templates/default/components/form/helpers/util.ts +17 -17
  117. package/templates/default/components/form/inputs/CheckboxFormInput.tsx +33 -33
  118. package/templates/default/components/form/inputs/ColorFormInput.tsx +44 -44
  119. package/templates/default/components/form/inputs/DateFormInput.tsx +156 -156
  120. package/templates/default/components/form/inputs/DocumentFormInput.tsx +222 -222
  121. package/templates/default/components/form/inputs/MapFormInput.tsx +140 -140
  122. package/templates/default/components/form/inputs/MultipleSelectFormInput.tsx +83 -83
  123. package/templates/default/components/form/inputs/NumberFormInput.tsx +42 -42
  124. package/templates/default/components/form/inputs/PasswordFormInput.tsx +47 -47
  125. package/templates/default/components/form/inputs/PhotoFormInput.tsx +219 -219
  126. package/templates/default/components/form/inputs/RichTextFormInput.tsx +135 -135
  127. package/templates/default/components/form/inputs/SelectFormInput.tsx +175 -175
  128. package/templates/default/components/form/inputs/SlugFormInput.tsx +129 -129
  129. package/templates/default/components/form/inputs/TagsFormInput.tsx +154 -154
  130. package/templates/default/components/form/inputs/TextFormInput.tsx +48 -48
  131. package/templates/default/components/form/inputs/TextareaFormInput.tsx +47 -47
  132. package/templates/default/components/form/inputs/VideoFormInput.tsx +118 -118
  133. package/templates/default/components/locale-dropdown.tsx +74 -74
  134. package/templates/default/components/locale-picker.tsx +85 -85
  135. package/templates/default/components/login-locale-dropdown.tsx +46 -46
  136. package/templates/default/components/multi-select.tsx +1144 -1144
  137. package/templates/default/components/pagination/Pagination.tsx +36 -36
  138. package/templates/default/components/pagination/PaginationButtons.tsx +147 -147
  139. package/templates/default/components/theme-toggle.tsx +37 -37
  140. package/templates/default/components/ui/accordion.tsx +53 -53
  141. package/templates/default/components/ui/alert-dialog.tsx +157 -157
  142. package/templates/default/components/ui/alert.tsx +46 -46
  143. package/templates/default/components/ui/badge.tsx +38 -38
  144. package/templates/default/components/ui/button.tsx +62 -62
  145. package/templates/default/components/ui/calendar.tsx +166 -166
  146. package/templates/default/components/ui/card.tsx +43 -43
  147. package/templates/default/components/ui/checkbox.tsx +29 -29
  148. package/templates/default/components/ui/command.tsx +137 -137
  149. package/templates/default/components/ui/custom-alert-dialog.tsx +113 -113
  150. package/templates/default/components/ui/custom-dialog.tsx +123 -123
  151. package/templates/default/components/ui/dialog.tsx +123 -123
  152. package/templates/default/components/ui/dropdown-menu.tsx +182 -182
  153. package/templates/default/components/ui/input-group.tsx +54 -54
  154. package/templates/default/components/ui/input.tsx +22 -22
  155. package/templates/default/components/ui/label.tsx +19 -19
  156. package/templates/default/components/ui/popover.tsx +42 -42
  157. package/templates/default/components/ui/progress.tsx +31 -31
  158. package/templates/default/components/ui/scroll-area.tsx +42 -42
  159. package/templates/default/components/ui/select.tsx +165 -165
  160. package/templates/default/components/ui/separator.tsx +28 -28
  161. package/templates/default/components/ui/sheet.tsx +103 -103
  162. package/templates/default/components/ui/switch.tsx +29 -29
  163. package/templates/default/components/ui/table.tsx +83 -83
  164. package/templates/default/components/ui/tabs.tsx +55 -55
  165. package/templates/default/components/ui/toast.tsx +113 -113
  166. package/templates/default/components/ui/toaster.tsx +35 -35
  167. package/templates/default/components/ui/tooltip.tsx +30 -30
  168. package/templates/default/components/ui/use-toast.ts +188 -188
  169. package/templates/default/components.json +21 -21
  170. package/templates/default/context/ModalProvider.tsx +53 -53
  171. package/templates/default/drizzle.config.ts +4 -4
  172. package/templates/default/dynamic-schemas/schema.ts +10 -0
  173. package/templates/default/env/env.js +130 -130
  174. package/templates/default/envConfig.ts +4 -4
  175. package/templates/default/hooks/useModal.ts +8 -8
  176. package/templates/default/lib/apiHelpers.ts +92 -92
  177. package/templates/default/lib/postinstall.js +14 -14
  178. package/templates/default/lib/utils.ts +6 -6
  179. package/templates/default/next-env.d.ts +6 -6
  180. package/templates/default/next.config.ts +23 -23
  181. package/templates/default/package.json +2 -4
  182. package/templates/default/postcss.config.mjs +6 -6
  183. package/templates/default/proxy.ts +32 -32
  184. package/templates/default/tsconfig.json +48 -48
@@ -1,57 +1,57 @@
1
- import { NextRequest, NextResponse } from 'next/server'
2
- import { SimpleSectionSubmit } from 'nextjs-cms/core/submit'
3
- import auth from 'nextjs-cms/auth'
4
- import { getRequestMetadataFromHeaders } from 'nextjs-cms/logging'
5
-
6
- export async function PUT(request: NextRequest) {
7
- const session = await auth()
8
-
9
- if (!session || !session.user) {
10
- return NextResponse.json(
11
- {
12
- error: 'Access token not provided',
13
- },
14
- { status: 401 },
15
- )
16
- }
17
-
18
- const user = session.user
19
- const formData = await request.formData()
20
- const sectionName = formData.get('sectionName') as string | null
21
- const requestMetadata = getRequestMetadataFromHeaders(request.headers)
22
-
23
- if (!sectionName) {
24
- return NextResponse.json(
25
- {
26
- error: 'Section name not provided',
27
- },
28
- { status: 400 },
29
- )
30
- }
31
-
32
- const submit = new SimpleSectionSubmit({
33
- itemId: '1',
34
- sectionName,
35
- user,
36
- postData: formData,
37
- requestMetadata,
38
- })
39
-
40
- await submit.initialize()
41
- await submit.submit()
42
- if (submit.error) {
43
- return NextResponse.json(
44
- {
45
- error: submit.errorMessage,
46
- },
47
- { status: 400 },
48
- )
49
- }
50
-
51
- return NextResponse.json(
52
- {
53
- message: 'Section item submitted successfully',
54
- },
55
- { status: 200 },
56
- )
57
- }
1
+ import { NextRequest, NextResponse } from 'next/server'
2
+ import { SimpleSectionSubmit } from 'nextjs-cms/core/submit'
3
+ import auth from 'nextjs-cms/auth'
4
+ import { getRequestMetadataFromHeaders } from 'nextjs-cms/logging'
5
+
6
+ export async function PUT(request: NextRequest) {
7
+ const session = await auth()
8
+
9
+ if (!session || !session.user) {
10
+ return NextResponse.json(
11
+ {
12
+ error: 'Access token not provided',
13
+ },
14
+ { status: 401 },
15
+ )
16
+ }
17
+
18
+ const user = session.user
19
+ const formData = await request.formData()
20
+ const sectionName = formData.get('sectionName') as string | null
21
+ const requestMetadata = getRequestMetadataFromHeaders(request.headers)
22
+
23
+ if (!sectionName) {
24
+ return NextResponse.json(
25
+ {
26
+ error: 'Section name not provided',
27
+ },
28
+ { status: 400 },
29
+ )
30
+ }
31
+
32
+ const submit = new SimpleSectionSubmit({
33
+ itemId: '1',
34
+ sectionName,
35
+ user,
36
+ postData: formData,
37
+ requestMetadata,
38
+ })
39
+
40
+ await submit.initialize()
41
+ await submit.submit()
42
+ if (submit.error) {
43
+ return NextResponse.json(
44
+ {
45
+ error: submit.errorMessage,
46
+ },
47
+ { status: 400 },
48
+ )
49
+ }
50
+
51
+ return NextResponse.json(
52
+ {
53
+ message: 'Section item submitted successfully',
54
+ },
55
+ { status: 200 },
56
+ )
57
+ }
@@ -1,33 +1,33 @@
1
- import { fetchRequestHandler } from '@trpc/server/adapters/fetch'
2
- import { createTRPCContext, getAppRouter } from 'nextjs-cms/api'
3
- import { NextRequest } from 'next/server'
4
-
5
- /**
6
- * This wraps the `createContext` helper and provides the required context for the tRPC API when
7
- * handling a HTTP request (e.g. when you make requests from Client Components).
8
- */
9
-
10
- const context = async (req: NextRequest) => {
11
- return createTRPCContext({
12
- headers: req.headers,
13
- })
14
- }
15
-
16
- const handler = async (req: NextRequest) =>
17
- fetchRequestHandler({
18
- endpoint: '/api/trpc',
19
- req,
20
- router: await getAppRouter(),
21
- createContext: () => context(req),
22
- /*onError(opts) {
23
- return opts.error
24
- },*/
25
- onError:
26
- process.env.NODE_ENV === 'development'
27
- ? ({ path, error }) => {
28
- console.error(`❌ tRPC failed on ${path ?? '<no-path>'}: ${error.message}`)
29
- }
30
- : undefined,
31
- })
32
-
33
- export { handler as GET, handler as POST }
1
+ import { fetchRequestHandler } from '@trpc/server/adapters/fetch'
2
+ import { createTRPCContext, getAppRouter } from 'nextjs-cms/api'
3
+ import { NextRequest } from 'next/server'
4
+
5
+ /**
6
+ * This wraps the `createContext` helper and provides the required context for the tRPC API when
7
+ * handling a HTTP request (e.g. when you make requests from Client Components).
8
+ */
9
+
10
+ const context = async (req: NextRequest) => {
11
+ return createTRPCContext({
12
+ headers: req.headers,
13
+ })
14
+ }
15
+
16
+ const handler = async (req: NextRequest) =>
17
+ fetchRequestHandler({
18
+ endpoint: '/api/trpc',
19
+ req,
20
+ router: await getAppRouter(),
21
+ createContext: () => context(req),
22
+ /*onError(opts) {
23
+ return opts.error
24
+ },*/
25
+ onError:
26
+ process.env.NODE_ENV === 'development'
27
+ ? ({ path, error }) => {
28
+ console.error(`❌ tRPC failed on ${path ?? '<no-path>'}: ${error.message}`)
29
+ }
30
+ : undefined,
31
+ })
32
+
33
+ export { handler as GET, handler as POST }
@@ -1,174 +1,174 @@
1
- import { NextRequest, NextResponse } from 'next/server'
2
- import path from 'path'
3
- import fs from 'fs'
4
- import { readChunk } from 'read-chunk'
5
- import { fileTypeFromBuffer } from 'file-type'
6
- import { SectionFactory } from 'nextjs-cms/core/factories'
7
- import type { VideoField } from 'nextjs-cms/core/fields'
8
- import auth from 'nextjs-cms/auth'
9
- import { sanitizeFileName, sanitizeFolderOrFileName } from 'nextjs-cms/utils'
10
- import { streamFile } from 'nextjs-cms/api/helpers'
11
- import { getCMSConfig } from 'nextjs-cms/core/config'
12
-
13
- /**
14
- * This route handler is used to stream a video file from the server
15
- * It's used to protect the video files from being accessed directly
16
- * It's being used in the `<ProtectedVideo />` component
17
- * @param request
18
- * @constructor
19
- */
20
-
21
- export async function GET(request: NextRequest) {
22
- const session = await auth()
23
- const searchParams = request.nextUrl.searchParams
24
-
25
- const name = searchParams.get('name')
26
- const sectionName = searchParams.get('sectionName')
27
- const fieldName = searchParams.get('fieldName')
28
-
29
- if (!name || !sectionName || !fieldName) {
30
- return NextResponse.json(
31
- {
32
- error: 'Invalid request',
33
- },
34
- { status: 400 },
35
- )
36
- }
37
-
38
- // Check if the session is valid
39
- if (!session || !session.user) {
40
- return NextResponse.json(
41
- {
42
- error: 'Invalid token',
43
- },
44
- { status: 401 },
45
- )
46
- }
47
-
48
- const uploadsFolder: string = (await getCMSConfig()).media.upload.path
49
-
50
- // Sanitize the inputs
51
- const sanitizedFolder = sanitizeFolderOrFileName(sectionName)
52
- const sanitizedName = sanitizeFileName(name)
53
- /**
54
- * Check the section and the field name, and get the allowed extensions,
55
- * while also checking if the user has access to the section
56
- */
57
- const section = await SectionFactory.getSectionForAdmin({
58
- name: sanitizedFolder,
59
- admin: { id: session.user.id },
60
- })
61
-
62
- /**
63
- * If the check fails, throw an error
64
- */
65
- if (!section || !section.name) {
66
- return NextResponse.json(
67
- {
68
- error: 'File not found, or you do not have access to it.',
69
- },
70
- { status: 400 },
71
- )
72
- }
73
-
74
- const fieldInfo = section.fields.find((field) => field.name === fieldName)?.build() as VideoField
75
-
76
- /**
77
- * If field is not found, throw an error
78
- */
79
- if (!fieldInfo || !fieldInfo.name || !fieldInfo.extensions || fieldInfo.extensions.length === 0) {
80
- return NextResponse.json(
81
- {
82
- error: 'Invalid request',
83
- },
84
- { status: 400 },
85
- )
86
- }
87
-
88
- /**
89
- * Split the allowed extensions into an array
90
- */
91
- const videoAllowedExtensions = fieldInfo.extensions
92
- const dir = '.videos'
93
- const pathToFile = path.join(uploadsFolder, dir, sanitizedFolder, sanitizedName)
94
- /**
95
- * First, check if the file exists
96
- */
97
- if (!fs.existsSync(pathToFile)) {
98
- return NextResponse.json(
99
- {
100
- error: 'File not found',
101
- },
102
- { status: 404 },
103
- )
104
- }
105
-
106
- /**
107
- * Read the first 4100 bytes of the file
108
- */
109
- const chunkBuffer = await readChunk(pathToFile, { length: 4100 })
110
- /**
111
- * Get the file type from the buffer
112
- */
113
- const fileType = await fileTypeFromBuffer(chunkBuffer)
114
-
115
- /**
116
- * If the file type is invalid, return an error
117
- */
118
- if (!fileType) {
119
- return NextResponse.json(
120
- {
121
- error: 'Invalid file type',
122
- },
123
- { status: 400 },
124
- )
125
- }
126
-
127
- /**
128
- * Check if the file type is allowed
129
- */
130
- if (!videoAllowedExtensions.includes(fileType.ext)) {
131
- return NextResponse.json(
132
- {
133
- error: 'Invalid file type',
134
- },
135
- { status: 400 },
136
- )
137
- }
138
-
139
- const fileStats = fs.statSync(pathToFile)
140
- const range = request.headers.get('range')
141
- const videoSize = fileStats.size
142
- const videoMimeType = fileType.mime
143
-
144
- let res = null
145
- if (range) {
146
- const parts = range.replace(/bytes=/, '').split('-')
147
- const start = parseInt(parts[0] ?? '0', 10)
148
- const end = parts[1] ? parseInt(parts[1], 10) : videoSize - 1
149
- const chunkSize = end - start + 1
150
-
151
- const data: ReadableStream<Uint8Array> = await streamFile(pathToFile, { start, end })
152
-
153
- res = new NextResponse(data, {
154
- headers: {
155
- 'Content-Range': `bytes ${start}-${end}/${videoSize}`,
156
- 'Accept-Ranges': 'bytes',
157
- 'Content-Length': chunkSize.toString(),
158
- 'Content-Type': videoMimeType,
159
- },
160
- status: 206,
161
- })
162
- } else {
163
- const data: ReadableStream<Uint8Array> = await streamFile(pathToFile)
164
- res = new NextResponse(data, {
165
- headers: {
166
- 'Content-Length': videoSize.toString(),
167
- 'Content-Type': videoMimeType,
168
- },
169
- status: 200,
170
- })
171
- }
172
-
173
- return res
174
- }
1
+ import { NextRequest, NextResponse } from 'next/server'
2
+ import path from 'path'
3
+ import fs from 'fs'
4
+ import { readChunk } from 'read-chunk'
5
+ import { fileTypeFromBuffer } from 'file-type'
6
+ import { SectionFactory } from 'nextjs-cms/core/factories'
7
+ import type { VideoField } from 'nextjs-cms/core/fields'
8
+ import auth from 'nextjs-cms/auth'
9
+ import { sanitizeFileName, sanitizeFolderOrFileName } from 'nextjs-cms/utils'
10
+ import { streamFile } from 'nextjs-cms/api/helpers'
11
+ import { getCMSConfig } from 'nextjs-cms/core/config'
12
+
13
+ /**
14
+ * This route handler is used to stream a video file from the server
15
+ * It's used to protect the video files from being accessed directly
16
+ * It's being used in the `<ProtectedVideo />` component
17
+ * @param request
18
+ * @constructor
19
+ */
20
+
21
+ export async function GET(request: NextRequest) {
22
+ const session = await auth()
23
+ const searchParams = request.nextUrl.searchParams
24
+
25
+ const name = searchParams.get('name')
26
+ const sectionName = searchParams.get('sectionName')
27
+ const fieldName = searchParams.get('fieldName')
28
+
29
+ if (!name || !sectionName || !fieldName) {
30
+ return NextResponse.json(
31
+ {
32
+ error: 'Invalid request',
33
+ },
34
+ { status: 400 },
35
+ )
36
+ }
37
+
38
+ // Check if the session is valid
39
+ if (!session || !session.user) {
40
+ return NextResponse.json(
41
+ {
42
+ error: 'Invalid token',
43
+ },
44
+ { status: 401 },
45
+ )
46
+ }
47
+
48
+ const uploadsFolder: string = (await getCMSConfig()).media.upload.path
49
+
50
+ // Sanitize the inputs
51
+ const sanitizedFolder = sanitizeFolderOrFileName(sectionName)
52
+ const sanitizedName = sanitizeFileName(name)
53
+ /**
54
+ * Check the section and the field name, and get the allowed extensions,
55
+ * while also checking if the user has access to the section
56
+ */
57
+ const section = await SectionFactory.getSectionForAdmin({
58
+ name: sanitizedFolder,
59
+ admin: { id: session.user.id },
60
+ })
61
+
62
+ /**
63
+ * If the check fails, throw an error
64
+ */
65
+ if (!section || !section.name) {
66
+ return NextResponse.json(
67
+ {
68
+ error: 'File not found, or you do not have access to it.',
69
+ },
70
+ { status: 400 },
71
+ )
72
+ }
73
+
74
+ const fieldInfo = section.fields.find((field) => field.name === fieldName)?.build() as VideoField
75
+
76
+ /**
77
+ * If field is not found, throw an error
78
+ */
79
+ if (!fieldInfo || !fieldInfo.name || !fieldInfo.extensions || fieldInfo.extensions.length === 0) {
80
+ return NextResponse.json(
81
+ {
82
+ error: 'Invalid request',
83
+ },
84
+ { status: 400 },
85
+ )
86
+ }
87
+
88
+ /**
89
+ * Split the allowed extensions into an array
90
+ */
91
+ const videoAllowedExtensions = fieldInfo.extensions
92
+ const dir = '.videos'
93
+ const pathToFile = path.join(uploadsFolder, dir, sanitizedFolder, sanitizedName)
94
+ /**
95
+ * First, check if the file exists
96
+ */
97
+ if (!fs.existsSync(pathToFile)) {
98
+ return NextResponse.json(
99
+ {
100
+ error: 'File not found',
101
+ },
102
+ { status: 404 },
103
+ )
104
+ }
105
+
106
+ /**
107
+ * Read the first 4100 bytes of the file
108
+ */
109
+ const chunkBuffer = await readChunk(pathToFile, { length: 4100 })
110
+ /**
111
+ * Get the file type from the buffer
112
+ */
113
+ const fileType = await fileTypeFromBuffer(chunkBuffer)
114
+
115
+ /**
116
+ * If the file type is invalid, return an error
117
+ */
118
+ if (!fileType) {
119
+ return NextResponse.json(
120
+ {
121
+ error: 'Invalid file type',
122
+ },
123
+ { status: 400 },
124
+ )
125
+ }
126
+
127
+ /**
128
+ * Check if the file type is allowed
129
+ */
130
+ if (!videoAllowedExtensions.includes(fileType.ext)) {
131
+ return NextResponse.json(
132
+ {
133
+ error: 'Invalid file type',
134
+ },
135
+ { status: 400 },
136
+ )
137
+ }
138
+
139
+ const fileStats = fs.statSync(pathToFile)
140
+ const range = request.headers.get('range')
141
+ const videoSize = fileStats.size
142
+ const videoMimeType = fileType.mime
143
+
144
+ let res = null
145
+ if (range) {
146
+ const parts = range.replace(/bytes=/, '').split('-')
147
+ const start = parseInt(parts[0] ?? '0', 10)
148
+ const end = parts[1] ? parseInt(parts[1], 10) : videoSize - 1
149
+ const chunkSize = end - start + 1
150
+
151
+ const data: ReadableStream<Uint8Array> = await streamFile(pathToFile, { start, end })
152
+
153
+ res = new NextResponse(data, {
154
+ headers: {
155
+ 'Content-Range': `bytes ${start}-${end}/${videoSize}`,
156
+ 'Accept-Ranges': 'bytes',
157
+ 'Content-Length': chunkSize.toString(),
158
+ 'Content-Type': videoMimeType,
159
+ },
160
+ status: 206,
161
+ })
162
+ } else {
163
+ const data: ReadableStream<Uint8Array> = await streamFile(pathToFile)
164
+ res = new NextResponse(data, {
165
+ headers: {
166
+ 'Content-Length': videoSize.toString(),
167
+ 'Content-Type': videoMimeType,
168
+ },
169
+ status: 200,
170
+ })
171
+ }
172
+
173
+ return res
174
+ }