示例#1
0
func exportAliases() {
	var (
		repositories *Repositories
		environments *Environments
		environment  *Environment
		err          error
	)
	if repositories, err = bot.GetRepositories(); err != nil {
		fmt.Println(err)
		os.Exit(-1)
	}
	if environments, err = bot.GetEnvironments(); err != nil {
		fmt.Println(err)
		os.Exit(-1)
	}
	mappedEnvironments := make(map[int][]*Environment)
	for _, environment = range environments.Entries {
		mappedEnvironments[environment.RepositoryId] = append(mappedEnvironments[environment.RepositoryId], environment)
	}

	fmt.Printf("[aliases]\n")
	for _, repository := range repositories.Entries {
		fmt.Printf("# %s\n", repository.Title)
		fmt.Printf("%s = %d\n", slug.Slug(repository.Title), repository.Id)
		for _, environment := range mappedEnvironments[repository.Id] {
			fmt.Printf("\t%s-%s = %d\n", slug.Slug(repository.Title), slug.Slug(environment.Name), environment.Id)
		}
	}

}
示例#2
0
// GetNodes returns the D3-compatible nodes by rta analysis
func GetNodes(prog *ssa.Program) ([]node.Node, error) {
	main, err := mainPackage(prog, false)
	if err != nil {
		return nil, err
	}

	roots := []*ssa.Function{
		main.Func("init"),
		main.Func("main"),
	}

	added := make(map[string]struct{})
	extraImports := make(map[string][]string)
	var nodes []node.Node

	callgraph := rta.Analyze(roots, true)
	callgraph.CallGraph.DeleteSyntheticNodes()
	for _, bar := range callgraph.CallGraph.Nodes {
		_, ok := added[bar.Func.Package().String()]
		if !ok {
			for _, edge := range bar.Out {
				if extraImports[edge.Callee.Func.Package().String()] == nil {
					extraImports[edge.Callee.Func.Package().String()] = make([]string, 0)
				}
				extraImports[edge.Callee.Func.Package().String()] = append(extraImports[edge.Callee.Func.Package().String()], strings.TrimPrefix(slug.Slug(bar.Func.Package().String()), "package-"))
			}

			added[bar.Func.Package().String()] = struct{}{}
		}
	}

	added = make(map[string]struct{})
	for _, bar := range callgraph.CallGraph.Nodes {
		_, ok := added[bar.Func.Package().String()]
		if !ok {
			var imports []string
			for _, edge := range bar.In {
				imports = append(imports, strings.TrimPrefix(slug.Slug(edge.Caller.Func.Package().String()), "package-"))
			}
			imports = append(imports, extraImports[bar.Func.Package().String()]...)

			nodes = append(nodes, node.Node{Name: strings.TrimPrefix(slug.Slug(bar.Func.Package().String()), "package-"), Imports: imports, Size: len(imports) * 100})

			added[bar.Func.Package().String()] = struct{}{}
		}
	}

	return nodes, nil
}
示例#3
0
文件: main.go 项目: xiam/luminos
func (p *Page) ProcessContent() {
	content := string(p.Content)
	titles := titlePattern.FindAllStringSubmatch(content, -1)
	for _, title := range titles {
		if p.Titles == nil {
			p.Titles = make(map[int][]anchor)
		}
		if len(title) == 3 {
			if level, _ := strconv.Atoi(title[1]); level > 0 {
				ll := level - 1
				text := title[2]

				id := slug.Slug(text)

				if id == "" {
					id = fmt.Sprintf("%05d", level)
				}

				if p.Titles[ll] == nil {
					p.Titles[ll] = []anchor{}
				}

				r := fmt.Sprintf(`<h%d><a href="#%s" name="%s">%s</a></h%d>`, level, id, id, text, level)
				p.Titles[ll] = append(p.Titles[ll], anchor{Text: text, URL: "#" + id})

				content = strings.Replace(content, title[0], r, 1)
			}
		}
	}
	p.Content = template.HTML(content)
}
示例#4
0
文件: tag.go 项目: mewben/onix
// fillAndValidate tag
func (model *Tag) fillAndValidate(payload Tag, isEdit bool) (err error) {

	if !isEdit {
		// new
	} else {
		model.ID = payload.ID
	}

	model.Name = strings.TrimSpace(payload.Name)
	model.Description = strings.TrimSpace(payload.Description)
	model.Slug = strings.TrimSpace(payload.Slug)
	if model.Slug == "" || !slug.IsSlugAscii(model.Slug) {
		// generate slug
		model.Slug = slug.Slug(model.Name)
	}
	model.Image = strings.TrimSpace(payload.Image)
	model.IsVisible = payload.IsVisible
	model.ParentID = payload.ParentID
	model.MetaTitle = payload.MetaTitle
	if model.MetaTitle == "" {
		model.MetaTitle = model.Name
	}
	model.MetaDescription = payload.MetaDescription
	if model.MetaDescription == "" {
		model.MetaDescription = model.Description
	}

	model.UpdatedBy = payload.UpdatedBy

	return
}
示例#5
0
文件: db.go 项目: rafadev7/server
func checkAndCreateCategories(db DB) {
	for i, categoryName := range categoryList {
		categorySlug := slug.Slug(categoryName)
		count, err := db.SelectInt("select count(*) from category where categoryslug=?", categorySlug)
		if err != nil {
			log.Printf("Error searching for the category with categorySlug %s\n", categorySlug)
			log.Println("Stopping the creation of categories")
			return
		}
		if count == 0 {
			category := &Category{
				CategoryId:   uniuri.NewLen(20),
				CategoryName: categoryName,
				CategorySlug: categorySlug,
				LikeCount:    0,
			}
			if i == 0 { // "Sem Categoria" is my default category
				category.CategoryId = "default"
			}
			err := db.Insert(category)
			if err != nil {
				log.Printf("Error when creating the category %s. %s\n", category.CategoryName, err)
			} else {
				log.Printf("Category %s created!\n", category.CategoryName)
			}
		}
	}
}
示例#6
0
func parseExamples() []*Example {
	exampleNames := readLines("examples.txt")
	examples := make([]*Example, 0)
	for _, exampleName := range exampleNames {
		if (exampleName != "") && !strings.HasPrefix(exampleName, "#") {
			example := Example{Name: exampleName}
			exampleId := slug.Slug(exampleName)
			example.Id = exampleId
			example.Segs = make([][]*Seg, 0)
			sourcePaths := mustGlob("examples/" + exampleId + "/*")
			for _, sourcePath := range sourcePaths {
				if strings.HasSuffix(sourcePath, ".hash") {
					example.GoCodeHash, example.UrlHash = parseHashFile(sourcePath)
				} else {
					sourceSegs, filecontents := parseAndRenderSegs(sourcePath)
					if filecontents != "" {
						example.GoCode = filecontents
					}
					example.Segs = append(example.Segs, sourceSegs)
				}
			}
			newCodeHash := sha1Sum(example.GoCode)
			if example.GoCodeHash != newCodeHash {
				example.UrlHash = resetUrlHashFile(newCodeHash, example.GoCode, "examples/"+example.Id+"/"+example.Id+".hash")
			}
			examples = append(examples, &example)
		}
	}
	for i, example := range examples {
		if i < (len(examples) - 1) {
			example.NextExample = examples[i+1]
		}
	}
	return examples
}
示例#7
0
文件: content.go 项目: rafadev7/irado
func CreateContent(db DB, user *User, url *Url, img *Image, content *Content) (*Content, error) {
	contentId := uniuri.NewLen(20)
	u, err := db.Get(Content{}, contentId)
	for err == nil && u != nil {
		contentId := uniuri.NewLen(20)
		u, err = db.Get(Content{}, contentId)
	}

	if err != nil {
		return nil, err
	}

	s := slug.Slug(content.Title)

	// Let's check if this slug already exists,
	// if existis, we will increment a sulfix to it
	newSlug := s
	increment := 1
	count, err := db.SelectInt("select count(*) from content where slug=?", newSlug)
	for err == nil && count != 0 {
		increment += 1
		newSlug = fmt.Sprintf("%s-%d", s, increment)
		count, err = db.SelectInt("select count(*) from content where slug=?", newSlug)
	}

	log.Printf("SLUG: %s, inc: %d, count: %d\n", newSlug, increment, count)

	if err != nil {
		return nil, err
	}

	newContent := &Content{
		ContentId:   contentId,
		UrlId:       url.UrlId,
		CategoryId:  "default", // First category will be "Sem categoria"
		Title:       content.Title,
		Slug:        newSlug,
		Description: content.Description,
		Host:        content.Host,
		UserId:      user.UserId,
		ImageId:     "default", // We will check the if there is an image below
		LikeCount:   0,
		Creation:    time.Now(),
		LastUpdate:  time.Now(),
		Deleted:     false,
	}

	if img != nil {
		newContent.ImageId = img.ImageId
	}

	err = db.Insert(newContent)

	if err != nil {
		return nil, err
	}

	return newContent, nil
}
示例#8
0
文件: post.go 项目: mewben/onix
func (model *Post) fillAndValidate(payload PostPayload, isEdit bool) (err error) {

	body := strings.TrimSpace(payload.Body)
	if !isEdit {
		// new
		// uuid
		model.UUID = uuid.NewV4().String()
		model.CreatedBy = payload.AuthorID

		// generate excerpt
		bodyLength := len(body)
		// get # of characters to generate excerpt
		// this is usually taken from settings
		// but we'll hard code it for now
		excerptChars := 200
		if bodyLength < excerptChars {
			excerptChars = bodyLength
		}

		model.Excerpt = body[:excerptChars]
	} else {
		model.ID = payload.ID
		model.Excerpt = strings.TrimSpace(payload.Excerpt)
	}

	model.Title = strings.TrimSpace(payload.Title)
	model.Slug = strings.TrimSpace(payload.Slug)
	if model.Slug == "" || !slug.IsSlugAscii(model.Slug) {
		// generate slug
		model.Slug = slug.Slug(model.Title)
	}

	model.Subtitle = strings.TrimSpace(payload.Subtitle)
	model.Body = body
	model.Featured = payload.Featured
	model.Image = strings.TrimSpace(payload.Image)
	model.AuthorID = payload.AuthorID
	model.UpdatedBy = payload.AuthorID
	model.MetaTitle = strings.TrimSpace(payload.MetaTitle)
	model.MetaDescription = strings.TrimSpace(payload.MetaDescription)

	if model.Status == "published" {
		// parse published_at from format: MM-DD-YYYY hh:mm
		publishedAt, err2 := utils.ParseDate(LONGFORM, payload.PublishedAt)
		if err2 != nil {
			err = err2
			return
		}
		model.PublishedAt = pq.NullTime{
			Time:  publishedAt,
			Valid: true,
		}
	}

	return
}
示例#9
0
func (u *Group) BeforeUpdate(tx *gorm.DB) (err error) {
	var count int
	tx.Model(u).Where("name = ?", u.Name).Count(&count)
	if count > 1 {
		err = errors.New("Conflicting Name!")
		return
	}
	u.Slug = slug.Slug(u.Name)
	return
}
示例#10
0
func (u *Media) BeforeCreate(tx *gorm.DB) (err error) {
	var count int
	tx.Model(u).Where("name = ?", u.Name).Count(&count)
	if count > 0 {
		err = errors.New("Media exists!")
		return
	}
	u.Slug = slug.Slug(u.Name)
	return
}
示例#11
0
// GetNodes returns the D3-compatible nodes by cha analysis -
// notably, works without a main()
func GetNodes(prog *ssa.Program) ([]node.Node, error) {
	added := make(map[string]struct{})
	extraImports := make(map[string][]string)
	var nodes []node.Node

	callgraph := cha.CallGraph(prog)
	callgraph.DeleteSyntheticNodes()
	for f, bar := range callgraph.Nodes {
		fName := fmt.Sprintf("%+v", f)
		_, ok := added[fName]
		if !ok {
			for _, edge := range bar.Out {
				if extraImports[edge.Callee.Func.String()] == nil {
					extraImports[edge.Callee.Func.String()] = make([]string, 0)
				}
				extraImports[edge.Callee.Func.String()] = append(extraImports[edge.Callee.Func.String()], strings.TrimPrefix(slug.Slug(fName), "package-"))
			}

			added[fName] = struct{}{}
		}
	}

	added = make(map[string]struct{})
	for f, bar := range callgraph.Nodes {
		fName := fmt.Sprintf("%+v", f)
		_, ok := added[fName]
		if !ok {
			var imports []string
			for _, edge := range bar.In {
				imports = append(imports, strings.TrimPrefix(slug.Slug(edge.Caller.Func.String()), "package-"))
			}
			imports = append(imports, extraImports[fName]...)

			nodes = append(nodes, node.Node{Name: strings.TrimPrefix(slug.Slug(fName), "package-"), Imports: imports, Size: len(imports) * 100})

			added[fName] = struct{}{}
		}
	}

	return nodes, nil
}
示例#12
0
//Create adds a skill to the database, based on it's owner
func (r *SkillRepo) Create(skill *Skill) error {
	id := bson.NewObjectId()

	Slug := slug.Slug(skill.Name + " " + skill.City + " " + randSeq(7))
	skill.Slug = Slug
	_, err := r.coll.UpsertId(id, skill)
	if err != nil {
		return err
	}

	skill.ID = id

	return nil
}
示例#13
0
文件: content.go 项目: rafadev7/irado
func GetSlug(content *Content) (string, error) {
	s := slug.Slug(content.Title)

	// Let's check if this slug already exists,
	// if existis, we will increment a sulfix to it
	newSlug := s
	increment := 1
	count, err := db.SelectInt("select count(*) from content where contentid!=? AND slug=?", content.ContentId, newSlug)
	for err == nil && count != 0 {
		increment += 1
		newSlug = fmt.Sprintf("%s-%d", s, increment)
		count, err = db.SelectInt("select count(*) from content where contentid!=? AND slug=?", content.ContentId, newSlug)
	}
	if err != nil {
		return "", err
	}

	log.Printf("SLUG: %s, inc: %d, count: %d\n", newSlug, increment, count)
	return newSlug, nil
}
示例#14
0
func (c *appContext) xmain() {
	inFile, err := os.Open("./places.json")
	if err != nil {

		log.Println(err)
	}
	defer inFile.Close()
	scanner := bufio.NewScanner(inFile)
	scanner.Split(bufio.ScanLines)

	//var pp []place
	for scanner.Scan() {
		//log.Println(scanner.Text())

		type Placex struct {
			ID           bson.ObjectId `bson:"_id,omitempty"`
			Slug         string
			Location     string
			State        string
			Budget       string
			Service      []string
			Name         string
			Overview     string
			Address      string
			WorkingHours string
			Phone        string
			PriceRange   string
			Owner        string
			//Timestamp    string
			Images []Images
			Rating int
		}
		var p Placex
		err := json.Unmarshal([]byte(scanner.Text()), &p)
		if err != nil {

			log.Println(err)
		}
		//log.Println(p.Images)

		//pp = append(pp, p)

		var services []string
		for _, s := range strings.Split(p.Service[0], " ") {
			log.Println(s)
			c.redis.SAdd("services", strings.Title(strings.ToLower(s)))

			services = append(services, strings.ToLower(s))
		}
		c.redis.SAdd("places", strings.Title(strings.ToLower(p.Location)+", Lagos"))
		xx := &place{
			Location:     strings.ToLower(p.Location),
			State:        "lagos",
			Name:         strings.ToLower(p.Name),
			Budget:       strings.ToLower(p.Budget),
			Service:      services,
			Overview:     p.Overview,
			Address:      p.Address,
			WorkingHours: p.WorkingHours,
			Phone:        p.Phone,
			Timestamp:    time.Now(),
			Images:       p.Images,
			Owner:        p.Owner,
			Slug:         slug.Slug(p.Name + " " + p.Location + " " + randSeq(5)),
		}
		cc := c.db.C("places")
		err = cc.Insert(xx)
		if err != nil {
			log.Println(err)

		}

	}
}
示例#15
0
func (c *appContext) newPlace(w http.ResponseWriter, r *http.Request, approve int) error {

	user, err := userget(r)
	if err != nil {
		log.Println(err)
	}
	log.Println(user)
	err = r.ParseMultipartForm(20000)
	if err != nil {
		log.Println(err)
		return err
	}

	f := r.MultipartForm

	files := f.File["images"] // grab filenames

	log.Println(files)

	var img = make([]Images, 0, 10)

	for _, v := range files {
		fn, tn := c.uploadPic(v)
		i := Images{
			Thumb: tn,
			Full:  fn,
		}

		img = append(img, i)

	}

	location := strings.ToLower(strings.Join(r.Form["location"], ""))

	budget := strings.Join(r.Form["budget"], "")

	service := strings.Split(strings.ToLower(strings.Join(r.Form["service"], "")), ",")

	Place := &place{
		Approved:     approve,
		Location:     location,
		Budget:       budget,
		Service:      service,
		State:        strings.Join(r.Form["state"], ""),
		Name:         strings.Join(r.Form["name"], ""),
		Address:      strings.Join(r.Form["address"], ""),
		Overview:     strings.Join(r.Form["overview"], ""),
		WorkingHours: strings.Join(r.Form["working-hours"], ""),
		Phone:        strings.Join(r.Form["phone"], ""),
		PriceRange:   strings.Join(r.Form["price-range"], ""),
		Owner:        user.ID,
		Timestamp:    time.Now(),
		Images:       img[:],
	}

	Place.Slug = slug.Slug(Place.Name + " " + Place.Location + " " + randSeq(5))

	cc := c.db.C("places")
	err = cc.Insert(Place)

	if err != nil {
		log.Println(err)
		return err
	}
	for _, s := range service {
		log.Println(s)
		c.redis.SAdd("services", strings.Title(s))
	}

	c.redis.SAdd("places", strings.Title(Place.Location+", "+Place.State))

	return nil

}
示例#16
0
文件: main.go 项目: composehub/server
func main() {
	router := httprouter.New()
	router.POST("/publish/:name", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		r.ParseForm()
		defer r.Body.Close()
		b, _ := ioutil.ReadAll(r.Body)
		devlog(string(b))
		postedpkg := Package{}
		if err := json.Unmarshal(b, &postedpkg); err != nil {
			devlog(string(b), err)
			message := "Sorry, something wrong happened"
			R.JSON(w, http.StatusInternalServerError, map[string]string{"message": message})
			return
		}
		u, p, ok := r.BasicAuth()
		if ok && p == "" {
			requireAuth(w)
		} else {
			if user, err := authUser(u, p); err != nil {
				requireAuth(w)
			} else {
				devlog("FOUND", user.Id, postedpkg.Name)
				pkg := Package{}
				if err := DB.Where(&Package{UserId: user.Id, Name: ps.ByName("name")}).First(&pkg).Error; err != nil &&
					err != gorm.RecordNotFound {
					R.JSON(w, http.StatusNotFound, "xpackage "+postedpkg.Name+" not found")
					return
				} else {
					pkg.UserId = user.Id
					pkg.Private = postedpkg.Private
					pkg.Cmd = postedpkg.Cmd
					if postedpkg.Name != "" {
						pkg.Name = slug.Slug(postedpkg.Name)
					}
					pkg.Tags = postedpkg.Tags
					if postedpkg.Email != "" {
						pkg.Email = postedpkg.Email
					}
					if postedpkg.Blurb != "" {
						pkg.Blurb = postedpkg.Blurb
					}
					if postedpkg.Description != "" {
						pkg.Description = postedpkg.Description
					}
					if postedpkg.RepoUrl != "" {
						pkg.RepoUrl = postedpkg.RepoUrl
					}

					if pkg.Name == "" {
						message := "Sorry, you need to specify a name for your package."
						R.JSON(w, http.StatusBadRequest, message)
						return
					}

					if pkg.RepoUrl == "" {
						message := "Sorry, you need to specify a git repo url for your package."
						R.JSON(w, http.StatusBadRequest, message)
						return
					}

					if err := DB.Save(&pkg).Error; err != nil {
						if strings.Contains(err.Error(), "Duplicate") {
							switch {
							case strings.Contains(err.Error(), "name"):
								devlog(pkg.Id, pkg)
								message := "sorry, a package with the same name " + pkg.Name + " already exists."
								R.JSON(w, http.StatusBadRequest, message)
								return
							}

							devlog(err, pkg.Id, pkg.Name, pkg)
							R.JSON(w, http.StatusNotFound, "package "+pkg.Name+" not found")
							return
						}
					} else {
						devlog("ok, package published!", pkg)
						R.JSON(w, http.StatusOK, pkg)
						return
					}

				}
			}
		}
	})
	router.POST("/packages", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		r.ParseForm()
		u, p, ok := r.BasicAuth()
		if ok && p == "" {
			requireAuth(w)
		} else {
			if user, err := authUser(u, p); err != nil {
				requireAuth(w)
			} else {
				newPackage := Package{
					Name:  r.Form.Get("name"),
					Email: r.Form.Get("email"),
					//Tags:        r.Form.Get("tags"),
					Blurb:       r.Form.Get("blurb"),
					Description: r.Form.Get("description"),
					RepoUrl:     r.Form.Get("repo_url"),
					Commit:      r.Form.Get("commit"),
					UserId:      user.Id,
				}
				newPackage.Name = slug.Slug(newPackage.Name)
				if err := DB.Save(&newPackage).Error; err == nil {
					R.JSON(w, http.StatusOK, newPackage)
					return
				} else {
					R.JSON(w, http.StatusBadRequest, "a package with the same name already exists")
					return
				}

			}
		}
	})
	router.POST("/users", func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
		newUser := User{}

		r.ParseForm()
		newUser.Email = r.Form.Get("email")
		newUser.Password = r.Form.Get("password")
		newUser.Handle = r.Form.Get("handle")
		if newUser.Email != "" && newUser.Password != "" && newUser.Handle != "" {
			if count, err := checkUser(newUser.Email); err != nil || count > 0 {
				R.JSON(w, http.StatusBadRequest, map[string]string{"message": "user with this email already exists"})
				return
			}

			ep, err := bcrypt.GenerateFromPassword([]byte(newUser.Password), 10)
			if err != nil {
				devlog(err)
				R.JSON(w, http.StatusInternalServerError, err)
				return
			}
			newUser.EncryptedPassword = string(ep)
			err = DB.Save(&newUser).Error
			if err != nil {
				// Handle error
				message := "Sorry, something wrong happened"
				if strings.Contains(err.Error(), "Duplicate") {
					switch {
					case strings.Contains(err.Error(), "'handle'"):
						message = "sorry, a user with the same handle " + newUser.Handle + " already exists."
					case strings.Contains(err.Error(), "'email'"):
						message = "sorry, a user with the same email " + newUser.Email + " already exists."
					}
				}
				R.JSON(w, http.StatusInternalServerError, map[string]string{"message": message})
				fmt.Println(err)
				return
			}
			R.JSON(w, http.StatusOK, newUser)
			return
		} else {
			R.JSON(w, http.StatusBadRequest, map[string]string{"message": "email or password missing"})
			return
		}
	})

	router.PUT("/users/:email", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		r.ParseForm()
		defer r.Body.Close()
		b, _ := ioutil.ReadAll(r.Body)
		postedUser := User{}
		if err := json.Unmarshal(b, &postedUser); err != nil {
			message := "Sorry, something wrong happened"
			R.JSON(w, http.StatusInternalServerError, map[string]string{"message": message})
			return
		}
		email := postedUser.Email
		password := postedUser.Password
		handle := postedUser.Handle
		u, p, ok := r.BasicAuth()
		if ok && p == "" {
			requireAuth(w)
		} else {
			if user, err := authUser(u, p); err != nil {
				requireAuth(w)
			} else {
				if email != "" {
					user.Email = email
				}
				if handle != "" {
					user.Handle = handle
				}
				if password != "" {
					ep, err := bcrypt.GenerateFromPassword([]byte(password), 10)
					if err != nil {
						devlog(err)
						R.JSON(w, http.StatusInternalServerError, err)
						return
					}
					user.EncryptedPassword = string(ep)
				}
				if err := DB.Save(&user).Error; err == nil {
					R.JSON(w, http.StatusOK, user)
					return
				} else {
					devlog(err.Error())
					message := "sorry, something went wrong, we're looking into it."
					if strings.Contains(err.Error(), "Duplicate") {
						switch {
						case strings.Contains(err.Error(), "'handle'"):
							message = "sorry, a user with the same handle " + handle + " already exists."
						case strings.Contains(err.Error(), "'email'"):
							message = "sorry, a user with the same email " + email + " already exists."
						}
					}
					R.JSON(w, http.StatusBadRequest, map[string]string{"message": message})
					return
				}
			}
		}
	})

	router.GET("/search/:q", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		packages := []Package{}
		q := "%" + ps.ByName("q") + "%"
		if err := DB.Model(Package{}).Preload("User").Order("total_downloads desc").
			Where("private = 0 and (name like ? or description like ? or blurb like ?)", q, q, q).Find(&packages).Error; err != nil {
			R.JSON(w, http.StatusBadRequest, "[]")
			return
		}
		R.JSON(w, http.StatusOK, packages)
		return

	})

	router.GET("/hsearch", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		vars := Vars{}
		r.ParseForm()
		q := r.Form.Get("q")
		vars.Q = q
		q = "%" + q + "%"

		if err := DB.Model(Package{}).Preload("User").Select("packages.*, users.handle").
			Joins("left join users on users.id = packages.user_id").
			Order("total_downloads desc").Where("private = 0 and (name like ? or description like ? or tags like ?)", q, q, q).
			Find(&vars.Packages).Error; err != nil {
			devlog(err)
		}
		vars.Length = len(vars.Packages)
		T["search.html"].ExecuteTemplate(w, "base", vars)

		//html, err := readAsset(vars, path)
		//if err == nil {
		//w.Header().Set("Content-Type", "text/html")
		//w.Write([]byte(html))
		//} else {
		//return
		//}
	})

	router.GET("/~:handle", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		handle := ps.ByName("handle")
		vars := Vars{}
		if err := DB.Where(User{Handle: handle}).First(&vars.User).Error; err != nil {
			R.JSON(w, http.StatusNotFound, "User not found.")
			return
		}
		if err := DB.Where("user_id = ? and private = ?", vars.User.Id, 0).Find(&vars.Packages).Error; err != nil {
			devlog(err)
		}
		vars.Length = len(vars.Packages)
		T["user.html"].ExecuteTemplate(w, "base", vars)

		//html, err := readAsset(vars, path)
		//if err == nil {
		//w.Header().Set("Content-Type", "text/html")
		//w.Write([]byte(html))
		//} else {
		//return
		//}

	})

	router.GET("/packages/:name", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		name := ps.ByName("name")
		pkg := Package{}
		if err := DB.Where(Package{Name: name}).First(&pkg).Error; err != nil {
			R.JSON(w, http.StatusBadRequest, "{}")
			return
		}
		if pkg.Private {
			u, p, ok := r.BasicAuth()
			if ok && p == "" {
				requireAuth(w)
				return
			} else {
				if user, err := authUser(u, p); err != nil {
					requireAuth(w)
					return
				} else {
					if user.Id != pkg.UserId {
						requireAuth(w)
						return
					}
				}

			}
		}
		if err := DB.Exec("update packages set total_downloads = total_downloads + 1 where name = ?", name).Error; err != nil {
			devlog(err)
		}
		var dl = Download{PackageId: pkg.Id}
		if err := DB.Save(&dl).Error; err != nil {
			devlog(err)
		}

		R.JSON(w, http.StatusOK, pkg)
		return

	})

	router.PUT("/users/:email/reset-password/:token", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		r.ParseForm()
		defer r.Body.Close()
		b, _ := ioutil.ReadAll(r.Body)
		user := User{}
		if err := json.Unmarshal(b, &user); err != nil {
			devlog(err)
			message := "Sorry, something wrong happened, we're looking into it."
			R.JSON(w, http.StatusBadRequest, map[string]string{"message": message})
			return
		}

		password := user.Password
		email := ps.ByName("email")
		token := ps.ByName("token")
		user = User{}
		if password == "" || token == "" {
			message := "Sorry, password can't be blank."
			R.JSON(w, http.StatusBadRequest, map[string]string{"message": message})
			return
		}

		if err := DB.Where(User{Email: email, PasswordToken: token}).First(&user).Error; err != nil {
			message := "Incorrect token, please reset your password again."
			R.JSON(w, http.StatusNotFound, map[string]string{"message": message})
			return
		}

		user.Password = password
		ep, err := bcrypt.GenerateFromPassword([]byte(user.Password), 10)
		if err != nil {
			devlog(err)
			R.JSON(w, http.StatusInternalServerError, err)
			return
		}
		user.EncryptedPassword = string(ep)
		DB.Save(&user)
		if err != nil {
			// Handle error
			message := "Sorry, user could not be saved, we're looking into it."
			R.JSON(w, http.StatusInternalServerError, message)
			fmt.Println(err)
			return
		}
		R.JSON(w, http.StatusOK, user)

	})

	router.POST("/users/:email/reset-password", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		user := User{}
		if err := DB.Where(User{Email: ps.ByName("email")}).First(&user).Error; err != nil {
			message := "Please check your email!"
			devlog(err, ps.ByName("email"))
			R.JSON(w, http.StatusOK, map[string]string{"message": message})
			return
		}
		uuid, err := newUUID()
		if err != nil {
			message := "Sorry, something went wrong, we're looking into it."
			R.JSON(w, http.StatusInternalServerError, map[string]string{"message": message})
			return
		}
		user.PasswordToken = uuid
		if err := DB.Save(&user).Error; err != nil {
			message := "Sorry, something went wrong, we're looking into it."
			R.JSON(w, http.StatusInternalServerError, map[string]string{"message": message})
			return
		}
		sgu := os.Getenv("SG_USER")
		sgp := os.Getenv("SG_PASS")
		devlog(sgu, sgp)
		sg := sendgrid.NewSendGridClient(sgu, sgp)
		message := sendgrid.NewMail()
		message.AddTo(user.Email)
		message.AddToName(user.Name)
		message.SetSubject("Password reset")
		message.SetText("Use this code to reset your password " + user.PasswordToken)
		message.SetFrom("*****@*****.**")
		if r := sg.Send(message); r == nil {
			message := "Please check your email!"
			R.JSON(w, http.StatusOK, map[string]string{"message": message})
			return
		} else {
			message := "Sorry, something went wrong, we're looking into it."
			R.JSON(w, http.StatusInternalServerError, map[string]string{"message": message})
			return
		}
	})

	router.GET("/package/:name", func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {
		vars := Vars{}
		name := ps.ByName("name")

		if err := DB.Model(Package{}).Where(Package{Name: name}).First(&vars.Package).Error; err != nil {
			devlog("err:", err)
			message := "Sorry, something went wrong, we're looking into it."
			R.JSON(w, http.StatusInternalServerError, map[string]string{"message": message})
			return
		}
		if err := DB.Model(User{}).Where(User{Id: vars.Package.UserId}).Find(&vars.User).Error; err != nil {
			devlog(err)
			message := "Sorry, something went wrong, we're looking into it."
			R.JSON(w, http.StatusInternalServerError, map[string]string{"message": message})
			return
		}
		T["package.html"].ExecuteTemplate(w, "base", vars)

		//if err == nil {
		//w.Header().Set("Content-Type", "text/html")
		//w.Write([]byte(html))
		//} else {
		//return
		//}

	})
	router.GET("/main.css", func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
		path := "assets/main.css"
		data, err := ioutil.ReadFile(path)

		if err != nil {
			devlog("Asset not found on path: " + path)
		} else {
			w.Header().Set("Content-Type", "text/css")
			w.Write(data)

		}

	})
	router.GET("/composehub.webm", func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
		path := "assets/composehub.webm"
		data, err := ioutil.ReadFile(path)

		if err != nil {
			devlog("Asset not found on path: " + path)
		} else {
			w.Header().Set("Content-Type", "video/webm")
			w.Write(data)

		}

	})

	router.GET("/composehub.mp4", func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
		path := "assets/composehub.mp4"
		data, err := ioutil.ReadFile(path)

		if err != nil {
			devlog("Asset not found on path: " + path)
		} else {
			w.Header().Set("Content-Type", "video/mp4")
			w.Write(data)

		}

	})

	router.GET("/favicon.ico", func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
		path := "assets/favicon.ico"
		data, err := ioutil.ReadFile(path)

		if err != nil {
			devlog("Asset not found on path: " + path)
		} else {
			w.Header().Set("Content-Type", "image/x-icon")
			w.Write(data)

		}

	})

	router.GET("/install/:os", func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
		os := p.ByName("os")
		if os != "darwin" && os != "linux" && os != "windows" {
			R.JSON(w, http.StatusNotFound, "build not found")
			return
		}
		path := "assets/ch-" + os + "-amd64"
		data, err := ioutil.ReadFile(path)

		if err != nil {
			devlog("Asset not found on path: " + path)
		} else {
			w.Header().Set("Content-Type", "octet-stream")
			w.Write(data)

		}

	})

	router.GET("/checkupdate/:version", func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
		latest := "0.2"
		if p.ByName("version") == latest {
			R.JSON(w, http.StatusOK, "ok")
		} else {
			R.JSON(w, http.StatusOK, latest)
		}
	})
	router.GET("/", func(w http.ResponseWriter, r *http.Request, p httprouter.Params) {
		vars := Vars{}
		//var path string
		//path = "assets/index.html"
		if err := DB.Where("private = ?", 0).Limit(10).Order("total_downloads desc").Find(&vars.Packages).Error; err != nil {
			devlog(err)
			message := "Sorry, something went wrong, we're looking into it."
			R.JSON(w, http.StatusInternalServerError, map[string]string{"message": message})
			return
		}
		T["index.html"].ExecuteTemplate(w, "base", vars)
		//devlog("Asset: ", string(data))
		//html, err := readAsset(vars, path)
		//if err == nil {
		//w.Header().Set("Content-Type", "text/html")
		//w.Write([]byte(html))
		//} else {
		//return
		//}

	})

	n := negroni.Classic()
	//n.Use(auth.Basic("username", "secretpassword"))
	n.UseHandler(router)
	n.Run(":3001")
}
示例#17
0
func createBranch() (action.Action, error) {
	// Get the current branch name.
	originalBranch, err := gitutil.CurrentBranch()
	if err != nil {
		return nil, err
	}

	// Fetch the remote repository.
	task := "Fetch the remote repository"
	log.Run(task)

	gitConfig, err := git.LoadConfig()
	if err != nil {
		return nil, errs.NewError(task, err)
	}

	var (
		remoteName = gitConfig.RemoteName
		baseBranch = gitConfig.TrunkBranchName
	)
	if flagBase != "" {
		baseBranch = flagBase
	}

	// Fetch the remote repository.
	if err := git.UpdateRemotes(remoteName); err != nil {
		return nil, errs.NewError(task, err)
	}

	// Make sure the trunk branch is up to date.
	task = fmt.Sprintf("Make sure branch '%v' is up to date", baseBranch)
	log.Run(task)
	if err := git.CheckOrCreateTrackingBranch(baseBranch, remoteName); err != nil {
		return nil, errs.NewError(task, err)
	}

	// Prompt the user for the branch name.
	task = "Prompt the user for the branch name"
	line, err := prompt.Prompt(`
Please insert the branch slug now.
Insert an empty string to skip the branch creation step: `)
	if err != nil && err != prompt.ErrCanceled {
		return nil, errs.NewError(task, err)
	}

	sluggedLine := slug.Slug(line)
	if sluggedLine == "" {
		fmt.Println()
		log.Log("Not creating any feature branch")
		return nil, nil
	}

	branchName := "story/" + sluggedLine
	ok, err := prompt.Confirm(
		fmt.Sprintf(
			"\nThe branch that is going to be created will be called '%s'.\nIs that alright?",
			branchName),
		true)
	if err != nil {
		return nil, errs.NewError(task, err)
	}
	if !ok {
		panic(prompt.ErrCanceled)
	}
	fmt.Println()

	createTask := fmt.Sprintf(
		"Create branch '%v' on top of branch '%v'", branchName, baseBranch)
	log.Run(createTask)
	if err := git.Branch(branchName, baseBranch); err != nil {
		return nil, errs.NewError(createTask, err)
	}

	deleteTask := fmt.Sprintf("Delete branch '%v'", branchName)
	deleteBranch := func() error {
		// Roll back and delete the newly created branch.
		log.Rollback(createTask)
		if err := git.Branch("-D", branchName); err != nil {
			return errs.NewError(deleteTask, err)
		}
		return nil
	}

	// Checkout the newly created branch.
	checkoutTask := fmt.Sprintf("Checkout branch '%v'", branchName)
	log.Run(checkoutTask)
	if err := git.Checkout(branchName); err != nil {
		if err := deleteBranch(); err != nil {
			errs.Log(err)
		}
		return nil, errs.NewError(checkoutTask, err)
	}

	// Push the newly created branch unless -no_push.
	pushTask := fmt.Sprintf("Push branch '%v' to remote '%v'", branchName, remoteName)
	if flagPush {
		log.Run(pushTask)
		if err := git.Push(remoteName, branchName); err != nil {
			if err := deleteBranch(); err != nil {
				errs.Log(err)
			}
			return nil, errs.NewError(pushTask, err)
		}
	}

	return action.ActionFunc(func() error {
		// Checkout the original branch.
		log.Rollback(checkoutTask)
		if err := git.Checkout(originalBranch); err != nil {
			return errs.NewError(
				fmt.Sprintf("Checkout the original branch '%v'", originalBranch), err)
		}

		// Delete the newly created branch.
		deleteErr := deleteBranch()

		// In case we haven't pushed anything, we are done.
		if !flagPush {
			return deleteErr
		}

		// Delete the branch from the remote repository.
		log.Rollback(pushTask)
		if _, err := git.Run("push", "--delete", remoteName, branchName); err != nil {
			// In case deleteBranch failed, tell the user now
			// since we are not going to return that error.
			if deleteErr != nil {
				errs.Log(deleteErr)
			}

			return errs.NewError(
				fmt.Sprintf("Delete branch '%v' from remote '%v'", branchName, remoteName), err)
		}

		// Return deleteErr to make sure it propagates up.
		return deleteErr
	}), nil
}
示例#18
0
func (this *FileManager) Bootstrap(in interface{}) interface{} {
	doc := in.(File)
	doc.Id = slug.Slug(doc.Name)
	return doc
}
示例#19
0
func CreateAlias(prod_id int64, prod_name string, shop_id int64) string {
	//check alias
	var count int
	var loop int
	loop = 0

	var found int
	found = 0

	var key string
	plain_key := slug.Slug(prod_name)

	for found == 0 {

		if loop == 0 {
			key = plain_key
		} else {
			key = plain_key + "-" + strconv.Itoa(loop)
		}

		row := db_product.QueryRow(`
            SELECT 
                count(product_id)
            FROM 
                ws_product_alias 
            WHERE 
                product_key = $1
                AND shop_id = $2`,
			key,
			shop_id)
		row.Scan(&count)

		if count == 0 {
			found = 1
		} else {
			loop++
		}
	}

	//insert alias to postgre
	_, err := db_product.Exec(`
        INSERT INTO ws_product_alias
            (product_id, product_key, shop_id)
        VALUES($1, $2, $3)
    `, prod_id, key, shop_id)
	checkErr(err, "Fail create alias in postgres")

	//insert alias to mongodb
	cmgo := mgo_prod.DB("product_dev").C("product_alias")
	alias := &ProductAlias{
		ProductId:  prod_id,
		ProductKey: key,
		ShopId:     shop_id,
	}
	_, err = cmgo.Upsert(bson.M{"product_id": prod_id, "shop_id": shop_id}, alias)
	checkErr(err, "Fail create alias in mongodb")

	//delete product alias in redis
	rds := redis.NewClient(&redis.Options{
		Addr:     redisconn.Redis_12_3,
		Password: "", // no password set
		DB:       0,  // use default DB
	})

	rds.Del("svq:aliasing-id_product-" + key + "-" + string(shop_id))
	rds.Close()

	return key
}
示例#20
0
func (this *DocumentTypeManager) Bootstrap(in interface{}) interface{} {
	doc := in.(*DocumentType)
	doc.Id = slug.Slug(doc.Name)
	return doc
}
示例#21
0
func filterSlugify(in *pongo2.Value, param *pongo2.Value) (*pongo2.Value, *pongo2.Error) {
	return pongo2.AsValue(slug.Slug(in.String())), nil
}