Skip to content

Commit

Permalink
Create Private Events (#3)
Browse files Browse the repository at this point in the history
* Create event implemented

* Error message if event creation fails

* Added redirect uri config setting

* Added link with each view event for update/delete

* Create LICENSE
  • Loading branch information
Gautime authored and d-gubert committed Jun 24, 2019
1 parent 375817a commit 2b456ef
Show file tree
Hide file tree
Showing 9 changed files with 134 additions and 30 deletions.
5 changes: 4 additions & 1 deletion Commands/GCCommands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,6 @@ export class GCCommand implements ISlashCommand {
public async executor(context: SlashCommandContext, read: IRead, modify: IModify, http: IHttp, persis: IPersistence): Promise<void> {



const msg = modify.getCreator().startMessage().setSender(context.getSender()).setRoom(context.getRoom());

try {
Expand All @@ -29,11 +28,15 @@ export class GCCommand implements ISlashCommand {
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());


} 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:');
}

}
}

11 changes: 11 additions & 0 deletions GoogleCalendar.ts
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,17 @@ export class GoogleCalendarApp extends App {
i18nDescription: 'Customize_Calendar_SecretKey',
});

await configuration.settings.provideSetting({
id: 'redirect_uri',
type: SettingType.STRING,
packageValue: '',
required: true,
public: false,
i18nLabel: 'Customize_Redirect_uri',
i18nDescription: 'Customize_Redirect_URI',
});


await configuration.slashCommands.provideSlashCommand(new GCCommand(this));

}
Expand Down
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2019 Rocket.Chat

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
8 changes: 7 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,13 @@ Integrates google calendar with your Rocket.Chat server.

#### Useful Slashcommands
* `/calendar auth` : To authenticate to your gmail account.
* `/calendar view` : Once the authentication is successful, you can use this command to view the private events on your calendar.

* `/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.




Expand Down
107 changes: 84 additions & 23 deletions helpers/GSGetter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,16 @@ import { AppPersistence } from '../helpers/persistence';
import { stringify } from 'querystring';
import { displayevents } from '../helpers/result';

import { stringify } from 'querystring';
import { displayevents } from '../helpers/result';


enum Command {
connect = 'auth',
lgout = 'logout',
show = 'view',
make = 'create',
}

enum Command {
connect = 'auth',
Expand All @@ -18,34 +28,31 @@ enum Command {


export class GCGetter {
private readonly SCOPES = "https://www.googleapis.com/auth/calendar.readonly";
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;






public async login(logger: ILogger, read: IRead, http: IHttp, modify: IModify, context: SlashCommandContext, persis: IPersistence): Promise<void> {


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());


let signedin: boolean = false;
const msg = modify.getCreator().startMessage().setSender(context.getSender()).setRoom(context.getRoom());


const [parame] = context.getArguments();
switch (parame) {
case (Command.connect): {
const msg = modify.getCreator().startMessage().setSender(context.getSender()).setRoom(context.getRoom());
const response = (`${this.urli}client_id=${Client_id}&redirect_uri=http://localhost:3000/api/apps/public/c759c4f1-a3c1-4202-8238-c6868633ed87/webhook&scope=https://www.googleapis.com/auth/calendar.readonly&prompt=consent&access_type=offline&response_type=code`);

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`);

try {
msg.setText(response);
Expand All @@ -55,31 +62,32 @@ export class GCGetter {
msg.setText('An error occurred when trying to send the login url:disappointed_relieved:');

modify.getNotifier().notifyUser(context.getSender(), msg.getMessage());

}
}
break;

case (Command.lgout): {
case (Command.lgout):

const msg = modify.getCreator().startMessage().setSender(context.getSender()).setRoom(context.getRoom());
const response = `https://www.google.com/accounts/Logout?continue=https://appengine.google.com/_ah/logout?continue=http://localhost:3000`;
const mesg = modify.getCreator().startMessage().setSender(context.getSender()).setRoom(context.getRoom());
const logresponse = `https://www.google.com/accounts/Logout?continue=https://appengine.google.com/_ah/logout?continue=${redirect}`;
try {
msg.setText(response);
await modify.getCreator().finish(msg);
mesg.setText(logresponse);
await modify.getCreator().finish(mesg);
} 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 sending logout url', e);
mesg.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(), mesg.getMessage());
}


const atoken = await persistence.getAT(context.getSender());

console.log('This is the access token inside GCGetter:', atoken);
// console.log('This is the access token inside GCGetter:', atoken);

}
break;

case (Command.show): {
case (Command.show):

const newatoken = await persistence.getAT(context.getSender());

Expand All @@ -94,8 +102,61 @@ export class GCGetter {

}

}
break;

case (Command.make):

const createatoken = await persistence.getAT(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 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 edate = array[3] + 'T' + array[7];
const enddate = new Date(edate);
const enddatetime = enddate.toISOString();


// console.log('Start date and time in ISO format is: ',startdatetime,'end date time:',enddatetime);

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({

text: `Event has been created. Find the event at [${createresponse.data.summary}](${createresponse.data.htmlLink}) `,


});
await modify.getCreator().finish(msg);
} catch (e) {
this.app.getLogger().error('Failed creating events', e);
msg.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);

try {
msg.addAttachment({

text: `Event could not be created. It encountered the error: ${createresponse.data.error.message}. Please try again. `,


});
await modify.getCreator().finish(msg);
} catch (e) {
this.app.getLogger().error('Failed creating events', e);
msg.setText('An error occurred when sending the event creation as message :disappointed_relieved:');
}
}
break;
}


Expand Down
1 change: 1 addition & 0 deletions helpers/Webhook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -51,3 +51,4 @@ export class WebhookEndpoint extends ApiEndpoint {
}

}

3 changes: 0 additions & 3 deletions helpers/persistence.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,4 @@ export class AppPersistence {
return result ? (result as any).atoken.atoken : undefined;

}



}
3 changes: 2 additions & 1 deletion helpers/result.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ export async function displayevents(result: any, modify: IModify, context: Slash
title: {
value: summ,
},
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]}) `,
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}) `,



});
Expand Down
5 changes: 4 additions & 1 deletion i18n/en.json
Original file line number Diff line number Diff line change
Expand Up @@ -6,5 +6,8 @@
"calendar_secret_key": "Your Secret Key",
"Customize_Calendar_SecretKey": "Insert your Secret Key from API Console",
"Calendar_Command_Description": "/calendar [subcommand]",
"Calendar_login": "/calendar {action}"

"Calendar_login": "/calendar {action}",
"redirect_uri": "Enter your server address"

}

0 comments on commit 2b456ef

Please sign in to comment.