def refresh_token(refresh): try: url = 'https://www.googleapis.com/oauth2/v4/token' data = { 'client_id': current_app.config.get('GOOGLE_CLIENT_ID'), 'client_secret': current_app.config.get('GOOGLE_CLIENT_SECRET'), 'grant_type': 'refresh_token', 'refresh_token': refresh } r = requests.post(url, data=data) if r.status_code == 200: return 0 else: # Delete the calendar if unable to refresh the token. Account.query.filter( Account.refresh_token == refresh).scalar().delete() return -1 except Exception as e: print_traceback(e) # Delete the calendar if unable to refresh the token. Account.query.filter( Account.refresh_token == refresh).scalar().delete() return -1
def signup(): from app.blueprints.base.functions import print_traceback form = SignupForm() try: if form.validate_on_submit(): if db.session.query(exists().where(User.email == request.form.get('email'))).scalar(): flash(Markup("There is already an account using this email. Please use another or <a href='" + url_for( 'user.login') + "'><span class='text-indigo-700'><u>login</span></u></a>."), category='danger') return redirect(url_for('user.signup')) u = User() form.populate_obj(u) u.password = User.encrypt_password(request.form.get('password')) u.role = 'member' # Save the user to the database u.save() if login_user(u): # from app.blueprints.user.tasks import send_owner_welcome_email # from app.blueprints.contact.mailerlite import create_subscriber # send_owner_welcome_email.delay(current_user.email) # create_subscriber(current_user.email) # Log the user in flash("You've successfully signed up!", 'success') return redirect(url_for('user.setup', new=True)) except Exception as e: print_traceback(e) return render_template('user/signup.html', form=form)
def get_end_time(time_string, duration, tz_offset): try: dt = dateutil.parser.isoparse(time_string) return (dt + datetime.timedelta(minutes=int(duration)) ).strftime('%Y-%m-%dT%H:%M:%S') + tz_offset except Exception as e: print_traceback(e) return None
def get_busy(accounts, date=None, tz=None): busy = list() keyfunc = lambda d: next(iter(d.values())) accounts = [{ 'account': k, 'calendars': [{ 'id': j['id'] } for j in v] } for k, v in itertools.groupby(sorted(accounts, key=keyfunc), key=lambda x: x['account'])] try: for account in accounts: a = Account.query.filter( Account.imported_account_id == account['account']).scalar() service = create_calendar_service(a.token, a.refresh_token) # Get the user's calendar time zone if it doesn't exist if not tz or not date: tz_string = service.settings().get( setting='timezone').execute()['value'] tz = datetime.datetime.now( pytz.timezone(tz_string)).strftime('%z') time_min = datetime.datetime.now( pytz.timezone(tz_string)).strftime('%Y-%m-%dT00:00:00%z') time_max = datetime.datetime.now( pytz.timezone(tz_string)).strftime('%Y-%m-%dT23:59:59%z') else: time_min = date + "T00:00:00" + tz time_max = date + "T23:59:59" + tz for calendar in account['calendars']: events = service.events().list(calendarId=calendar['id'], timeZone=tz, timeMin=time_min, timeMax=time_max, singleEvents=True, orderBy='startTime').execute() if events and 'items' in events: # pprint(events) for event in events['items']: if 'end' in event and 'start' in event and 'dateTime' in event[ 'start'] and 'dateTime' in event['end']: busy.append({ 'start': event['start']['dateTime'].replace('T', ' '), 'end': event['end']['dateTime'].replace('T', ' ') }) return busy except HttpError as e: print(e) except Exception as e: print_traceback(e) return None
def test(): from app.blueprints.base.functions import print_traceback try: results = t() print(results) flash("Test was successful.", 'success') flash("Results are: " + str(results), 'danger') return redirect(url_for('user.calendar')) except Exception as e: print_traceback(e) flash("Test was unsuccessful.", 'danger') return redirect(url_for('user.calendar'))
def cancel(): from app.blueprints.base.functions import print_traceback try: form = CancelSubscriptionForm() if form.validate_on_submit(): # If there is no subscription, then delete the user canceled = True # Cancel the user's subscription if current_user.subscription: subscription = Subscription() canceled = subscription.cancel(user=current_user) if canceled: # Set the user to inactive from app.blueprints.base.functions import set_inactive set_inactive(current_user) logout_user() # Get the user's email # email = current_user.email # Delete the user. # from app.blueprints.billing.tasks import delete_users # ids = [current_user.id] # Delete the user # delete_users.delay(ids) # current_user.delete() # Send a cancellation email. from app.blueprints.user.tasks import send_cancel_email # send_cancel_email.delay(email) flash( 'Sorry to see you go! Your subscription has been canceled.', 'success') return redirect(url_for('user.signup')) return render_template('billing/cancel.html', form=form) except Exception as e: print_traceback(e) return redirect(url_for('user.settings'))
def create_event_on_calendar(user, **data): try: calendar = Calendar.query.filter( and_(Calendar.user_id == user.id, Calendar.primary.is_(True))).scalar() if calendar is None: calendar = Calendar.query.filter( and_(Calendar.user_id == user.id, Calendar.imported_primary.is_(True))).scalar() account = Account.query.filter( Account.account_id == calendar.account_id).scalar() if account is None: return False # Format the event description if 'zoom' in data and data['zoom']: description = 'Zoom link:\n' + data['zoom'] + '\n\n' + data['notes'] else: description = data['notes'] # Get the end time end_time = get_end_time(data['event_datetime'], data['duration_minutes'], data['tz_offset']) e = { 'summary': current_app.config.get('SITE_NAME') + ' meeting with ' + data['requester_name'], 'description': description, 'start': { 'dateTime': data['event_datetime'], 'timeZone': data['tz_name'] }, 'end': { 'dateTime': end_time, 'timeZone': data['tz_name'] }, 'attendees': [{ 'email': data['requester_email'] }, { 'email': user.email }] } pprint(e) service = create_calendar_service(account.token, account.refresh_token) event = service.events().insert( calendarId=calendar.imported_calendar_id, body=e).execute() print('Event created: %s' % (event.get('htmlLink'))) # TODO: Create the event in the events table # e = Event(u.id, None, **data) # e.save() # TODO: Send the confirmation email return True except Exception as e: print_traceback(e) return False
def save_google_credentials(r=None): flow = google_auth_oauthlib.flow.Flow.from_client_secrets_file( 'credentials.json', scopes=SCOPES) flow.redirect_uri = current_app.config.get( 'GOOGLE_REDIRECT' ) if r is None else current_app.config.get('SERVER_URL') + r authorization_response = request.url flow.fetch_token(authorization_response=authorization_response) # Get the credentials credentials = flow.credentials # Get the account's info to save with the calendar info = get_user_info(credentials) try: # If credentials don't exist, return an error if not credentials: return False # There is a refresh token in the request, so this is a new access (or refreshed access) if credentials.refresh_token is not None: # Refresh the credentials if they're expired if credentials.expired: credentials.refresh(Request()) # This user is already in the database, so we are refreshing the access token. if db.session.query(exists().where( Account.imported_account_id == info['id'])).scalar(): account = Account.query.filter( Account.imported_account_id == info['id']).scalar() account.token = credentials.token account.refresh_token = credentials.refresh_token account.save() # Create the calendars in the db for this account from app.blueprints.calendar.functions import create_calendars_in_db create_calendars_in_db(account.account_id, current_user.id, credentials.token, credentials.refresh_token) return False else: account = Account() account.user_id = current_user.id account.imported_account_id = info['id'] account.email = info['email'] account.token = credentials.token, account.refresh_token = credentials.refresh_token account.save() # Create the calendars in the db for this account from app.blueprints.calendar.functions import create_calendars_in_db create_calendars_in_db(account.account_id, current_user.id, credentials.token, credentials.refresh_token) return True else: # Otherwise the account is already connected return False except Exception as e: print_traceback(e) return 1