Skip to content

Commit

Permalink
Added caching + Templater support + Color Fix
Browse files Browse the repository at this point in the history
  • Loading branch information
YukiGasai committed Aug 8, 2022
1 parent 32b8039 commit 3bb4285
Show file tree
Hide file tree
Showing 13 changed files with 262 additions and 128 deletions.
2 changes: 1 addition & 1 deletion manifest.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"id": "obsidian-google-calendar",
"name": "Obsidian Google Calendar",
"version": "1.1.1",
"version": "1.1.2",
"minAppVersion": "0.12.0",
"description": "Interact with your Google Calendar from Inside Obsidian",
"author": "YukiGasai",
Expand Down
2 changes: 1 addition & 1 deletion package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "obsidian-sample-plugin",
"version": "1.1.1",
"version": "1.1.2",
"description": "Interact with your Google Calendar from Inside Obsidian",
"main": "main.js",
"scripts": {
Expand Down
23 changes: 16 additions & 7 deletions src/GoogleCalendarPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import {
import { googleListCalendars } from "./googleApi/GoogleListCalendars";
import { CalendarsListModal } from "./modal/CalendarsListModal";
import { googleListTodayEvents } from "./googleApi/GoogleListEvents";
import { getGoogleColors } from "./googleApi/GoogleColors";
import { checkEditorForCodeBlocks } from "./helper/CheckEditorForCodeBlocks";
import { DayCalendarView, VIEW_TYPE_GOOGLE_CALENDAR_DAY } from "./view/DayCalendarView";
import { MonthCalendarView, VIEW_TYPE_GOOGLE_CALENDAR_MONTH } from "./view/MonthCalendarView";
Expand All @@ -32,9 +33,11 @@ const DEFAULT_SETTINGS: GoogleCalendarPluginSettings = {

export default class GoogleCalendarPlugin extends Plugin {
settings: GoogleCalendarPluginSettings;

overwriteCache = false;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
coreTemplatePlugin:any;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
templatePlugin:any;
templaterPlugin:any;

initView = async (viewId:string): Promise<void> => {
if (
Expand All @@ -55,17 +58,23 @@ export default class GoogleCalendarPlugin extends Plugin {
onLayoutReady = ():void => {
//Get the template plugin to run their commands
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const templatePlugin = (this.app as any).internalPlugins?.plugins["templates"];
if(templatePlugin && templatePlugin.enabled){
this.templatePlugin = templatePlugin;
const coreTemplatePlugin = (this.app as any).internalPlugins?.plugins["templates"];
if(coreTemplatePlugin && coreTemplatePlugin.enabled){
this.coreTemplatePlugin = coreTemplatePlugin;
}

// eslint-disable-next-line @typescript-eslint/no-explicit-any
const templaterPlugin = (this.app as any).plugins.plugins["templater-obsidian"];
if(templaterPlugin && templaterPlugin._loaded){
this.templaterPlugin = templaterPlugin;
}

checkForEventNotes(this);
}

async onload(): Promise<void> {
await this.loadSettings();

await getGoogleColors(this);
this.app.workspace.onLayoutReady(this.onLayoutReady);


Expand Down Expand Up @@ -168,7 +177,7 @@ export default class GoogleCalendarPlugin extends Plugin {
name: "Insert Google Event CodeBlock",
editorCallback: (editor: Editor) => {
editor.replaceRange(
"```gEvent\ndate:today\ntype:self\n```",
"```gEvent\ndate:"+window.moment().format("YYYY-MM-DD")+"\ntype:day\n```",
editor.getCursor()
);
},
Expand Down
83 changes: 35 additions & 48 deletions src/googleApi/GoogleColors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,65 +8,52 @@
*/

import type { GoogleEvent } from "../helper/types";
import type GoogleCalendarPlugin from './../GoogleCalendarPlugin';

export function googleCalendarColors(): string[] {
return [
"#ac725e",
"#d06b64",
"#f83a22",
"#fa573c",
"#ff7537",
"#ffad46",
"#42d692",
"#16a765",
"#7bd148",
"#b3dc6c",
"#fbe983",
"#fad165",
"#92e1c0",
"#9fe1e7",
"#9fc6e7",
"#4986e7",
"#9a9cff",
"#b99aff",
"#c2c2c2",
"#cabdbf",
"#cca6ac",
"#f691b2",
"#cd74e6",
"#a47ae2",
];
}
const calendarColors = new Map<string, string>();
const eventColors = new Map<string, string>();

export function googleEventColors(): string[] {
return [
"#a4bdfc",
"#7ae7bf",
"#dbadff",
"#ff887c",
"#fbd75b",
"#ffb878",
"#46d6db",
"#e1e1e1",
"#5484ed",
"#51b749",
"#dc2127",
];
}
export async function getGoogleColors(plugin:GoogleCalendarPlugin):Promise<void> {

const requestHeaders: HeadersInit = new Headers();
requestHeaders.append("Content-Type", "application/json");

const response = await fetch(`https://www.googleapis.com/calendar/v3/colors?key=${plugin.settings.googleApiToken}`, {
method: "GET",
headers: requestHeaders
});

const colorData = await response.json();

for (let i = 1; ; i++) {
const color = colorData.calendar[i+""]?.background;
if(!color)break;

calendarColors.set(i+"", color)
}

for (let i = 1; ; i++) {
const color = colorData.event[i+""]?.background;
if(!color)break;

eventColors.set(i+"", color)
}
}

/**
* This function just returns the true color of an event
* @param event to get the color from
* @returns a hex color string
*/
export function getColorFromEvent(event: GoogleEvent): string {
if(event.colorId) {
return googleEventColors()[event.colorId]
}else if( event.parent.colorId ){
return googleCalendarColors()[event.parent.colorId]

if(event.colorId && eventColors.has(event.colorId)) {
return eventColors.get(event.colorId);

}else if( event.parent.colorId && calendarColors.has(event.parent.colorId)){
return calendarColors.get(event.parent.colorId);

} else {
return "#a4bdfc"
}

}
44 changes: 37 additions & 7 deletions src/googleApi/GoogleListEvents.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type {
EventCacheValue,
GoogleCalander,
GoogleEvent,
GoogleEventList,
Expand All @@ -12,6 +13,9 @@ import { googleListCalendars } from "./GoogleListCalendars";
import ct from 'countries-and-timezones'


const cachedEvents = new Map<string, EventCacheValue>();


const dateToTimeParam = (date:string, tz:string) :string => {
return encodeURIComponent(`${date}T00:00:00${tz}`);
}
Expand All @@ -32,6 +36,30 @@ export async function googleListEventsByCalendar(
endDate?: moment.Moment
): Promise<GoogleEvent[]> {

//Turn dates into strings for request and caching
const timezone = ct.getTimezone(googleCalander.timeZone);

const startString = dateToTimeParam(date.format('YYYY-MM-DD'),timezone.dstOffsetStr);
let endString = "";
if(endDate){

endString = dateToTimeParam(endDate.format('YYYY-MM-DD'),timezone.dstOffsetStr);

}else{
endDate = date.clone().add(1, "day")
endString = dateToTimeParam(endDate.format('YYYY-MM-DD'),timezone.dstOffsetStr)
}

const cacheKey:string = JSON.stringify({start: startString, end: endString, calendar: googleCalander.id});


if(cachedEvents.has(cacheKey) && !plugin.overwriteCache){
const {events, updated} = cachedEvents.get(cacheKey);
if(updated.clone().add(plugin.settings.refreshInterval, "second").isAfter(moment())){
return events;
}
}

let totalEventList: GoogleEvent[] = [];
let tmpRequestResult: GoogleEventList;
const resultSizes = 2500;
Expand All @@ -43,7 +71,7 @@ export async function googleListEventsByCalendar(
);
requestHeaders.append("Content-Type", "application/json");

const timezone = ct.getTimezone(googleCalander.timeZone);


try {
do {
Expand All @@ -54,12 +82,8 @@ export async function googleListEventsByCalendar(
requestUrl += `&maxResults=${resultSizes}`;
requestUrl += `&singleEvents=True`;
requestUrl += `&orderBy=startTime`;
requestUrl += `&timeMin=${dateToTimeParam(date.format('YYYY-MM-DD'), timezone.dstOffsetStr)}`

// TODO This could lead to problems displaying events at the wrong dates

const tomorrow = (endDate ?? date).clone().add(1, "day").format('YYYY-MM-DD');
requestUrl += `&timeMax=${dateToTimeParam(tomorrow, timezone.dstOffsetStr)}`;
requestUrl += `&timeMin=${startString}`
requestUrl += `&timeMax=${endString}`;


if (tmpRequestResult && tmpRequestResult.nextPageToken) {
Expand Down Expand Up @@ -91,6 +115,8 @@ export async function googleListEventsByCalendar(
return startA.isBefore(startB, "minute") ? -1 : 1;
})

cachedEvents.set(cacheKey, {events: totalEventList, updated:moment()})

return totalEventList;
} catch (error) {
console.log(error);
Expand Down Expand Up @@ -127,6 +153,10 @@ export async function googleListEvents(
return startA.isBefore(startB, "minute") ? -1 : 1;
})

if(plugin.overwriteCache){
plugin.overwriteCache = false;
}

return eventList;
} catch (error) {
console.log(error);
Expand Down
3 changes: 0 additions & 3 deletions src/googleApi/GoogleUpdateEvent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,9 +33,6 @@ export async function googleUpdateEvent(
id = event.id;
}


console.log(id);

//clean the event object to send it to the api directly
const calenderId = event.parent.id;
delete event.parent;
Expand Down
Loading

0 comments on commit 3bb4285

Please sign in to comment.