Ejemplo n.º 1
0
func send(c context.Context, message *PostmarkMessage) error {
	client := urlfetch.Client(c)
	requestBody, err := json.Marshal(message)
	if err != nil {
		return err
	}

	req, err := http.NewRequest("POST", "https://api.postmarkapp.com/email/withTemplate", strings.NewReader(string(requestBody)))
	if err != nil {
		return err
	}

	req.Header.Add("Content-Type", "application/json")
	req.Header.Add("X-Postmark-Server-Token", config.Get(c, "POSTMARK_KEY"))

	res, err := client.Do(req)
	log.Infof(c, "Postmark: %v %v %v", req, res, err)
	if err != nil {
		return err
	}

	defer res.Body.Close()
	resBody, err := ioutil.ReadAll(res.Body)
	log.Infof(c, "Postmark response: %s", string(resBody))

	return nil
}
Ejemplo n.º 2
0
func ShipHandler(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	sc := client.New(config.Get(c, "STRIPE_KEY"), stripe.NewBackends(urlfetch.Client(c)))

	r.ParseForm()
	orderID := r.Form.Get("orderID")
	trackingNumber := r.Form.Get("trackingNumber")

	order, err := sc.Orders.Update(orderID, &stripe.OrderUpdateParams{
		Status: stripe.StatusFulfilled,
		Params: stripe.Params{
			Meta: map[string]string{"tracking_number": trackingNumber},
		},
	})
	if err != nil {
		web.SendError(c, w, err, 500, "Error marking order as fulfilled")
		return
	}

	customer, err := sc.Customers.Get(order.Customer.ID, nil)
	if err != nil {
		web.LogError(c, err, "Error fetching customer info for email")
	} else {
		err = email.SendShippingNotification(c, customer.Desc, customer.Email, order.Shipping, trackingNumber)
		if err != nil {
			web.LogError(c, err, "Error sending shipping notification")
		}
	}

	web.SendJSON(c, w, ChargeResponse{Success: true})
}
Ejemplo n.º 3
0
func OrdersHandler(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	sc := client.New(config.Get(c, "STRIPE_KEY"), stripe.NewBackends(urlfetch.Client(c)))

	lastKey := "or_17fQDrKpn8lOrcLslDTTOnWv"

	r.ParseForm()

	before := r.Form.Get("before")
	if before != "" {
		lastKey = before
	}

	params := &stripe.OrderListParams{
		ListParams: stripe.ListParams{
			Single: true,
			End:    lastKey,
		},
	}

	status := r.Form.Get("status")
	if status != "" && status != "all" {
		params = &stripe.OrderListParams{
			Status: stripe.OrderStatus(status),
			ListParams: stripe.ListParams{
				Single: true,
				End:    lastKey,
			},
		}
	}

	iter := sc.Orders.List(params)

	var response OrdersResponse
	response.Orders = []*ShortOrder{}

	for iter.Next() {
		if iter.Order().Status != stripe.StatusCanceled {
			o := iter.Order()
			response.Orders = append(response.Orders, &ShortOrder{
				ID:       o.ID,
				Created:  o.Created,
				Status:   o.Status,
				Shipping: o.Shipping,
				Customer: o.Customer,
				Meta:     o.Meta,
			})
		}
	}

	web.SendJSON(c, w, response)
}
Ejemplo n.º 4
0
func init() {
	if config.Get("AWS_ACCESS_KEY_ID") == "" {
		panic("AWS_ACCESS_KEY_ID environmental variable not specified.")
	}

	if config.Get("AWS_SECRET_ACCESS_KEY") == "" {
		panic("AWS_SECRET_ACCESS_KEY environmental variable not specified.")
	}

	aws.DefaultConfig.Credentials = credentials.NewStaticCredentials(
		config.Get("AWS_ACCESS_KEY_ID"),
		config.Get("AWS_SECRET_ACCESS_KEY"), "")

	if config.Get("AWS_REGION") == "" {
		panic("AWS_REGION environmental variable not specified.")
	}

	aws.DefaultConfig.Region = config.Get("AWS_REGION")

}
Ejemplo n.º 5
0
// Replaces contents from the source for the transition from old to new
// Author: Ryan Benson
package replacer

import (
	"config"
	"net/url"
	"path/filepath"
	"strings"
)

var oldWebsite = config.Get("Oldwebsite")
var website = config.Get("Website")
var oldWebsitePath = config.Get("Oldwebsitepath")
var Websitepath = config.Get("Websitepath")
var imageCdn = config.Get("Cdn")

func init() {
	// Initializer
}

// ReplaceUrl (public) - replace url from a string to once that is given
// but keeps the URL path. Example:
//   http://www.test.com/articles/hello-world ->
//   http://www.new-website.com/articles/hello-world
// @params: from {string} - origin URL
// @params: to   {string} - new URL
// @return: {string} - final URL
func ReplaceUrl(from, to string) string {
	return to + getUrlPath(from)
}
Ejemplo n.º 6
0
	"net"
	"net/http"
	"time"

	"appengine"
	"appengine/socket"
	"appengine/urlfetch"

	"github.com/aws/aws-sdk-go/aws"
	"github.com/aws/aws-sdk-go/service/ec2"

	"config"
)

var (
	dreamServerAmi          = config.Get("DREAMPICS_DREAMSERVER_AMI")
	dreamServerInstanceType = config.Get("DREAMPICS_DREAMSERVER_INSTANCE_TYPE")
	awsSecurityGroup        = config.Get("AWS_SECURITY_GROUP")
)

func init() {
	if dreamServerAmi == "" {
		panic("DREAMPICS_DREAMSERVER_AMI environmental variable missing.")
	}
	if dreamServerInstanceType == "" {
		panic("DREAMPICS_DREAMSERVER_INSTANCE_TYPE environmental variable missing.")
	}
	if awsSecurityGroup == "" {
		panic("AWS_SECURITY_GROUP environmental variable missing.")
	}
}
Ejemplo n.º 7
0
// Downloads invidual assets or bulk downloads assets, and also ensures
// that there's a proper directory locally to hold them
// Author: Ryan Benson
package downloader

import (
	"config"
	"io"
	"net/http"
	"os"
	"replacer"
	"scraper"
)

var filesDir string = config.Get("Dir")
var oldWebsite string = config.Get("Oldwebsite")

func init() {
	// check to see if directory exists, if not make it
	if isDir(filesDir) == false {
		makeDir(filesDir)
	}
}

// Download (public) - downloads a remote file to local directory
// @params: output {string} - filename to save file as
// @params: file   {string} - URL to download the file from
// @return: {nil}
func Download(output, file string) {
	out, err := os.Create(filesDir + "/" + output)
	if err != nil {
Ejemplo n.º 8
0
package storage

import (
	"config"
)

var (
	gcsBucket = config.Get("GCS_BUCKET")
)

func init() {
	if gcsBucket == "" {
		panic("Missing GCS_BUCKET environmental variable.")
	}
}
Ejemplo n.º 9
0
Archivo: main.go Proyecto: IMQS/tsgen
func main() {

	var ex profile.TSProfile
	ex.Execute.Start(0)
	/**
	 * Get the configuration information and set the properties
	 * of each data set
	 */
	var configs = config.Get("conf.json")
	for _, config := range configs.Property {
		fmt.Println(config)
	}

	// Initialise each data set
	var sets = make([]data.TSSet, len(configs.Property))
	// Iterate through each data set as defined by its properties
	for idxProps, v := range configs.Property {
		/**
		 * Set each data set's properties from the configuration
		 * information pulled from the JSON configuration file
		 */
		sets[idxProps].Id = int64(idxProps)
		sets[idxProps].Property = v
		if sets[idxProps].Property.Now {
			sets[idxProps].Property.Start = time.Now()
		}
		sets[idxProps].Property.Verbose = false
		sets[idxProps].Output.Verbose = false

		// Create a channel for each data set to indicate when it is done
		sets[idxProps].Done = make(chan bool)

		// Open Report with config settings
		sets[idxProps].Report = new(report.TSReport)
		sets[idxProps].Report.Name = "Report_" + strconv.Itoa(idxProps+1)
		sets[idxProps].Report.AddString("Report_" + strconv.Itoa(idxProps+1) + " of " + strconv.Itoa(len(configs.Property)))
		sets[idxProps].Report.AddString("***Config***")
		sets[idxProps].Report.AddStruct(v)

		/**
		 * Start the creation of each dataset as a separate go concurrent
		 * process(es)
		 */
		go sets[idxProps].Create()

	}

	// Wait for each of the data sets to complete before exit
	for idxProps := 0; idxProps < len(configs.Property); idxProps++ {
		<-sets[idxProps].Done
		fmt.Println("Samples/s:", float64(float64(sets[idxProps].Property.Samples)/float64(float64(ex.Execute.Elapsed())/1e9)))
		fmt.Println("Sites:", sets[idxProps].Property.Sites)
		fmt.Println("Samples:", sets[idxProps].Property.Samples)
		fmt.Println("Batch:", sets[idxProps].Property.Batch)
		fmt.Println("Spools:", sets[idxProps].Property.Spools)

	}

	fmt.Println("Done")
	fmt.Println("Total execution time:", float64(ex.Execute.Elapsed())/1e9, "s")

}
Ejemplo n.º 10
0
// Initializer - sets up the CLI flag, includes default from config (from JSON)
// @params: {nil}
// @return: {nil}
func init() {
	defaultCsvFile := config.Get("DefaultCsvFile")
	flag.StringVar(&file, "file", defaultCsvFile, "Path and filename to import (e.g. files/content.csv)")
	flag.Parse()
}
Ejemplo n.º 11
0
func PaymentHandler(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	decoder := json.NewDecoder(r.Body)
	body := new(PaymentRequestBody)
	err := decoder.Decode(&body)
	if err != nil {
		web.SendError(c, w, err, 400, "Could not parse payment information")
		return
	}

	token := body.Token
	args := body.Args

	sc := client.New(config.Get(c, "STRIPE_KEY"), stripe.NewBackends(urlfetch.Client(c)))

	shipping := &stripe.ShippingParams{
		Name: args.ShippingName,
		Address: &stripe.AddressParams{
			Line1:      args.ShippingAddressLine1,
			Line2:      args.ShippingAddressLine2,
			City:       args.ShippingAddressCity,
			State:      args.ShippingAddressState,
			PostalCode: args.ShippingAddressZIP,
			Country:    args.ShippingAddressCountry,
		},
	}

	customer, err := sc.Customers.New(&stripe.CustomerParams{
		Email:  token.Email,
		Desc:   args.BillingName,
		Source: &stripe.SourceParams{Token: token.ID},
	})

	if err != nil {
		web.SendError(c, w, err, 500, "Error saving customer to Stripe")
		return
	}

	order, err := sc.Orders.New(&stripe.OrderParams{
		Currency: "usd",
		Customer: customer.ID,
		Shipping: shipping,
		Items: []*stripe.OrderItemParams{
			&stripe.OrderItemParams{
				Type:   "sku",
				Parent: "book",
			},
		},
	})
	if err != nil {
		web.SendError(c, w, err, 500, "Error saving order to Stripe")
		return
	}

	err = incrementSoldCounter(c)
	if err != nil {
		web.LogError(c, err, "Error incrementing sold counter")
	}

	err = email.SendReceipt(c, args.BillingName, token.Email, order.Shipping)
	if err != nil {
		web.LogError(c, err, "Error sending receipt")
	}

	web.SendJSON(c, w, PaymentResponse{Ok: true})
}
Ejemplo n.º 12
0
func ChargeHandler(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	sc := client.New(config.Get(c, "STRIPE_KEY"), stripe.NewBackends(urlfetch.Client(c)))

	r.ParseForm()
	orderID := r.Form.Get("orderID")
	customerID := r.Form.Get("customerID")

	_, err := sc.Orders.Pay(orderID, &stripe.OrderPayParams{
		Customer: customerID,
	})
	if err != nil {
		stripeErr := err.(*stripe.Error)
		web.LogError(c, err, "Error from Stripe")

		switch stripeErr.Code {
		case stripe.IncorrectNum:
			fallthrough
		case stripe.InvalidNum:
			fallthrough
		case stripe.InvalidExpM:
			fallthrough
		case stripe.InvalidExpY:
			fallthrough
		case stripe.InvalidCvc:
			fallthrough
		case stripe.ExpiredCard:
			fallthrough
		case stripe.IncorrectCvc:
			fallthrough
		case stripe.IncorrectZip:
			fallthrough
		case stripe.CardDeclined:

			customer, err := sc.Customers.Get(customerID, nil)
			if err != nil {
				web.SendError(c, w, err, 500, "Error getting customer")
				return
			}

			_, err = sc.Orders.Update(orderID, &stripe.OrderUpdateParams{
				Status: stripe.StatusCanceled,
			})
			if err != nil {
				web.SendError(c, w, err, 500, "Error marking order as cancelled")
				return
			}

			err = email.SendPaymentDeclinedNotification(c, customer.Desc, customer.Email)
			if err != nil {
				web.SendError(c, w, err, 500, "Error sending payment declined email")
			}

			web.SendJSON(c, w, ChargeResponse{Success: false})
			return

		default:
			web.SendError(c, w, err, 500, "Error charging card")
			return
		}

	}

	web.SendJSON(c, w, ChargeResponse{Success: true})
}