Insert Event in Google Calendar for dynamic dates Using OAuth in Odoo 12.0/Python [complete example code]

I couldn't find any direct documentation when I was working with the insert event functionality to the google calendar. So, I have given the code that was developed for my requirement in python. Hope, it may help to someone who needs more or less the same functionality.

Before starting with the code,  you have to create account in google cloud.

Complete python code

class CalendarEvents(http.Controller):
    SCOPES = ['https://www.googleapis.com/auth/calendar']


odoo.http.HttpRequest.session.__setattr__('credentials', {'token': 'None',
'refresh_token': 'None',
'token_uri': "None",
'client_id': "None",
'client_secret': "None",
'scopes':SCOPES})

def get_client_config(self):
baseroot = request.env['ir.config_parameter'].sudo().get_param('web.base.url')
return { "web": {"client_id": "replace this string with your client_id",
"project_id": "replace this string with your project ID",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://oauth2.googleapis.com/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_secret": "replace this string with your client secret",
"redirect_uris": [baseroot.replace('http', 'https') + "/mysample/calendarevent", baseroot.replace('http', 'https') + "/mysample/oauth2callback"],
},
}

def initiate_credentials(self):
return {'token': 'None',
'refresh_token': 'None',
'token_uri': "None",
'client_id': 'None',
'client_secret': "None",
'scopes': self.SCOPES}

def credentials_to_dict(self, credentials):
return {'token': credentials.token,
'refresh_token': credentials.refresh_token,
'token_uri': "https://oauth2.googleapis.com/token",
'client_id': "replace this string with your client id",
'client_secret': "replace this string with your client secret",
'scopes': self.SCOPES}


def createevent(self, pstartdate, ptimezone, penddate, precurrence, pattendees, peventtitle, plocation, pdescription):
event = {
'summary': peventtitle,
# 'location': plocation,
'description': pdescription,
'start': {
'dateTime': pstartdate,
'timeZone': ptimezone,
},
'end': {
'dateTime': penddate,
'timeZone': ptimezone,
},
'recurrence': precurrence,
'attendees': pattendees,
'reminders': {
'useDefault': False,
'overrides': [
{'method': 'email', 'minutes': 24 * 60},
{'method': 'popup', 'minutes': 10},
],
},
}
return (event)

def get_event_date_time(self):
dt_col = ["10/01/21 0:0:0", "05/02/21 0:0:0", "14/03/21 0:0:0", "20/04/21 0:0:0", "22/05/21 0:0:0", "19/06/21 0:0:0", "11/07/21 0:0:0",
"10/08/21 0:0:0", "08/09/21 0:0:0", "05/10/21 0:0:0", "12/11/21 0:0:0", "18/12/21 0:0:0"]
return(dt_col)

def calculate_end_date(self,p_st_date,region_time):
manupulated_dates={}
mp_st_date=datetime.datetime.strptime(p_st_date, '%d/%m/%y %H:%M:%S')
mp_en_date=datetime.datetime.strptime(p_st_date, '%d/%m/%y %H:%M:%S')
manupulated_dates={
'start_date':mp_st_date,
'end_date':mp_en_date,
}
return(manupulated_dates)

def get_time_details(self):
time_dict={
'st_tm_col' : 'T19:00:00',
'en_tm_col' : 'T20:30:00',
'reg_name' : 'Asia/Calcutta',
}

return(time_dict)


@http.route('/mysample/calendarevent', type='http', auth="public", methods=['GET','POST'], website=True, csrf=False)
def createcalendar(self, **post):
request.session.__setattr__('timezonevalue_demo', post.get('tvalue'))
timezonevalue=post.get('tvalue')
credentials = google.oauth2.credentials.Credentials(**request.session.__getattribute__('credentials'))
if (credentials.client_id != "replace this with your client id" and credentials.client_secret!="replace this with your client secret"):
return werkzeug.utils.redirect('/mysample/authorize?tvalue='+timezonevalue)

service = build('calendar', 'v3', credentials=credentials)
recursrule = [
'RRULE:FREQ=DAILY;COUNT=1'
]
attendees = []
initialdate = self.get_event_date_time()
tmp_time_details = self.get_time_details()

for i in range(12):
tmpdate = self.calculate_end_date(initialdate[i], timezonevalue)
tmpevent = self.createevent(tmpdate['start_date'].strftime('%Y-%m-%d') + tmp_time_details['st_tm_col'] , tmp_time_details['reg_name'], tmpdate['end_date'].strftime('%Y-%m-%d') + tmp_time_details['en_tm_col'], recursrule, attendees, "Sample Event Text", "@ Online", "Sample event description")
event = service.events().insert(calendarId='primary', body=tmpevent).execute()
request.session.__setattr__('credentials',self.initiate_credentials())
return request.render('mysample.eventaddedsuccessfully') #replace with your template name

def encode_dict(self, source_dict):
json_encode = json.dumps(source_dict)
encoded_bytes = base64.urlsafe_b64encode(json_encode.encode("utf-8"))
return str(encoded_bytes, "utf-8")

def decode_dict(self,encoded_string):
decoded_bytes = base64.urlsafe_b64decode(encoded_string)
decoded_string = str(decoded_bytes, "utf-8")
return eval(decoded_string)

@http.route('/mysample/authorize',type='http',auth="public",methods=['GET','POST'],website=True,csrf=False)
def authorize(self,**post):
if request.httprequest.method == "GET":

flow = google_auth_oauthlib.flow.Flow.from_client_config(self.get_client_config(), scopes=self.SCOPES)
baseroot=request.env['ir.config_parameter'].sudo().get_param('web.base.url')
flow.redirect_uri = baseroot.replace('http','https') + "/mysample/oauth2callback"
            authorization_url, state = flow.authorization_url(
state=self.encode_dict({'tvalue': post.get('tvalue')}),
access_type='offline',
include_granted_scopes='true')

return werkzeug.utils.redirect(authorization_url)

@http.route('/mysample/oauth2callback', type='http',auth="public",methods=['GET','POST'],website=True,csrf=False)
def oauth2callback(self,**post):
state = post.get('state')
param_values= self.decode_dict(state)

flow = google_auth_oauthlib.flow.Flow.from_client_config(self.get_client_config(), scopes=self.SCOPES)
baseroot = request.env['ir.config_parameter'].sudo().get_param('web.base.url')
flow.redirect_uri = baseroot.replace('http','https') + "/mysample/oauth2callback"
authorization_response = request.httprequest.url.replace('http://','https://')
flow.fetch_token(authorization_response=authorization_response)
credentials = flow.credentials
request.session.__setattr__('credentials', self.credentials_to_dict(credentials))
tvalue=param_values['tvalue']
return werkzeug.utils.redirect(baseroot.replace('http','https')+"/mysample/calendarevent?tvalue="+tvalue)


How to Work with the above code

1. create a module in your custom addon folder

2. create a controller class

3. copy paste the above code.  do the required changes

4. Start odoo server. Install your module.

5. Then visit the URL 

"your URL/mysample/calendarevent?tvalue=IST"


for any clarification, leave your doubts in comments.  I will try to clarify as much as possible.




Comments

Popular posts from this blog

How to Select a Project for Under Graduation?

From the Creator