|
| 1 | +import { isValidSignature, SIGNATURE_HEADER_NAME } from '@sanity/webhook' |
| 2 | +import axios from 'axios' |
| 3 | +import type { NextRequest } from 'next/server' |
| 4 | +import { domain, languages } from '@/languageConfig' |
| 5 | +import { distributeOld } from './old-distribution' |
| 6 | + |
| 7 | +const SANITY_API_TOKEN = process.env.SANITY_API_TOKEN || '' |
| 8 | +const SLACK_NEWSLETTER_WEBHOOK_URL = process.env.SLACK_NEWSLETTER_WEBHOOK_URL |
| 9 | +const MAKE_NEWSLETTER_API_BASE_URL = process.env.MAKE_NEWSLETTER_API_BASE_URL |
| 10 | +const MAKE_NEWSLETTER_ID_EN = process.env.MAKE_NEWSLETTER_ID_EN |
| 11 | +const MAKE_NEWSLETTER_ID_NO = process.env.MAKE_NEWSLETTER_ID_NO |
| 12 | +const MAKE_API_USER = process.env.MAKE_API_USERID || '' |
| 13 | +const MAKE_API_KEY = process.env.MAKE_API_KEY || '' |
| 14 | + |
| 15 | +// NEeded? |
| 16 | +//Next.js will by default parse the body, which can lead to invalid signatures |
| 17 | +// https://nextjs.org/docs/api-routes/api-middlewares#custom-config |
| 18 | +/* export const config = { |
| 19 | + api: { |
| 20 | + bodyParser: false, |
| 21 | + }, |
| 22 | +} */ |
| 23 | + |
| 24 | +async function sendSlackNotification(message: string): Promise<void> { |
| 25 | + if (!SLACK_NEWSLETTER_WEBHOOK_URL) return |
| 26 | + |
| 27 | + try { |
| 28 | + await fetch(SLACK_NEWSLETTER_WEBHOOK_URL, { |
| 29 | + method: 'POST', |
| 30 | + headers: { |
| 31 | + 'Content-Type': 'application/json', |
| 32 | + }, |
| 33 | + body: JSON.stringify({ text: message }), |
| 34 | + }) |
| 35 | + console.log('Slack notification sent sucessfully!') |
| 36 | + } catch (error) { |
| 37 | + console.error('Failed to send Slack notification:', error) |
| 38 | + } |
| 39 | +} |
| 40 | + |
| 41 | +function getDateWithMs(): string { |
| 42 | + const date = new Date() |
| 43 | + const milliseconds = date.getMilliseconds().toString().padStart(3, '0') |
| 44 | + const formatter = new Intl.DateTimeFormat('en-GB', { |
| 45 | + year: '2-digit', |
| 46 | + month: '2-digit', |
| 47 | + day: '2-digit', |
| 48 | + hour: '2-digit', |
| 49 | + minute: '2-digit', |
| 50 | + second: '2-digit', |
| 51 | + hour12: false, |
| 52 | + }) |
| 53 | + const dateTime = formatter.format(date) |
| 54 | + |
| 55 | + return `${dateTime}:${milliseconds}` |
| 56 | +} |
| 57 | + |
| 58 | +export type NewsDistributionParameters = { |
| 59 | + title: string |
| 60 | + link: string |
| 61 | + languageCode?: string |
| 62 | +} |
| 63 | + |
| 64 | +const newsletterApi = axios.create({ |
| 65 | + baseURL: MAKE_NEWSLETTER_API_BASE_URL, |
| 66 | + headers: { |
| 67 | + 'Content-Type': 'application/json', |
| 68 | + Authorization: `Basic ${Buffer.from(`${MAKE_API_USER}:${MAKE_API_KEY}`).toString('base64')}`, |
| 69 | + }, |
| 70 | +}) |
| 71 | + |
| 72 | +/** |
| 73 | + * Distribute a newsletter |
| 74 | + */ |
| 75 | +export const distribute = async ( |
| 76 | + newsDistributionParameters: NewsDistributionParameters, |
| 77 | +) => { |
| 78 | + try { |
| 79 | + const url = `${MAKE_NEWSLETTER_API_BASE_URL}/recurring_actions/${ |
| 80 | + newsDistributionParameters.languageCode === 'no' |
| 81 | + ? MAKE_NEWSLETTER_ID_NO |
| 82 | + : MAKE_NEWSLETTER_ID_EN |
| 83 | + }/trigger` |
| 84 | + |
| 85 | + const response = await newsletterApi.post(url) |
| 86 | + return response.status === 200 |
| 87 | + } catch (error: any) { |
| 88 | + console.error('❌ Error in distribute:', { |
| 89 | + message: error.message, |
| 90 | + responseData: error.response?.data, |
| 91 | + responseStatus: error.response?.status, |
| 92 | + requestHeaders: error.config?.headers, |
| 93 | + }) |
| 94 | + |
| 95 | + return false |
| 96 | + } |
| 97 | +} |
| 98 | + |
| 99 | +interface DistributionResult { |
| 100 | + success: boolean |
| 101 | + message: string |
| 102 | +} |
| 103 | + |
| 104 | +async function distributeWithRetry( |
| 105 | + newsDistributionParameters: NewsDistributionParameters, |
| 106 | + oldNewsDistributionParameters: any, |
| 107 | + attempt = 1, |
| 108 | +): Promise<DistributionResult> { |
| 109 | + let res: DistributionResult = { |
| 110 | + success: false, |
| 111 | + message: `Initial state: Distribution not started for *${newsDistributionParameters.title}* (${newsDistributionParameters.link})`, |
| 112 | + } |
| 113 | + |
| 114 | + const date = getDateWithMs() |
| 115 | + |
| 116 | + try { |
| 117 | + //For migration period just log. |
| 118 | + const isNewSuccessful = await distribute(newsDistributionParameters) |
| 119 | + console.log(`New distribution was successful: ${isNewSuccessful}`) |
| 120 | + |
| 121 | + const isSuccessful = await distributeOld(oldNewsDistributionParameters) |
| 122 | + |
| 123 | + if (!isSuccessful) throw new Error('Distribution was unsuccessful.') |
| 124 | + res = { |
| 125 | + success: true, |
| 126 | + message: 'Newsletter sent successfully!', |
| 127 | + } |
| 128 | + |
| 129 | + const message = `${date} :white_check_mark: *${newsDistributionParameters.title}*: Successfully distributed (${newsDistributionParameters.link})` |
| 130 | + await sendSlackNotification(message) |
| 131 | + } catch (error) { |
| 132 | + const errorMessage = |
| 133 | + error instanceof Error ? error.message : 'An unknown error occurred' |
| 134 | + const message = `${date} :x: *${newsDistributionParameters.title}*: Distribution of (${newsDistributionParameters.link}) failed after attempt #${attempt}: ${errorMessage}` |
| 135 | + await sendSlackNotification(message) |
| 136 | + |
| 137 | + if (attempt < 3) { |
| 138 | + console.log(`Retrying... Attempt ${attempt + 1}`) |
| 139 | + return distributeWithRetry(newsDistributionParameters, attempt + 1) |
| 140 | + } |
| 141 | + res = { |
| 142 | + success: false, |
| 143 | + message: `Distribution failed for: ${newsDistributionParameters.title} (${newsDistributionParameters.link})`, |
| 144 | + } |
| 145 | + } |
| 146 | + |
| 147 | + return res |
| 148 | +} |
| 149 | + |
| 150 | +export async function POST(req: NextRequest) { |
| 151 | + console.log('Sending newsletter... ') |
| 152 | + console.log('Datetime: ' + new Date()) |
| 153 | + const signature = req.headers.get(SIGNATURE_HEADER_NAME) |
| 154 | + const body = await req.text() |
| 155 | + |
| 156 | + if (!isValidSignature(body, signature || '', SANITY_API_TOKEN)) { |
| 157 | + console.log(req, 'Unauthorized request: Newsletter Distribution Endpoint') |
| 158 | + return new Response( |
| 159 | + JSON.stringify({ success: false, msg: 'Unauthorized!' }), |
| 160 | + { status: 401 }, |
| 161 | + ) |
| 162 | + } |
| 163 | + const data = JSON.parse(body) |
| 164 | + const locale = |
| 165 | + languages.find(lang => lang.name === data.languageCode)?.locale || 'en' |
| 166 | + |
| 167 | + //To be removed after migration period |
| 168 | + const oldNewsDistributionParameters: any = { |
| 169 | + timeStamp: data.timeStamp, |
| 170 | + title: data.title, |
| 171 | + ingress: data.ingress, |
| 172 | + link: `${domain}/${locale}${data.link}`, |
| 173 | + newsType: data.newsType, |
| 174 | + languageCode: locale, |
| 175 | + } |
| 176 | + // END |
| 177 | + |
| 178 | + const newsDistributionParameters: NewsDistributionParameters = { |
| 179 | + title: data.title, |
| 180 | + link: `${domain}/${locale}${data.link}`, |
| 181 | + languageCode: locale, |
| 182 | + } |
| 183 | + console.log('Newsletter link: ', newsDistributionParameters.link) |
| 184 | + |
| 185 | + await distributeWithRetry( |
| 186 | + newsDistributionParameters, |
| 187 | + oldNewsDistributionParameters, |
| 188 | + ) |
| 189 | + .then(result => { |
| 190 | + if (result.success) { |
| 191 | + return new Response(JSON.stringify({ message: result.message }), { |
| 192 | + status: 200, |
| 193 | + }) |
| 194 | + } |
| 195 | + return new Response(JSON.stringify({ message: result.message }), { |
| 196 | + status: 400, |
| 197 | + }) |
| 198 | + }) |
| 199 | + .catch(error => { |
| 200 | + console.log(error) |
| 201 | + return new Response( |
| 202 | + JSON.stringify({ message: 'Internal server error' }), |
| 203 | + { |
| 204 | + status: 500, |
| 205 | + }, |
| 206 | + ) |
| 207 | + }) |
| 208 | +} |
0 commit comments