Exemplo n.º 1
0
func main() {
	logger := log.New(os.Stdout, "", log.Ldate|log.Ltime|log.Lshortfile)

	args, _ := docopt.Parse(usage, nil, true, "cdef", false)

	if !utility.FileExists(args["<name>"].(string)) {
		logger.Fatalf("File %s not found", args["<name>"])
	}

	cbytes, err := ioutil.ReadFile(args["<name>"].(string))
	if err != nil {
		logger.Fatalf("Error while reading from the file; %s", err)
	}

	logger.Printf("Opened file %s", args["<name>"].(string))

	lines := strings.Split(string(cbytes), "\n")

	gocode := ""
	counter := 0

	for i, v := range lines {
		if len(v) > 2 && v[:2] == "$ " {
			gocode += v[2:] + "\n"
			counter++
		}

		if i == 0 {
			gocode += "const (\n"
		}

		if v[0] != '$' && v[0] != '#' && strings.Trim(v, " \r\t") != "" {
			parts := strings.Split(v, " ")

			if len(parts) != 2 {
				logger.Printf("Line %d has invalid syntax", i+1)
			} else {
				gocode += "\t" + strings.Trim(parts[1], "\r\n") + " = " + parts[0] + "\n"
				counter++
			}
		}

		if i == len(lines)-1 {
			gocode += ")\n"
		}
	}

	logger.Printf("Parsed %d valid lines", counter)

	err = ioutil.WriteFile(args["-o"].(string), []byte(gocode), 0644)
	if err != nil {
		logger.Fatalf("Error while writing to %s; %s", args["-o"].(string), err)
	} else {
		logger.Printf("Successfully generated %s", args["-o"].(string))
	}
}
Exemplo n.º 2
0
func init() {
	// If the file exists, read the current secret
	if utility.FileExists(secretfile) {
		// Read the file
		contents, _ := ioutil.ReadFile(secretfile)
		// Set the secret
		secret = string(contents)
		// Print it to the logs
		logger.Printf("%s loaded", secretfile)
	} else {
		// Generate a new random 32 char-long string
		secret = uniuri.NewLen(32)
		// Write it to the secretfile
		ioutil.WriteFile(secretfile, []byte(secret), os.ModePerm)
		// Print it to the logs
		logger.Printf("%s created", secretfile)
	}
}
func RPCFriendsGetUserAvatarMessage(conn net.Conn, connection_data *structs.ConnData, packet_data *structs.PacketData) error {
	// Unmarshal the message
	msg := new(protocol.FriendsGetUserAvatarMessage)
	err := proto.Unmarshal(packet_data.Content, msg)
	if err != nil {
		return err
	}

	mutexCreation.Lock()
	mutex, exists := downloadMutexes[msg.GetGuid()]
	if !exists {
		downloadMutexes[msg.GetGuid()] = new(sync.Mutex)
		mutex = downloadMutexes[msg.GetGuid()]
	}
	mutexCreation.Unlock()

	mutex.Lock()
	defer mutex.Unlock()

	// Check for data in the cache
	cached, ok := avatarCache[msg.GetGuid()]
	if ok {
		//logger.Errorf("Getting %d avatar from cache", msg.GetGuid())

		return reply.Reply(conn, packet_data.Header.Id, &protocol.FriendsGetUserAvatarResultMessage{
			Result:   proto.Int32(0),
			Guid:     msg.Guid,
			FileData: cached,
		})
	}

	// Query the database for the avatar info
	var rows []*struct {
		Email string
		Type  string
		Image string
	}

	err = environment.Env.Database.Query(`
SELECT
	email,
	avatar_type as type,
	avatar_image as image
FROM 
	misago_user
WHERE
	id = ?`, int(msg.GetGuid())).Rows(&rows)

	// Query error, something's wrong!
	if err != nil {
		return err
	}

	// No user found, might be a bug or invalid client request
	if len(rows) < 1 {
		return nil
	}

	// Load file from disk
	if rows[0].Type == "upload" {
		// Generate the filepath
		filename := filepath.Join(environment.Env.Config.NP.AvatarsPath, rows[0].Image)

		//logger.Errorf("Getting %d avatar from disk; %s", msg.GetGuid(), filename)

		// Ensure the file exists
		if !utility.FileExists(filename) {
			return nil
		}

		// Read file contents
		filecontents, err := ioutil.ReadFile(filename)
		if err != nil {
			return err
		}

		// Get the extension of the file
		ext := filepath.Ext(filename)

		// Convert from jpg to png
		if ext == ".jpg" || ext == ".jpeg" {
			rd := bytes.NewReader(filecontents)
			img, err := jpeg.Decode(rd)
			if err != nil {
				return err
			}

			buf := make([]byte, 0)
			wr := bytes.NewBuffer(buf)
			err = png.Encode(wr, img)
			if err != nil {
				return err
			}

			filecontents = wr.Bytes()
		}

		// Convert from gif to png
		if ext == ".gif" {
			rd := bytes.NewReader(filecontents)
			img, err := gif.Decode(rd)
			if err != nil {
				return err
			}

			buf := make([]byte, 0)
			wr := bytes.NewBuffer(buf)
			err = png.Encode(wr, img)
			if err != nil {
				return err
			}

			filecontents = wr.Bytes()
		}

		// Cache it
		avatarCache[msg.GetGuid()] = filecontents
		//avatarCache.Set(strconv.Itoa(int(msg.GetGuid())), filecontents, -1)

		// Return it to the client
		return reply.Reply(conn, packet_data.Header.Id, &protocol.FriendsGetUserAvatarResultMessage{
			Result:   proto.Int32(0),
			Guid:     msg.Guid,
			FileData: filecontents,
		})
	} else if rows[0].Type == "gravatar" {
		// Download the avatar
		data, err := gravatar.GetAvatar("http", gravatar.EmailHash(rows[0].Email), 96, gravatar.DefaultIdentIcon)
		if err != nil {
			return err
		}

		//logger.Errorf("Getting %d avatar from internet; %s", msg.GetGuid(), rows[0].Email)

		// Cache it
		//avatarCache.Set(strconv.Itoa(int(msg.GetGuid())), data, -1)
		avatarCache[msg.GetGuid()] = data

		// Return it to the client
		return reply.Reply(conn, packet_data.Header.Id, &protocol.FriendsGetUserAvatarResultMessage{
			Result:   proto.Int32(0),
			Guid:     msg.Guid,
			FileData: data,
		})
	}

	return nil
}
Exemplo n.º 4
0
func main() {
	reader := bufio.NewReader(os.Stdin)

	fmt.Println("aiw3/maps 0.1.1")
	fmt.Print("Please type which kind of files you want to download [client/server]: ")
	cur_type, err := reader.ReadString('\n')
	cur_type = strings.Trim(cur_type, "\n\r")
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	if cur_type != "client" && cur_type != "server" {
		fmt.Println("Invalid type")
		os.Exit(1)
	}

	fmt.Println("Loading packages list...")

	resp, err := http.Get("https://cloudrack.io/aiw3/maps.json")
	if err != nil {
		fmt.Printf("Error while downloading map data; %s", err)
		os.Exit(1)
	}
	defer resp.Body.Close()

	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Printf("Error while downloading map data; %s", err)
		os.Exit(1)
	}

	var maps Maps
	err = json.Unmarshal(body, &maps)
	if err != nil {
		fmt.Printf("Error while parsing map data; %s", err)
		os.Exit(1)
	}

	fmt.Println("Verifying repository's integrity...")
	for _, pkg := range maps.Packages {
		for name, _ := range pkg.Files {
			if _, exists := maps.Files[name]; !exists {
				fmt.Printf("Invalid repository; File %s does not exist (required by %s).\n", name, pkg.Id)
				os.Exit(1)
			}
		}
	}

	fmt.Println("Choose the map to install:")

	for i, pkg := range maps.Packages {
		fmt.Printf("[%d] %s (%s)\n", i, pkg.Name, pkg.Id)
	}

	fmt.Printf("[%d] All files (both client and server)\n", len(maps.Packages))

	fmt.Print("Type in the ID of the map you want to install: ")

	input, err := reader.ReadString('\n')
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	i, err := strconv.Atoi(strings.Trim(input, "\r\n"))
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}

	if i > len(maps.Packages) || i < 0 {
		fmt.Println("Package does not exist.")
		os.Exit(1)
	}

	if i < len(maps.Packages) {
		pkg := maps.Packages[i]

		for name, side := range pkg.Files {
			if side == "shared" || side == cur_type {
				abs, err := filepath.Abs(name)
				if err != nil {
					fmt.Println(err)
					os.Exit(1)
				}

				if utility.FileExists(abs) {
					fmt.Println(name + " already exists")
					continue
				}

				dir := filepath.Dir(abs)

				err = mkdirp.Mk(dir, 755)
				if err != nil {
					fmt.Println(err)
					os.Exit(1)
				}

				fmt.Printf("Downloading %s\n", name)
				var cmd *exec.Cmd

				if runtime.GOOS == "windows" {
					cmd = exec.Command("megatools/megadl", "--path="+dir, maps.Files[name])
				} else {
					cmd = exec.Command("megadl", "--path="+dir, maps.Files[name])
				}

				cmd.Stdout = os.Stdout
				cmd.Stderr = os.Stderr
				err = cmd.Run()
				if err != nil {
					fmt.Println(err)
					os.Exit(1)
				}
			}
		}
	} else {
		for name, url := range maps.Files {
			abs, err := filepath.Abs(name)
			if err != nil {
				fmt.Println(err)
				os.Exit(1)
			}

			if utility.FileExists(abs) {
				fmt.Println(name + " already exists")
				continue
			}

			dir := filepath.Dir(abs)

			err = mkdirp.Mk(dir, 755)
			if err != nil {
				fmt.Println(err)
				os.Exit(1)
			}

			fmt.Printf("Downloading %s\n", name)
			cmd := exec.Command("megatools/megadl", "--path="+dir, url)
			cmd.Stdout = os.Stdout
			cmd.Stderr = os.Stderr
			err = cmd.Run()
			if err != nil {
				fmt.Println(err)
				os.Exit(1)
			}
		}
	}

	fmt.Println("Install completed.")
}