def create_event(title, description, event_end_timedelta, reminder_date,
                 reminder_time, user_email, user_timezone):

    uid = uuid.uuid4()
    time_to_convert = f"{reminder_date} {reminder_time}"
    # %I instead of %H to recognize %p- AM/PM
    clean_time = dt.datetime.strptime(time_to_convert, "%m/%d/%Y %I:%M%p")
    local_date_time_obj = pytz.timezone(user_timezone).localize(clean_time)
    end_date_time_obj = local_date_time_obj + dt.timedelta(
        minutes=event_end_timedelta)

    logger.info(f"creating ical with start time {local_date_time_obj}")
    logger.info(f"creating ical with end time {end_date_time_obj}")

    cal = Calendar()
    cal.add('prodid', '-//nindio product//mxm.dk//')
    cal.add('version', '2.0')

    event = Event()
    event.add('summary', title)
    event.add('dtstart', local_date_time_obj)
    event.add('dtend', end_date_time_obj)
    event.add('dtstamp', dt.datetime.now(tz=pytz.utc))
    event.add('attendee', user_email)
    event.add('organizer', "*****@*****.**")
    event.add('status', "confirmed")
    event.add('category', "Event")
    event.add('description', description)
    event['uid'] = uuid.uuid4()
    event.add('priority', 5)

    cal.add_component(event)
    return cal
예제 #2
0
def convert_datetime_to_rfc2822(datestamp):
    datetuple = datestamp.timetuple()
    epoch = datetime.utcfromtimestamp(0)
    timestamp = (datestamp - epoch).total_seconds()
    ts = utils.formatdate(timestamp)
    logger.info(f"datetime to rfc2822; {ts}")
    return ts
def register():

    form = RegisterForm()

    if current_user.is_authenticated:
        mp.track(f"user_{current_user.id}", "register visit")
        return redirect(url_for('dashboard.landing'))

    if form.validate_on_submit():
        user = BaseUser(name=form.name.data,
                        email=form.email.data,
                        time_zone=form.time_zone.data)
        user.set_password(form.password.data)
        db.session.add(user)
        db.session.commit()
        login_user(user)

        logger.info(f"registering user; {form.name.data}; {form.email.data}")
        m = MailGunEmailService()
        m.send_welcome_email(user_email=form.email.data,
                             user_name=form.name.data)
        flash(f"welcome {form.name.data}")
        return redirect(url_for("dashboard.landing"))

    return render_template("auth/register.html", form=form)
예제 #4
0
    def _base_email_logger(self, from_address, to_address, subject,
                           request_data):

        logger.info('attempting to send email from {}'.format(from_address))
        logger.info('attempting to send email to {}'.format(to_address))
        logger.info('attempting to send email with subject {}'.format(subject))
        logger.info('email status {}'.format(request_data.status_code))
        logger.info('email response text {}'.format(request_data.text))
예제 #5
0
def convert_db_timestamp_to_readable_format(timestamp):
    """
		convert to MM/DD/YY from the db format of YY/MM/DD - HH/MM/SS
	"""
    try:
        clean_date = datetime.strptime(
            str(timestamp), '%Y-%m-%d %H:%M:%S.%f').strftime('%m/%d/%Y')
    except ValueError as e:
        logger.info(f"errored timestamp; {timestamp}")
        logger.error(e)
        clean_date = None
    return clean_date
def delete_s3_files(s3_filename_list, upload_bucket):

    try:
        s3 = boto3.resource('s3')
        for s3_file in s3_filename_list:
            logger.info(f"deleting s3 file - {s3_file}")
            s3_key_value = get_s3_file_key(s3_url=s3_file)
            s3.Object(upload_bucket, s3_key_value).delete()

    except ClientError as e:
        logger.error(f"error deleting s3 {e}")
        return None
def email_calendar_event(cal_obj, title, description, user_email):

    uid = uuid.uuid4()
    temp_dir = tempfile.mkdtemp(prefix='nindio_calendar_event_')
    cwf = f"{temp_dir}/example_{uid}.ics"
    logger.info(f"temp calendar file location; {cwf}")

    with open(cwf, "wb") as f:
        f.write(cal_obj.to_ical())

    m = MailGunEmailService()
    m.send_calendar_reminder(user_email=user_email,
                             title=title,
                             description=description,
                             temp_calendar_file=cwf)

    shutil.rmtree(temp_dir)
    logger.info(f"deleted temp calendar file location; {cwf}")
def api_login():

    form = LoginForm()

    if form.validate_on_submit():

        base_api = f"{current_app.config['BASE_URL']}/api/v1/login"
        payload = {"email": form.email.data, "password": form.password.data}

        r = requests.post(base_api, json=payload, timeout=30)
        if r.status_code == 401:
            return render_template("error_pages/401.html")
        access_token_data = r.json()
        logger.info(f"access_token_data; {access_token_data}")

        resp = make_response(
            render_template("dashboard/landing.html", form=NotesForm()))
        set_access_cookies(resp, access_token_data["access_token"])
        return resp, 200

    return render_template("auth/login.html", form=form)
def upload_files_to_s3(form_files, hashid, upload_bucket):
    """
        returns: s3 upload urls
        takes files uploaded and directly pushes them into s3
    """

    s3_upload_urls = []

    for f in form_files:
        secure_name = secure_filename(f.filename)
        logger.info(f"aws starting file save; {secure_name}")

        # aws presigned url
        presigned_data = get_presigned_s3_url(filedata=f,
                                              hashid=hashid,
                                              upload_bucket=upload_bucket)

        s3_url = presigned_data["url"]

        payload = presigned_data["data"]["fields"]
        payload["file"] = f

        # post information to aws url
        # requests: multi-part payload use "files" instead of "data"
        r = requests.post(presigned_data["data"]["url"], files=payload)
        logger.info(f"aws post information; {r.text}; {r.status_code}")

        s3_upload_urls.append(s3_url)

    logger.info(f"s3 upload urls returned {s3_upload_urls}")
    return s3_upload_urls
def get_presigned_s3_url(filedata, hashid, upload_bucket):
    """
        Ref - https://devcenter.heroku.com/articles/s3-upload-python
        These attributes are also available
        file.filename           
        file.content_type
        file.content_length
        file.mimetype
    """

    file_name = f"{hashid}/{filedata.filename}"
    file_type = filedata.content_type

    s3 = boto3.client('s3')

    presigned_post = s3.generate_presigned_post(Bucket=upload_bucket,
                                                Key=file_name,
                                                Fields={
                                                    "acl": "public-read",
                                                    "Content-Type": file_type
                                                },
                                                Conditions=[{
                                                    "acl":
                                                    "public-read"
                                                }, {
                                                    "Content-Type":
                                                    file_type
                                                }],
                                                ExpiresIn=3600)

    generated_data = {
        'data': presigned_post,
        'url': f'https://{upload_bucket}.s3.amazonaws.com/{file_name}'
    }

    logger.info(f"aws presigned data {generated_data};")

    return generated_data
예제 #11
0
def convert_db_day_to_dateutil_day(db_days_list):
    day_of_week_converter = {
        "mon": "MO",
        "tue": "TU",
        "wed": "WE",
        "thu": "TH",
        "fri": "FR",
        "sat": "SA",
        "sun": "SU"
    }
    logger.info(f"db_days_list; {db_days_list}")
    # check if its list of list
    if all(isinstance(elem, list) for elem in db_days_list):
        converted_days = [
            day_of_week_converter[item] for sublist in db_days_list
            for item in sublist
        ]
    else:
        converted_days = [
            day_of_week_converter[db_day] for db_day in db_days_list
        ]
    logger.info(f"converted days for dateutil; {converted_days}")
    return converted_days
예제 #12
0
def convert_to_utc(time_to_convert, time_zone):
    utc = pytz.utc
    tz_setup = pytz.timezone(time_zone)

    # %I instead of %H to recognize %p- AM/PM
    clean_time = datetime.strptime(time_to_convert, "%m/%d/%Y %I:%M%p")
    localized_time = pytz.timezone(time_zone).localize(clean_time)

    # check if dst is in effect
    is_dst = dst_converter(localized_time.timetuple().tm_isdst)
    logger.info(f"is_dst; {is_dst}")

    # re-check for localized time taking dst into account
    localized_time_with_dst = tz_setup.localize(clean_time, is_dst=is_dst)
    logger.info(f"localized_time_with_dst; {localized_time_with_dst}")

    # convert to UTC
    utc_time = localized_time_with_dst.astimezone(utc)
    utc_str = utc_time.strftime("%Y-%m-%d %H:%M:%S")
    logger.info(f"utc_str_time; {utc_str}")

    return utc_str
예제 #13
0
def current_utc_datetime():
    d = datetime.now(tz=pytz.utc)
    logger.info(f"current utc datetime; {d}")
    return d
예제 #14
0
 def post(self):
     logger.info(request.json)
     return {"msg": "success"}
예제 #15
0
def current_utc_str_time():
    ts = datetime.now(tz=pytz.utc).strftime('%m/%d/%Y: %H:%M:%S')
    logger.info(f"current utc str time; {ts}")
    return ts
예제 #16
0
def current_utc_naive_datetime():
    d = datetime.utcnow()
    logger.info(f"current utc naive datetime; {d}")
    return d
예제 #17
0
def convert_utc_str_to_datetime(str_datestamp):
    ts = parser.parse(str_datestamp)
    logger.info(f"utc str time to datetime; {ts}")
    return ts
예제 #18
0
def index():
    logger.info(f"{__name__}")
    return render_template("index.html")
예제 #19
0
def readable_date(datestamp):
    clean_date = datetime.strftime(datestamp, "%m/%d/%Y")
    logger.info(f"readable_date; {clean_date}")
    return clean_date
예제 #20
0
def get_week_number(date_value):
    dt = date_value.isocalendar()[1] - date_value.replace(
        day=1).isocalendar()[1] + 1
    logger.info(f"week number; {dt}")
    return dt
예제 #21
0
def convert_utc_to_localtime(utc_time, time_zone):
    localtime = pytz.utc.localize(utc_time, is_dst=None).astimezone(
        pytz.timezone(time_zone))
    logger.info(f"utc to local time; {localtime}")
    return localtime