UNPKG

@app-sh/o365

Version:

App Shell plugin for Office 365

2 lines (1 loc) 2.66 kB
"use strict";var e=require("app-sh"),t=require("node:querystring");class n extends e.AppShPlugin{_appId;_clientSecret;_tenantId;_grantType;_resource;_tokenGracePeriod;_tokenTimeout;_token;constructor(e){super({name:"o365",appSh:e.appSh,appShConfig:e.appShConfig,pluginVersion:"1.1.1"});let t={grantType:"client_credentials",resource:"https://graph.microsoft.com",tokenGracePeriod:5,...e};this._appId=t.appId,this._clientSecret=t.clientSecret,this._tenantId=t.tenantId,this._grantType=t.grantType,this._resource=t.resource,this._tokenGracePeriod=60*t.tokenGracePeriod*1e3,this._token=null}async login(){this.info("Logging in and getting new token now!");let e={client_id:this._appId,client_secret:this._clientSecret,scope:`${this._resource}/.default`,grant_type:this._grantType},n=await this.httpReq("https://login.microsoftonline.com",`/${this._tenantId}/oauth2/v2.0/token`,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:t.stringify(e)}).catch((e=>{this.error("Error while getting new token - (%s)",e),this._token=null,this.info("Will try and get new token again in 1 min"),this._tokenTimeout=setTimeout((()=>this.login()),6e4)}));if(void 0!==n){let e=n.body;this._token=e.access_token;let t=1e3*e.expires_in-this._tokenGracePeriod;this._tokenTimeout=setTimeout((()=>this.login()),t),this.info("Will get new token again in (%s) mins",Math.round(t/1e3/60))}}async logout(){this.info("Logging out and clearing timer!"),void 0!==this._tokenTimeout&&clearTimeout(this._tokenTimeout),this._token=null}async stop(){await this.logout()}async loggedIn(){return null!==this._token}async sendOutlookMessage(e,t,n,i,o,s,r,a,c){if(null===this._token)return this.warn("Not logged into O365 therefore can't send any mails at the moment!"),!1;let h={subject:o,body:{contentType:r,content:s}};void 0!==a&&(h.singleValueExtendedProperties=[{id:"String {a75e89ac-9033-49c0-a4fc-52d83c8468ac} Name app-sh-o365-ref-code",value:a}]),h.toRecipients=[];for(let t of e)h.toRecipients.push({emailAddress:{address:t}});h.ccRecipients=[];for(let e of t)h.ccRecipients.push({emailAddress:{address:e}});h.bccRecipients=[];for(let e of n)h.bccRecipients.push({emailAddress:{address:e}});if(h.attachments=[],void 0!==c)for(let e of c){let t={"@odata.type":"#microsoft.graph.fileAttachment",name:e.name,contentType:e.contentType,contentBytes:e.contentB64,contentId:"",isInline:!1};h.attachments.push(t)}let l=await this.httpReq(this._resource,`/v1.0/users/${i}/sendMail`,{method:"POST",body:{message:h},bearerToken:this._token}).catch((e=>{this.error("Error while sending email (%j) - (%s)",h,e)}));return void 0!==l&&202===l.statusCode}}exports.O365=n;