Returns Google calendar items of a specific user

    :param int user_id: (Humhub) User ID
    :return: Busy appointments
    :rtype: list
174419
def get_google_calendar_items(user_id):
    
    global client_id
    global client_secret

    with open('tokens.json') as f:
        try:
            data = json.load(f)
        except ValueError:
            raise AccessTokenCredentialsError
    credentials = GoogleCredentials(
        data[str(user_id)]['access_token'],
        client_id,
        client_secret,
        data[str(user_id)]['refresh_token'],
        None,
        "https://accounts.google.com/o/oauth2/token",
        'my-user-agent/1.0'
    )
    service = build('calendar', 'v3', credentials=credentials)

    page_token = None
    # get utc time diff
    utcdiff = (time.mktime(time.localtime()) - time.mktime(time.gmtime())) / 60 / 60
    # check if diff is full-hour or half
    minutes = utcdiff * 2
    if minutes % 2: # full hour
        minutesoffset = '30'
    else: # half hour
        minutesoffset = '00'
    # check sign
    if utcdiff < 0:
        sign = '-'
    else:
        sign = '+'
    utcdiff = str(abs(int(utcdiff))).zfill(2)
    appointments = []
    while True:
        try:
            calendar_list = service.events().list(
                calendarId='primary', # TODO handle other calendars too
                timeMin=time.strftime("%Y-%m-%dT00:00:00")+sign+utcdiff+':'+minutesoffset,
                timeMax=time.strftime("%Y-%m-%dT23:59:59")+sign+utcdiff+':'+minutesoffset,
                pageToken=page_token).execute()
        except AccessTokenCredentialsError:
            # re-auth
            raise AccessTokenCredentialsError

        # collect busy appointments
        for calendar_list_entry in calendar_list['items']:
            appointments.append({"start": calendar_list_entry['start']['dateTime'][:-6], "end": calendar_list_entry['end']['dateTime'][:-6]}) # remove utc diff
        page_token = calendar_list.get('nextPageToken')
        if not page_token:
            break

    return appointments


    @app.route('/login')
    def login():
        """
        Handles login process, gets auth url

        :return: Redirect to auth url
        """
        global client
        auth_uri = client.step1_get_authorize_url()
        return redirect(auth_uri)


    @app.route('/oauth2callback')
    def oauth2callback():
        """
        Handles token exchange, saves token

        :return: Redirect to index
        """
        code = request.args.get('code')
        credentials = client.step2_exchange(code)

        # save credentials
        with open('tokens.json') as f:
            try:
                data = json.load(f)
            except ValueError:
                data = {}

        token = {}
        token['refresh_token'] = credentials.refresh_token
        token['access_token'] = credentials.access_token
        token['token_expiry'] = time.mktime(credentials.token_expiry.timetuple()) # read: datetime.fromtimestamp(<timestamp>)
        data[session['user_id']] = token

        # store credentials
        with open('tokens.json', mode='w', encoding='utf-8') as jsonfile:
            json.dump(data, jsonfile)

        # redirect to index
        return redirect(url_for('index'))


    @app.route('/')
    @app.route('/<int:user_id>')
    def index(user_id = 0):
        """
        Main page, displays calendar items if logged in, redirects to login otherwise

        :param int user_id: (Humhub) User ID
        """
        # check user id
        if (user_id == 0):
            if session is not None and 'user_id' in session and session['user_id'] is not None:
                user_id = session['user_id']
            else:
                return "No User ID specified."
        else:
            session['user_id'] = user_id

        # check if token is available for user
        with open('tokens.json') as f:
            try:
                data = json.load(f)
            except ValueError:
                return redirect(url_for('login'))
        body = ""
        if str(user_id) in data:
            global client_id
            global client_secret
            credentials = GoogleCredentials(
                data[str(user_id)]['access_token'],
                client_id,
                client_secret,
                data[str(user_id)]['refresh_token'],
                None,
                "https://accounts.google.com/o/oauth2/token",
                'my-user-agent/1.0'
            )
            #credentials = AccessTokenCredentials(data[str(user_id)]['access_token'], 'my-user-agent/1.0')
            service = build('calendar', 'v3', credentials=credentials)

            page_token = None
            # get utc time diff
            utcdiff = (time.mktime(time.localtime()) - time.mktime(time.gmtime())) / 60 / 60
            # check if diff is full-hour or half
            minutes = utcdiff * 2
            if minutes % 2: # full hour
                minutesoffset = '30'
            else: # half hour
                minutesoffset = '00'
            # check sign
            if utcdiff < 0:
                sign = '-'
            else:
                sign = '+'
            utcdiff = str(abs(int(utcdiff))).zfill(2)
            appointments = []
            while True:
                try:
                    calendar_list = service.events().list(
                        calendarId='primary', # TODO handle other calendars too
                        timeMin=time.strftime("%Y-%m-%dT00:00:00")+sign+utcdiff+':'+minutesoffset,
                        timeMax=time.strftime("%Y-%m-%dT23:59:59")+sign+utcdiff+':'+minutesoffset,
                        pageToken=page_token).execute()
                except AccessTokenCredentialsError:
                    # re-auth
                    return redirect(url_for('login'))

                for calendar_list_entry in calendar_list['items']:
                    appointments.append({"start": calendar_list_entry['start']['dateTime'][:-6], "end": calendar_list_entry['end']['dateTime'][:-6]}) # remove utc diff
                page_token = calendar_list.get('nextPageToken')
                if not page_token:
                    break

            for event in appointments:
                body += json.dumps(event)
        else:
            return redirect(url_for('login'))
        return body
722897
def scheduled_status(self, id):
        
        id = self.__unpack_id(id)
        url = '/api/v1/scheduled_statuses/{0}'.format(str(id))
        return self.__api_request('GET', url)
307560
def list_members(self, list_id):
        
        return [User(user._json) for user in self._client.list_members(list_id=list_id)]
8572
def get_user_contact_lists(self, id, **data):
        
        
        return self.get("/users/{0}/contact_lists/".format(id), data=data)
705505
def get_user(self, id, **data):
        
        
        return self.get("/users/{0}/".format(id), data=data)
367923
def get_user(self, user_id):
        
        if user_id in self._users:
            return self._users.get(user_id)
        else:
            # Load user
            # Save user in cache
            return
1113771
def list_users(self, pattern=None):
        
        request_url = "{}/api/0/users".format(self.instance)
        params = None
        if pattern:
            params = {'pattern': pattern}
        return_value = self._call_api(request_url, params=params)
        return return_value['users']
98684
def fetch_user(id)
      user_data = connection.get("/users/#{id}.json")
      user = user_data && user_data[:user]
      user[:created_at] = Time.parse(user[:created_at])
      user
    end
879471
def get(self, user_id):
        """"""
        user = db.User.find_one(User.user_id == user_id)
        roles = db.Role.all()

        if not user:
            return self.make_response('Unable to find the user requested, might have been removed', HTTP.NOT_FOUND)

        return self.make_response({
            'user': user.to_json(),
            'roles': roles
        }, HTTP.OK)
221422
def get_schedules(profile='pagerduty', subdomain=None, api_key=None):
    '''
    
    '''

    return _list_items(
        'schedules',
        'id',
        profile=profile,
        subdomain=subdomain,
        api_key=api_key,
    )
721808
def get_user_info(self, user_id, **kwargs):
        
        return GetUserInfo(settings=self.settings, **kwargs).call(
            user_id=user_id,
            **kwargs
        )
326713
def get_contacts_for(self, user):
        
        contacts = self.filter(Q(um_from_user=user) | Q(um_to_user=user))
        return contacts
664930
def get_user(self, username):
        
        for user in self.users:
            if user.id.name == username:
                return user
        return None
611030
def show_user(self, user):
        
        res = self.post('loadUsers', {'userId': user})
        if isinstance(res, list) and len(res) > 0:
            res = res[0]
        return _fix_user(res)
1128703
def get_calendar(self, listing_id, starting_month=datetime.datetime.now().month, starting_year=datetime.datetime.now().year, calendar_months=12):
        
        params = {
            'year': str(starting_year),
            'listing_id': str(listing_id),
            '_format': 'with_conditions',
            'count': str(calendar_months),
            'month': str(starting_month)
        }

        r = self._session.get(API_URL + "/calendar_months", params=params)
        r.raise_for_status()

        return r.json()
450020
def get_users_by_ids(self, user_ids):
        
        urls = [urljoin(self.user_url, F"{i}.json") for i in user_ids]
        result = self._run_async(urls=urls)
        return [User(r) for r in result if r]
1145127
def get_user_by_userid(self, userid):
        '''  '''
        response, status_code = self.__pod__.Users.get_v2_user(
            sessionToken=self.__session__,
            uid=userid
        ).result()
        self.logger.debug('%s: %s' % (status_code, response))
        return status_code, response