import com.onresolve.scriptrunner.runner.rest.common.CustomEndpointDelegate
import com.atlassian.applinks.api.ApplicationLinkResponseHandler
import com.atlassian.applinks.api.ApplicationLinkService
import com.atlassian.applinks.api.application.jira.JiraApplicationType
import com.atlassian.sal.api.component.ComponentLocator
import com.atlassian.sal.api.net.Request
import com.atlassian.sal.api.net.Response as SalResponse
import com.atlassian.sal.api.net.ResponseException
import com.atlassian.confluence.user.AuthenticatedUserThreadLocal
import groovy.json.JsonSlurper
import groovy.json.JsonOutput
import groovy.transform.BaseScript
import javax.ws.rs.core.MultivaluedMap
import javax.ws.rs.core.Response
import java.net.URLEncoder
@BaseScript CustomEndpointDelegate delegate
/* MEDIQ V46.1 - unified Confluence DC proxy; preserves original endpoint paths and contracts.
* INSTALL: Replace the THREE existing Confluence scripts defining:
* mediqGateway*, mediqMaintenanceProxy*, mediqUserFaultProxy* with THIS ONE script.
* Never install alongside them: duplicate route registration is ambiguous.
* Existing Jira endpoints remain in Jira. Authenticated AppLink must impersonate user.
*/
def respondMediq = { int status, Object obj ->
Response.status(status).type('application/json; charset=UTF-8').entity(JsonOutput.toJson(obj)).build()
}
def invokeMediq = { String path, String method, String body, int maximum, boolean normalizeId, String operation ->
try {
// Resolve the actual Confluence request principal, not SAL remoteUserKey.
// Do not trust an identity sent by the browser or fall back to anonymous access.
def currentUser = AuthenticatedUserThreadLocal.get()
if (currentUser == null || !currentUser.name) {
return respondMediq(401,[ok:false,message:'نشست کاربری معتبر شناسایی نشد. لطفاً وارد حساب خود شوید و صفحه را دوباره باز کنید.'])
}
if (method == 'POST') {
if ((body ?: '').length() > maximum) return respondMediq(413,[ok:false,message:'حجم درخواست بیش از حد مجاز است.'])
def parsed = new JsonSlurper().parseText(body ?: '{}')
if (!(parsed instanceof Map)) return respondMediq(400,[ok:false,message:'ساختار درخواست نامعتبر است.'])
}
def appLinks = ComponentLocator.getComponent(ApplicationLinkService)
def link = appLinks?.getPrimaryApplicationLink(JiraApplicationType)
if (!link) return respondMediq(503,[ok:false,message:'اتصال سرویس مدیکیو برقرار نشده است.'])
def factory = link.createAuthenticatedRequestFactory()
def req = factory.createRequest(method == 'GET' ? Request.MethodType.GET : Request.MethodType.POST,path)
req.addHeader('Accept','application/json, text/plain')
req.setSoTimeout(90000)
if (method == 'POST') {
req.addHeader('Content-Type','application/json; charset=UTF-8')
req.addHeader('X-Atlassian-Token','no-check')
req.setRequestBody(body ?: '{}')
}
Map remote = req.execute(new ApplicationLinkResponseHandler