<commit_before>"""Environment params and backend implementations."""

import json
import logging
import datetime

from rauth import OAuth2Service

from google.appengine.api import mail
from google.appengine.ext import deferred
from mailchimp import mailchimp
import stripe

import handlers
import model


def get_env():
  """Get environmental parameters."""
  j = json.load(open('config.json'))

  stripe_backend = None
  mailing_list_subscriber = None
  if j['appName'] == 'local':
    stripe_backend = ProdStripe(model.Config.get().stripe_private_key)
    mailing_list_subscriber = FakeSubscriber()
  else:
    stripe_backend = ProdStripe(model.Config.get().stripe_private_key)
    mailing_list_subscriber = MailchimpSubscriber()

  return handlers.Environment(
    app_name=j['appName'],
    stripe_public_key=model.Config.get().stripe_public_key,
    stripe_backend=stripe_backend,
    mailing_list_subscriber=mailing_list_subscriber,
    mail_sender=MailSender())


class ProdStripe(handlers.StripeBackend):
  def __init__(self, stripe_private_key):
    self.stripe_private_key = stripe_private_key

  def CreateCustomer(self, email, card_token):
    stripe.api_key = self.stripe_private_key
    customer = stripe.Customer.create(card=card_token, email=email)
    return customer

  def RetrieveCardData(self, customer_id):
    stripe.api_key = self.stripe_private_key
    cus = stripe.Customer.retrieve(customer_id)
    return cus.cards.data[0] if len(cus.cards.data) > 0 else {}

  def Charge(self, customer_id, amount_cents):
    stripe.api_key = self.stripe_private_key
    try:
      charge = stripe.Charge.create(
        amount=amount_cents,
        currency='usd',
        customer=customer_id,
        statement_descriptor="Lessig Equal Citizens"
      )
    except stripe.CardError, e:
      logging.info('Stripe returned error for customer: %s ' % customer_id)
      raise handlers.PaymentError(str(e))
    return charge.id
    
  def CreateCustomerWithPlan(self, email, card_token, amount_dollars,
    recurrence_period):
    stripe.api_key = self.stripe_private_key
    if recurrence_period == "monthly":
      plan = "one_dollar_monthly"
    elif recurrence_period == "weekly":
      plan = "one_dollar_weekly"
    else:
      plan = "one_dollar_monthly"
      
    customer = stripe.Customer.create(
      card=card_token,
      email=email,
      plan=plan,
      quantity=amount_dollars
    )

    return customer


class FakeStripe(handlers.StripeBackend):
  def CreateCustomer(self, email, card_token):
    logging.warning('USING FAKE STRIPE')
    cus = stripe.Customer()
    cus.cards = stripe.ListObject()
    if email == '<EMAIL>':
      cus.id = 'doomed_customer'
      cus.cards.data = []
    else:
      cus.id = 'fake_1234'
      cus.cards.data = [self.RetrieveCardData(id)]
    return cus

  def RetrieveCardData(self, customer_id):
    return {
      "address_city": "Washington",
      "address_country": "US",
      "address_line1": "1600 Pennsylvania Ave NW",
      "address_line1_check": "pass",
      "address_line2": "",
      "address_state": "DC",
      "address_zip": "20500",
      "address_zip_check": "pass",
      "brand": "Visa",
      "country": "US",
      "customer": customer_id,
      "cvc_check": "pass",
      "exp_month": 3,
      "exp_year": 2020,
      "fingerprint": "fakefingerprint",
      "funding": "debit",
      "id": "card_fakeid",
      "last4": "4242",
      "name": "<NAME>",
      "object": "card",
      "type": "Visa"
    }

  def Charge(self, customer_id, amount_cents):
    logging.error('USING FAKE STRIPE')
    if customer_id == 'doomed_customer':
      raise handlers.PaymentError(
        'You have no chance to survive make your time')
    logging.error('CHARGED CUSTOMER %s %d cents', customer_id, amount_cents)
    return 'fake_charge_1234'

  def CreateCustomerWithPlan(self, email, card_token, amount_dollars,
    recurrence_period):
    logging.warning('USING FAKE STRIPE')
    cus = stripe.Customer()
    cus.cards = stripe.ListObject()
    if email == '<EMAIL>':
      cus.id = 'doomed_customer'
      cus.cards.data = []
    else:
      cus.id = 'fake_1234'
      cus.cards.data = [self.RetrieveCardData(id)]
    return cus

class MailchimpSubscriber(handlers.MailingListSubscriber):
  def Subscribe(self, email, first_name, last_name, amount_cents, ip_addr, time,
                source, phone=None, zipcode=None, volunteer=None, skills=None, rootstrikers=None,
                nonce=None, pledgePageSlug=None, otherVars = None,
		is_supporter=None, nationBuilderVars=None):
    deferred.defer(_subscribe_to_mailchimp,
                   email, first_name, last_name,
                   amount_cents, ip_addr, source, phone, zipcode,
                   volunteer, skills, rootstrikers, 
                   nonce, pledgePageSlug, otherVars)
                   
      deferred.defer(_subscribe_to_nationbuilder,
                     email, first_name, last_name,
                     amount_cents, ip_addr, source, phone, zipcode,
                     volunteer, skills, rootstrikers,
                     nonce, pledgePageSlug, otherVars,
                     is_supporter, nationBuilderVars)

class FakeSubscriber(handlers.MailingListSubscriber):
  def Subscribe(self, **kwargs):
    logging.info('Subscribing %s', kwargs)


class MailSender(object):
  def __init__(self, defer=True):
    # this can
    self.defer = defer

  def Send(self, to, subject, text_body, html_body, reply_to=None):
    if self.defer:
      deferred.defer(_send_mail, to, subject, text_body, html_body, reply_to)
    else:
      _send_mail(to, subject, text_body, html_body, reply_to)

<commit_msg>fixed indent<commit_after>"""Environment params and backend implementations."""

import json
import logging
import datetime

from rauth import OAuth2Service

from google.appengine.api import mail
from google.appengine.ext import deferred
from mailchimp import mailchimp
import stripe

import handlers
import model


def get_env():
  """Get environmental parameters."""
  j = json.load(open('config.json'))

  stripe_backend = None
  mailing_list_subscriber = None
  if j['appName'] == 'local':
    stripe_backend = ProdStripe(model.Config.get().stripe_private_key)
    mailing_list_subscriber = FakeSubscriber()
  else:
    stripe_backend = ProdStripe(model.Config.get().stripe_private_key)
    mailing_list_subscriber = MailchimpSubscriber()

  return handlers.Environment(
    app_name=j['appName'],
    stripe_public_key=model.Config.get().stripe_public_key,
    stripe_backend=stripe_backend,
    mailing_list_subscriber=mailing_list_subscriber,
    mail_sender=MailSender())


class ProdStripe(handlers.StripeBackend):
  def __init__(self, stripe_private_key):
    self.stripe_private_key = stripe_private_key

  def CreateCustomer(self, email, card_token):
    stripe.api_key = self.stripe_private_key
    customer = stripe.Customer.create(card=card_token, email=email)
    return customer

  def RetrieveCardData(self, customer_id):
    stripe.api_key = self.stripe_private_key
    cus = stripe.Customer.retrieve(customer_id)
    return cus.cards.data[0] if len(cus.cards.data) > 0 else {}

  def Charge(self, customer_id, amount_cents):
    stripe.api_key = self.stripe_private_key
    try:
      charge = stripe.Charge.create(
        amount=amount_cents,
        currency='usd',
        customer=customer_id,
        statement_descriptor="Lessig Equal Citizens"
      )
    except stripe.CardError, e:
      logging.info('Stripe returned error for customer: %s ' % customer_id)
      raise handlers.PaymentError(str(e))
    return charge.id
    
  def CreateCustomerWithPlan(self, email, card_token, amount_dollars,
    recurrence_period):
    stripe.api_key = self.stripe_private_key
    if recurrence_period == "monthly":
      plan = "one_dollar_monthly"
    elif recurrence_period == "weekly":
      plan = "one_dollar_weekly"
    else:
      plan = "one_dollar_monthly"
      
    customer = stripe.Customer.create(
      card=card_token,
      email=email,
      plan=plan,
      quantity=amount_dollars
    )

    return customer


class FakeStripe(handlers.StripeBackend):
  def CreateCustomer(self, email, card_token):
    logging.warning('USING FAKE STRIPE')
    cus = stripe.Customer()
    cus.cards = stripe.ListObject()
    if email == '<EMAIL>':
      cus.id = 'doomed_customer'
      cus.cards.data = []
    else:
      cus.id = 'fake_1234'
      cus.cards.data = [self.RetrieveCardData(id)]
    return cus

  def RetrieveCardData(self, customer_id):
    return {
      "address_city": "Washington",
      "address_country": "US",
      "address_line1": "1600 Pennsylvania Ave NW",
      "address_line1_check": "pass",
      "address_line2": "",
      "address_state": "DC",
      "address_zip": "20500",
      "address_zip_check": "pass",
      "brand": "Visa",
      "country": "US",
      "customer": customer_id,
      "cvc_check": "pass",
      "exp_month": 3,
      "exp_year": 2020,
      "fingerprint": "fakefingerprint",
      "funding": "debit",
      "id": "card_fakeid",
      "last4": "4242",
      "name": "<NAME>",
      "object": "card",
      "type": "Visa"
    }

  def Charge(self, customer_id, amount_cents):
    logging.error('USING FAKE STRIPE')
    if customer_id == 'doomed_customer':
      raise handlers.PaymentError(
        'You have no chance to survive make your time')
    logging.error('CHARGED CUSTOMER %s %d cents', customer_id, amount_cents)
    return 'fake_charge_1234'

  def CreateCustomerWithPlan(self, email, card_token, amount_dollars,
    recurrence_period):
    logging.warning('USING FAKE STRIPE')
    cus = stripe.Customer()
    cus.cards = stripe.ListObject()
    if email == '<EMAIL>':
      cus.id = 'doomed_customer'
      cus.cards.data = []
    else:
      cus.id = 'fake_1234'
      cus.cards.data = [self.RetrieveCardData(id)]
    return cus

class MailchimpSubscriber(handlers.MailingListSubscriber):
  def Subscribe(self, email, first_name, last_name, amount_cents, ip_addr, time,
                source, phone=None, zipcode=None, volunteer=None, skills=None, rootstrikers=None,
                nonce=None, pledgePageSlug=None, otherVars = None,
		is_supporter=None, nationBuilderVars=None):
    deferred.defer(_subscribe_to_mailchimp,
                   email, first_name, last_name,
                   amount_cents, ip_addr, source, phone, zipcode,
                   volunteer, skills, rootstrikers, 
                   nonce, pledgePageSlug, otherVars)
                   
    deferred.defer(_subscribe_to_nationbuilder,
                   email, first_name, last_name,
                   amount_cents, ip_addr, source, phone, zipcode,
                   volunteer, skills, rootstrikers,
                   nonce, pledgePageSlug, otherVars,
                   is_supporter, nationBuilderVars)

class FakeSubscriber(handlers.MailingListSubscriber):
  def Subscribe(self, **kwargs):
    logging.info('Subscribing %s', kwargs)


class MailSender(object):
  def __init__(self, defer=True):
    # this can
    self.defer = defer

  def Send(self, to, subject, text_body, html_body, reply_to=None):
    if self.defer:
      deferred.defer(_send_mail, to, subject, text_body, html_body, reply_to)
    else:
      _send_mail(to, subject, text_body, html_body, reply_to)


{'fraction_non_alphanumeric': 0.10734812980811743, 'fraction_numerical': 0.006543460960297108, 'mean_word_length': 3.2614920874152222, 'pattern_counts': {'":': 46, '<': 9, '<?xml version=': 0, '>': 11, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3164717', 'n_tokens_mistral': 3780, 'n_tokens_neox': 3576, 'n_words': 749}