Ejemplo n.º 1
0
func InsertPost(title []byte, slug string, markdown []byte, html []byte, featured bool, isPage bool, published bool, image []byte, created_at time.Time, created_by int64) (int64, error) {

	status := "draft"
	if published {
		status = "published"
	}
	writeDB, err := readDB.Begin()
	if err != nil {
		writeDB.Rollback()
		return 0, err
	}
	var result sql.Result
	if published {
		result, err = writeDB.Exec(stmtInsertPost, nil, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), title, slug, markdown, html, featured, isPage, status, image, created_by, created_at, created_by, created_at, created_by, created_at, created_by)
	} else {
		result, err = writeDB.Exec(stmtInsertPost, nil, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), title, slug, markdown, html, featured, isPage, status, image, created_by, created_at, created_by, created_at, created_by, nil, nil)
	}
	if err != nil {
		writeDB.Rollback()
		return 0, err
	}
	postId, err := result.LastInsertId()
	if err != nil {
		writeDB.Rollback()
		return 0, err
	}
	return postId, writeDB.Commit()
}
Ejemplo n.º 2
0
func NewEntry() *Entry {
	id := uuid.NewV4()

	return &Entry{
		uuid: strings.ToUpper(uuid.Formatter(id, uuid.Clean)), // e.g. FF755C6D7D9B4A5FBC4E41C07D622C65
	}
}
Ejemplo n.º 3
0
func NewNode(controllerUrl string, dockerUrl string, tlsConfig *tls.Config, cpus float64, memory float64, heartbeatInterval int, ip string, showOnlyGridContainers bool, enableDebug bool) (*Node, error) {
	if enableDebug {
		log.SetLevel(log.DebugLevel)
	}

	u := uuid.NewV4()
	id := uuid.Formatter(u, uuid.CleanHyphen)

	client, err := dockerclient.NewDockerClient(dockerUrl, tlsConfig)
	if err != nil {
		return nil, err
	}

	node := &Node{
		Id:                     id,
		client:                 client,
		controllerUrl:          controllerUrl,
		heartbeatInterval:      heartbeatInterval,
		showOnlyGridContainers: showOnlyGridContainers,
		ip:     ip,
		Cpus:   cpus,
		Memory: memory,
	}
	return node, nil
}
Ejemplo n.º 4
0
func Initialize() error {
	// If journey.db does not exist, look for a Ghost database to convert
	if !helpers.FileExists(filenames.DatabaseFilename) {
		// Convert Ghost database if available (time format needs to change to be compatible with journey)
		migration.Ghost()
	}
	// Open or create database file
	var err error
	readDB, err = sql.Open("sqlite3", filenames.DatabaseFilename)
	if err != nil {
		return err
	}
	readDB.SetMaxIdleConns(256) // TODO: is this enough?
	err = readDB.Ping()
	if err != nil {
		return err
	}
	currentTime := time.Now()
	_, err = readDB.Exec(stmtInitialization, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), currentTime, currentTime, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), currentTime, currentTime, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), currentTime, currentTime, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), currentTime, currentTime, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), currentTime, currentTime, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), currentTime, currentTime, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), currentTime, currentTime, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), currentTime, currentTime, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), currentTime, currentTime, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), currentTime, currentTime, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), currentTime, currentTime, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), currentTime, currentTime)
	// TODO: Is Commit()/Rollback() needed for DB.Exec()?
	if err != nil {
		return err
	}
	err = checkBlogSettings()
	if err != nil {
		return err
	}
	return nil
}
Ejemplo n.º 5
0
func saveImage(image string) (string, error) {
	if image == "" {
		return "", nil
	}

	var number = uuid.NewV4()
	var newImage = "download/" + uuid.Formatter(number, uuid.CurlyHyphen)
	out, error := os.Create(newImage)
	if error != nil {
		return "", error
	}
	defer out.Close()

	response, error := http.Get(image)
	if error != nil {
		return "", error
	}
	defer response.Body.Close()

	pix, error := ioutil.ReadAll(response.Body)
	if error != nil {
		return "", error
	}

	_, error = io.Copy(out, bytes.NewReader(pix))
	if error != nil {
		return "", error
	}

	return newImage, nil
}
Ejemplo n.º 6
0
func GuidHandler(w http.ResponseWriter, r *http.Request) {
	id := uuid.NewV4()
	containerId, _ := os.Hostname()
	guidReponse := GuidReponse{}
	guidReponse.Guid = uuid.Formatter(id, uuid.FormatCanonicalCurly)
	guidReponse.ContainerId = containerId

	jsonValue, _ := json.Marshal(guidReponse)
	w.Write([]byte(jsonValue))
}
Ejemplo n.º 7
0
func insertSettingInt64(key string, value int64, setting_type string, created_at time.Time, created_by int64) error {
	writeDB, err := readDB.Begin()
	if err != nil {
		writeDB.Rollback()
		return err
	}
	_, err = writeDB.Exec(stmtInsertSetting, nil, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), key, value, setting_type, created_at, created_by, created_at, created_by)
	if err != nil {
		writeDB.Rollback()
		return err
	}
	return writeDB.Commit()
}
Ejemplo n.º 8
0
func ApiUsersRegister(r *http.Request, enc encoder.Encoder, store Store) (int, []byte) {
	if r.URL.Query().Get("email") != "" && r.URL.Query().Get("password") != "" {
		db := GetDbSession()
		user := User{ID: uuid.Formatter(uuid.NewV4(), uuid.CleanHyphen), Email: r.URL.Query().Get("email"), Password: sha1Password(r.URL.Query().Get("password")), Token: uuid.Formatter(uuid.NewV4(), uuid.CleanHyphen)}
		err := db.Insert(&user)
		if err != nil {
			log.Println(err)
			return http.StatusBadRequest, encoder.Must(enc.Encode(err))
		}
		log.Printf("Registering new user with email %s, password: %s , userid:%s, token:%s", user.Email, user.Password, user.ID, user.Token)
		return http.StatusOK, encoder.Must(enc.Encode(user))
	}
	return http.StatusBadRequest, encoder.Must(enc.Encode("Missing email param"))
}
Ejemplo n.º 9
0
func NewClient(base string, contextType string) *Client {
	client := snooze.Client{
		Root: "http://" + base,
		Before: func(r *http.Request, c *http.Client) {
			c.Timeout = 0
		},
	}
	result := new(Client)
	result.Root = base
	result.ContextType = contextType
	result.Process = uuid.Formatter(uuid.NewV4(), uuid.CleanHyphen)
	client.Create(&result.API)
	return result
}
Ejemplo n.º 10
0
func InsertTag(name []byte, slug string, created_at time.Time, created_by int64) (int64, error) {
	writeDB, err := readDB.Begin()
	if err != nil {
		writeDB.Rollback()
		return 0, err
	}
	result, err := writeDB.Exec(stmtInsertTag, nil, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), name, slug, created_at, created_by, created_at, created_by)
	if err != nil {
		writeDB.Rollback()
		return 0, err
	}
	tagId, err := result.LastInsertId()
	if err != nil {
		writeDB.Rollback()
		return 0, err
	}
	return tagId, writeDB.Commit()
}
Ejemplo n.º 11
0
func InsertUser(name []byte, slug string, password string, email []byte, image []byte, cover []byte, created_at time.Time, created_by int64) (int64, error) {
	writeDB, err := readDB.Begin()
	if err != nil {
		writeDB.Rollback()
		return 0, err
	}
	result, err := writeDB.Exec(stmtInsertUser, nil, uuid.Formatter(uuid.NewV4(), uuid.FormatCanonical), name, slug, password, email, image, cover, created_at, created_by, created_at, created_by)
	if err != nil {
		writeDB.Rollback()
		return 0, err
	}
	userId, err := result.LastInsertId()
	if err != nil {
		writeDB.Rollback()
		return 0, err
	}
	return userId, writeDB.Commit()
}
Ejemplo n.º 12
0
// Create a Todo item
// Returns the id of the new item, or an error on failure
func (dbm *DatabaseManager) CreateTodoItem(item *TodoItem) (string, error) {
	//Generate a UUID for this new Todo item
	id := uuid.Formatter(uuid.NewV4(), uuid.Clean)
	//Fill in some values
	nowTime := time.Now().UTC()
	item.Created = nowTime
	item.Type = "todo_item"
	//validate
	if !item.Validate() {
		return "", &couchdb.Error{
			StatusCode: 400,
			Reason:     "TodoItem is invalid",
		}
	}
	//Save it to the database
	if _, err := dbm.db.Save(item, id, ""); err != nil {
		return "", err
	} else {
		return id, nil
	}
}
Ejemplo n.º 13
0
func Example() {
	var config = uuid.StateSaverConfig{SaveReport: true, SaveSchedule: 30 * time.Minute}
	uuid.SetupFileSystemStateSaver(config)
	u1 := uuid.NewV1()
	fmt.Printf("version %d variant %x: %s\n", u1.Version(), u1.Variant(), u1)

	uP, _ := uuid.Parse("6ba7b810-9dad-11d1-80b4-00c04fd430c8")
	u3 := uuid.NewV3(uP, uuid.Name("test"))

	u4 := uuid.NewV4()
	fmt.Printf("version %d variant %x: %s\n", u4.Version(), u4.Variant(), u4)

	u5 := uuid.NewV5(uuid.NamespaceURL, uuid.Name("test"))

	if uuid.Equal(u1, u3) {
		fmt.Printf("Will never happen")
	}

	fmt.Printf(uuid.Formatter(u5, uuid.CurlyHyphen))

	uuid.SwitchFormat(uuid.BracketHyphen)
}
Ejemplo n.º 14
0
func ApiFilesPost(r *http.Request, enc encoder.Encoder, store Store, parms martini.Params) (int, []byte) {
	db := GetDbSession()

	token := r.Header.Get("X-API-TOKEN")
	user := User{}
	err := db.SelectOne(&user, "select * from users where token=?", token)
	if err != nil {
		return http.StatusUnauthorized, encoder.Must(enc.Encode(
			NewError(ErrCodeNotExist, "Error")))
	}

	var userFiles []UserFile

	body, _ := ioutil.ReadAll(r.Body)
	r.Body.Close()
	err = json.Unmarshal(body, &userFiles)

	if err != nil {
		return http.StatusNotFound, encoder.Must(enc.Encode(
			NewError(ErrCodeNotExist, "Could not decode body")))
	}

	for userFile_i, userFile := range userFiles {
		err = db.SelectOne(&userFiles[userFile_i], "select * from users_files where user_id=? and relative_path=?", userFile.UserID, userFile.RelativePath)
		if err == sql.ErrNoRows {
			userFiles[userFile_i].ID = uuid.Formatter(uuid.NewV4(), uuid.CleanHyphen)
			userFiles[userFile_i].UserID = user.ID
			db.Insert(&userFiles[userFile_i])
			// TODO Error
		} else if err != nil {
			// TODO Error
		}
	}
	//Temp call for testing
	go func(userId string) {
		ApiProcessFiles(userId)
	}(user.ID)
	return http.StatusOK, encoder.Must(enc.Encode(userFiles))
}
Ejemplo n.º 15
0
func Example() {
	saver := new(savers.FileSystemSaver)
	saver.Report = true
	saver.Duration = time.Second * 3

	// Run before any v1 or v2 UUIDs to ensure the savers takes
	uuid.RegisterSaver(saver)

	up, _ := uuid.Parse("6ba7b810-9dad-11d1-80b4-00c04fd430c8")
	fmt.Printf("version %d variant %x: %s\n", up.Version(), up.Variant(), up)

	uuid.New(up.Bytes())

	u1 := uuid.NewV1()
	fmt.Printf("version %d variant %x: %s\n", u1.Version(), u1.Variant(), u1)

	u4 := uuid.NewV4()
	fmt.Printf("version %d variant %x: %s\n", u4.Version(), u4.Variant(), u4)

	u3 := uuid.NewV3(u1, u4)

	url, _ := url.Parse("www.example.com")

	u5 := uuid.NewV5(uuid.NameSpaceURL, url)

	if uuid.Equal(u1, u3) {
		fmt.Println("Will never happen")
	}

	if uuid.Compare(uuid.NameSpaceDNS, uuid.NameSpaceDNS) == 0 {
		fmt.Println("They are equal")
	}

	// Default Format is Canonical
	fmt.Println(uuid.Formatter(u5, uuid.FormatCanonicalCurly))

	uuid.SwitchFormat(uuid.FormatCanonicalBracket)
}
Ejemplo n.º 16
0
// API function to upload images
func apiUploadHandler(w http.ResponseWriter, r *http.Request, _ map[string]string) {
	userName := authentication.GetUserName(r)
	if userName != "" {
		// Create multipart reader
		reader, err := r.MultipartReader()
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		// Slice to hold all paths to the files
		allFilePaths := make([]string, 0)
		// Copy each part to destination.
		for {
			part, err := reader.NextPart()
			if err == io.EOF {
				break
			}
			// If part.FileName() is empty, skip this iteration.
			if part.FileName() == "" {
				continue
			}
			// Folder structure: year/month/randomname
			filePath := filepath.Join(filenames.ImagesFilepath, time.Now().Format("2006"), time.Now().Format("01"))
			if os.MkdirAll(filePath, 0777) != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
			dst, err := os.Create(filepath.Join(filePath, strconv.FormatInt(time.Now().Unix(), 10)+"_"+uuid.Formatter(uuid.NewV4(), uuid.Clean)+filepath.Ext(part.FileName())))
			defer dst.Close()
			if err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
			if _, err := io.Copy(dst, part); err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
			// Rewrite to file path on server
			filePath = strings.Replace(dst.Name(), filenames.ImagesFilepath, "/images", 1)
			// Make sure to always use "/" as path separator (to make a valid url that we can use on the blog)
			filePath = filepath.ToSlash(filePath)
			allFilePaths = append(allFilePaths, filePath)
		}
		json, err := json.Marshal(allFilePaths)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		w.Header().Set("Content-Type", "application/json")
		w.Write(json)
		return
	} else {
		http.Error(w, "Not logged in!", http.StatusInternalServerError)
		return
	}
}
Ejemplo n.º 17
0
func GenUuid() string {
	return uuid.Formatter(uuid.NewV4(), uuid.Clean)
}
Ejemplo n.º 18
0
func ExampleFormatter() {
	u4 := uuid.NewV4()
	fmt.Println(uuid.Formatter(u4, uuid.FormatCanonicalCurly))
}
Ejemplo n.º 19
0
	. "github.com/onsi/gomega"
	"github.com/twinj/uuid"
)

var _ = Describe("Core", func() {

	Describe("DeviceFile", func() {
		It("should implement DeviceFile", func() {
			var f DeviceFile
			f = &HardwareFile{}
			Ω(f).ShouldNot(BeNil())
		})
		It("should read/write to a real file", func() {
			f := HardwareFile{}
			u4 := uuid.NewV4()
			name := uuid.Formatter(u4, uuid.Clean)
			tmp := path.Join(os.TempDir(), name+".gotest.tmp")

			By("using tmp " + tmp)
			// Write to the file
			err := f.Write(tmp, "Hello World")
			Ω(err).Should(BeNil())
			// Read and verify file
			text, err := f.Read(tmp)
			Ω(err).Should(BeNil())
			Ω(text).Should(Equal("Hello World"))
			// Test file existence directly
			found, err := ioutil.ReadFile(tmp)
			Ω(err).Should(BeNil())
			Ω(found).Should(Equal([]byte("Hello World")))
			// Clean up
Ejemplo n.º 20
0
func getUuid() string {
	theUuid := uuid.NewV4()
	return uuid.Formatter(theUuid, uuid.Clean)
}
Ejemplo n.º 21
0
func ExampleFormatter() {
	u4 := uuid.NewV4()
	fmt.Printf(uuid.Formatter(u4, uuid.CurlyHyphen))
}
Ejemplo n.º 22
0
func HandleInstancesPost(w rest.ResponseWriter, r *rest.Request) {
	fmt.Println("POST /instances")

	// Get body
	body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
	if err != nil {
		panic(err)
	}
	if err := r.Body.Close(); err != nil {
		panic(err)
	}

	// Create and populate instance
	var instance Instance = Instance{}
	instance.SetPayloadFromJson(body)

	// Check if request is authorized
	_, ok := r.Env["REMOTE_USER"]
	if ok == true {
		// Request is from our own identity
		instance.Owner = rt.self
		instance.ID = uuid.Formatter(uuid.NewV4(), uuid.CleanHyphen)
		instance.Payload.ID = instance.ID
		instance.Payload.Owner = instance.Owner.ID
		err = instance.Sign()

		if err == nil {
			// Insert instance
			_, err = db.C("instances").UpsertId(instance.ID, &instance)
			if err == nil {
				w.WriteJson(instance.Payload)
				instance.Push()
				instance.Broadcast()
				return
			}
		}
	} else {
		// Request is not authorized
		// so check if it should be
		if instance.Payload.Owner == rt.self.ID {
			fmt.Println("Missing authentication")
			clientError(w, "An authenticated request is required to post as this identity's owner")
			return
		}
		// Request is from a different identity
		valid, err := instance.Verify()
		if err == nil {
			if valid == true {
				fmt.Println(">>> IS VALID")
				// Insert instance
				_, err = db.C("instances").UpsertId(instance.ID, &instance)
				if err == nil {
					w.WriteJson(instance.Payload)
					instance.Push()
					instance.Broadcast()
					return
				}
			} else {
				fmt.Println(">>> IS *NOT* VALID")
				clientError(w, "Invalid signature")
				return
			}
		} else {
			fmt.Println(">>> error validating", err)
			clientError(w, "Could not validate signature")
			return
		}
	}
	clientError(w, err.Error())
}
Ejemplo n.º 23
0
func (neo *neoSession) Id() string {
	return uuid.Formatter(uuid.NewV4(), uuid.CleanHyphen)
}