예제 #1
0
func (h handler) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
	reqId := uuid.New()
	w.Header().Set("X-Request-Id", reqId)
	r.Header.Set("X-Request-Id", reqId)

	return h.Next.ServeHTTP(w, r)
}
예제 #2
0
파일: url.go 프로젝트: Xe/betterbot-common
// Connect just connects you to nats, no fuss.
func Connect() (*Uplink, error) {
	nc, err := nats.Connect(*natsServer)
	if err != nil {
		return nil, err
	}

	c, err := nats.NewEncodedConn(nc, nats.JSON_ENCODER)
	if err != nil {
		return nil, err
	}

	id := uuid.New()

	u := &Uplink{
		EncodedConn: c,
		Logger:      log.New(os.Stdout, id+" ", log.LstdFlags),
		ID:          id,
		Nats:        nc,
	}

	_, err = c.Subscribe(u.ID+":ping", func(subj, reply string, msg string) {
		c.Publish(reply, "pong")
	})
	if err != nil {
		return nil, err
	}

	return u, nil
}
예제 #3
0
func NewTag(name string) (*Tag, error) {
	tag := &Tag{}
	var err error

	name = strings.ToLower(name)

	q := Db.Where(&Tag{
		Name: strings.ToLower(name),
	}).First(tag)
	if q.Error != nil {
		if q.Error.Error() != "record not found" {
			return nil, q.Error
		}
	}

	if tag.UUID == "" {
		log.Printf("Need to make a new tag for %s", name)

		tag = &Tag{
			UUID: uuid.New(),
			Name: name,
		}

		q := Db.Create(tag)
		if q.Error != nil {
			return nil, q.Error
		}
	}

	return tag, err
}
예제 #4
0
파일: main.go 프로젝트: Xe/betterbot
func eventToMessage(e *irc.Event) *common.Message {
	kind, ok := verbKind[e.Code]
	if !ok {
		kind = "irc:" + e.Code
	}

	if len(e.Arguments) == 0 {
		e.Arguments = []string{""}
	}

	return &common.Message{
		ID:       uuid.New(),
		Protocol: "irc",
		ReplyTo:  e.Arguments[0],
		Via:      uplink.ID,

		Body:   e.Arguments[len(e.Arguments)-1],
		Sender: e.Nick,
		SenderParams: map[string]interface{}{
			"user": e.User,
			"host": e.Host,
		},
		Destination: e.Arguments[0],

		Kind: kind,
		Metadata: map[string]interface{}{
			"ircserver": *ircServer,
			"raw_line":  e.Raw,
			"source":    e.Source,
		},
	}
}
예제 #5
0
// SetToken sets a random CSRF token for a given HTTP request.
func SetToken(r *http.Request) string {
	sess := sessions.GetSession(r)

	token := uuid.New()

	sess.Set("CSRF", token)

	return token
}
예제 #6
0
// NewUser makes a new user in the database given the values from a HTTP POST request.
func NewUser(values url.Values) (u *User, err error) {
	username := values.Get("username")
	if username == "" {
		return nil, ErrUserCreateMissingValues
	}

	email := values.Get("email")
	if email == "" {
		return nil, ErrUserCreateMissingValues
	}

	// TODO: check for duplicate email addresses
	if !strings.Contains(email, "@") {
		return nil, ErrInvalidEmail
	}

	password := values.Get("password")
	if password == "" {
		return nil, ErrUserCreateMissingValues
	}

	confirm := values.Get("password_confirm")
	if confirm == "" {
		return nil, ErrUserCreateMissingValues
	}

	if password != confirm {
		return nil, ErrDifferentPasswords
	}

	salt := uuid.New()[0:14]
	result := hashPassword(password, salt)

	myUuid := uuid.NewUUID().String()

	u = &User{
		Email:        email,
		DisplayName:  username,
		ActualName:   url.QueryEscape(strings.ToLower(username)),
		Activated:    false,
		UUID:         myUuid,
		Salt:         salt,
		PasswordHash: result,
		AvatarURL:    "/img/avatar_default.jpg",
	}

	query := Db.Create(u)
	if query.Error != nil {
		return nil, query.Error
	}

	if Db.NewRecord(u) {
		return nil, errors.New("could not create user")
	}

	return
}
예제 #7
0
파일: log.go 프로젝트: Xe/gurren
// Log sends arbitrary data to Elasticsearch.
//
// If you send this a string or a fmt.Stringer, it will be wrapped as an UnformattedMessage.
func (l *Logger) Log(data interface{}) (err error) {
	m := &Message{
		Date:    time.Now().Format(time.RFC3339),
		Program: path.Base(os.Args[0]),
		Type:    reflect.TypeOf(data).String(),
	}

	hostname, err := os.Hostname()
	if err != nil {
		return err
	}

	m.Hostname = hostname

	switch data.(type) {
	case string:
		myData := data.(string)

		um := &unformattedMessage{
			Kind: "unformatted",
			Text: myData,
		}

		m.Data = um

	case fmt.Stringer:
		myData := data.(fmt.Stringer)

		um := &unformattedMessage{
			Kind: "unformatted",
			Text: myData.String(),
		}

		m.Data = um

	default:
		m.Data = data
	}

	rep, err := l.conn.Index().
		Index(l.index).
		Type("gurren").
		Id(uuid.New()).
		BodyJson(m).Do()

	if err != nil {
		return err
	}

	if !rep.Created {
		return ErrCantInsertLog
	}

	return nil
}
예제 #8
0
파일: main.go 프로젝트: Xe/trolling
func (f *FactCTR) MarshalJSON() ([]byte, error) {
	b, e := json.Marshal(Result{
		uuid.New(),
		"article",
		f.Facts[0],
		f.Facts[0],
		10,
	})

	return b, e
}
예제 #9
0
파일: main.go 프로젝트: Xe/betterbot
func messageCreate(s *discordgo.Session, m *discordgo.MessageCreate) {
	uplink.Printf("%20s %20s > %s\n", m.ChannelID, m.Author.Username, m.Content)

	msg := &common.Message{
		ID:       uuid.New(),
		Protocol: "discord",
		Kind:     "TextMessage",
		Via:      uplink.ID,
		Body:     m.Content,
		Sender:   m.Author.Username,
		ReplyTo:  m.ChannelID,
	}

	uplink.Publish("betterbot.input", msg)
}
예제 #10
0
파일: main.go 프로젝트: Xe/betterbot
func main() {
	conn, err := common.Connect()
	if err != nil {
		panic(err)
	}
	uplink = conn

	session := goMatrix.Init(*matrixHomeserver)
	err = session.Login(*matrixUser, *matrixPass)
	if err != nil {
		panic(err)
	}

	session.Start()
	uplink.Println("Connected to matrix")

	conn.Subscribe(uplink.ID+":input", func(subj, reply string, msg *common.Message) {
		switch msg.Kind {
		case "TextMessage":
			if msg.Body == "" {
				return
			}

			session.SendToRoom(msg.Destination, msg.Body)
		}
	})

	for {
		msg := <-session.OnNewMsg
		msgToq := &common.Message{
			ID:          uuid.New(),
			Protocol:    "matrix",
			Kind:        "TextMessage",
			Via:         uplink.ID,
			Body:        msg.Text,
			Sender:      msg.Sender,
			ReplyTo:     msg.RoomID,
			Destination: msg.RoomName,
		}

		uplink.Publish("betterbot.input", msgToq)
	}
}
예제 #11
0
파일: main.go 프로젝트: Xe/betterbot
func main() {
	conn, err := common.Connect()
	if err != nil {
		panic(err)
	}
	uplink = conn

	bot, err := tgbotapi.NewBotAPI(*apiToken)
	if err != nil {
		panic(err)
	}

	uplink.Println("Connected to telegram")
	uplink.Printf("Authorized on account %s", bot.Self.UserName)

	u := tgbotapi.NewUpdate(0)
	u.Timeout = 60

	updates, err := bot.GetUpdatesChan(u)

	conn.Subscribe(uplink.ID+":input", func(subj, reply string, msg *common.Message) {
		switch msg.Kind {
		case "TextMessage":
			if msg.Body == "" {
				return
			}

			s, err := strconv.ParseInt(msg.Destination, 10, 64)
			if err != nil {
				uplink.Printf("Could not send message: %v", err)
				return
			}

			msg := tgbotapi.NewMessage(s, msg.Body)

			_, err = bot.Send(msg)
			if err != nil {
				uplink.Printf("Error in sending: %#v", err)
			}
		}
	})

	for update := range updates {
		if update.Message == nil {
			continue
		}

		log.Printf("[%s] %s", update.Message.From.UserName, update.Message.Text)

		msg := update.Message.Text
		cid := fmt.Sprintf("%v", update.Message.Chat.ID)

		msgToq := &common.Message{
			ID:       uuid.New(),
			Protocol: "telegram",
			Kind:     "TextMessage",
			Via:      uplink.ID,
			Body:     msg,
			Sender:   update.Message.From.UserName,
			ReplyTo:  cid,
		}

		uplink.Publish("betterbot.input", msgToq)
	}
}
예제 #12
0
func NewImage(r *http.Request, user *User) (i *Image, err error) {
	userUpload, header, err := r.FormFile("file")
	if err != nil {
		return nil, err
	}

	data, err := ioutil.ReadAll(userUpload)
	if err != nil {
		return nil, err
	}

	c := &blake2b.Config{
		Salt: []byte("lol as if"),
		Size: blake2b.Size,
	}

	b2b, err := blake2b.New(c)
	if err != nil {
		panic(err)
	}

	b2b.Reset()
	io.Copy(b2b, bytes.NewBuffer(data))
	hash := fmt.Sprintf("%x", b2b.Sum(nil))

	tagsRaw := r.FormValue("tags")
	tags := strings.Split(tagsRaw, ",")

	for _, tag := range tags {
		if strings.HasPrefix(tag, "rating:") {
			goto ok
		}
	}

	return nil, ErrNeedRatingTag

ok:

	mime := header.Header.Get("Content-Type")

	if mime == "image/svg+xml" {
		return nil, errors.New("Unsupported image format")
	}

	if !strings.HasPrefix(mime, "image/") {
		return nil, errors.New("Unsupported image format")
	}

	i = &Image{
		UUID:        uuid.New(),
		Poster:      user,
		PosterID:    user.ID,
		Mime:        mime,
		Filename:    header.Filename,
		Hash:        hash,
		Description: r.Form.Get("description"),
	}

	for _, tag := range tags {
		t, err := NewTag(tag)
		if err != nil {
			return nil, err
		}

		i.Tags = append(i.Tags, t)
	}

	err = os.Mkdir(Config.Storage.Path+"/"+i.UUID, os.ModePerm)
	if err != nil {
		return nil, err
	}

	fout, err := os.Create(Config.Storage.Path + "/" + i.UUID + "/" + i.Filename)
	if err != nil {
		return nil, err
	}

	io.Copy(fout, bytes.NewBuffer(data))

	conn := Redis.Get()
	defer conn.Close()

	query := Db.Create(i)
	if query.Error != nil {
		return nil, query.Error
	}

	_, err = conn.Do("RPUSH", "uploads", i.UUID)
	if err != nil {
		return nil, err
	}

	return
}