Ejemplo n.º 1
0
 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
Ejemplo n.º 3
0
 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
Ejemplo n.º 4
0
    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']
            ]
Ejemplo n.º 5
0
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)
Ejemplo n.º 6
0
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."
Ejemplo n.º 7
0
    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
Ejemplo n.º 8
0
    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