Skip to content

Commit

Permalink
Fixed timezone bug in view and create (#23)
Browse files Browse the repository at this point in the history
* Fixed timezone bug in view and create

* Updated webhook and create timezone

* updated create command timezone

* Updated view command time function

* Function for datetime string

* Removed all console logs

* Updated the requested changes
  • Loading branch information
Gautime authored and d-gubert committed Oct 11, 2019
1 parent ff65867 commit 126c724
Show file tree
Hide file tree
Showing 4 changed files with 94 additions and 55 deletions.
1 change: 1 addition & 0 deletions Commands/GCCommands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,3 +29,4 @@ export class GCCommand implements ISlashCommand {

}
}

54 changes: 28 additions & 26 deletions helpers/GSGetter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { ISlashCommand, ISlashCommandPreview, ISlashCommandPreviewItem, SlashCom
import { MessageActionType } from '@rocket.chat/apps-engine/definition/messages/MessageActionType';
import { GoogleCalendarApp } from '../GoogleCalendar';
import { AppPersistence } from '../helpers/persistence';
import { displayevents, refresh_access_token } from '../helpers/result';
import { displayEvents, refresh_access_token, make_time_string } from '../helpers/result';
import { IUser } from '@rocket.chat/apps-engine/definition/users';
import { RocketChatAssociationModel, RocketChatAssociationRecord } from '@rocket.chat/apps-engine/definition/metadata';

Expand Down Expand Up @@ -106,15 +106,14 @@ export class GCGetter {
const minimum_date = dat.toISOString();
const url = `https://www.googleapis.com/calendar/v3/calendars/primary/events?key=${api_key}&showDeleted=false&timeMin=${minimum_date}`;
let api_response = await http.get(url, { headers: { Authorization: `Bearer ${view_token}` } });

if (api_response.statusCode == HttpStatusCode.UNAUTHORIZED) {
const persistence = new AppPersistence(persis, read.getPersistenceReader());
view_token = await refresh_access_token(view_refresh, read, http, modify, context, persis);
api_response = await http.get(url, { headers: { Authorization: `Bearer ${view_token}` } });
}

let timezone = api_response.data.timeZone;
for (let i = 0; i < api_response.data.items.length; i++) {
await displayevents(api_response.data.items[i], modify, context);
await displayEvents(api_response.data.items[i], modify, context, timezone);
}
break;

Expand All @@ -126,19 +125,21 @@ export class GCGetter {
const array = params.split("\"");
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 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 user_info = await read.getUserReader().getById(users_id);

let start_time;
let end_time;
let utc = user_info.utcOffset;
start_time = await make_time_string(array[3], array[5], utc);
end_time = await make_time_string(array[3], array[7], utc);

let 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}` }
'end': { 'dateTime': `${end_time}`, },
'start': { 'dateTime': `${start_time}` }
}
});

Expand All @@ -150,8 +151,8 @@ export class GCGetter {
headers: { 'Authorization': `Bearer ${access_token}`, },
data: {
'summary': `${array[1]}`,
'end': { 'dateTime': `${end_datetime}`, },
'start': { 'dateTime': `${start_datetime}` }
'end': { 'dateTime': `${end_time}`, },
'start': { 'dateTime': `${start_time}` }
}
});
}
Expand All @@ -169,7 +170,7 @@ export class GCGetter {
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);
this.app.getLogger().error('This is the error message:', create_api_response.data.error.message);

try {
message.addAttachment({
Expand Down Expand Up @@ -257,18 +258,18 @@ export class GCGetter {
for (let index = 0; index < all_users_id.length; index++) {
email_ids[index] = all_users_id[index].emails[0].address;
}
await modify.getCreator().finish(message);
let 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();
const users_info = await read.getUserReader().getById(users_id);

let final_start;
let final_end;
let utcoffset = users_info.utcOffset;
final_start = await make_time_string(invite_array[3], invite_array[5], utcoffset);
final_end = await make_time_string(invite_array[3], invite_array[7], utcoffset);

for (let index = 0; index < email_ids.length; index++) {
mapping.push({ email: email_ids[index] });
Expand All @@ -278,9 +279,9 @@ export class GCGetter {
headers: { Authorization: `Bearer ${invite_token}` },
data: {
'summary': `${invite_array[1]}`,
'end': { 'dateTime': `${invite_end_datetime}`, },
'end': { 'dateTime': `${final_end}`, },
'attendees': mapping,
'start': { 'dateTime': `${invitestart_datetime}` }
'start': { 'dateTime': `${final_start}` }
}
});

Expand All @@ -291,9 +292,9 @@ export class GCGetter {
headers: { Authorization: `Bearer ${invite_token}`, },
data: {
'summary': `${invite_array[1]}`,
'end': { 'dateTime': `${invite_end_datetime}`, },
'end': { 'dateTime': `${final_end}`, },
'attendees': mapping,
'start': { 'dateTime': `${invitestart_datetime}` },
'start': { 'dateTime': `${final_start}` },
}
});
}
Expand Down Expand Up @@ -328,3 +329,4 @@ export class GCGetter {
}

}

7 changes: 4 additions & 3 deletions helpers/Webhook.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,17 +7,18 @@ import { get_refresh_token, get_access_token } from '../helpers/result';
export class WebhookEndpoint extends ApiEndpoint {
public path = 'webhook';
public tokenid;
private readonly urli = 'http://localhost:3000/api/apps/public/c759c4f1-a3c1-4202-8238-c6868633ed87/webhook';
private readonly urli = '/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<IApiResponse> {

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

const redirect = await read.getEnvironmentReader().getSettings().getValueById('redirect_uri');
const final_url = redirect + this.urli;
const auth_code = request.query.code;
const url = 'https://www.googleapis.com/oauth2/v4/token';
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', } });
const new_response = await http.post(url, { data: { 'code': `${auth_code}`, 'client_id': `${client_id}`, 'client_secret': `${secret}`, 'redirect_uri': `${final_url}`, 'grant_type': 'authorization_code', } });

if (new_response.statusCode !== HttpStatusCode.OK || !new_response.data) {
console.log('Did not get a valid response', new_response);
Expand Down
87 changes: 61 additions & 26 deletions helpers/result.ts
Original file line number Diff line number Diff line change
@@ -1,41 +1,30 @@
import { IModify, IRead, IHttp, HttpStatusCode, IPersistence } from '@rocket.chat/apps-engine/definition/accessors';
import { IModify, IRead, IHttp, HttpStatusCode, IPersistence, ILogger } from '@rocket.chat/apps-engine/definition/accessors';
import { SlashCommandContext, ISlashCommand } from '@rocket.chat/apps-engine/definition/slashcommands';
import { AppPersistence } from '../helpers/persistence';

export async function displayevents(result: any, modify: IModify, context: SlashCommandContext): Promise<void> {
export async function displayEvents(result: any, modify: IModify, context: SlashCommandContext, time: any): Promise<void> {

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 = start_time.split('-', 2);
sign = '-';
}
const array1 = start_time.split('T');
const array2 = end_time.split('T');

const start_date = array1[0].split('-');
const start_final = array1[1].split(':');

const end_date = array2[0].split('-');
const end_final = array2[1].split(':');
let timezone = time;

const builder = modify.getCreator().startMessage().setSender(context.getSender()).setRoom(context.getRoom());
try {
builder.addAttachment({
title: {
value: summary,
},
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}) `,
text: `is a due event on your calendar starting from date ${start_date[2]}/${start_date[1]}/${start_date[0]} at ${start_final[0]}:${start_final[1]}(${timezone}) to ${end_date[2]}/${end_date[1]}/${end_date[0]} at ${end_final[0]}:${end_final[1]} (${timezone}). [Find and manage the event here](${result.htmlLink}) `,
});
await modify.getCreator().finish(builder);
} catch (e) {
Expand Down Expand Up @@ -64,7 +53,6 @@ export async function refresh_access_token(token: string, read: IRead, http: IHt
const message = modify.getCreator().startMessage().setSender(context.getSender()).setRoom(context.getRoom());

const refresh_response = await http.post(url);
console.log('This is respones from new ref token inside refresh acc-token function:', refresh_response);
if (refresh_response.statusCode == HttpStatusCode.OK) {
const access_token = refresh_response.data.access_token;
const persistence = new AppPersistence(persis, read.getPersistenceReader());
Expand All @@ -73,6 +61,53 @@ export async function refresh_access_token(token: string, read: IRead, http: IHt

return access_token;
} else {
console.log('Encountered error during refreshing access token:', refresh_response.data.error.message);
this.app.getlogger().error('Encountered error during refreshing access token:', refresh_response.data.error.message);
}
}

export function make_time_string(date: string, time: string, utc: number): Promise<string> {

const date_string = date + 'T' + time + 'Z';
const new_date = new Date(date_string);
const datetime = new_date.toISOString();
const datetime_ms = datetime.split(".");

let final_time;
let decimal = Math.abs(utc - Math.floor(utc));
decimal = decimal * 60;
if (utc > 0) {
utc = utc - (decimal / 60);
}
if (utc < 0) {
utc = utc + (decimal / 60);
}

if (utc > 0 && utc < 10) {
if (decimal == 0) {
final_time = datetime_ms[0] + '+0' + utc + ':' + decimal + '0';
} else {
final_time = datetime_ms[0] + '+0' + utc + ':' + decimal;
}
} else if (utc < 0 && utc > -10) {
utc = utc * -1;
if (decimal == 0) {
final_time = datetime_ms[0] + '-0' + utc + ':' + decimal + '0';
} else {
final_time = datetime_ms[0] + '-0' + utc + ':' + decimal;
}
} else if (utc >= 10) {
if (decimal == 0) {
final_time = datetime_ms[0] + '+' + utc + ':' + decimal + '0';
} else {
final_time = datetime_ms[0] + '+' + utc + ':' + decimal;
}
} else {

if (decimal == 0) {
final_time = datetime_ms[0] + utc + ':' + decimal + '0';
} else {
final_time = datetime_ms[0] + utc + ':' + decimal;
}
}
return final_time;
}

0 comments on commit 126c724

Please sign in to comment.