|
| 1 | +const axios = require('axios'); |
| 2 | + |
| 3 | +// example url: https://bioimage.netlify.app/.netlify/functions/download/10.5281/zenodo.5764892/files/weights.onnx?debug=1 |
| 4 | +exports.handler = async function(event, context) { |
| 5 | + const queryParams = event.queryStringParameters; |
| 6 | + const uadata = queryParams.uadata || '{"brands":[{"brand":"unknown","version":"unknown"}]}'; |
| 7 | + |
| 8 | + // Extracting the initial DOI from the path, assuming path format and initial parsing logic |
| 9 | + const pathSegments = event.path.split('/').filter(segment => segment); |
| 10 | + if (pathSegments.length < 7) { |
| 11 | + return { statusCode: 400, body: JSON.stringify({ message: "Invalid path format." }) }; |
| 12 | + } |
| 13 | + const doi = `${pathSegments[3]}/${pathSegments[4]}`; // Combines "10.5281" and "zenodo.XXXXX" |
| 14 | + const initialDoiUrl = `https://doi.org/${doi}`; |
| 15 | + |
| 16 | + try { |
| 17 | + // Attempt to resolve the DOI URL without following redirects |
| 18 | + const response = await axios.get(initialDoiUrl, { maxRedirects: 0, validateStatus: status => status >= 300 && status < 400 }); |
| 19 | + const finalZenodoUrl = response.headers.location; |
| 20 | + |
| 21 | + // Extract Zenodo version ID from the redirect URL |
| 22 | + const zenodoVersionIdMatch = finalZenodoUrl.match(/record\/(\d+)/); |
| 23 | + |
| 24 | + if (!zenodoVersionIdMatch || !zenodoVersionIdMatch[1]) { |
| 25 | + return { statusCode: 500, body: JSON.stringify({ message: "Failed to extract Zenodo version ID.", pathSegments, finalZenodoUrl, zenodoVersionIdMatch}) }; |
| 26 | + } |
| 27 | + const zenodoVersionId = zenodoVersionIdMatch[1]; |
| 28 | + |
| 29 | + // Update the DOI and construct URLs with the specific version ID |
| 30 | + const updatedDoi = `10.5281/zenodo.${zenodoVersionId}`; |
| 31 | + const filePath = pathSegments.slice(6).join('/'); |
| 32 | + const actualFileUrl = `https://zenodo.org/api/records/${zenodoVersionId}/files/${filePath}/content`; |
| 33 | + const matomoReportUrl = `https://bioimage.matomo.cloud/matomo.php?download=https://doi.org/${updatedDoi}&idsite=1&rec=1&r=646242&h=13&m=35&s=20&url=http://bioimage.io/#/?id=${updatedDoi}&uadata=${encodeURIComponent(uadata)}`; |
| 34 | + |
| 35 | + if (queryParams.debug) { |
| 36 | + return { statusCode: 200, body: JSON.stringify({ actualFileUrl, matomoReportUrl }) }; |
| 37 | + } |
| 38 | + |
| 39 | + // Log the download event to Matomo |
| 40 | + await axios.get(matomoReportUrl); |
| 41 | + |
| 42 | + // Redirect to the actual file URL |
| 43 | + return { statusCode: 302, headers: { 'Location': actualFileUrl } }; |
| 44 | + } catch (error) { |
| 45 | + // Handle errors during the DOI resolution process or HTTP requests |
| 46 | + return { statusCode: 500, body: JSON.stringify({ message: "Error during processing.", error: error.message }) }; |
| 47 | + } |
| 48 | +}; |
0 commit comments