I have a Google Form that I want to automatically create a Jira ticket upon submission and include the Google Form responses within the appropriate fields within the newly created Jira ticket. I have this working.
What else I need is to attach the file that may be selected by the user within the Google Form to the newly created Jira ticket. I also have this working. However, the attached file in Jira when clicked, won't open, and is giving me an "Ouch! We can't load the image."
I'm not sure what I need to do in order to make the attached image within Jira readable.
Here is my current google apps script code that is located within the Google Sheet that is populated with all the responses from the Google Sheet:
// Utilities
var mySSID = '16HL3q6L3lEsfoX_JWwrg8q02FQFZpFXpG6iazAUGlX0';
var myLookupSheet = 'Lookup Values';
var jiraToken = "OTE0Mzc0MTAyOTg2OouSdJ6P6ASObxv0uU+usAe1Kzp/"; // Add your Jira API token here
// searches for a value in a given column of a particular sheet and returns the entire row if found
function getLookupValue(searchValue) {
var spreadsheet = SpreadsheetApp.openById(mySSID);
var sheet = spreadsheet.getSheetByName(myLookupSheet);
var data = sheet.getDataRange().getValues();
// Create a regular expression with the "i" flag for case-insensitivity and a pattern that excludes empty strings
var regex = new RegExp(searchValue === "" ? "^(?!$)" : searchValue, 'i');
for (var row = 1; row < data.length; row++) { // Start from row 1 (assuming row 0 is header)
if (regex.test(data[row][0])) {
var myRow = data[row];
var myValue = myRow[1];
Logger.log(searchValue + " = [" + myValue + "]");
return myValue;
}
}
Logger.log("Could not find lookup for " + searchValue);
return null; // Return null if not found
}
function createJiraIssue(e) {
try {
// Log the entire form response to inspect its structure
Logger.log("Form Response:", JSON.stringify(e));
// Get form responses from the trigger event object
var email = e.values[1];
var requestType = e.values[2];
var emrPlatform = e.values[3];
var requestSource = e.values[4];
var province = e.values[5];
var summary = e.values[6];
var desc = e.values[7];
// Get the file URL from the form response
var fileUrl = e.values[8]; // Assuming the file URL is in the 9th column, adjust as needed
// Log the file URL to check if it's retrieved correctly
Logger.log("File URL:", fileUrl);
// Assign values to emrPlatformId and sourceId
var emrPlatformId = getLookupValue(emrPlatform);
var sourceId = getLookupValue(requestSource);
// Log the retrieved IDs for troubleshooting
Logger.log("EMR Platform ID:", emrPlatformId);
Logger.log("Request Source ID:", sourceId);
// Check if emrPlatformId is not null before replacing
if (emrPlatformId !== null) {
// Convert the comma-separated values to an array
var provinceArray = province.split(',').map(function (item) {
return { "value": item.trim() };
});
var epicName = email + " " + summary;
// Log the IDs before using them in the Jira payload
Logger.log("EMR Platform ID before replace:", emrPlatformId);
Logger.log("Request Source ID before API call:", sourceId);
// Jira details
var jiraProjectKey = "NCC";
var jiraIssueType = "Epic"; // Change this to your desired issue type
// Prepare Jira API request payload
var jiraData = {
"fields": {
"project": {
"key": jiraProjectKey
},
"customfield_10004": epicName,
"summary": summary,
"description": desc,
"issuetype": {
"name": jiraIssueType
},
"customfield_13464": emrPlatformId ? { "id": String(emrPlatformId).replace(/\s+$/, '') } : null,
"customfield_13343": sourceId ? { "id": String(sourceId) } : null,
"customfield_13600": provinceArray
}
};
// Convert payload to JSON string
var jiraPayload = JSON.stringify(jiraData);
// Set up headers for Jira API request
var jiraHeaders = {
"Content-Type": "application/json",
"Authorization": "Bearer " + jiraToken
};
// Set up options for UrlFetchApp
var jiraOptions = {
"method": "POST",
"headers": jiraHeaders,
"payload": jiraPayload
};
// Make the HTTP call to the Jira API to create the issue
var jiraResponse = UrlFetchApp.fetch(jiraUrl, jiraOptions);
// Extract Jira issue key from the response
var jiraResponseData = JSON.parse(jiraResponse.getContentText());
var jiraIssueKey = jiraResponseData.key;
// Attach the file to the created Jira issue using JIRA REST API
if (fileUrl) {
attachFileToJiraIssueRestAPI(jiraIssueKey, fileUrl);
}
// Send an email to the requestor
var emailSubject = "Your Jira issue has been created";
var emailBody = "Thank you for your submission.\n\n" +
"Your Jira issue has been created with the key: " + jiraIssueKey + "\n\n" +
MailApp.sendEmail(email, emailSubject, emailBody);
} else {
Logger.log("emrPlatformId is null. Check if the value is being retrieved correctly.");
}
} catch (error) {
Logger.log("Error: " + error);
}
}
function attachFileToJiraIssueRestAPI(issueKey, fileUrl) {
try {
// Fetch the file content
var fileContent = UrlFetchApp.fetch(fileUrl);
// Convert file content to base64
var base64File = Utilities.base64Encode(fileContent.getContent());
// Jira attachment API endpoint
// Set up headers for Jira attachment API request
var jiraAttachmentHeaders = {
"Authorization": "Bearer " + jiraToken,
"Accept": "application/json",
"X-Atlassian-Token": "no-check", // Add this header to bypass XSRF check
"Content-Type": "multipart/form-data; boundary=gc0p4Jq0M2Yt08jU534c0p"
};
// Set up options for UrlFetchApp
var jiraAttachmentOptions = {
"method": "POST",
"headers": jiraAttachmentHeaders,
"payload": Utilities.newBlob(
"--gc0p4Jq0M2Yt08jU534c0p\r\n" +
"Content-Disposition: form-data; name=\"file\"; filename=\"2023-10-25_9-23-53.png\"\r\n" +
"Content-Type: image/png\r\n\r\n" +
base64File + "\r\n" +
"--gc0p4Jq0M2Yt08jU534c0p--"
)
};
// Make the HTTP call to the Jira attachment API
var jiraAttachmentResponse = UrlFetchApp.fetch(jiraAttachmentUrl, jiraAttachmentOptions);
// Log the Jira attachment API response for troubleshooting
Logger.log("Jira Attachment API Response Code:", jiraAttachmentResponse.getResponseCode());
Logger.log("Jira Attachment API Response Content:", jiraAttachmentResponse.getContentText());
} catch (attachmentError) {
Logger.log("Error attaching file to Jira issue: " + attachmentError);
}
}
// Function to extract file ID from Google Drive URL
function extractFileId(fileUrl) {
var fileIdMatch = /\/d\/(.*?)(?:\/|$)|\/open\?id=(.*?)(?:&|$)|\/file\/d\/(.*?)(?:\/|$)/.exec(fileUrl);
if (fileIdMatch && fileIdMatch.length > 1) {
return fileIdMatch[1] || fileIdMatch[2] || fileIdMatch[3];
} else {
Logger.log("Error extracting file ID from URL: " + fileUrl);
return null;
}
}
function attachFileToJiraIssue(issueKey, fileUrl) {
try {
// Fetch the file content
var fileContent = UrlFetchApp.fetch(fileUrl);
// Log the file content type
var fileContentType = fileContent.getHeaders()["Content-Type"];
Logger.log("File Content Type:", fileContentType);
// Convert file content to base64
var base64File = Utilities.base64Encode(fileContent.getContent());
// Log the base64File (for troubleshooting)
Logger.log("Base64 File:", base64File);
// Jira attachment API endpoint
// Prepare Jira attachment API request payload
var jiraAttachmentData = {
"file": base64File,
"filename": "2023-10-25_9-23-53.png", // Ensure the correct filename with the correct extension
"mimeType": "image/png" // Adjust the MIME type based on your file format
};
// Convert payload to JSON string
var jiraAttachmentPayload = JSON.stringify(jiraAttachmentData);
// Log the Jira attachment payload (for troubleshooting)
Logger.log("Jira Attachment Payload:", jiraAttachmentPayload);
// Set up headers for Jira attachment API request
var jiraAttachmentHeaders = {
"Authorization": "Bearer " + jiraToken
};
// Set up options for UrlFetchApp
var jiraAttachmentOptions = {
"method": "POST",
"headers": jiraAttachmentHeaders,
"payload": jiraAttachmentPayload,
"muteHttpExceptions": true // Add this option to examine full response
};
// Make the HTTP call to the Jira attachment API
var jiraAttachmentResponse = UrlFetchApp.fetch(jiraAttachmentUrl, jiraAttachmentOptions);
// Log the Jira attachment API response for troubleshooting
Logger.log("Jira Attachment API Response Code:", jiraAttachmentResponse.getResponseCode());
Logger.log("Jira Attachment API Response Content:", jiraAttachmentResponse.getContentText());
} catch (attachmentError) {
Logger.log("Error attaching file to Jira issue: " + attachmentError);
}
}
Not sure if any one is able to help me troubleshoot this. And if additional information is required, please let me know.
Thanks!