<%@ language = "JavaScript" %>
<% /*
     $Revision$
     $Id$

     File:          api_msgraphnotification.asp
     Description:   Opvangscript voor msgraph notifications

     Parameters:
     Status:
     Context:
     Notes:
*/
    DOCTYPE_Disable = 1; // Anders problemen met het terugsturen van het validationtoken
    THIS_FILE = "appl/api/api_msgraphnotification.asp";
%>
<!-- #include file="../Shared/common.inc" -->
<!-- #include file="../api/api.inc" -->
<%

var API = new API_func();

// Bij aanmaken van de subscription doet Graph direct aan validatie-aanroep
// De token parameter moet je teruggeven.
var validationToken = getQParam("validationToken", "");
if (validationToken) {
    __Log("Subscribtion validated: " + validationToken);
    Response.ContentType = "text/plain";
    Response.Write(validationToken);
    Response.End;
}

// Als we hier komen hebben we een echte notificatie binnengekregen
var notidata = RequestJSON(API.apidata.loglevel).value;
if (notidata.length > 1) {
    __DoLog("INTERNAL ERROR; We hebben meerdere notificaties in 1x ontvangen, dat kunnen we (nog) niet aan", "#FF0000");
}
// We behandelen alleen de eerste, het is overigens nog niet opgevallen dat notificaties gebundeld worden
notidata = notidata[0];

try {
    var etag = notidata.resourceData["@odata.etag"];
} catch (e) {
    __DoLog("Malformed MS Graph notification received:", "#FF0000");
    __DoLog(notidata, "#FF0000");
    Response.Status = "400 - Bad Request";
    Response.End;
}

// {
//   "value": [
//     {
//       "subscriptionId": "7b8d9ffc-1d50-41b7-b0c9-c85be52836fd",
//       "subscriptionExpirationDateTime": "2021-02-19T04:51:01-08:00",
//       "changeType": "updated",
//       "resource": "Users/5381c9d7-d7ef-4b6f-930d-f7893adf0b14/Events/AAMkADgwY2U2OTNlLTUzNjgtNDI4Zi1hZTdmLWU0NzRlODA0MTQ3YQBGAAAAAAAiY_3E-_MuTaCgYlN5eIOoBwAsO-qkNQq_Sqb0Bq5U7JV3AAAAAAENAAAsO-qkNQq_Sqb0Bq5U7JV3AAC550IPAAA=",
//       "resourceData": {
//         "@odata.type": "#Microsoft.Graph.Event",
//         "@odata.id": "Users/5381c9d7-d7ef-4b6f-930d-f7893adf0b14/Events/AAMkADgwY2U2OTNlLTUzNjgtNDI4Zi1hZTdmLWU0NzRlODA0MTQ3YQBGAAAAAAAiY_3E-_MuTaCgYlN5eIOoBwAsO-qkNQq_Sqb0Bq5U7JV3AAAAAAENAAAsO-qkNQq_Sqb0Bq5U7JV3AAC550IPAAA=",
//         "@odata.etag": "W/\"DwAAABYAAAAsO/qkNQq+Sqb0Bq5U7JV3AAC50Ux3\"",
//         "id": "AAMkADgwY2U2OTNlLTUzNjgtNDI4Zi1hZTdmLWU0NzRlODA0MTQ3YQBGAAAAAAAiY_3E-_MuTaCgYlN5eIOoBwAsO-qkNQq_Sqb0Bq5U7JV3AAAAAAENAAAsO-qkNQq_Sqb0Bq5U7JV3AAC550IPAAA="
//       },
//       "clientState": "b70f833c968537eb8f6e86a8c50de7e3221c8485",
//       "tenantId": "bab7c51b-2329-47f1-b6ff-1a5270efc193"
//     }
//   ]
// }
// We hebben res_ruimte_key meegegeven in de hookurl. Er zijn meer manieren
// om de ruimte te achterhalen maar deze is het snelst/ simpelst
var res_ruimte_key = getQParamInt("res_ruimte", -1);
if (res_ruimte_key == -1) {
    Response.Status = "422 - Unprocessable Content";
    Response.End;
}
var sql = "SELECT res_ruimte_extern_id,"
        + "       res_ruimte_graphhooksecret"
        + "  FROM res_ruimte"
        + " WHERE res_ruimte_key = " + res_ruimte_key;
var oRs = Oracle.Execute(sql);
var zaalemail = oRs("res_ruimte_extern_id").Value;
__Log("Incoming hook notification for {0}".format(zaalemail));
if (zaalemail == null || oRs("res_ruimte_graphhooksecret").Value != notidata.clientState)
{
    if (zaalemail == null) {
        __Log("Extern ID (and with that, the subscription) has been removed");
    } else {
        __Log(notidata);
        __Log("clientState does not match (should {0} is {1}.\nOld subscription? It will expire {2}".format(oRs("res_ruimte_graphhooksecret").Value,
                                                                                                            notidata.clientState,
                                                                                                            notidata.subscriptionExpirationDateTime));
    }
    oRs.Close();
    Response.Status = "422 - Unprocessable Content";
    Response.End;
}
oRs.Close();

var fso = Server.CreateObject("Scripting.FileSystemObject");
var tempFolder = shared.tempFolder();
if (!fso.FolderExists(tempFolder)) {
    fso.CreateFolder(tempFolder);
}
var exchangeFolder = tempFolder + "/exchange";
if (!fso.FolderExists(exchangeFolder)) {
    fso.CreateFolder(exchangeFolder);
}
var logfile_path = exchangeFolder + "/" + safe.filename(etag) + ".data";
if (fso.FileExists(logfile_path)) { // Notificaties zijn uniek obv etag, deze is dus dubbel
    __Log("MS Graph, duplicate notification ignored", "#FFFF44");
} else {
    try {
        var ts = fso.CreateTextFile(logfile_path, true);
        ts.Write(JSON.stringify(notidata, null, 2));
        ts.Close();
    } catch (e) {
        __DoLog("Failed writing to {0}\n{1}".format(logfile_path, e.description));
    }
    sql = "INSERT INTO fac_notificatie (fac_srtnotificatie_key,"
        + "                             fac_notificatie_queue,"
        + "                             fac_notificatie_refkey,"
        + "                             fac_notificatie_attachments,"
        + "                             fac_notificatie_naam,"
        + "                             fac_notificatie_notbefore,"
        + "                             fac_notificatie_status)"
        + "    SELECT fac_srtnotificatie_key"
        + "         , 'EXCHANGE'"
        + "         , " + res_ruimte_key
        + "         , " + safe.quoted_sql(logfile_path)
        + "         , " + safe.quoted_sql(zaalemail)
        + "         , SYSDATE"
        + "         , 1" // Met 1 omzeilen we fac.cleannotifications en zorgen we dat fac_t_fac_notificatie_A_IU niet de PUTORDERS inschiet (Wij doen er verder niets mee)
        + "      FROM fac_srtnotificatie"
        + "     WHERE fac_srtnotificatie_code = 'RESUPD'";
    Oracle.Execute(sql);
}

Response.Status = "202 - Accepted";
ASPPAGE_END();
Response.End;
%>
