def get_transaction_status(order_identifier): paytm_params = {} paytm_checksum_params = {} url = "" paytm_mode = get_settings()['paytm_mode'] merchant_id = ( get_settings()['paytm_sandbox_merchant'] if paytm_mode == 'test' else get_settings()['paytm_live_merchant'] ) paytm_checksum_params["body"] = {"mid": merchant_id, "orderId": order_identifier} checksum = PaytmPaymentsManager.generate_checksum(paytm_checksum_params) paytm_params["MID"] = merchant_id paytm_params["ORDERID"] = order_identifier paytm_params["CHECKSUMHASH"] = checksum post_data = json.dumps(paytm_params) if paytm_mode == 'test': url = "https://securegw-stage.paytm.in/order/status" else: url = "https://securegw.paytm.in/order/status" response = requests.post( url, data=post_data, headers={"Content-type": "application/json"} ).json() return response
def reset_password_post(): try: email = request.json['data']['email'] except TypeError: return BadRequestError({'source': ''}, 'Bad Request Error').respond() try: user = User.query.filter_by(email=email).one() except NoResultFound: logger.info('Tried to reset password not existing email %s', email) else: link = make_frontend_url('/reset-password', {'token': user.reset_password}) if user.was_registered_with_order: send_email_with_action(user, PASSWORD_RESET_AND_VERIFY, app_name=get_settings()['app_name'], link=link) else: send_email_with_action(user, PASSWORD_RESET, app_name=get_settings()['app_name'], link=link, token=user.reset_password) return make_response( jsonify(message="If your email was registered with us, you'll get an \ email with reset link shortly", email=email), 200)
def send_notification(self, follow_up=False): prev_month = self.previous_month_date.strftime("%b %Y") # Displayed as Aug 2016 app_name = get_settings()['app_name'] frontend_url = get_settings()['frontend_url'] link = '{}/event-invoice/{}/review'.format(frontend_url, self.identifier) currency = self.event.payment_currency amount = f"{currency} {self.amount}" send_email_for_monthly_fee_payment( self.user, self.event.name, prev_month, amount, app_name, link, follow_up=follow_up, ) if isinstance(follow_up, bool): send_notif_monthly_fee_payment( self.user, self.event.name, prev_month, amount, app_name, link, self.event_id, follow_up=follow_up, )
def send_event_fee_notification_followup(): from app.instance import current_app as app with app.app_context(): incomplete_invoices = EventInvoice.query.filter( EventInvoice.status != 'paid' ).all() for incomplete_invoice in incomplete_invoices: if incomplete_invoice.amount > 0: prev_month = monthdelta(incomplete_invoice.created_at, 1).strftime( "%b %Y" ) # Displayed as Aug 2016 app_name = get_settings()['app_name'] frontend_url = get_settings()['frontend_url'] link = '{}/event-invoice/{}/review'.format( frontend_url, incomplete_invoice.identifier ) send_followup_email_for_monthly_fee_payment( incomplete_invoice.user.email, incomplete_invoice.event.name, prev_month, incomplete_invoice.amount, app_name, link, ) send_followup_notif_monthly_fee_payment( incomplete_invoice.user, incomplete_invoice.event.name, prev_month, incomplete_invoice.amount, app_name, link, incomplete_invoice.event.id, )
def process_transaction(order_identifier, txn_token): paytm_mode = get_settings()['paytm_mode'] merchant_id = ( get_settings()['paytm_sandbox_merchant'] if paytm_mode == 'test' else get_settings()['paytm_live_merchant'] ) if paytm_mode == 'test': url = "https://securegw-stage.paytm.in/theia/api/v1/processTransaction?mid={}&orderId={}".format( get_settings()['paytm_sandbox_merchant'], order_identifier ) else: url = "https://securegw.paytm.in/theia/api/v1/processTransaction?mid={}&orderId={}".format( get_settings()['paytm_live_merchant'], order_identifier ) head = { "version": "v1", "requestTimestamp": str(int(time.time())), "channelId": "WEB", "txnToken": txn_token, } body = { "requestType": "NATIVE", "mid": merchant_id, "orderId": order_identifier, "paymentMode": "BALANCE", } response = PaytmPaymentsManager.hit_paytm_endpoint(url=url, head=head, body=body) return response
def send_email_to_attendees(order, purchaser_id, attachments=None): for holder in order.ticket_holders: if holder.user and holder.user.id == purchaser_id: # Ticket holder is the purchaser send_email( to=holder.email, action=TICKET_PURCHASED, subject=MAILS[TICKET_PURCHASED]['subject'].format( event_name=order.event.name, invoice_id=order.invoice_number, frontend_url=get_settings()['frontend_url'], ), html=MAILS[TICKET_PURCHASED]['message'].format( event_name=order.event.name, frontend_url=get_settings()['frontend_url'], ), attachments=attachments, ) else: # The Ticket holder is not the purchaser send_email( to=holder.email, action=TICKET_PURCHASED_ATTENDEE, subject=MAILS[TICKET_PURCHASED_ATTENDEE]['subject'].format( event_name=order.event.name, invoice_id=order.invoice_number), html=MAILS[TICKET_PURCHASED_ATTENDEE]['message'].format( my_tickets_url=get_settings()['frontend_url'] + '/my-tickets', event_name=order.event.name, ), attachments=attachments, )
def after_update_object(self, session, data, view_kwargs): """ Send email if session accepted or rejected """ if 'state' in data and data.get('send_email', None) and (session.state == 'accepted' or session.state == 'rejected'): # Email for speaker speakers = session.speakers for speaker in speakers: frontend_url = get_settings()['frontend_url'] link = "{}/events/{}/sessions/{}" \ .format(frontend_url, session.event_id, session.id) send_email_session_accept_reject(speaker.email, session, link) send_notif_session_accept_reject(speaker, session.title, session.state, link, session.id) # Email for organizer if session.event.get_organizer(): organizer = session.event.get_organizer() organizer_email = organizer.email frontend_url = get_settings()['frontend_url'] link = "{}/events/{}/sessions/{}" \ .format(frontend_url, session.event_id, session.id) send_email_session_accept_reject(organizer_email, session, link) send_notif_session_accept_reject(organizer, session.title, session.state, link, session.id)
def send_order_cancel_email(order): cancel_msg = '' if order.cancel_note: cancel_msg = "<br/>Message from the organizer: {cancel_note}".format( cancel_note=order.cancel_note) order_url = (get_settings()['frontend_url'] + '/orders/' + str(order.identifier) + '/view/') event_url = get_settings()['frontend_url'] + '/e/' + order.event.identifier action = MailType.TICKET_CANCELLED mail = MAILS[action] send_email( to=order.user.email, action=action, subject=mail['subject'].format( event_name=order.event.name, invoice_id=order.invoice_number, ), html=render_template( mail['template'], event_name=order.event.name, order_url=order_url, event_url=event_url, cancel_msg=cancel_msg, app_name=get_settings()['app_name'], ), )
def generate_checksum(paytm_params): if get_settings()['paytm_mode'] == 'test': merchant_key = get_settings()['paytm_sandbox_secret'] else: merchant_key = get_settings()['paytm_live_secret'] return checksum.generate_checksum_by_str( json.dumps(paytm_params["body"]), merchant_key)
def send_event_fee_notification_followup(): from app import current_app as app with app.app_context(): incomplete_invoices = EventInvoice.query.filter(EventInvoice.status != 'completed').all() for incomplete_invoice in incomplete_invoices: if incomplete_invoice.amount > 0: prev_month = monthdelta(incomplete_invoice.created_at, 1).strftime( "%b %Y") # Displayed as Aug 2016 app_name = get_settings()['app_name'] frontend_url = get_settings()['frontend_url'] link = '{}/invoices/{}'.format(frontend_url, incomplete_invoice.identifier) send_followup_email_for_monthly_fee_payment(incomplete_invoice.user.email, incomplete_invoice.event.name, prev_month, incomplete_invoice.amount, app_name, link) send_followup_notif_monthly_fee_payment(incomplete_invoice.user, incomplete_invoice.event.name, prev_month, incomplete_invoice.amount, app_name, link, incomplete_invoice.event.id)
def export_event_task(self, event_id, settings): try: logging.info('Exporting started') path = event_export_task_base(event_id, settings) # task_id = self.request.id.__str__() # str(async result) if get_settings()['storage_place'] == 'local' or get_settings()['storage_place'] == None: download_url = url_for( 'api.exports_export_download', event_id=event_id, path=path ) else: download_url = path result = { 'download_url': download_url } except BaseError as e: result = {'__error': True, 'result': e.to_dict()} except Exception: print(traceback.format_exc()) result = {'__error': True, 'result': ServerError().to_dict()} logging.info('Exporting done.. sending email') # send email send_export_mail(event_id, result) # return result return result
def send_event_fee_notification(): from app.instance import current_app as app with app.app_context(): events = Event.query.filter_by(deleted_at=None, state='published').all() for event in events: latest_invoice = EventInvoice.query.filter_by( event_id=event.id).order_by( EventInvoice.created_at.desc()).first() if latest_invoice: orders = Order.query \ .filter_by(event_id=event.id) \ .filter_by(status='completed') \ .filter(Order.completed_at > latest_invoice.created_at).all() else: orders = Order.query.filter_by(event_id=event.id).filter_by( status='completed').all() fee_total = 0 for order in orders: for ticket in order.tickets: if order.paid_via != 'free' and order.amount > 0 and ticket.price > 0: fee = ticket.price * ( get_fee(event.payment_country, order.event.payment_currency) / 100.0) fee_total += fee if fee_total > 0: owner = get_user_event_roles_by_role_name(event.id, 'owner').first() new_invoice = EventInvoice(amount=fee_total, event_id=event.id, user_id=owner.user.id) if event.discount_code_id and event.discount_code: r = relativedelta(datetime.datetime.utcnow(), event.created_at) if r <= event.discount_code.valid_till: new_invoice.amount = fee_total - \ (fee_total * (event.discount_code.value / 100.0)) new_invoice.discount_code_id = event.discount_code_id save_to_db(new_invoice) prev_month = monthdelta(new_invoice.created_at, 1).strftime( "%b %Y") # Displayed as Aug 2016 app_name = get_settings()['app_name'] frontend_url = get_settings()['frontend_url'] link = '{}/invoices/{}'.format(frontend_url, new_invoice.identifier) send_email_for_monthly_fee_payment(new_invoice.user.email, event.name, prev_month, new_invoice.amount, app_name, link) send_notif_monthly_fee_payment(new_invoice.user, event.name, prev_month, new_invoice.amount, app_name, link, new_invoice.event_id)
def send_event_fee_notification(): from app import current_app as app with app.app_context(): events = Event.query.all() for event in events: latest_invoice = EventInvoice.query.filter_by( event_id=event.id).order_by(EventInvoice.created_at.desc()).first() if latest_invoice: orders = Order.query \ .filter_by(event_id=event.id) \ .filter_by(status='completed') \ .filter(Order.completed_at > latest_invoice.created_at).all() else: orders = Order.query.filter_by( event_id=event.id).filter_by(status='completed').all() fee_total = 0 for order in orders: for order_ticket in order.tickets: ticket = safe_query(db, Ticket, 'id', order_ticket.ticket_id, 'ticket_id') if order.paid_via != 'free' and order.amount > 0 and ticket.price > 0: fee = ticket.price * (get_fee(order.event.payment_currency) / 100.0) fee_total += fee if fee_total > 0: organizer = get_user_event_roles_by_role_name(event.id, 'organizer').first() new_invoice = EventInvoice( amount=fee_total, event_id=event.id, user_id=organizer.user.id) if event.discount_code_id and event.discount_code: r = relativedelta(datetime.utcnow(), event.created_at) if r <= event.discount_code.valid_till: new_invoice.amount = fee_total - \ (fee_total * (event.discount_code.value / 100.0)) new_invoice.discount_code_id = event.discount_code_id save_to_db(new_invoice) prev_month = monthdelta(new_invoice.created_at, 1).strftime( "%b %Y") # Displayed as Aug 2016 app_name = get_settings()['app_name'] frontend_url = get_settings()['frontend_url'] link = '{}/invoices/{}'.format(frontend_url, new_invoice.identifier) send_email_for_monthly_fee_payment(new_invoice.user.email, event.name, prev_month, new_invoice.amount, app_name, link) send_notif_monthly_fee_payment(new_invoice.user, event.name, prev_month, new_invoice.amount, app_name, link, new_invoice.event_id)
def after_update_object(self, session, data, view_kwargs): """ Send email if session accepted or rejected """ if ('state' in data and data.get('send_email', None) and (session.state == 'accepted' or session.state == 'rejected')): event = session.event # Email for speaker speakers = session.speakers for speaker in speakers: frontend_url = get_settings()['frontend_url'] link = "{}/events/{}/sessions/{}".format( frontend_url, event.identifier, session.id) if not speaker.is_email_overridden: send_email_session_accept_reject(speaker.email, session, link) send_notif_session_accept_reject(speaker, session.title, session.state, link, session.id) # Email for owner if session.event.get_owner(): owner = session.event.get_owner() owner_email = owner.email frontend_url = get_settings()['frontend_url'] link = "{}/events/{}/sessions/{}".format( frontend_url, event.identifier, session.id) send_email_session_accept_reject(owner_email, session, link) send_notif_session_accept_reject(owner, session.title, session.state, link, session.id) if 'state' in data: entry_count = SessionsSpeakersLink.query.filter_by( session_id=session.id) if entry_count.count() == 0: is_patch_request = False else: is_patch_request = True if is_patch_request: for focus_session in entry_count: focus_session.session_state = session.state db.session.commit() else: current_session = Session.query.filter_by( id=session.id).first() for speaker in current_session.speakers: session_speaker_link = SessionsSpeakersLink( session_state=session.state, session_id=session.id, event_id=session.event.id, speaker_id=speaker.id, ) save_to_db(session_speaker_link, "Session Speaker Link Saved")
def send_order_purchase_organizer_email(order, recipients): order_tickets = OrderTicket.query.filter_by(order_id=order.id).all() emails = list({organizer.email for organizer in recipients}) print(emails[0]) context = dict( buyer_email=order.user.email, buyer_name=order.user.full_name, event_name=order.event.name, invoice_id=order.invoice_number, frontend_url=get_settings()['frontend_url'], site_link=order.event.site_link, order_url=order.site_view_link, event_date=convert_to_user_locale( order.user.email, date=order.event.starts_at, ), event_time=convert_to_user_locale( order.user.email, time=order.event.starts_at, tz=order.event.timezone, ), timezone=order.event.timezone, purchase_time=convert_to_user_locale( emails[0], date_time=order.completed_at, tz=order.event.timezone ), payment_mode=order.payment_mode, payment_status=order.status, order_amount=convert_to_user_locale( emails[0], amount=order.amount, currency=order.event.payment_currency ), tickets_count=order.tickets_count, order_tickets=order_tickets, buyer_org=order.company, buyer_address=order.address, buyer_zipcode=order.zipcode, buyer_city=order.city, buyer_state=order.state, buyer_country=order.country, buyer_tax_id=order.tax_business_info, app_name=get_settings()['app_name'], ) if emails: send_email_with_action( emails[0], MailType.TICKET_PURCHASED_ORGANIZER, 'ticket_purchased_organizer', bcc=emails[1:], **context, )
def after_create_object(self, user, data, view_kwargs): """ method to send- email notification mail link for register verification add image urls :param user: :param data: :param view_kwargs: :return: """ if user.was_registered_with_order: link = make_frontend_url('/reset-password', {'token': user.reset_password}) send_email_with_action( user, PASSWORD_RESET_AND_VERIFY, app_name=get_settings()['app_name'], email=user.email, link=link, ) else: s = get_serializer() hash = str( base64.b64encode( str(s.dumps([user.email, str_generator()])).encode()), 'utf-8', ) link = make_frontend_url('/verify'.format(id=user.id), {'token': hash}) send_email_with_action( user, USER_REGISTER_WITH_PASSWORD, app_name=get_settings()['app_name'], email=user.email, ) send_email_confirmation(user.email, link) # TODO Handle in a celery task # if data.get('original_image_url'): # try: # uploaded_images = create_save_image_sizes(data['original_image_url'], 'speaker-image', user.id) # except (urllib.error.HTTPError, urllib.error.URLError): # raise UnprocessableEntityError( # {'source': 'attributes/original-image-url'}, 'Invalid Image URL' # ) # uploaded_images['small_image_url'] = uploaded_images['thumbnail_image_url'] # del uploaded_images['large_image_url'] # self.session.query(User).filter_by(id=user.id).update(uploaded_images) if data.get('avatar_url'): start_image_resizing_tasks(user, data['avatar_url'])
def display_event_schedule_xcal(identifier): event = get_published_event_or_abort(identifier) file_url = event.xcal_url if not event.has_session_speakers: abort(404) accepted_sessions_count = get_count(DataGetter.get_sessions(event.id)) if accepted_sessions_count == 0 or not event.schedule_published_on: abort(404) if get_settings()['storage_place'] != "s3" and get_settings()['storage_place'] != 'gs': file_url = "file://" + app.config['BASE_DIR'] + file_url.replace("/serve_", "/") response = make_response(urlopen(file_url).read()) response.headers["Content-Type"] = "application/xml" return response
def template_context(): return dict(all_languages=LANGUAGES, selected_lang=get_locale(), settings=get_settings(), app_name=get_settings()['app_name'], tagline=get_settings()['tagline'], event_typo=DataGetter.get_event_types()[:10], base_dir=app.config['BASE_DIR'], system_pages=DataGetter.get_all_pages(get_locale()), datetime_now=datetime.now(), logo=DataGetter.get_custom_placeholder_by_name('Logo'), avatar=DataGetter.get_custom_placeholder_by_name('Avatar'), integrate_socketio=app.config.get('INTEGRATE_SOCKETIO', False))
def upload(file, key, **kwargs): """ Upload handler """ # refresh settings bucket_name = get_settings()['aws_bucket_name'] aws_key = get_settings()['aws_key'] aws_secret = get_settings()['aws_secret'] storage_place = get_settings()['storage_place'] # upload if bucket_name and aws_key and aws_secret and storage_place == 's3': return upload_to_aws(bucket_name, aws_key, aws_secret, file, key, **kwargs) else: return upload_local(file, key, **kwargs)
def upload(uploaded_file, key, upload_dir='static/media/', **kwargs): """ Upload handler """ # refresh settings aws_bucket_name = get_settings()['aws_bucket_name'] aws_key = get_settings()['aws_key'] aws_secret = get_settings()['aws_secret'] aws_region = get_settings()['aws_region'] gs_bucket_name = get_settings()['gs_bucket_name'] gs_key = get_settings()['gs_key'] gs_secret = get_settings()['gs_secret'] storage_place = get_settings()['storage_place'] # upload if aws_bucket_name and aws_key and aws_secret and storage_place == 's3': return upload_to_aws(aws_bucket_name, aws_region, aws_key, aws_secret, uploaded_file, key, **kwargs) elif gs_bucket_name and gs_key and gs_secret and storage_place == 'gs': return upload_to_gs(gs_bucket_name, gs_key, gs_secret, uploaded_file, key, **kwargs) else: return upload_local(uploaded_file, key, upload_dir, **kwargs)
def send_email(to, action, subject, html): """ Sends email and records it in DB """ if not string_empty(to): email_service = get_settings()['email_service'] email_from = get_settings()['email_from'] payload = { 'to': to, 'from': email_from, 'subject': subject, 'html': html } if not current_app.config['TESTING']: if email_service == 'smtp': smtp_encryption = get_settings()['smtp_host'] if smtp_encryption == 'tls': smtp_encryption = 'required' elif smtp_encryption == 'ssl': smtp_encryption = 'ssl' elif smtp_encryption == 'tls_optional': smtp_encryption = 'optional' else: smtp_encryption = 'none' config = { 'host': get_settings()['smtp_host'], 'username': get_settings()['smtp_username'], 'password': get_settings()['smtp_password'], 'tls': smtp_encryption, 'port': get_settings()['smtp_port'], } from tasks import send_mail_via_smtp_task send_mail_via_smtp_task.delay(config, payload) else: key = get_settings()['sendgrid_key'] if not key and not current_app.config['TESTING']: print 'Sendgrid key not defined' return headers = { "Authorization": ("Bearer " + key) } from tasks import send_email_task send_email_task.delay(payload, headers) # record_mail(to, action, subject, html) mail = Mail( recipient=to, action=action, subject=subject, message=html, time=datetime.now() ) from data import save_to_db, record_activity save_to_db(mail, 'Mail Recorded') record_activity('mail_event', email=to, action=action, subject=subject) return
def validate_complex_fields_json(self, data, original_data): if data.get('complex_field_values'): if any(((not isinstance(i, (str, bool, int, float))) and i is not None) for i in data['complex_field_values'].values()): raise UnprocessableEntity( {'pointer': '/data/attributes/complex_field_values'}, "Only flattened JSON of form {key: value} where value is a string, " "integer, float, bool or null is permitted for this field") if len(data['complex_field_values']) > get_settings( )['max_complex_custom_fields']: raise UnprocessableEntity( {'pointer': '/data/attributes/complex_field_values'}, "A maximum of {} complex custom form fields are currently supported" .format(get_settings()['max_complex_custom_fields']))
def template_context(): return dict( all_languages=LANGUAGES, selected_lang=get_locale(), settings=get_settings(), app_name=get_settings()['app_name'], tagline=get_settings()['tagline'], event_typo=DataGetter.get_event_types()[:10], base_dir=app.config['BASE_DIR'], system_pages=DataGetter.get_all_pages(get_locale()), datetime_now=datetime.now(), logo=DataGetter.get_custom_placeholder_by_name('Logo'), avatar=DataGetter.get_custom_placeholder_by_name('Avatar'), integrate_socketio=app.config.get('INTEGRATE_SOCKETIO', False) )
def check_smtp_config(smtp_encryption): """ Checks config of SMTP """ config = { 'host': get_settings()['smtp_host'], 'username': get_settings()['smtp_username'], 'password': get_settings()['smtp_password'], 'encryption': smtp_encryption, 'port': get_settings()['smtp_port'], } for field in config: if field is None: return False return True
def charge_payment(order_identifier, token): if get_settings()['app_environment'] == Environment.PRODUCTION: omise.api_secret = get_settings()['omise_test_secret'] omise.api_public = get_settings()['omise_test_public'] else: omise.api_secret = get_settings()['omise_test_secret'] omise.api_public = get_settings()['omise_test_public'] order = safe_query(Order, 'identifier', order_identifier, 'identifier') charge = omise.Charge.create( amount=int(round(order.amount)), currency=order.event.payment_currency, card=token, metadata={"order_id": str(order_identifier), "status": True}, ) return charge
def export_event_json(event_id, settings): """ Exports the event as a zip on the server and return its path """ # make directory exports_dir = app.config['BASE_DIR'] + '/static/uploads/exports/' if not os.path.isdir(exports_dir): os.mkdir(exports_dir) dir_path = exports_dir + 'event%d' % event_id if os.path.isdir(dir_path): shutil.rmtree(dir_path, ignore_errors=True) os.mkdir(dir_path) # save to directory for e in EXPORTS: if e[0] == 'event': data = _order_json(marshal(e[1].get(event_id), e[2]), e) _download_media(data, 'event', dir_path, settings) else: data = marshal(e[1].list(event_id), e[2]) for count in range(len(data)): data[count] = _order_json(data[count], e) _download_media(data[count], e[0], dir_path, settings) data_str = json.dumps(data, indent=4, ensure_ascii=False).encode('utf-8') fp = open(dir_path + '/' + e[0], 'w') fp.write(data_str) fp.close() # add meta data_str = json.dumps(_generate_meta(), sort_keys=True, indent=4, ensure_ascii=False).encode('utf-8') fp = open(dir_path + '/meta', 'w') fp.write(data_str) fp.close() # make zip shutil.make_archive(dir_path, 'zip', dir_path) dir_path = dir_path + ".zip" storage_path = UPLOAD_PATHS['exports']['zip'].format(event_id=event_id) uploaded_file = UploadedFile(dir_path, dir_path.rsplit('/', 1)[1]) storage_url = upload(uploaded_file, storage_path) if get_settings()['storage_place'] != "s3" and get_settings( )['storage_place'] != 'gs': storage_url = app.config['BASE_DIR'] + storage_url.replace( "/serve_", "/") return storage_url
def get_sold_and_reserved_tickets_count(ticket_id): order_expiry_time = get_settings()['order_expiry_time'] return ( db.session.query(TicketHolder.id) .join(Order) .filter( TicketHolder.ticket_id == ticket_id, TicketHolder.order_id == Order.id, TicketHolder.deleted_at.is_(None), ) .filter( or_( Order.status == 'placed', Order.status == 'completed', and_( Order.status == 'initializing', Order.created_at + datetime.timedelta(minutes=order_expiry_time) > datetime.datetime.utcnow(), ), and_( Order.status == 'pending', Order.created_at + datetime.timedelta(minutes=30 + order_expiry_time) > (datetime.datetime.utcnow()), ), ), ) .count() )
def get_credentials(event=None): """ If the event parameter is None, It returns the secret and publishable key of the Admin's Stripe account. Else, it returns the corresponding values for the event organizer's account. :param event: :return: Stripe secret and publishable keys. """ if not event: settings = get_settings() if settings['app_environment'] == 'development' and settings['stripe_test_secret_key'] and \ settings['stripe_test_publishable_key']: return { 'SECRET_KEY': settings['stripe_test_secret_key'], 'PUBLISHABLE_KEY': settings["stripe_test_publishable_key"] } elif settings['stripe_secret_key'] and settings["stripe_publishable_key"]: return { 'SECRET_KEY': settings['stripe_secret_key'], 'PUBLISHABLE_KEY': settings["stripe_publishable_key"] } else: return None else: if represents_int(event): authorization = StripeAuthorization.query.filter_by(event_id=event).first() else: authorization = event.stripe_authorization if authorization: return { 'SECRET_KEY': authorization.stripe_secret_key, 'PUBLISHABLE_KEY': authorization.stripe_publishable_key } else: return None
def index_view(): placeholder_images = DataGetter.get_event_default_images() pages = DataGetter.get_all_pages() custom_placeholder = DataGetter.get_custom_placeholders() subtopics = DataGetter.get_event_subtopics() settings = get_settings() languages_copy = copy.deepcopy(LANGUAGES) try: languages_copy.pop("en") except: pass if request.method == 'POST': dic = dict(request.form.copy()) for key, value in dic.items(): settings[key] = value[0] set_settings(**settings) flash("Changes have been saved.") return render_template('gentelella/admin/super_admin/content/content.html', pages=pages, settings=settings, placeholder_images=placeholder_images, subtopics=subtopics, custom_placeholder=custom_placeholder, languages=languages_copy, navigation_bar=list_navbar())
def after_create_object(self, role_invite, data, view_kwargs): """ after create object method for role invite links :param role_invite: :param data: :param view_kwargs: :return: """ user = User.query.filter_by(email=role_invite.email).first() if 'status' in data and data['status'] == 'accepted': role = Role.query.filter_by(name=role_invite.role_name).first() event = Event.query.filter_by(id=role_invite.event_id).first() uer = UsersEventsRoles.query.filter_by(user=user).filter_by( event=event).filter_by(role=role).first() if not uer: uer = UsersEventsRoles(user, event, role) save_to_db(uer, 'Role Invite accepted') event = Event.query.filter_by(id=role_invite.event_id).first() frontend_url = get_settings()['frontend_url'] link = "{}/events/{}/role-invites/{}" \ .format(frontend_url, event.id, role_invite.hash) send_email_role_invite(role_invite.email, role_invite.role_name, event.name, link) if user: send_notif_event_role(user, role_invite.role_name, event.name, link, event.id)
def send_after_event_mail(): from app import current_app as app with app.app_context(): events = Event.query.all() upcoming_events = get_upcoming_events() upcoming_event_links = "<ul>" for upcoming_event in upcoming_events: frontend_url = get_settings()['frontend_url'] upcoming_event_links += "<li><a href='{}/events/{}'>{}</a></li>" \ .format(frontend_url, upcoming_event.id, upcoming_event.name) upcoming_event_links += "</ul>" for event in events: organizers = get_user_event_roles_by_role_name(event.id, 'organizer') speakers = get_user_event_roles_by_role_name(event.id, 'speaker') current_time = datetime.datetime.now(pytz.timezone(event.timezone)) time_difference = current_time - event.ends_at time_difference_minutes = (time_difference.days * 24 * 60) + \ (time_difference.seconds / 60) if current_time > event.ends_at and time_difference_minutes < 1440: for speaker in speakers: send_email_after_event(speaker.user.email, event.name, upcoming_event_links) send_notif_after_event(speaker.user, event.name) for organizer in organizers: send_email_after_event(organizer.user.email, event.name, upcoming_event_links) send_notif_after_event(organizer.user.email, event.name)
def send_email(to, action, subject, html): """ Sends email and records it in DB """ if not string_empty(to): key = get_settings()['sendgrid_key'] if not key and not current_app.config['TESTING']: print 'Sendgrid key not defined' return if not current_app.config['TESTING']: headers = { "Authorization": ("Bearer " + key) } payload = { 'to': to, 'from': '*****@*****.**', 'subject': subject, 'html': html } from tasks import send_email_task send_email_task.delay(payload, headers) # record_mail(to, action, subject, html) mail = Mail( recipient=to, action=action, subject=subject, message=html, time=datetime.now() ) from data import save_to_db save_to_db(mail, 'Mail Recorded') return
def robots_txt(): if get_settings()['app_environment'] == Environment.STAGING: resp = make_response(render_template('staging-robots.txt')) else: resp = make_response(render_template('robots.txt')) resp.headers['Content-type'] = 'text/plain' return resp
def send_after_event_mail(): from app import current_app as app with app.app_context(): events = Event.query.all() upcoming_events = get_upcoming_events() upcoming_event_links = "<ul>" for upcoming_event in upcoming_events: frontend_url = get_settings()['frontend_url'] upcoming_event_links += "<li><a href='{}/events/{}'>{}</a></li>" \ .format(frontend_url, upcoming_event.id, upcoming_event.name) upcoming_event_links += "</ul>" for event in events: organizers = get_user_event_roles_by_role_name( event.id, 'organizer') speakers = Speaker.query.filter_by(event_id=event.id, deleted_at=None).all() current_time = datetime.datetime.now(pytz.timezone(event.timezone)) time_difference = current_time - event.ends_at time_difference_minutes = (time_difference.days * 24 * 60) + \ (time_difference.seconds / 60) if current_time > event.ends_at and time_difference_minutes < 1440: for speaker in speakers: send_email_after_event(speaker.user.email, event.name, upcoming_event_links) send_notif_after_event(speaker.user, event.name) for organizer in organizers: send_email_after_event(organizer.user.email, event.name, upcoming_event_links) send_notif_after_event(organizer.user, event.name)
def configure_paypal(): """ Configure the paypal sdk :return: Credentials """ settings = get_settings() # Use Sandbox by default. paypal_mode = settings.get('paypal_mode', 'live' if (settings['app_environment'] == Environment.PRODUCTION) else 'sandbox') paypal_key = None if paypal_mode == 'sandbox': paypal_key = 'paypal_sandbox' elif paypal_mode == 'live': paypal_key = 'paypal' if not paypal_key: raise ConflictException({'pointer': ''}, "Paypal Mode must be 'live' or 'sandbox'") paypal_client = settings.get('{}_client'.format(paypal_key), None) paypal_secret = settings.get('{}_secret'.format(paypal_key), None) if not paypal_client or not paypal_secret: raise ConflictException({'pointer': ''}, "Payments through Paypal have not been configured on the platform") paypalrestsdk.configure({ "mode": paypal_mode, "client_id": paypal_client, "client_secret": paypal_secret})
def get_credentials(event=None): """ If the event parameter is None, It returns the secret and publishable key of the Admin's Stripe account. Else, it returns the corresponding values for the event organizer's account. :param event: :return: Stripe secret and publishable keys. """ if not event: settings = get_settings() if settings['stripe_secret_key'] and settings["stripe_publishable_key"] and settings[ 'stripe_secret_key'] != "" and \ settings["stripe_publishable_key"] != "": return { 'SECRET_KEY': settings['stripe_secret_key'], 'PUBLISHABLE_KEY': settings["stripe_publishable_key"] } else: return None else: if represents_int(event): authorization = StripeAuthorization.query.filter_by(event_id=event).first() else: authorization = event.stripe_authorization if authorization: return { 'SECRET_KEY': authorization.stripe_secret_key, 'PUBLISHABLE_KEY': authorization.stripe_publishable_key } else: return None
def send_email_for_monthly_fee_payment( user, event_name, previous_month, amount, app_name, link, follow_up=False ): """email for monthly fee payment""" options = { False: MONTHLY_PAYMENT_EMAIL, True: MONTHLY_PAYMENT_FOLLOWUP_EMAIL, 'pre_due': MONTHLY_PAYMENT_PRE_DUE_EMAIL, 'post_due': MONTHLY_PAYMENT_POST_DUE_EMAIL, } key = options[follow_up] email = user.email send_email( to=email, action=key, subject=MAILS[key]['subject'].format( date=previous_month, event_name=event_name, app_name=app_name ), html=MAILS[key]['message'].format( name=user.full_name, email=email, event_name=event_name, date=previous_month, amount=amount, app_name=app_name, payment_url=link, ), bcc=get_settings()['admin_billing_email'], )
def generate_hash(key): """ Generate hash for key """ phash = generate_password_hash(key, get_settings()['secret']) return str(b64encode(phash), 'utf-8')[:10] # limit len to 10, is sufficient
def export_event_json(event_id, settings): """ Exports the event as a zip on the server and return its path """ # make directory exports_dir = app.config['BASE_DIR'] + '/static/uploads/exports/' if not os.path.isdir(exports_dir): os.mkdir(exports_dir) dir_path = exports_dir + 'event%d' % event_id if os.path.isdir(dir_path): shutil.rmtree(dir_path, ignore_errors=True) os.mkdir(dir_path) # save to directory for e in EXPORTS: if e[0] == 'event': data = _order_json(marshal(e[1].get(event_id), e[2]), e) _download_media(data, 'event', dir_path, settings) else: data = marshal(e[1].list(event_id), e[2]) for count in range(len(data)): data[count] = _order_json(data[count], e) _download_media(data[count], e[0], dir_path, settings) data_str = json.dumps(data, indent=4, ensure_ascii=False).encode('utf-8') fp = open(dir_path + '/' + e[0], 'w') fp.write(data_str) fp.close() # add meta data_str = json.dumps( _generate_meta(), sort_keys=True, indent=4, ensure_ascii=False ).encode('utf-8') fp = open(dir_path + '/meta', 'w') fp.write(data_str) fp.close() # make zip shutil.make_archive(dir_path, 'zip', dir_path) dir_path = dir_path + ".zip" storage_path = UPLOAD_PATHS['exports']['zip'].format( event_id=event_id ) uploaded_file = UploadedFile(dir_path, dir_path.rsplit('/', 1)[1]) storage_url = upload(uploaded_file, storage_path) if get_settings()['storage_place'] != "s3" and get_settings()['storage_place'] != 'gs': storage_url = app.config['BASE_DIR'] + storage_url.replace("/serve_", "/") return storage_url
def send_email_after_account_create(form): """Send email after account create""" send_email( to=form['email'], action=USER_REGISTER, subject=MAILS[USER_REGISTER]['subject'].format(app_name=get_settings()['app_name']), html=MAILS[USER_REGISTER]['message'].format(email=form['email']) )
def send_email_with_reset_password_hash(email, link): """Send email with reset password hash""" send_email( to=email, action=PASSWORD_RESET, subject=MAILS[PASSWORD_RESET]['subject'].format(app_name=get_settings()['app_name']), html=MAILS[PASSWORD_RESET]['message'].format(link=link) )
def send_email_after_account_create_with_password(form): """Send email after account create""" send_email( to=form['email'], action=USER_REGISTER_WITH_PASSWORD, subject=MAILS[USER_REGISTER_WITH_PASSWORD]['subject'].format(app_name=get_settings()['app_name']), html=MAILS[USER_REGISTER_WITH_PASSWORD]['message'].format(email=form['email'], password=form['password']) )
def render_pages_sitemap(): if get_settings()['app_environment'] == Environment.STAGING: abort(404) urls = [ page.url if page.url.find('://') > -1 else full_url(url_for('basicpagesview.url_view', url=page.url)) for page in DataGetter.get_all_pages() ] return make_sitemap_response(urls)
def send_followup_email_for_monthly_fee_payment(email, event_name, date, amount, payment_url): """Send email every month with invoice to pay service fee""" send_email( to=email, action=MONTHLY_PAYMENT_FOLLOWUP_EMAIL, subject=MAILS[MONTHLY_PAYMENT_FOLLOWUP_EMAIL]['subject'].format(event_name=event_name, date=date), html=MAILS[MONTHLY_PAYMENT_FOLLOWUP_EMAIL]['message'].format(event_name=event_name, date=date, payment_url=payment_url, amount=amount, app_name=get_settings()['app_name']) )
def index_view(self): if request.method == "POST": dic = dict(request.form.copy()) for i in dic: v = dic[i][0] if not v: dic[i] = None else: dic[i] = v set_settings(**dic) settings = get_settings() return self.render("/gentelella/admin/super_admin/settings/settings.html", settings=settings)
def upload_local(uploaded_file, key, **kwargs): """ Uploads file locally. Base dir - static/media/ """ filename = secure_filename(uploaded_file.filename) file_relative_path = 'static/media/' + key + '/' + generate_hash(key) + '/' + filename file_path = app.config['BASE_DIR'] + '/' + file_relative_path dir_path = file_path.rsplit('/', 1)[0] # delete current try: rmtree(dir_path) except OSError: pass # create dirs if not os.path.isdir(dir_path): os.makedirs(dir_path) uploaded_file.save(file_path) file_relative_path = '/' + file_relative_path if get_settings()['static_domain']: return get_settings()['static_domain'] + \ file_relative_path.replace('/static', '') url = urlparse(request.url) return url.scheme + '://' + url.hostname + file_relative_path
def index_view(self): placeholder_images = DataGetter.get_event_default_images() pages = DataGetter.get_all_pages() custom_placeholder = DataGetter.get_custom_placeholders() settings = get_settings() if request.method == 'POST': dic = dict(request.form.copy()) for key, value in dic.items(): settings[key] = value[0] set_settings(**settings) return self.render( '/gentelella/admin/super_admin/content/content.html', pages=pages, settings=settings, placeholder_images=placeholder_images, custom_placeholder=custom_placeholder )
def applications_view(): user = DataGetter.get_user(login.current_user.id) settings = get_settings() no_fb = settings['fb_client_id'] is None or settings['fb_client_secret'] is None no_twitter = settings['tw_consumer_key'] is None or settings['tw_consumer_secret'] is None no_insta = settings['in_client_id'] is None or settings['in_client_secret'] is None no_gplus = settings['google_client_id'] is None or settings['google_client_secret'] is None session['next_redirect'] = '/settings/applications' return render_template('gentelella/users/settings/pages/applications.html', user=user, fb= not no_fb, twitter= not no_twitter, insta= not no_insta, gplus= not no_gplus)
def render_event_pages(num): if get_settings()['app_environment'] == Environment.STAGING: abort(404) main_urls = [] start = (num - 1) * PER_PAGE_EVENTS end = PER_PAGE_EVENTS * num events = get_indexable_events()[start:end] if len(events) == 0: abort(404) for e in events: urls = [ full_url(url_for('event_detail.' + view, identifier=e.identifier)) for view in event_details_pages ] main_urls += urls return make_sitemap_response(main_urls)
def after_create_object(self, session, data, view_kwargs): """ method to send email for creation of new session mails session link to the concerned user :param session: :param data: :param view_kwargs: :return: """ if session.event.get_organizer(): event_name = session.event.name organizer = session.event.get_organizer() organizer_email = organizer.email frontend_url = get_settings()['frontend_url'] link = "{}/events/{}/sessions/{}"\ .format(frontend_url, session.event_id, session.id) send_email_new_session(organizer_email, event_name, link) send_notif_new_session_organizer(organizer, event_name, link)
def render_sitemap(): if get_settings()['app_environment'] == Environment.STAGING: urls = [] else: urls = [full_url(url_for('sitemaps.render_pages_sitemap'))] # pages sitemap # get events pages events = get_indexable_events() pages = int(ceil(len(events) / (PER_PAGE_EVENTS * 1.0))) for num in range(1, pages + 1): urls.append( full_url(url_for('sitemaps.render_event_pages', num=num)) ) # make sitemap sitemap = render_template('sitemap/sitemap_index.xml', sitemaps=urls) resp = make_response(sitemap) resp.headers['Content-Type'] = 'application/xml' return resp
def index_view(): placeholder_images = DataGetter.get_event_default_images() pages = DataGetter.get_all_pages() custom_placeholder = DataGetter.get_custom_placeholders() subtopics = DataGetter.get_event_subtopics() settings = get_settings() languages_copy = copy.deepcopy(LANGUAGES) try: languages_copy.pop("en") except: pass if request.method == 'POST': dic = dict(request.form.copy()) for key, value in dic.items(): settings[key] = value[0] set_settings(**settings) return render_template( 'gentelella/admin/super_admin/content/content.html', pages=pages, settings=settings, placeholder_images=placeholder_images, subtopics=subtopics, custom_placeholder=custom_placeholder, languages=languages_copy, navigation_bar=list_navbar() )
def get_credentials(event=None, override_mode=False, is_testing=False): if event and represents_int(event): event = DataGetter.get_event(event) settings = get_settings() if not override_mode: if settings['paypal_mode'] and settings['paypal_mode'] != "": if settings['paypal_mode'] == 'live': is_testing = False else: is_testing = True else: return None if is_testing: credentials = { 'USER': settings['paypal_sandbox_username'], 'PWD': settings['paypal_sandbox_password'], 'SIGNATURE': settings['paypal_sandbox_signature'], 'SERVER': 'https://api-3t.sandbox.paypal.com/nvp', 'CHECKOUT_URL': 'https://www.sandbox.paypal.com/cgi-bin/webscr', 'EMAIL': '' if not event or not event.paypal_email or event.paypal_email == "" else event.paypal_email } else: credentials = { 'USER': settings['paypal_live_username'], 'PWD': settings['paypal_live_password'], 'SIGNATURE': settings['paypal_live_signature'], 'SERVER': 'https://api-3t.paypal.com/nvp', 'CHECKOUT_URL': 'https://www.paypal.com/cgi-bin/webscr', 'EMAIL': '' if not event or not event.paypal_email or event.paypal_email == "" else event.paypal_email } if credentials['USER'] and credentials['USER'] and credentials['USER'] and credentials['USER'] != "" and \ credentials['USER'] != "" and credentials['USER'] != "": return credentials else: return None
def upload(uploaded_file, key, **kwargs): """ Upload handler """ # refresh settings aws_bucket_name = get_settings()['aws_bucket_name'] aws_key = get_settings()['aws_key'] aws_secret = get_settings()['aws_secret'] aws_region = get_settings()['aws_region'] gs_bucket_name = get_settings()['gs_bucket_name'] gs_key = get_settings()['gs_key'] gs_secret = get_settings()['gs_secret'] storage_place = get_settings()['storage_place'] # upload if aws_bucket_name and aws_key and aws_secret and storage_place == 's3': return upload_to_aws(aws_bucket_name, aws_region, aws_key, aws_secret, uploaded_file, key, **kwargs) elif gs_bucket_name and gs_key and gs_secret and storage_place == 'gs': return upload_to_gs(gs_bucket_name, gs_key, gs_secret, uploaded_file, key, **kwargs) else: return upload_local(uploaded_file, key, **kwargs)
def get_credentials(event=None): if not event: settings = get_settings() if settings['stripe_secret_key'] and settings["stripe_publishable_key"] and settings['stripe_secret_key'] != "" and \ settings["stripe_publishable_key"] != "": return { 'SECRET_KEY': settings['stripe_secret_key'], 'PUBLISHABLE_KEY': settings["stripe_publishable_key"] } else: return None else: if represents_int(event): authorization = StripeAuthorization.query.filter_by(event_id=event).first() else: authorization = event.stripe if authorization: return { 'SECRET_KEY': authorization.stripe_secret_key, 'PUBLISHABLE_KEY': authorization.stripe_publishable_key } else: return None
def configure_paypal(): """ Configure the paypal sdk :return: Credentials """ # Use Sandbox by default. settings = get_settings() paypal_mode = 'sandbox' paypal_client = settings.get('paypal_sandbox_client', None) paypal_secret = settings.get('paypal_sandbox_secret', None) # Switch to production if paypal_mode is production. if settings['paypal_mode'] == Environment.PRODUCTION: paypal_mode = 'live' paypal_client = settings.get('paypal_client', None) paypal_secret = settings.get('paypal_secret', None) if not paypal_client or not paypal_secret: raise ConflictException({'pointer': ''}, "Payments through Paypal hasn't been configured on the platform") paypalrestsdk.configure({ "mode": paypal_mode, "client_id": paypal_client, "client_secret": paypal_secret})