File size: 5,976 Bytes
6b95d78
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
from gcsa.google_calendar import GoogleCalendar
from gcsa.event import Event
from datetime import datetime
from pathlib import Path
import pickle
import os.path
from google.auth.transport.requests import Request
from google_auth_oauthlib.flow import InstalledAppFlow

BASE_DIR = Path(__file__).parent


class GoogleCalendarAPI:
    def __init__(self) -> None:
        self.scopes = ['https://www.googleapis.com/auth/calendar']
        self.calendar = self.create_service()

    def create_service(self):
        """create service with credentials set up and token file,
        Note:
            If you use a new machine or browser, just delete the `token.pickle`
                in folder `credentials`. And then run application again,
                a new `sign in cookie pop up` would appear and loging in.
                After logged, a new `token.pickle` would be created
                automatically in folder credentials.

        Returns:
            GoogleCalendar: Calendar object
        """
        creds = None

        if os.path.exists(Path(BASE_DIR, 'credentials', 'token.pickle')):
            with open(
                Path(BASE_DIR, 'credentials', 'token.pickle'), 'rb'
            ) as token:
                creds = pickle.load(token)

        if not creds or not creds.valid:
            if creds and creds.expired and creds.refresh_token:
                creds.refresh(Request())
            else:
                flow = InstalledAppFlow.from_client_secrets_file(
                    Path(BASE_DIR, 'credentials', 'credentials.json'),
                    self.scopes
                )
                creds = flow.run_local_server(port=0)

            with open(
                Path(BASE_DIR, 'credentials', 'token.pickle'), 'wb'
            ) as token:
                pickle.dump(creds, token)

        try:
            calendar = GoogleCalendar('primary', credentials=creds)
        except Exception as e:
            print(e)
            return None

        return calendar

    def setup_event(
        self,
        event_name: str,
        event_start_time: str,
        event_end_time: str,
        attendees: list = [],
        event_description: str = None
    ):
        """Set up event to calendar from given information from user

        Args:
            event_name (str): The title of event,
                you could generate out by yourself if user not provided
            event_start_time (str): The start time string of event that user
                want to set calendar. Format is "%Y-%m-%d %H:%M"
                Example:
                    "2001-01-02 13:55": which means 13:55 at 1s Feburary 2001
            event_end_time (str): The end time string of event that user
                want to set calendar. Format is "%Y-%m-%d %H:%M"
                Example:
                    "2001-01-02 14:30": which means 14:30 at 1s Feburary 2001
            attendees (list, optional): List of attendee's email.
                Defaults to [].
            event_description (str, optional): The desription of event.
                Defaults to None.

        Returns:
            str: result status of this action
        """

        try:
            event = Event(
                event_name,
                start=datetime.strptime(event_start_time, "%Y-%m-%d %H:%M"),
                end=datetime.strptime(event_end_time, "%Y-%m-%d %H:%M"),
                attendees=attendees,
                description=event_description,
                default_reminders=True
            )
            self.calendar.add_event(event)
        except Exception as ex:
            return f"There is a problem while setting calendar, {ex}"
        return "Set calendar successfully !"

    def get_events(
        self,
        year_range: list,
        month_range: list,
        day_range: list,
        hour_range: list
    ) -> list:
        """To get out all the events in user's calendar with
            given range of time

        Args:
            year_range (list): Range year that user need to require
                Example:
                    [2023, 2025]: Range from 2023 to 2025
            month_range (list): Range month that user need to require
                Example:
                    [1, 5]: Range from January to May
            day_range (list): Range day that user need to require
                Example:
                    [1, 31]: Range from 1st to 31st
            day_range (list): Range hour that user need to require,
                if user want to require in same date, hour must be [0, 23]
                Example:
                    [0, 23]: Range from 0am to 23pm

        Returns:
            list: list of events found in user calendar with given range time
        """
        start_date = datetime(
            year=year_range[0],
            month=month_range[0],
            day=day_range[0],
            hour=hour_range[0]
        )
        end_date = datetime(
            year=year_range[1],
            month=month_range[1],
            day=day_range[1],
            hour=hour_range[1]
        )

        return [event for event in self.calendar.get_events(
            time_min=start_date, time_max=end_date
        )]

    def get_events_by_date(
        self,
        start_date: datetime,
        end_date: datetime
    ) -> list:
        return [event for event in self.calendar.get_events(
            time_min=start_date, time_max=end_date
        )]


if __name__ == "__main__":
    calendar = GoogleCalendarAPI()
#     # Sample set up event on calendar
#     calendar.setup_event(
#         event_name="This is sample buy signal",
#         event_start_time="02/17/2024 14:33",
#         event_end_time="02/17/2024 15:30",
#         attendees=['ndthinh0201@gmail.com', 'camphong.work@gmail.com'],
#         event_description="""
#             W trend has found in 7 days past and today figure out
#                 the rise significantly, better to buy.
#         """
#     )