def setup_service(self): service = CalendarService() service.email = self.options['email'] service.password = self.options['password'] service.source = 'bopen-smithery.recipe.miners:google_calendar-0.1' service.ProgrammaticLogin() return service
def get_service(self, email, password): """ Get an authenticated gdata.calendar.service.CalendarService instance. """ if self.service is None: self.service = CalendarService(email=email, password=password) self.service.ProgrammaticLogin() return self.service
def login(email, password): client = CalendarService() client.email = email client.password = password client.source = 'github-gnome_shell_google_calendar-0.1' client.ProgrammaticLogin() return client
def connectClient(gventPassword, gventEmail, **kw): """ Return a new client instance, already logged in """ client = CalendarService() client.password = gventPassword client.email = gventEmail client.source = AFLOAT_USERAGENT client.ProgrammaticLogin() return client
def __init__(self, email, password): CalendarEventEntry.__init__(self) self.calendar_service = CalendarService() self.calendar_service.email = email self.calendar_service.password = password self.calendar_service.source = 'Google-Calendar_Python_Sample-1.0' try: self.calendar_service.ProgrammaticLogin() except: self.calendar_service = None
def activate(self): IEventCollectorPlugin.activate(self) self.calendar_service = CalendarService() try: self.login() except Exception: # pragma: no cover self.calendars = None else: self.calendars = [ self.get_calendar_uri(calendar) for calendar in self.settings['calendars'] ]
def setup(self): try: calendar_service = CalendarService() calendar_service.email = self.uid calendar_service.password = self.pwd calendar_service.source = self.src calendar_service.ProgrammaticLogin() self.service = calendar_service self.uri = self.feedURI % self.cal self.initialized = True except Exception, e: raise e
def authsub_login(request): if "token" in request.GET: request.session["authsub_token"] = request.GET["token"] update_other_services(request.user, gcal=request.GET["token"]) token = request.GET["token"] # calendar_service = gdata.calendar.service.CalendarService() # calendar_service.SetAuthSubToken(token) # calendar_service.auth_token = token # calendar_service.UpgradeToSessionToken() # feed = calendar_service.GetCalendarListFeed() # for i, a_calendar in enumerate(feed.entry): return render_to_response( "schedule/gcal.html", RequestContext(request, {'token': request.GET["token"]})) calendar_service = CalendarService() authsub_url = calendar_service.GenerateAuthSubURL( request.build_absolute_uri(), GOOGLE_CALENDAR_URI, False, True) return HttpResponseRedirect(authsub_url)
class EntryManager(gdata.calendar.CalendarEventEntry): ''' classdocs ''' def __init__(self, email, password): CalendarEventEntry.__init__(self) self.calendar_service = CalendarService() self.calendar_service.email = email self.calendar_service.password = password self.calendar_service.source = 'Google-Calendar_Python_Sample-1.0' try: self.calendar_service.ProgrammaticLogin() except: self.calendar_service = None def insert_single_event(self, title, start_time=None, end_time=None): self.title = atom.Title(text=title) start_strtime = time.strftime('%Y-%m-%dT%H:%M:%S', start_time.timetuple()) end_strtime = time.strftime('%Y-%m-%dT%H:%M:%S', end_time.timetuple()) self.when.append( gdata.calendar.When(start_time=start_strtime, end_time=end_strtime)) if self.calendar_service != None: try: new_event = self.calendar_service.InsertEvent( self, '/calendar/feeds/default/private/full') return new_event except: return None else: return None
class zoho_integrate(session_handler.BaseSessionHandler): def getTaskList(self): module_name = 'Tasks' authtoken = '7b64e8f8c6a3039b0e8199e02cdcca6b' params = {'authtoken': authtoken, 'scope': 'crmapi'} final_URL = 'https://crm.zoho.com/crm/private/json/' + [ module_name ] + '/getRecords' data = urllib.urlencode(params) request = urllib2.Request(final_URL, data) response = urllib2.urlopen(request) xml_response = response.read() data = json.loads(xml_response) tasks_list = data['response']['result'][module_name]['row'] tasks = [] for task in tasks_list: taskl = {} ts = task['FL'] for point in ts: if point['val'] == 'Subject': #print "subject:",str(point['content']) taskl['title'] = str(point['content']) elif point['val'] == 'ACTIVITYID': #print "id:",str(point['content']) taskl['id'] = str(point['content']) elif point['val'] == 'Due Date': #print "subject:",str(point['content']) taskl['due'] = str(point['content']) + 'T12:00:00.000Z' elif point['val'] == 'Priority': #print "subject:",str(point['content']) taskl['priority'] = str(point['content']) elif point['val'] == 'status': #print "subject:",str(point['content']) taskl['status'] = str(point['content']) elif point['val'] == 'Related To': #print "subject:",str(point['content']) taskl['related_to'] = str(point['content']) elif point['val'] == 'Modified Time': #print "subject:",str(point['content']) taskl['modifiedtime'] = str(point['content']) @decorator.oauth_required def get(self): if decorator.has_credentials(): service = build('tasks', 'v1', http=decorator.http()) http = decorator.http() tasks = service.tasks().list(tasklist='@default').execute( http=decorator.http()) task_det = self.getTaskList() #tasklist = { # 'title': 'Zoho Tasks' #} #result = service.tasklists().insert(body=tasklist).execute(http=decorator.http()) #listID = result['id'] for task in task_det: taskd = { 'title': task['title'], 'due': task['due'], 'priority': task['priority'], 'related_to': task['related_to'], 'modifiedtime': task['modifiedtime'] } try: #print decorator #dbhelper.AddData().addGoogleAuthTokens(username, decorator.http(), str(datetime.datetime.now())) user_details = decorator.http().request( "https://www.googleapis.com/oauth2/v3/userinfo?alt=json", method="POST") #print user_details[0] det = json.loads(user_details[1]) #print det #print "lalal:",det['email'] #user_det = user_details[1][1] #print str(user_det[1]['email']) username = det['email'] dbhelper.AddData().addGoogleAuthTokens( username, decorator.http(), str(datetime.datetime.now())) gid = det['id'] #gmodifiedtime=det['modifiedtime'] tmodifiedtime = task['modifiedtime'] print task['id'] print str(datetime.datetime.now()) print username print gid print task['modifiedtime'] #print gmodifiedtime #while(zid==task['id'] || gid==) #if(gmodifiedtime!=gmodifiedtime && ) dbhelper.AddData().addZohoLogs(task['id'], 'task', str(datetime.datetime.now()), username, gid, task['modifiedtime']) newTask = service.tasks().insert( tasklist='@default', body=taskd).execute(http=decorator.http()) except Exception, e: print str(e), "Entry already thr !! " calendar_service = CalendarService() calendar_service.email = '*****@*****.**' calendar_service.password = '******' calendar_service.source = 'Google-Calendar_Python_Sample-1.0' calendar_service.ProgrammaticLogin() feed = calendar_service.GetCalendarListFeed() for i, a_calendar in enumerate(feed.entry): print '\t%s. %s' % ( i, a_calendar.title.text, ) module_name = 'Events' authtoken = '7b64e8f8c6a3039b0e8199e02cdcca6b' params = {'authtoken': authtoken, 'scope': 'crmapi'} final_URL = "https://crm.zoho.com/crm/private/json/" + module_name + "/getRecords" data = urllib.urlencode(params) request = urllib2.Request(final_URL, data) response = urllib2.urlopen(request) xml_response = response.read() data = json.loads(xml_response) tasks_list = data['response']['result']['Events']['row'] for task in tasks_list: ts = task['FL'] for point in ts: if point['val'] == 'Subject': #print "subject:",str(point['content']) subject = str(point['content']) elif point['val'] == 'Start DateTime': #print "subject:",str(point['content']) start_time = str(point['content']) elif point['val'] == 'ACTIVITYID': print "subject:", str(point['content']) zoho_id = str(point['content']) elif point['val'] == 'Contact Name': #print "subject:",str(point['content']) contact_name = str(point['content']) elif point['val'] == 'Related To': #print "subject:",str(point['content']) related_to = str(point['content']) elif point['val'] == 'End DateTime': #print "subject:",str(point['content']) end_time = str(point['content']) #event = gdata.calendar.CalendarEventEntry() #event.title = atom.Title(text=subject) #event.content = atom.Content(text=contact_name+" related to "+related_to) #event.where.append(gdata.calendar.Where(value_string="Call")) #start_time = time.strptime( start_time,'%Y-%m-%d %H:%M:%S') #end_time = time.strptime(end_time,'%Y-%m-%d %H:%M:%S') #start_time = start_time.strftime('%Y-%m-%dT%H:%M:%S.000Z') start_time = datetime.datetime.strptime( start_time, '%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%dT%H:%M:%S.000') end_time = datetime.datetime.strptime( end_time, '%Y-%m-%d %H:%M:%S').strftime('%Y-%m-%dT%H:%M:%S.000') #end_time = end_time.strftime('%Y-%m-%dT%H:%M:%S.000Z') #print start_time,end_time if start_time is None: # Use current time for the start_time and have the event last 1 hour start_time = time.strftime('%Y-%m-%d %H:%M:%S.000Z', time.gmtime()) end_time = time.strftime( '%Y-%m-%d %H:%M:%S.000Z', time.gmtime(time.time() + 3600)) #event.when.append(gdata.calendar.When(start_time=start_time, end_time=end_time)) print start_time, end_time event = { 'summary': subject, 'location': 'On Call', 'start': { 'dateTime': str(start_time) + '+05:30' }, 'end': { 'dateTime': str(end_time) + '+05:30' } } try: print zoho_id print username print str(datetime.datetime.now()) #dbhelper.AddData().addZohoLogs(zoho_id,'event',str(datetime.datetime.now()),username) #new_event = cal_service.events().insert(calendarId='primary', body=event).execute(http=decorator.http()) #print 'New single event inserted: %s' % (new_event.id.text,) #print '\tEvent edit URL: %s' % (new_event.GetEditLink().href,) #print '\tEvent HTML URL: %s' % (new_event.GetHtmlLink().href,) except Exception, e: print "Error:", str( e), "The calender entry is already entered."
def get(self): variables = { 'url': decorator.authorize_url(), 'has_credentials': decorator.has_credentials() } template = JINJA_ENVIRONMENT.get_template('main.html') self.response.write(template.render(variables)) if decorator.has_credentials(): service = build('calendar', 'v3', http=decorator.http()) http = decorator.http() # Build a service object for interacting with the API. Visit # the Google Cloud Console # to get a developerKey for your own application. #service = build(serviceName='calendar', version='v3', http=http,developerKey='YOUR_DEVELOPER_KEY') module_name = 'Tasks' authtoken = '7b64e8f8c6a3039b0e8199e02cdcca6b' params = {'authtoken': authtoken, 'scope': 'crmapi'} final_URL = "https://crm.zoho.com/crm/private/json/Tasks/getRecords" data = urllib.urlencode(params) request = urllib2.Request(final_URL, data) response = urllib2.urlopen(request) xml_response = response.read() data = json.loads(xml_response) tasks_list = data['response']['result']['Tasks']['row'] tasks = [] for task in tasks_list: taskl = {} ts = task['FL'] for point in ts: if point['val'] == 'Subject': self.response.write(point['content']) """taskl['title'] = str(point['content']) elif point['val'] == 'ACTIVITYID': #print "id:",str(point['content']) taskl['id'] = str(point['content']) elif point['val'] == 'Due Date': #print "subject:",str(point['content']) taskl['due'] = str(point['content'])+'T12:00:00.000Z' elif point['val'] == 'Priority': #print "subject:",str(point['content']) taskl['priority'] = str(point['content']) elif point['val'] == 'status': #print "subject:",str(point['content']) taskl['status'] = str(point['content']) elif point['val'] == 'Related To': #print "subject:",str(point['content']) taskl['related_to'] = str(point['content']) elif point['val'] == 'Modified Time': #print "subject:",str(point['content']) taskl['modifiedtime'] = str(point['content'])""" #dbhelper.AddData().addZohoLogs(task['id'],'task',str(datetime.datetime.now()),username,gid,task['modifiedtime']) #rule = service.acl().get(calendarId='primary', ruleId='ruleId').execute() #print '%s: %s' % (rule['id'], rule['role']) calendar_service = CalendarService() calendar_service.email = '*****@*****.**' calendar_service.password = '******' calendar_service.source = 'Google-Calendar_Python_Sample-1.0' calendar_service.ProgrammaticLogin() feed = calendar_service.GetCalendarListFeed() event = service.events().get( calendarId='primary', eventId='5nhvgdb7s2uiagopo07p141jug').execute() self.response.write(event['status']) self.response.write(event['htmlLink']) self.response.write(event['created']) self.response.write(event['updated']) self.response.write(event['description']) self.response.write(event['status']) self.response.write(event['creator']['displayName']) self.response.write(event['id']) #self.response.write(event['etag']) #self.response.write(event['id']) dbhelper.AddData().addcalendarlogs(event['id'], event['summary'], event['created'], event['updated'], event['description']) calendar_list_entry = service.calendarList().get( calendarId='primary').execute() #self.response.write(calendar_list_entry) """rule = { 'scope': { 'type': 'default', 'value': '', }, 'role': 'read' }""" calendar_list_entry = service.calendarList().get( calendarId='primary').execute() #self.response.write(calendar_list_entry) """page_token = None
dt_start = dt + timedelta(hours=-9) dt_end = dt_start + timedelta(hours=1) event = CalendarEventEntry() event.title = atom.Title(text=self.prefix + title) event.where.append(Where(value_string=place)) event.content = atom.Content(text=type) event.when.append(When( start_time=dt_start.isoformat() + '.000Z', end_time=dt_end.isoformat() + '.000Z')) self.client.InsertEvent(event, url) if __name__=='__main__': cal_url = 'http://www.google.com/calendar/feeds/random_string%40group.calendar.google.com/private/full' client = CalendarService() bs5 = BoyScout(client) client.email = bs5.google_email client.password = bs5.google_passwd client.ProgrammaticLogin() dt = datetime(2009, 1, 20, 15, 00, 00) bs5.post(dt, u'隊集会テスト', u'大田ふれあいセンター', u'ハイキング', cal_url) # __EOF__
if type(dt) is not StringType: raise TypeError('Type of argument is invalid: datetime') _year = int(dt.split('-')[0]) _month = int(dt.split('-')[1]) _day = int(dt.split('-')[2]) return self.getDatetimeFromTuple((_year, _month, _day)) def getDatetimeFromTuple(self, dt=localtime()[:2]): """Convert tuple of datetime to datetime object.""" _dt = datetime(dt[0], dt[1], dt[2]) return True def post(self, dt, title, place, content, url): """ """ if url == '': url = '/calendar/feeds/default/private/full' return True if __name__=='__main__': client = CalendarService() client.email = '*****@*****.**' client.password = '******' client.ProgrammaticLogin() obj = GoogleCalendar() obj
class CalendarObserver(object): """ """ DEFAULT_FEED = '/calendar/feeds/default/private/full' def __init__(self, feed=DEFAULT_FEED, service=None): """ Initialize an instance of the CalendarObserver class. """ self.adapters = {} self.feed = feed self.service = service def observe(self, model, adapter): """ Establishes a connection between the model and Google Calendar, using adapter to transform data. """ self.adapters[model] = adapter signals.post_save.connect(self.on_update, sender=model) signals.post_delete.connect(self.on_delete, sender=model) def observe_related(self, model, related, selector): """ Updates the Google Calendar entry for model when the related model is changed or deleted. Selector should be a function object which accepts an instance of related as a parameter and returns an instance of type model. """ def on_related_update(**kwargs): self.update(model, selector(kwargs['instance'])) signals.post_save.connect(on_related_update, sender=related, weak=False) signals.post_delete.connect(on_related_update, sender=related, weak=False) def on_update(self, **kwargs): """ Called by Django's signal mechanism when an observed model is updated. """ self.update(kwargs['sender'], kwargs['instance']) def on_delete(self, **kwargs): """ Called by Django's signal mechanism when an observed model is deleted. """ self.delete(kwargs['sender'], kwargs['instance']) def get_service(self, email, password): """ Get an authenticated gdata.calendar.service.CalendarService instance. """ if self.service is None: self.service = CalendarService(email=email, password=password) self.service.ProgrammaticLogin() return self.service def get_event(self, service, instance): """ Retrieves the specified event from Google Calendar, or returns None if the retrieval fails. """ event_id = CalendarEvent.objects.get_event_id(instance, self.feed) try: event = service.GetCalendarEventEntry(event_id) except Exception: event = None return event def update(self, sender, instance, retry=False): """ Update or create an entry in Google Calendar for the given instance of the sender model type. """ adapter = self.adapters[sender] email, password = adapter.get_username_password(instance) if adapter.can_save(instance): service = self.get_service(email, password) event = self.get_event(service, instance) or CalendarEventEntry() adapter.get_event_data(instance).populate_event(event) if adapter.can_notify(instance): event.send_event_notifications = SendEventNotifications( value='true') if event.GetEditLink(): try: service.UpdateEvent(event.GetEditLink().href, event) except RequestError: if not retry: self.service = None self.update(sender, instance, retry=True) else: raise else: new_event = service.InsertEvent(event, self.feed) CalendarEvent.objects.set_event_id(instance, self.feed, new_event.id.text) def delete(self, sender, instance): """ Delete the entry in Google Calendar corresponding to the given instance of the sender model type. """ adapter = self.adapters[sender] email, password = adapter.get_username_password(instance) if adapter.can_delete(instance): service = self.get_service(email, password) event = self.get_event(service, instance) if event: if adapter.can_notify(instance): event.send_event_notifications = SendEventNotifications( value='true') service.DeleteEvent(event.GetEditLink().href) CalendarEvent.objects.delete_event_id(instance, self.feed)
class GoogleCalendarPlugin(IEventCollectorPlugin): default_settings = { 'username': '******', 'password': '******', 'calendars': ['default'] } def activate(self): IEventCollectorPlugin.activate(self) self.calendar_service = CalendarService() try: self.login() except Exception: # pragma: no cover self.calendars = None else: self.calendars = [ self.get_calendar_uri(calendar) for calendar in self.settings['calendars'] ] def login(self, username=None, password=None): if username is None or password is None: username = self.settings['username'] password = self.settings['password'] try: self.calendar_service.ClientLogin(username=username, password=password, source='Alarmclock Plugin') except BadAuthentication: logging.getLogger(__name__).error( "Login failed: check username and password.") raise else: logging.getLogger(__name__).info( "Logged in to Google Calendar Webservice.") def get_calendar_uri(self, name): if name == 'default': return name try: feed = self.calendar_service.GetAllCalendarsFeed() except Exception as e: # pragma: no cover logging.getLogger(__name__).info("Failed to resolve Calendar URI.") logging.getLogger(__name__).error(e) return # pylint: disable=maybe-no-member for calendar in feed.entry: if name in calendar.title.text: return calendar.content.src.split('/')[5].replace('%40', '@') def query(self, start_date, end_date, calendar='default'): query = CalendarEventQuery(calendar, 'private', 'full') query.start_min = str(start_date) query.start_max = str(end_date) logging.getLogger(__name__).info("Querying Google Calendar %s." % calendar) try: return self.calendar_service.CalendarQuery(query) except NotAuthenticated: # pragma: no cover try: self.login() except BadAuthentication: pass else: return self.query(start_date, end_date) def feed_to_events(self, feed): for event in feed.entry: for when in event.when: try: start_time = datetime.strptime( when.start_time.split(".")[0], "%Y-%m-%dT%H:%M:%S") end_time = datetime.strptime( when.end_time.split(".")[0], "%Y-%m-%dT%H:%M:%S") except ValueError: # pragma: no cover # ValueError happens on parsing error. Parsing errors # usually happen for "all day" events since they have # not time, but we do not care about this events. continue event_dict = { 'name': event.title.text, 'start_time': start_time, 'duration': end_time - start_time } reminders = [] for reminder in when.reminder: if reminder.method == "alert": reminders.append( timedelta(minutes=int(reminder.minutes))) if reminders: reminders.sort() event_dict['reminder'] = reminders[-1] for where in event.where: if not where.value_string is None: event_dict['location'] = where.value_string yield Event(**event_dict) def collect(self): if self.calendars is None: # pragma: no cover logging.getLogger(__name__).info( "No Calendars to collect events from.") return for calendar in self.calendars: feed = self.query(calendar=calendar, start_date=str(date.today()), end_date=str(date.today() + timedelta(days=1))) for event in self.feed_to_events(feed): yield event
def refresh_creds(self, credentials, sleep): global gd_client time.sleep(sleep) credentials.refresh(httplib2.Http()) now = datetime.utcnow() expires = credentials.token_expiry expires_seconds = (expires - now).seconds # print ("Expires %s from %s = %s" % (expires,now,expires_seconds) ) if self.service == 'docs': gd_client = DocsService(email='default', additional_headers={ 'Authorization': 'Bearer %s' % credentials.access_token }) elif self.service == 'picasa': gd_client = PhotosService(email='default', additional_headers={ 'Authorization': 'Bearer %s' % credentials.access_token }) elif self.service == 'finance': gd_client = FinanceService(email='default', additional_headers={ 'Authorization': 'Bearer %s' % credentials.access_token }) elif self.service == 'calendar': gd_client = CalendarService(email='default', additional_headers={ 'Authorization': 'Bearer %s' % credentials.access_token }) elif self.service == 'contacts': gd_client = ContactsService(email='default', additional_headers={ 'Authorization': 'Bearer %s' % credentials.access_token }) elif self.service == 'youtube': gd_client = YouTubeService(email='default', additional_headers={ 'Authorization': 'Bearer %s' % credentials.access_token }) elif self.service == 'blogger': gd_client = BloggerService(email='default', additional_headers={ 'Authorization': 'Bearer %s' % credentials.access_token }) d = threading.Thread(name='refresh_creds', target=self.refresh_creds, args=(credentials, expires_seconds - 10)) d.setDaemon(True) d.start() return gd_client