Skip to content

Instantly share code, notes, and snippets.

@rubypirate
Created November 25, 2016 10:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rubypirate/35d6d5bac091247af847cc45dfb4bfdb to your computer and use it in GitHub Desktop.
Save rubypirate/35d6d5bac091247af847cc45dfb4bfdb to your computer and use it in GitHub Desktop.
module GoogleCore
ICAL = 0
SYNC_TWO_WAYS = 0
SYNC_TO_GCAL = 1
SYNC_TO_BB = 2
### Google Calendar Syncing Options
IGNORE_CHANGES = 0
APPLY_TO_BB = 1
RECREATE_ON_GCAL = 2
APPLY_TO_BB_AND_RECREATE = 3
def google_busy
return nil if !google_cal
tz = company.time_zone.to_s.length > 0 ? company.time_zone : get_time_zone
client = company.conf_connection.init_client
if client
service = client.discovered_api('calendar', 'v3')
begin
result = client.execute(
:api_method => service.events.list,
:parameters => {'calendarId' => google_cal, 'timeZone' => tz, 'timeMin' => (Time.now - 10.days).utc.iso8601, 'timeMax' => 2.months.from_now.utc.iso8601 },
:headers => {'Content-Type' => 'application/json'})
rescue Exception => e
end
if result && result.body
body = JSON.parse(result.body.force_encoding("utf-8"))
items = (body['items'] && body['items'].any?) ? body['items'] : []
if company.conf_connection.email["gcal_sync_options"] != IGNORE_CHANGES
check_for_moved_bookings items
end
out = ""
items.each_with_index do |item, i|
next if item['transparency'] && item['transparency'] == 'transparent'
if item['summary'].to_s.include?('BBID:')
next
end
if item['start'] && item['start']['dateTime'] && item['start']['dateTime'] != ''
d1 = item['start']['dateTime'].to_datetime
d2 = item['end']['dateTime'].to_datetime
out += d1.utc.strftime("%Y%m%dT%H%M%SZ") + "-" + d2.utc.strftime("%Y%m%dT%H%M%SZ") + "\n"
out += "-" + item['summary'].to_s.gsub(/\n/, " ") + "\n"
end
end # each end
end
return out
end
end
def google_freebusy
return nil if !google_cal
tz = company.time_zone.to_s.length > 0 ? company.time_zone : get_time_zone
client = company.conf_connection.init_client
if client
service = client.discovered_api('calendar', 'v3')
result = client.execute(
:api_method => service.freebusy.query,
:body_object => { :timeMin => (Time.now - 10.days).utc.iso8601,
:timeMax => 2.months.from_now.utc.iso8601, # 2 years at the moment - could make it configuarable later! ... had to limit it to 2 months as over than that google will error with message The requested time range is too long
:items => [{id: google_cal}]
},
:headers => {'Content-Type' => 'application/json'})
body = JSON.parse(result.body.force_encoding("utf-8"))
busy_days = body['calendars'][google_cal]['errors'] ? [] : body['calendars'][google_cal]['busy']
out = ""
busy_days.each_with_index do |day, i|
d1 = day['start'].to_datetime
d2 = day['end'].to_datetime
out += d1.utc.strftime("%Y%m%dT%H%M%SZ") + "-" + d2.utc.strftime("%Y%m%dT%H%M%SZ") + "\n"
end
return out
end
end
def google_add_event start_date_time=(Time.now + 2.days).utc.iso8601, end_date_time=(Time.now + 2.days).utc.iso8601, summary='', body=nil, location='', url=nil
return {} if company.conf_connection.email["gcal_sync"] == SYNC_TO_BB
client = company.conf_connection.init_client
return {} unless client
service = client.discovered_api('calendar', 'v3')
# HACK FOR AVENUES CUSTOM GCAL TITLE
if MULTI_SITE && (MultiSite.respond_to?("get_shard") && (MultiSite.get_shard == "mtus_avenues_dev" || MultiSite.get_shard == "mtus_avenues_staging" || MultiSite.get_shard == "mtus_avenues_prod"))
summary = "#{summary}"
body = summary unless body
else
summary = "BBID: #{summary}"
body = summary unless body
end
begin
result = client.execute(
:api_method => service.events.insert,
:parameters => {'calendarId' => self.google_cal},
:body_object => {
:start => {:dateTime => DateTime.parse(start_date_time).utc.iso8601},
:end => {:dateTime => DateTime.parse(end_date_time).utc.iso8601},
#:recurrence => ['RRULE:FREQ=WEEKLY;UNTIL=20110701T100000-07:00'],
#'attendees' => [:email=>'a@bc.com'],
:location => location,
:summary => summary,
:description => body,
:source =>{:url=>url, :title=>"Edit Appointment on BookingBug"}
},
:headers => {'Content-Type' => 'application/json'})
return body = JSON.parse(result.body.force_encoding("utf-8"))
rescue Exception => error
# Airbrake exception
Airbrake.notify(error,
:backtrace => error.backtrace,
:error_class => error.class,
:error_message => error.message,
:parameters => "#{start_date_time} - #{end_date_time} - #{summary} - #{location} - #{url} - #{self.google_cal}"
)
end
return {}
end
def google_edit_event event_id, start_date_time=(Time.now + 2.days).utc.iso8601, end_date_time=(Time.now + 2.days).utc.iso8601, summary='', location=''
return false if company.conf_connection.email["gcal_sync"] == SYNC_TO_BB
client = company.conf_connection.init_client
return false unless client
service = client.discovered_api('calendar', 'v3')
google_delete_event event_id
# HACK FOR AVENUES CUSTOM GCAL TITLE
if MULTI_SITE && (MultiSite.respond_to?("get_shard") && (MultiSite.get_shard == "mtus_avenues_dev" || MultiSite.get_shard == "mtus_avenues_staging" || MultiSite.get_shard == "mtus_avenues_prod"))
summary = "#{summary}"
else
summary = "BBID: #{summary}"
end
begin
result = client.execute(
:api_method => service.events.insert,
:parameters => {'calendarId' => self.google_cal, 'eventId' => event_id},
:body_object => {
:start => {:dateTime => DateTime.parse(start_date_time).utc.iso8601},
:end => {:dateTime => DateTime.parse(end_date_time).utc.iso8601},
#:recurrence => ['RRULE:FREQ=WEEKLY;UNTIL=20110701T100000-07:00'],
#'attendees' => [:email=>'a@bc.com'],
:location => location,
:summary => summary
},
:headers => {'Content-Type' => 'application/json'})
return JSON.parse result.body.force_encoding("utf-8")
rescue Exception => error
# Airbrake exception
Airbrake.notify(error,
:backtrace => error.backtrace,
:error_class => error.class,
:error_message => error.message
)
end
end
def google_delete_event event_id
return [] if company.conf_connection.email["gcal_sync"] == SYNC_TO_BB
client = company.conf_connection.init_client
return [] unless client
service = client.discovered_api('calendar', 'v3')
begin
result = client.execute(
:api_method => service.events.delete,
:parameters => {'calendarId' => self.google_cal, 'eventId' => event_id},
:headers => {'Content-Type' => 'application/json'})
return result.body.force_encoding("utf-8") if result && result.body
rescue Exception => error
# Airbrake exception
Airbrake.notify(error,
:backtrace => error.backtrace,
:error_class => error.class,
:error_message => error.message
)
end
end
def google_all_events calendar_id
client = init_client
return [] unless client
service = client.discovered_api('calendar', 'v3')
result = client.execute(
:api_method => service.events.list,
:parameters => {'calendarId' => calendar_id},
:headers => {'Content-Type' => 'application/json'})
return JSON.parse(result.body.force_encoding("utf-8")) if result && result.body
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment