diff --git a/Commands/GCCommands.ts b/Commands/GCCommands.ts index d6fc7cc..0c28c5a 100644 --- a/Commands/GCCommands.ts +++ b/Commands/GCCommands.ts @@ -1,13 +1,10 @@ import { IHttp, IModify, IPersistence, IRead } from '@rocket.chat/apps-engine/definition/accessors'; import { ISlashCommand, ISlashCommandPreview, ISlashCommandPreviewItem, SlashCommandContext } from '@rocket.chat/apps-engine/definition/slashcommands'; import { GoogleCalendarApp } from '../GoogleCalendar'; -import { GCGetter } from '../helpers/GSGetter'; import { ApiEndpoint, IApiEndpointInfo, IApiRequest, IApiResponse } from '@rocket.chat/apps-engine/definition/api'; import { AppPersistence } from '../helpers/persistence'; import { IUser } from '@rocket.chat/apps-engine/definition/users'; - - export class GCCommand implements ISlashCommand { public command = 'calendar'; @@ -25,16 +22,9 @@ export class GCCommand implements ISlashCommand { try { - const loginstatus = await this.app.getGCGetter().login(this.app.getLogger(), read, http, modify, context, persis); - - msg.setText('Slashcommand executed'); - // await modify.getCreator().finish(msg); - modify.getNotifier().notifyUser(context.getSender(), msg.getMessage()); - - + const login_status = await this.app.getGCGetter().login(this.app.getLogger(), read, http, modify, context, persis); } catch (e) { - this.app.getLogger().error('Failed sending login url', e); - //msg.setText('An error occurred when trying to send the login url:disappointed_relieved:'); + this.app.getLogger().error('Failed executing slashcommand', e); } } diff --git a/GoogleCalendar.ts b/GoogleCalendar.ts index 47f1bf0..06dab2d 100644 --- a/GoogleCalendar.ts +++ b/GoogleCalendar.ts @@ -22,7 +22,6 @@ export class GoogleCalendarApp extends App { constructor(info: IAppInfo, logger: ILogger, accessors: IAppAccessors) { super(info, logger, accessors); this.gcGetter = new GCGetter(); - //this.webhook= new WebhookEndpoint(this); } public getGCGetter(): GCGetter { @@ -81,7 +80,6 @@ export class GoogleCalendarApp extends App { i18nDescription: 'Customize_Redirect_URI', }); - await configuration.slashCommands.provideSlashCommand(new GCCommand(this)); } diff --git a/README.md b/README.md index a361136..192a889 100644 --- a/README.md +++ b/README.md @@ -6,9 +6,18 @@ Integrates google calendar with your Rocket.Chat server. * Authenticate to your gmail account from inside your Rocket.Chat. * Create your private events in your google calendar fom your Rocket.Chat using just a slashcommand. * View and update your private events using just a slashcommand. +* Create a quick event using *quickadd* slashcommand. +* View all the calendars present on your profile and can even select any one of those calendars to work with. * Get reminders and notifications of events. * Create public events inside a room inviting all the users inside the room. +## How to use it? +* Download or clone the repository to your local system. +* Get your local Rocket.Chat server running. +* Navigate inside the folder using terminal. +* Run command `rc-apps deploy --url http://localhost:3000 --username {your_username} --password {your_password}` +* This gets the app installed in your local server, now navigate to app screen inside Options -> Administration -> Apps -> Google Calendar +* Activate the app and put in the credentials and start using it inside any of your room! ## Quick Start Guide @@ -21,7 +30,19 @@ Integrates google calendar with your Rocket.Chat server. * `/calendar logout` : Once you are done with viewing, creating your calendar events and wants to log out of the gmail account, use this command and it will log you out and redirect to your home page. +* `/calendar view` : Once the authentication is successful, you can use this command to view the private events on your calendar. Events will be displayed with title, date, start time and end time. You will also get the link, which you can click on and it will take directly to your calendar where you can udpate or delete that event. + +* `/calendar create "Title" "Date" "Start time" "Endtime"` : This command can be used to create a private on your primary calendar, where Title is the title of the event you are creating, and date should be in format YYYY-MM-DD and time in 24 hours format. + +* `/calendar logout` : Once you are done with viewing, creating your calendar events and wants to log out of the gmail account, use this command and it will log you out and redirect to your home page. + +* `/calendar quickadd {title of the event}` - This slashcommand can be used to create an event starting from time the slashcommand is called to one hour in duration. + +* `/calendar list` - Shows you the list of the calendars that are present on your user profile. For each calendar there is a button, which you can click and decide which calendar to communicate with and that calendar will be used for fetching and editing events (though this is optional, Google Calendar app uses your primary calendar by default.) +* `/calendar invite "Title" "Date" "Starttime" "Endtime" ` - This slashcommand will create public events which will include inviting all the users present inside the room (in which command is called) to this event. All the users will receive the event invite through e-mails. They can respond to that invite and the organizer will receive their response notifications via e-mails. +### Feedback and Suggestions +Contribute to this repository by opening an issue if you have any feedback or suggestions for improvements or even some feature request! diff --git a/helpers/GCResult.ts b/helpers/GCResult.ts index c1d882d..f9e7b41 100644 --- a/helpers/GCResult.ts +++ b/helpers/GCResult.ts @@ -3,20 +3,20 @@ import { HttpStatusCode, IHttp, ILogger, IRead } from '@rocket.chat/apps-engine/ import { IApiRequest } from '@rocket.chat/apps-engine/definition/api'; export class GCResults { - public atoken: string; + public acess_token: string; constructor(data?: any) { if (data) { - this.atoken = data.access_token as string; + this.acess_token = data.access_token as string; } } public result(): string { - if (!this.atoken) { + if (!this.acess_token) { throw new Error('Invalid result'); } - return this.atoken; + return this.acess_token; } } \ No newline at end of file diff --git a/helpers/GSGetter.ts b/helpers/GSGetter.ts index 60705e0..7659e45 100644 --- a/helpers/GSGetter.ts +++ b/helpers/GSGetter.ts @@ -1,21 +1,26 @@ import { HttpStatusCode, IHttp, ILogger, IRead, IHttpResponse, IModify, IPersistence } from '@rocket.chat/apps-engine/definition/accessors'; import { ISlashCommand, ISlashCommandPreview, ISlashCommandPreviewItem, SlashCommandContext } from '@rocket.chat/apps-engine/definition/slashcommands'; -import { GCResults } from '../helpers/GCResult'; +import { MessageActionType } from '@rocket.chat/apps-engine/definition/messages/MessageActionType'; import { GoogleCalendarApp } from '../GoogleCalendar'; -import { WebhookEndpoint } from '../helpers/Webhook'; import { AppPersistence } from '../helpers/persistence'; import { displayevents } from '../helpers/result'; +import { IUser } from '@rocket.chat/apps-engine/definition/users'; enum Command { connect = 'auth', lgout = 'logout', show = 'view', make = 'create', + quick = 'quickadd', + calendar = 'list', + config = 'configure', + public = 'invite', } + export class GCGetter { - private readonly SCOPES = "https://www.googleapis.com/auth/calendar"; + private readonly SCOPES = 'https://www.googleapis.com/auth/calendar'; private readonly urli = 'https://accounts.google.com/o/oauth2/v2/auth?'; private res; private readonly app: GoogleCalendarApp; @@ -23,70 +28,83 @@ export class GCGetter { public async login(logger: ILogger, read: IRead, http: IHttp, modify: IModify, context: SlashCommandContext, persis: IPersistence): Promise { - const Client_id = await read.getEnvironmentReader().getSettings().getValueById('calendar_clientid'); + const client_id = await read.getEnvironmentReader().getSettings().getValueById('calendar_clientid'); const api_key = await read.getEnvironmentReader().getSettings().getValueById('calendar_apikey'); const secret = await read.getEnvironmentReader().getSettings().getValueById('calendar_secret_key'); const redirect = await read.getEnvironmentReader().getSettings().getValueById('redirect_uri'); const persistence = new AppPersistence(persis, read.getPersistenceReader()); - const id = await persistence.connectUserToClient(Client_id, context.getSender()); - + const id = await persistence.connectUserToClient(client_id, context.getSender()); - let signedin: boolean = false; - const msg = modify.getCreator().startMessage().setSender(context.getSender()).setRoom(context.getRoom()); + const message = modify.getCreator().startMessage().setSender(context.getSender()).setRoom(context.getRoom()); + const [parameter] = context.getArguments(); - const [parame] = context.getArguments(); + switch (parameter) { - switch (parame) { - case (Command.connect): - const response = (`${this.urli}client_id=${Client_id}&redirect_uri=${redirect}/api/apps/public/c759c4f1-a3c1-4202-8238-c6868633ed87/webhook&scope=https://www.googleapis.com/auth/calendar&prompt=consent&access_type=offline&response_type=code`); + const response = (`${this.urli}client_id=${client_id}&redirect_uri=${redirect}/api/apps/public/c759c4f1-a3c1-4202-8238-c6868633ed87/webhook&scope=${this.SCOPES}&prompt=consent&access_type=offline&response_type=code`); + try { - msg.setText(response); - await modify.getCreator().finish(msg); + message.addAttachment({ + text: 'Click the button to authenticate to your Gmail account.', + actions: [{ + type: MessageActionType.BUTTON, + text: 'Authenticate', + msg_in_chat_window: false, + url: `${response}`, + }], + }); + + await modify.getCreator().finish(message); } catch (e) { this.app.getLogger().error('Failed sending login url', e); - msg.setText('An error occurred when trying to send the login url:disappointed_relieved:'); + message.setText('An error occurred when trying to send the login url:disappointed_relieved:'); - modify.getNotifier().notifyUser(context.getSender(), msg.getMessage()); + modify.getNotifier().notifyUser(context.getSender(), message.getMessage()); } break; case (Command.lgout): - const logresponse = `https://www.google.com/accounts/Logout?continue=https://appengine.google.com/_ah/logout?continue=${redirect}`; + try { - msg.setText(logresponse); - await modify.getCreator().finish(msg); + message.addAttachment({ + text: 'Click the button to logout your Gmail account.', + actions: [{ + type: MessageActionType.BUTTON, + text: 'Logout', + msg_in_chat_window: false, + url: `${logresponse}`, + }], + }); + await modify.getCreator().finish(message); } catch (e) { this.app.getLogger().error('Failed sending logout url', e); - msg.setText('An error occurred when trying to send the logout url:disappointed_relieved:'); + message.setText('An error occurred when trying to send the logout url:disappointed_relieved:'); - modify.getNotifier().notifyUser(context.getSender(), msg.getMessage()); - } + modify.getNotifier().notifyUser(context.getSender(), message.getMessage()); + } - const atoken = await persistence.getAT(context.getSender()); - // console.log('This is the access token inside GCGetter:', atoken); + const atoken = await persistence.get_access_token(context.getSender()); break; case (Command.show): - const newatoken = await persistence.getAT(context.getSender()); + const new_token = await persistence.get_access_token(context.getSender()); const dat = new Date(); - const newdate = dat.toISOString(); - const url = `https://www.googleapis.com/calendar/v3/calendars/primary/events?key=${api_key}&showDeleted=false&timeMin=${newdate}`; - const newresponse = await http.get(url, { headers: { 'Authorization': `Bearer ${newatoken}`, } }); + const minimum_date = dat.toISOString(); + const url = `https://www.googleapis.com/calendar/v3/calendars/primary/events?key=${api_key}&showDeleted=false&timeMin=${minimum_date}`; + const api_response = await http.get(url, { headers: { Authorization: `Bearer ${new_token}` } }); - for (var i = 0; i < newresponse.data.items.length; i++) { - // console.log( newresponse.data.items[i].summary); - await displayevents(newresponse.data.items[i], modify, context); + for (let i = 0; i < api_response.data.items.length; i++) { + await displayevents(api_response.data.items[i], modify, context); } @@ -94,59 +112,154 @@ export class GCGetter { case (Command.make): - const createatoken = await persistence.getAT(context.getSender()); + const access_token = await persistence.get_access_token(context.getSender()); const params = context.getArguments().join(' '); const array = params.split("\""); - const createurl = `https://www.googleapis.com/calendar/v3/calendars/primary/events?key=${api_key}`; - console.log('Create event array elements are these:', array[1], array[3]); + const create_url = `https://www.googleapis.com/calendar/v3/calendars/primary/events?key=${api_key}`; const datetime = array[3] + 'T' + array[5]; const date = new Date(datetime); - //const starttime = new Date(date.getTime() - date.getTimezoneOffset() * 60000); - const startdatetime = date.toISOString(); + const start_datetime = date.toISOString(); + const e_date = array[3] + 'T' + array[7]; + const end_date = new Date(e_date); + const end_datetime = end_date.toISOString(); + const create_api_response = await http.post(create_url, { headers: { 'Authorization': `Bearer ${access_token}`, }, data: { 'summary': `${array[1]}`, 'end': { 'dateTime': `${end_datetime}`, }, 'start': { 'dateTime': `${start_datetime}` } } }); + if (create_api_response.statusCode == HttpStatusCode.OK && create_api_response.data.status == "confirmed") { + try { + message.addAttachment({ - const edate = array[3] + 'T' + array[7]; - const enddate = new Date(edate); - const enddatetime = enddate.toISOString(); + text: `Event has been created. Find the event at [${create_api_response.data.summary}](${create_api_response.data.htmlLink}) `, - // console.log('Start date and time in ISO format is: ',startdatetime,'end date time:',enddatetime); + }); + await modify.getCreator().finish(message); + } catch (e) { + this.app.getLogger().error('Failed creating events', e); + message.setText('An error occurred when sending the event creation as message :disappointed_relieved:'); + } + } else { + console.log('This is the error message:', create_api_response.data.error.message); - const createresponse = await http.post(createurl, { headers: { 'Authorization': `Bearer ${createatoken}`, }, data: { 'summary': `${array[1]}`, 'end': { 'dateTime': `${enddatetime}`, }, 'start': { 'dateTime': `${startdatetime}` } } }); - console.log('This is the create event request response: ', createresponse); - if (createresponse.statusCode == HttpStatusCode.OK && createresponse.data.status == "confirmed") { //console.log('Event created wohoooooo!!!'); try { - msg.addAttachment({ + message.addAttachment({ - text: `Event has been created. Find the event at [${createresponse.data.summary}](${createresponse.data.htmlLink}) `, + text: `Event could not be created. It encountered the error: ${create_api_response.data.error.message}. Please try again. `, }); - await modify.getCreator().finish(msg); + await modify.getCreator().finish(message); } catch (e) { this.app.getLogger().error('Failed creating events', e); - msg.setText('An error occurred when sending the event creation as message :disappointed_relieved:'); + message.setText('An error occurred when sending the event creation as message :disappointed_relieved:'); } } - else { - console.log('This is the error message:', createresponse.data.error.message); + break; + + case (Command.quick): + + const title = context.getArguments().join(' '); + const title_new = title.split('\"'); + const token = await persistence.get_access_token(context.getSender()); + const quick_url = `https://www.googleapis.com/calendar/v3/calendars/primary/events/quickAdd?key=${api_key}&text=${title_new[1]}`; + const quick_api_response = await http.post(quick_url, { headers: { Authorization: `Bearer ${token}`, } }); + if (quick_api_response && quick_api_response.statusCode === HttpStatusCode.OK) { + // const msg = modify.getCreator().startMessage().setSender(context.getSender()).setRoom(context.getRoom()); + message.setText('Quickadd event succcessfully created!'); + await modify.getCreator().finish(message); + } + break; + + case (Command.calendar): + + const list_token = await persistence.get_access_token(context.getSender()); + const list_url = `https://www.googleapis.com/calendar/v3/users/me/calendarList?key=${api_key}`; + const list_api_response = await http.get(list_url, { headers: { Authorization: `Bearer ${list_token}`, } }); + let current_calendar = await persistence.get_preferred_calendar_id(context.getSender()); + (list_api_response.data.items as Array).forEach((value) => { + if (current_calendar == value.id || value.primary && current_calendar == undefined) { + message.addAttachment({ + color: value.backgroundColor, + text: value.summary, + }); + } else { + message.addAttachment({ + color: value.backgroundColor, + text: value.summary, + actions: [{ + type: MessageActionType.BUTTON, + text: 'Set as default', + msg_in_chat_window: true, + msg: `/calendar configure ${value.id}`, + }], + }); + } + }); + await modify.getCreator().finish(message); + break; + + case (Command.config): + + const calendar = context.getArguments(); + const id = await persistence.connect_user_to_calendar_id(calendar[1], context.getSender()); + const final_calendar_id = await persistence.get_preferred_calendar_id(context.getSender()); + break; + + case (Command.public): + + const user_id = await read.getRoomReader().getMembers(context.getRoom().id); + let email_ids: Array = user_id; + let mapping: Array = []; + + for (let index = 0; index < user_id.length; index++) { + email_ids[index] = user_id[index].emails[0].address; + } + await modify.getCreator().finish(message); + const invite_token = await persistence.get_access_token(context.getSender()); + const invite_parameters = context.getArguments().join(' '); + const invite_array = invite_parameters.split("\""); + const invite_url = `https://www.googleapis.com/calendar/v3/calendars/primary/events?key=${api_key}&sendUpdates=all`; + + const invite_datetime = invite_array[3] + 'T' + invite_array[5]; + const invite_date = new Date(invite_datetime); + const invitestart_datetime = invite_date.toISOString(); + const invite_e_date = invite_array[3] + 'T' + invite_array[7]; + const inviteend_date = new Date(invite_e_date); + const invite_end_datetime = inviteend_date.toISOString(); + + for (let index = 0; index < email_ids.length; index++) { + mapping.push({ email: email_ids[index] }); + } + const invite_api_response = await http.post(invite_url, { headers: { Authorization: `Bearer ${invite_token}`, }, data: { 'summary': `${invite_array[1]}`, 'end': { 'dateTime': `${invite_end_datetime}`, }, 'attendees': mapping, 'start': { 'dateTime': `${invitestart_datetime}` }, } }); + if (invite_api_response.statusCode === HttpStatusCode.OK && invite_api_response.data.status === 'confirmed') { try { - msg.addAttachment({ + message.addAttachment({ - text: `Event could not be created. It encountered the error: ${createresponse.data.error.message}. Please try again. `, + text: `Event has been created. Find the event at [${invite_api_response.data.summary}](${invite_api_response.data.htmlLink}) `, }); - await modify.getCreator().finish(msg); + await modify.getCreator().finish(message); } catch (e) { this.app.getLogger().error('Failed creating events', e); - msg.setText('An error occurred when sending the event creation as message :disappointed_relieved:'); + message.setText('An error occurred when sending the event creation as message :disappointed_relieved:'); + } + } else { + try { + message.addAttachment({ + + text: `Event could not be created. It encountered the error: ${invite_api_response.data.error.message}. Please try again. `, + + + }); + await modify.getCreator().finish(message); + } catch (e) { + this.app.getLogger().error('Failed creating events', e); + message.setText('An error occurred when sending the event creation as message :disappointed_relieved:'); } } break; } - } } diff --git a/helpers/Webhook.ts b/helpers/Webhook.ts index eac69d4..662963c 100644 --- a/helpers/Webhook.ts +++ b/helpers/Webhook.ts @@ -1,53 +1,42 @@ import { HttpStatusCode, IHttp, ILogger, IModify, IPersistence, IRead } from '@rocket.chat/apps-engine/definition/accessors'; import { ApiEndpoint, IApiEndpointInfo, IApiRequest, IApiResponse } from '@rocket.chat/apps-engine/definition/api'; -import { RocketChatAssociationModel, RocketChatAssociationRecord } from '@rocket.chat/apps-engine/definition/metadata'; -import { GCGetter } from './GSGetter'; -import { ISlashCommand, ISlashCommandPreview, ISlashCommandPreviewItem, SlashCommandContext } from '@rocket.chat/apps-engine/definition/slashcommands'; import { GCResults } from '../helpers/GCResult'; -import { IUser } from '@rocket.chat/apps-engine/definition/users'; import { AppPersistence } from '../helpers/persistence'; - export class WebhookEndpoint extends ApiEndpoint { public path = 'webhook'; - private readonly urli = 'http://localhost:3000/api/apps/public/c759c4f1-a3c1-4202-8238-c6868633ed87/webhook'; public tokenid; + private readonly urli = 'http://localhost:3000/api/apps/public/c759c4f1-a3c1-4202-8238-c6868633ed87/webhook'; public async get(request: IApiRequest, endpoint: IApiEndpointInfo, read: IRead, modify: IModify, http: IHttp, persist: IPersistence): Promise { - const Client_id = await read.getEnvironmentReader().getSettings().getValueById('calendar_clientid'); + const client_id = await read.getEnvironmentReader().getSettings().getValueById('calendar_clientid'); const secret = await read.getEnvironmentReader().getSettings().getValueById('calendar_secret_key'); const api_key = await read.getEnvironmentReader().getSettings().getValueById('calendar_apikey'); - //logger.debug('response from first request is:', request.params);` - const auth_code = request.query.code; const url = 'https://www.googleapis.com/oauth2/v4/token'; - const newresponse = await http.post(url, { data: { 'code': `${auth_code}`, 'client_id': `${Client_id}`, 'client_secret': `${secret}`, 'redirect_uri': `${this.urli}`, 'grant_type': 'authorization_code', } }); + const new_response = await http.post(url, { data: { 'code': `${auth_code}`, 'client_id': `${client_id}`, 'client_secret': `${secret}`, 'redirect_uri': `${this.urli}`, 'grant_type': 'authorization_code', } }); - if (newresponse.statusCode !== HttpStatusCode.OK || !newresponse.data) { - console.log('Did not get a valid response', newresponse); + if (new_response.statusCode !== HttpStatusCode.OK || !new_response.data) { + console.log('Did not get a valid response', new_response); throw new Error('Unable to retrieve response with auth code.'); } - console.log('This is the response from post api', newresponse); - const acesstoken = new GCResults(newresponse.data); + console.log('This is the response from post api', new_response); + const acess_token = new GCResults(new_response.data); // logger.debug('Auth token received is: ', auth_code); - const atoken = acesstoken; + const atoken = acess_token; const persistence = new AppPersistence(persist, read.getPersistenceReader()); - const uid = await persistence.getuid(Client_id); - const id = await persistence.connectUserToAT(acesstoken, uid); + const user_id = await persistence.getuid(client_id); + const id = await persistence.connect_user_to_token(acess_token, user_id); - - if (acesstoken) { - //location.assign('http://localhost:3000/home'); + if (acess_token) { return this.success('
Sign-in successful! Please close this window/tab and continue using!
'); - } - else + } else { throw new Error('Sign-in not successful'); - // return auth_cod - //return this.success(); + } } } diff --git a/helpers/persistence.ts b/helpers/persistence.ts index f60c331..93abf1a 100644 --- a/helpers/persistence.ts +++ b/helpers/persistence.ts @@ -1,35 +1,49 @@ import { RocketChatAssociationModel, RocketChatAssociationRecord } from '@rocket.chat/apps-engine/definition/metadata'; -import { IPersistence, IPersistenceRead } from '@rocket.chat/apps-engine/definition/accessors'; +import { IPersistence, IPersistenceRead, IRead, IRoomRead, IHttp, IModify } from '@rocket.chat/apps-engine/definition/accessors'; import { IUser } from '@rocket.chat/apps-engine/definition/users'; - export class AppPersistence { constructor(private readonly persistence: IPersistence, private readonly persistenceRead: IPersistenceRead) { } public async connectUserToClient(clientid: string, user: IUser): Promise { - const userAssociation = new RocketChatAssociationRecord(RocketChatAssociationModel.ROOM, user.id); - const clientAssociation = new RocketChatAssociationRecord(RocketChatAssociationModel.MISC, `${clientid}`); + const user_association = new RocketChatAssociationRecord(RocketChatAssociationModel.ROOM, user.id); + const client_association = new RocketChatAssociationRecord(RocketChatAssociationModel.MISC, `${clientid}`); - await this.persistence.updateByAssociations([userAssociation, clientAssociation], { uid: user.id }, true); + await this.persistence.updateByAssociations([user_association, client_association], { uid: user.id }, true); } public async getuid(Clientid: string): Promise { - const clientAssociation = new RocketChatAssociationRecord(RocketChatAssociationModel.MISC, Clientid); - const [result] = await this.persistenceRead.readByAssociations([clientAssociation]); + const client_association = new RocketChatAssociationRecord(RocketChatAssociationModel.MISC, Clientid); + const [result] = await this.persistenceRead.readByAssociations([client_association]); return result ? (result as any).uid : undefined; } - public async connectUserToAT(atoken: any, user: string): Promise { - const userAssociation = new RocketChatAssociationRecord(RocketChatAssociationModel.USER, user); + public async connect_user_to_token(atoken: any, user: string): Promise { + const user_association = new RocketChatAssociationRecord(RocketChatAssociationModel.USER, user); + + await this.persistence.updateByAssociations([user_association], { atoken }, true); + + } + public async get_access_token(user: IUser): Promise { + const user_association = new RocketChatAssociationRecord(RocketChatAssociationModel.USER, user.id); + + const [result] = await this.persistenceRead.readByAssociation(user_association); + return result ? (result as any).atoken.acess_token : undefined; + + } - await this.persistence.updateByAssociations([userAssociation], { atoken }, true); + public async connect_user_to_calendar_id(calendar: any, user: IUser): Promise { + const user_association = new RocketChatAssociationRecord(RocketChatAssociationModel.USER, user.id); + const calendarid = new RocketChatAssociationRecord(RocketChatAssociationModel.MISC, 'selected calendar'); + await this.persistence.updateByAssociations([user_association, calendarid], { calendar }, true); } - public async getAT(user: IUser): Promise { - const userAssociation = new RocketChatAssociationRecord(RocketChatAssociationModel.USER, user.id); - const [result] = await this.persistenceRead.readByAssociation(userAssociation); - return result ? (result as any).atoken.atoken : undefined; + public async get_preferred_calendar_id(user: IUser): Promise { + const user_association = new RocketChatAssociationRecord(RocketChatAssociationModel.USER, user.id); + const calendarid = new RocketChatAssociationRecord(RocketChatAssociationModel.MISC, 'selected calendar'); + const [result] = await this.persistenceRead.readByAssociations([user_association, calendarid]); + return result ? (result as any).calendar : 'primary'; } -} \ No newline at end of file +} diff --git a/helpers/result.ts b/helpers/result.ts index 511651b..17c6338 100644 --- a/helpers/result.ts +++ b/helpers/result.ts @@ -1,52 +1,45 @@ -import { IModify } from "@rocket.chat/apps-engine/definition/accessors"; +import { IModify } from '@rocket.chat/apps-engine/definition/accessors'; import { SlashCommandContext } from '@rocket.chat/apps-engine/definition/slashcommands'; export async function displayevents(result: any, modify: IModify, context: SlashCommandContext): Promise { - console.log('This is inside result function'); - const summ = result.summary as string; - const starttime = result.start.dateTime as string; - let endtime = result.end.dateTime as string; - - const startdate = new Date(starttime); - const startyear = startdate.getFullYear(); - const startmonth = (startdate.getMonth() + 1); - const datestart = startdate.getDate();//prints expected format. - const starthours = startdate.getHours(); - const startminutes = startdate.getMinutes(); - - const shortcutdate = new Date(endtime); - const yearnew = shortcutdate.getFullYear(); - const monthnew = (shortcutdate.getMonth() + 1); - const datenew = shortcutdate.getDate();//prints expected format. - const hoursend = shortcutdate.getHours(); - const minutesend = shortcutdate.getMinutes(); - let timezone = starttime.split('+', 2); + const summary = result.summary as string; + const start_time = result.start.dateTime as string; + let end_time = result.end.dateTime as string; + + const start_date = new Date(start_time); + const start_year = start_date.getFullYear(); + const start_month = (start_date.getMonth() + 1); + const date_start = start_date.getDate(); + const start_hours = start_date.getHours(); + const start_minutes = start_date.getMinutes(); + + const short_cut_date = new Date(end_time); + const year_new = short_cut_date.getFullYear(); + const month_new = (short_cut_date.getMonth() + 1); + const date_new = short_cut_date.getDate(); + const hours_end = short_cut_date.getHours(); + const minutes_end = short_cut_date.getMinutes(); + let timezone = start_time.split('+', 2); let sign; if (timezone) { sign = '+'; - } - else { - timezone = starttime.split('-', 2); - sign = '-' + } else { + timezone = start_time.split('-', 2); + sign = '-'; } const builder = modify.getCreator().startMessage().setSender(context.getSender()).setRoom(context.getRoom()); try { builder.addAttachment({ title: { - value: summ, + value: summary, }, - text: `is a due event on your calendar starting from date ${datestart}/${startmonth}/${startyear} at ${starthours}:${startminutes} (UTC ${sign}${timezone[1]}) to ${datenew}/${monthnew}/${[yearnew]} at ${hoursend}:${minutesend} (UTC ${sign}${timezone[1]}). [Find and manage the event here](${result.htmlLink}) `, - - - + text: `is a due event on your calendar starting from date ${date_start}/${start_month}/${start_year} at ${start_hours}:${start_minutes}(UTC ${sign}${timezone[1]}) to ${date_new}/${month_new}/${[year_new]} at ${hours_end}:${minutes_end} (UTC ${sign}${timezone[1]}). [Find and manage the event here](${result.htmlLink}) `, }); await modify.getCreator().finish(builder); } catch (e) { this.app.getLogger().error('Failed displaying events', e); builder.setText('An error occurred when sending the events as message :disappointed_relieved:'); } - - -} \ No newline at end of file +}