Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Prune CLI comments

Manav Rathi02c4c2000869
diff --git a/cli/Dockerfile b/cli/Dockerfile
index c484afd333..b0028cb733 100644
--- a/cli/Dockerfile
+++ b/cli/Dockerfile
@@ -8,7 +8,6 @@ COPY go.sum .
RUN go mod download
COPY . .
-# the --mount option requires BuildKit. Refer to https://docs.docker.com/go/buildkit/ to learn how to build images with BuildKit enabled
RUN --mount=type=cache,target=/root/.cache/go-build \
go build -o ente-cli main.go
diff --git a/cli/cmd/account.go b/cli/cmd/account.go
index 6c381fc2b3..60db8ca108 100644
--- a/cli/cmd/account.go
+++ b/cli/cmd/account.go
@@ -8,13 +8,11 @@ import (
"github.com/spf13/cobra"
)
-// Define the 'account' command and its subcommands
var accountCmd = &cobra.Command{
Use: "account",
Short: "Manage account settings",
}
-// Subcommand for 'account list'
var listAccCmd = &cobra.Command{
Use: "list",
Short: "list configured accounts",
@@ -24,7 +22,6 @@ var listAccCmd = &cobra.Command{
},
}
-// Subcommand for 'account add'
var addAccCmd = &cobra.Command{
Use: "add",
Short: "login into existing account",
@@ -35,7 +32,6 @@ var addAccCmd = &cobra.Command{
},
}
-// Subcommand for 'account update'
var updateAccCmd = &cobra.Command{
Use: "update",
Short: "Update an existing account's export directory",
@@ -74,7 +70,6 @@ var updateAccCmd = &cobra.Command{
},
}
-// Subcommand for 'account update'
var getTokenCmd = &cobra.Command{
Use: "get-token",
Short: "Get token for an account for a specific app",
@@ -85,7 +80,6 @@ var getTokenCmd = &cobra.Command{
if email == "" {
fmt.Println("email must be specified, use --help for more information")
- // print help
return
}
@@ -110,9 +104,7 @@ var getTokenCmd = &cobra.Command{
}
func init() {
- // Add 'config' subcommands to the root command
rootCmd.AddCommand(accountCmd)
- // Add 'config' subcommands to the 'config' command
updateAccCmd.Flags().String("dir", "", "update export directory")
updateAccCmd.Flags().String("email", "", "email address of the account")
updateAccCmd.Flags().String("app", "photos", "Specify the app, default is 'photos'")
diff --git a/cli/cmd/authenticator.go b/cli/cmd/authenticator.go
index c9a7bdad63..8c26981bf9 100644
--- a/cli/cmd/authenticator.go
+++ b/cli/cmd/authenticator.go
@@ -5,17 +5,15 @@ import (
"github.com/spf13/cobra"
)
-// Define the 'config' command and its subcommands
var authenticatorCmd = &cobra.Command{
Use: "auth",
Short: "Authenticator commands",
}
-// Subcommand for 'config update'
var decryptExportCmd = &cobra.Command{
Use: "decrypt [input] [output]",
Short: "Decrypt authenticator export",
- Args: cobra.ExactArgs(2), // Ensures exactly two arguments are passed
+ Args: cobra.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
inputPath := args[0]
outputPath := args[1]
diff --git a/cli/cmd/config.go b/cli/cmd/config.go
index 632d7559fd..89c8d63f62 100644
--- a/cli/cmd/config.go
+++ b/cli/cmd/config.go
@@ -6,13 +6,11 @@ import (
"github.com/spf13/viper"
)
-// Define the 'config' command and its subcommands
var configCmd = &cobra.Command{
Use: "config",
Short: "Manage configuration settings",
}
-// Subcommand for 'config show'
var showCmd = &cobra.Command{
Use: "show",
Short: "Show configuration settings",
@@ -21,7 +19,6 @@ var showCmd = &cobra.Command{
},
}
-// Subcommand for 'config update'
var updateCmd = &cobra.Command{
Use: "update",
Short: "Update a configuration setting",
@@ -36,22 +33,13 @@ var updateCmd = &cobra.Command{
},
}
-// Flag to specify the 'host' configuration value
var host string
func init() {
- // Set up Viper configuration
- // Set a default value for 'host' configuration
viper.SetDefault("host", "https://api.ente.com")
- // Add 'config' subcommands to the root command
- //rootCmd.AddCommand(configCmd)
-
- // Add flags to the 'config store' and 'config update' subcommands
updateCmd.Flags().StringVarP(&host, "host", "H", viper.GetString("host"), "Update the 'host' configuration")
- // Mark 'host' flag as required for the 'update' command
updateCmd.MarkFlagRequired("host")
- // Add 'config' subcommands to the 'config' command
configCmd.AddCommand(showCmd, updateCmd)
}
diff --git a/cli/cmd/export.go b/cli/cmd/export.go
index 4145fec50c..6cc95812bf 100644
--- a/cli/cmd/export.go
+++ b/cli/cmd/export.go
@@ -5,19 +5,16 @@ import (
"github.com/spf13/cobra"
)
-// exportCmd represents the export command
var exportCmd = &cobra.Command{
Use: "export",
Short: "Starts the export process",
Long: ``,
Run: func(cmd *cobra.Command, args []string) {
- // Retrieve flag values
shared, _ := cmd.Flags().GetBool("shared")
hidden, _ := cmd.Flags().GetBool("hidden")
albums, _ := cmd.Flags().GetStringSlice("albums")
emails, _ := cmd.Flags().GetStringSlice("emails")
excludeAlbums, _ := cmd.Flags().GetStringSlice("exclude-albums")
- // Create Filters struct with flag values
filters := model.Filter{
ExcludeShared: !shared,
ExcludeHidden: !hidden,
@@ -25,7 +22,6 @@ var exportCmd = &cobra.Command{
Albums: albums,
Emails: emails,
}
- // Call the Export function with the filters
ctrl.Export(filters)
},
}
@@ -33,7 +29,6 @@ var exportCmd = &cobra.Command{
func init() {
rootCmd.AddCommand(exportCmd)
- // Add flags for Filters struct fields with default value true
exportCmd.Flags().Bool("shared", true, "to exclude shared albums, pass --shared=false")
exportCmd.Flags().Bool("hidden", true, "to exclude hidden albums, pass --hidden=false")
exportCmd.Flags().StringSlice("albums", []string{}, "Comma-separated list of album names to export")
diff --git a/cli/cmd/root.go b/cli/cmd/root.go
index 2782b8df5d..7dd912dcd1 100644
--- a/cli/cmd/root.go
+++ b/cli/cmd/root.go
@@ -17,7 +17,6 @@ var version string
var ctrl *pkg.ClICtrl
-// rootCmd represents the base command when called without any subcommands
var rootCmd = &cobra.Command{
Use: "ente",
Short: "CLI tool for exporting your photos from Ente",
@@ -27,8 +26,6 @@ func GenerateDocs() error {
return doc.GenMarkdownTree(rootCmd, "./docs/generated")
}
-// Execute adds all child commands to the root command and sets flags appropriately.
-// This is called by main.main(). It only needs to happen once to the rootCmd.
func Execute(controller *pkg.ClICtrl, ver string) {
ctrl = controller
version = ver
@@ -39,24 +36,15 @@ func Execute(controller *pkg.ClICtrl, ver string) {
}
func init() {
- // Here you will define your flags and configuration settings.
- // Cobra supports persistent flags, which, if defined here,
- // will be global for your application.
-
- // rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.cli-go.yaml)")
-
- // Cobra also supports local flags, which will only run
- // when this action is called directly.
rootCmd.Flags().BoolP("toggle", "t", false, "Help message for toggle")
- viper.SetConfigName("config") // Name of your configuration file (e.g., config.yaml)
- viper.AddConfigPath(".") // Search for config file in the current directory
- viper.ReadInConfig() // Read the configuration file if it exists
+ viper.SetConfigName("config")
+ viper.AddConfigPath(".")
+ viper.ReadInConfig()
}
func recoverWithLog() {
if r := recover(); r != nil {
fmt.Println("Panic occurred:", r)
- // Print the stack trace
stackTrace := make([]byte, 1024*8)
stackTrace = stackTrace[:runtime.Stack(stackTrace, false)]
fmt.Printf("Stack Trace:\n%s", stackTrace)
diff --git a/cli/cmd/version.go b/cli/cmd/version.go
index 3431bcfc31..8c7a87c2c6 100644
--- a/cli/cmd/version.go
+++ b/cli/cmd/version.go
@@ -6,7 +6,6 @@ import (
"github.com/spf13/cobra"
)
-// versionCmd represents the version command
var versionCmd = &cobra.Command{
Use: "version",
Short: "Prints the current version",
diff --git a/cli/internal/api/client.go b/cli/internal/api/client.go
index a46ceac7c7..1ea75b59e9 100644
--- a/cli/internal/api/client.go
+++ b/cli/internal/api/client.go
@@ -21,7 +21,6 @@ var tokenMap map[string]string = make(map[string]string)
type Client struct {
restClient *resty.Client
- // use separate client for downloading files
downloadClient *resty.Client
}
diff --git a/cli/internal/api/collection.go b/cli/internal/api/collection.go
index f8c4c24d4e..7052521d7e 100644
--- a/cli/internal/api/collection.go
+++ b/cli/internal/api/collection.go
@@ -43,7 +43,6 @@ func (c *Client) GetFiles(ctx context.Context, collectionID, sinceTime int64) ([
return res.Files, res.HasMore, err
}
-// GetFile ..
func (c *Client) GetFile(ctx context.Context, collectionID, fileID int64) (*File, error) {
var res struct {
File File `json:"file"`
diff --git a/cli/internal/api/collection_type.go b/cli/internal/api/collection_type.go
index f3bba7bb80..a034d94660 100644
--- a/cli/internal/api/collection_type.go
+++ b/cli/internal/api/collection_type.go
@@ -1,6 +1,5 @@
package api
-// Collection represents a collection
type Collection struct {
ID int64 `json:"id"`
Owner CollectionUser `json:"owner"`
@@ -19,7 +18,6 @@ type Collection struct {
collectionKey []byte
}
-// CollectionUser represents the owner of a collection
type CollectionUser struct {
ID int64 `json:"id"`
Email string `json:"email"`
@@ -35,7 +33,6 @@ type MagicMetadata struct {
Header string `json:"header,omitempty" binding:"required"`
}
-// CollectionFileItem represents a file in an AddFilesRequest and MoveFilesRequest
type CollectionFileItem struct {
ID int64 `json:"id" binding:"required"`
EncryptedKey string `json:"encryptedKey" binding:"required"`
diff --git a/cli/internal/api/file_type.go b/cli/internal/api/file_type.go
index 93a23b7b0b..018db35a64 100644
--- a/cli/internal/api/file_type.go
+++ b/cli/internal/api/file_type.go
@@ -1,6 +1,5 @@
package api
-// File represents an encrypted file in the system
type File struct {
ID int64 `json:"id"`
OwnerID int64 `json:"ownerID"`
@@ -22,13 +21,11 @@ func (f File) IsRemovedFromAlbum() bool {
return f.IsDeleted || f.File.EncryptedData == "-"
}
-// FileInfo has information about storage used by the file & it's metadata(future)
type FileInfo struct {
FileSize int64 `json:"fileSize,omitempty"`
ThumbnailSize int64 `json:"thumbSize,omitempty"`
}
-// FileAttributes represents a file item
type FileAttributes struct {
EncryptedData string `json:"encryptedData,omitempty"`
DecryptionHeader string `json:"decryptionHeader" binding:"required"`
diff --git a/cli/internal/api/log.go b/cli/internal/api/log.go
index 31ce404df0..da7c9f3e22 100644
--- a/cli/internal/api/log.go
+++ b/cli/internal/api/log.go
@@ -30,7 +30,6 @@ func logRequest(req *resty.Request) {
}
}
}
- // log query params if present
if len(req.QueryParam) > 0 {
fmt.Println(color.GreenString("Query Params:"))
for k, v := range req.QueryParam {
diff --git a/cli/internal/api/login_type.go b/cli/internal/api/login_type.go
index 6735f7ee81..10a760f511 100644
--- a/cli/internal/api/login_type.go
+++ b/cli/internal/api/login_type.go
@@ -21,7 +21,6 @@ type CreateSRPSessionResponse struct {
SRPB string `json:"srpB" binding:"required"`
}
-// KeyAttributes stores the key related attributes for a user
type KeyAttributes struct {
KEKSalt string `json:"kekSalt" binding:"required"`
KEKHash string `json:"kekHash"`
@@ -42,8 +41,7 @@ type AuthorizationResponse struct {
Token string `json:"token,omitempty"`
TwoFactorSessionID string `json:"twoFactorSessionID"`
PassKeySessionID string `json:"passkeySessionID"`
- // SrpM2 is sent only if the user is logging via SRP
- // SrpM2 is the SRP M2 value aka the proof that the server has the verifier
+ // SrpM2 proves that the server has the SRP verifier.
SrpM2 *string `json:"srpM2,omitempty"`
}
diff --git a/cli/internal/crypto/crypto.go b/cli/internal/crypto/crypto.go
index e01ac52d1f..d82991f6ae 100644
--- a/cli/internal/crypto/crypto.go
+++ b/cli/internal/crypto/crypto.go
@@ -31,40 +31,23 @@ var (
const ()
-// DeriveArgonKey generates a 32-bit cryptographic key using the Argon2id algorithm.
-// Parameters:
-// - password: The plaintext password to be hashed.
-// - salt: The salt as a base64 encoded string.
-// - memLimit: The memory limit in bytes.
-// - opsLimit: The number of iterations.
-//
-// Returns:
-// - A byte slice representing the derived key.
-// - An error object, which is nil if no error occurs.
func DeriveArgonKey(password, salt string, memLimit, opsLimit int) ([]byte, error) {
if memLimit < 1024 || opsLimit < 1 {
return nil, fmt.Errorf("invalid memory or operation limits")
}
- // Decode salt from base64
saltBytes, err := base64.StdEncoding.DecodeString(salt)
if err != nil {
return nil, fmt.Errorf("invalid salt: %v", err)
}
- // Generate key using Argon2id
- // Note: We're assuming a fixed key length of 32 bytes and changing the threads
key := argon2.IDKey([]byte(password), saltBytes, uint32(opsLimit), uint32(memLimit/1024), 1, 32)
return key, nil
}
-// DeriveLoginKey derives a login key from the given key encryption key.
-// This loginKey act as user provided password during SRP authentication.
-// Parameters: keyEncKey: This is the keyEncryptionKey that is derived from the user's password.
func DeriveLoginKey(keyEncKey []byte) []byte {
subKey, _ := deriveSubKey(keyEncKey, loginSubKeyContext, loginSubKeyId, loginSubKeyLen)
- // return the first 16 bytes of the derived key
return subKey[:16]
}
@@ -72,14 +55,11 @@ func deriveSubKey(masterKey []byte, context string, subKeyID uint64, subKeyLengt
if subKeyLength < cryptoKDFBlake2bBytesMin || subKeyLength > cryptoKDFBlake2bBytesMax {
return nil, fmt.Errorf("subKeyLength out of bounds")
}
- // Pad the context
ctxPadded := make([]byte, cryptoGenerichashBlake2bPersonalBytes)
copy(ctxPadded, []byte(context))
- // Convert subKeyID to byte slice and pad
salt := make([]byte, cryptoGenerichashBlake2bSaltBytes)
binary.LittleEndian.PutUint64(salt, subKeyID)
- // Create a BLAKE2b configuration
config := &blake2b.Config{
Size: uint8(subKeyLength),
Key: masterKey,
@@ -90,23 +70,20 @@ func deriveSubKey(masterKey []byte, context string, subKeyID uint64, subKeyLengt
if err != nil {
return nil, err
}
- hasher.Write(nil) // No data, just using key, salt, and personalization
+ hasher.Write(nil)
return hasher.Sum(nil), nil
}
func DecryptChaChaBase64(data string, key []byte, nonce string) (string, []byte, error) {
- // Decode data from base64
dataBytes, err := base64.StdEncoding.DecodeString(data)
if err != nil {
// safe to log the encrypted data
return "", nil, fmt.Errorf("invalid base64 data %s: %v", data, err)
}
- // Decode nonce from base64
nonceBytes, err := base64.StdEncoding.DecodeString(nonce)
if err != nil {
return "", nil, fmt.Errorf("invalid nonce: %v", err)
}
- // Decrypt data
decryptedData, err := decryptChaCha20poly1305(dataBytes, key, nonceBytes)
if err != nil {
return "", nil, fmt.Errorf("failed to decrypt data: %v", err)
@@ -115,18 +92,15 @@ func DecryptChaChaBase64(data string, key []byte, nonce string) (string, []byte,
}
func DecryptChaChaBase64Auth(data string, key []byte, nonce string) (string, []byte, error) {
- // Decode data from base64
dataBytes, err := base64.StdEncoding.DecodeString(data)
if err != nil {
// safe to log the encrypted data
return "", nil, fmt.Errorf("invalid base64 data %s: %v", data, err)
}
- // Decode nonce from base64
nonceBytes, err := base64.StdEncoding.DecodeString(nonce)
if err != nil {
return "", nil, fmt.Errorf("invalid nonce: %v", err)
}
- // Decrypt data
decryptedData, err := decryptChaCha20poly1305V2(dataBytes, key, nonceBytes)
if err != nil {
return "", nil, fmt.Errorf("failed to decrypt data: %v", err)
diff --git a/cli/internal/crypto/crypto_native.go b/cli/internal/crypto/crypto_native.go
index 986bdec1da..70df751f3d 100644
--- a/cli/internal/crypto/crypto_native.go
+++ b/cli/internal/crypto/crypto_native.go
@@ -11,15 +11,6 @@ import (
"os"
)
-// EncryptChaCha20poly1305 encrypts the given data using the ChaCha20-Poly1305 algorithm.
-// Parameters:
-// - data: The plaintext data as a byte slice.
-// - key: The key for encryption as a byte slice.
-//
-// Returns:
-// - A byte slice representing the encrypted data.
-// - A byte slice representing the header of the encrypted data.
-// - An error object, which is nil if no error occurs.
func EncryptChaCha20poly1305(data []byte, key []byte) ([]byte, []byte, error) {
encryptor, header, err := NewEncryptor(key)
if err != nil {
@@ -47,8 +38,7 @@ func decryptChaCha20poly1305(data []byte, key []byte, nonce []byte) ([]byte, err
return decoded, nil
}
-// decryptChaCha20poly1305V2 is used only to decrypt Ente Auth data, where the
-// final tag value may be 0x0 instead of TagFinal.
+// Ente Auth data may end with TagMessage instead of TagFinal.
func decryptChaCha20poly1305V2(data []byte, key []byte, nonce []byte) ([]byte, error) {
decryptor, err := NewDecryptor(key, nonce)
if err != nil {
@@ -69,7 +59,6 @@ func SecretBoxOpenBase64(cipher string, nonce string, k []byte) ([]byte, error)
}
func SecretBoxOpen(c []byte, n []byte, k []byte) ([]byte, error) {
- // Check for valid lengths of nonce and key
if len(n) != 24 || len(k) != 32 {
return nil, ErrOpenBox
}
@@ -79,7 +68,6 @@ func SecretBoxOpen(c []byte, n []byte, k []byte) ([]byte, error) {
copy(nonce[:], n)
copy(key[:], k)
- // Decrypt the message using Go's nacl/secretbox
decrypted, ok := secretbox.Open(nil, c, &nonce, &key)
if !ok {
return nil, ErrOpenBox
@@ -93,15 +81,12 @@ func SealedBoxOpen(cipherText, publicKey, masterSecret []byte) ([]byte, error) {
return nil, ErrOpenBox
}
- // Extract ephemeral public key from the ciphertext
var ephemeralPublicKey [32]byte
copy(ephemeralPublicKey[:], publicKey[:32])
- // Extract ephemeral public key from the ciphertext
var masterKey [32]byte
copy(masterKey[:], masterSecret[:32])
- // Decrypt the message using nacl/box
decrypted, ok := box.OpenAnonymous(nil, cipherText, &ephemeralPublicKey, &masterKey)
if !ok {
return nil, ErrOpenBox
diff --git a/cli/internal/crypto/crypto_test.go b/cli/internal/crypto/crypto_test.go
index 6f9656a71d..b0a793f6f1 100644
--- a/cli/internal/crypto/crypto_test.go
+++ b/cli/internal/crypto/crypto_test.go
@@ -9,7 +9,7 @@ import (
const (
password = "test_password"
kdfSalt = "vd0dcYMGNLKn/gpT6uTFTw=="
- memLimit = 64 * 1024 * 1024 // 64MB
+ memLimit = 64 * 1024 * 1024
opsLimit = 2
cipherText = "kBXQ2PuX6y/aje5r22H0AehRPh6sQ0ULoeAO"
cipherNonce = "v7wsI+BFZsRMIjDm3rTxPhmi/CaUdkdJ"
diff --git a/cli/internal/crypto/stream.go b/cli/internal/crypto/stream.go
index 9e6d2bcaff..baf725128b 100644
--- a/cli/internal/crypto/stream.go
+++ b/cli/internal/crypto/stream.go
@@ -10,16 +10,10 @@ import (
"golang.org/x/crypto/poly1305"
)
-// public constants
const (
- //TagMessage the most common tag, that doesn't add any information about the nature of the message.
TagMessage = 0
- // TagPush indicates that the message marks the end of a set of messages,
- // but not the end of the stream. For example, a huge JSON string sent as multiple chunks can use this tag to indicate to the application that the string is complete and that it can be decoded. But the stream itself is not closed, and more data may follow.
TagPush = 0x01
- // TagRekey "forget" the key used to encrypt this message and the previous ones, and derive a new secret key.
TagRekey = 0x02
- // TagFinal indicates that the message marks the end of the stream, and erases the secret key used to encrypt the previous sequence.
TagFinal = TagPush | TagRekey
StreamKeyBytes = chacha20poly1305.KeySize
@@ -83,7 +77,6 @@ func NewEncryptor(key []byte) (Encryptor, []byte, error) {
k, err := chacha20.HChaCha20(key[:], header[:16])
if err != nil {
- //fmt.Printf("error: %v", err)
return nil, nil, err
}
copy(stream.k[:], k)
@@ -96,8 +89,6 @@ func NewEncryptor(key []byte) (Encryptor, []byte, error) {
for i, b := range header[cryptoCoreHchacha20InputBytes:] {
stream.nonce[i+cryptoSecretStreamXchacha20poly1305Counterbytes] = b
}
- // fmt.Printf("stream: %+v\n", stream.streamState)
-
return stream, header, nil
}
diff --git a/cli/internal/promt.go b/cli/internal/promt.go
index eec2a0295f..9c824fbb39 100644
--- a/cli/internal/promt.go
+++ b/cli/internal/promt.go
@@ -29,7 +29,6 @@ func GetUserInput(label string) (string, error) {
var input string
reader := bufio.NewReader(os.Stdin)
input, err := reader.ReadString('\n')
- //_, err := fmt.Scanln(&input)
if err != nil {
return "", err
}
@@ -42,7 +41,6 @@ func GetUserInput(label string) (string, error) {
func WaitForEnter(prompt string) error {
fmt.Println(prompt)
- // Create a new reader from standard input.
reader := bufio.NewReader(os.Stdin)
_, err := reader.ReadString('\n')
if err != nil {
@@ -95,7 +93,6 @@ func GetCode(promptText string, length int) (string, error) {
}
}
-// parseStorageSize parses a string representing a storage size (e.g., "500MB", "2GB") into bytes.
func parseStorageSize(input string) (int64, error) {
units := map[string]int64{
"MB": 1 << 20,
@@ -143,7 +140,6 @@ func ConfirmAction(promptText string) (bool, error) {
}
}
-// GetStorageSize prompts the user for a storage size and returns the size in bytes.
func GetStorageSize(promptText string) (int64, error) {
for {
input, err := GetUserInput(promptText)
@@ -195,7 +191,6 @@ func GetExportDir() string {
}
func ValidateDirForWrite(dir string) (bool, error) {
- // Check if the path exists
fileInfo, err := os.Stat(dir)
if err != nil {
if os.IsNotExist(err) {
@@ -204,13 +199,10 @@ func ValidateDirForWrite(dir string) (bool, error) {
return false, err
}
- // Check if the path is a directory
if !fileInfo.IsDir() {
return false, fmt.Errorf("path is not a directory")
}
- // Check for write permission
- // Check for write permission by creating a temp file
tempFile, err := os.CreateTemp(dir, "write_test_")
if err != nil {
return false, fmt.Errorf("write permission denied: %v", err)
@@ -227,7 +219,6 @@ func ValidateDirForWrite(dir string) (bool, error) {
}
func ResolvePath(path string) (string, error) {
- // Expand home directory if path starts with ~
if strings.HasPrefix(path, "~") {
home, err := os.UserHomeDir()
if err != nil {
@@ -240,7 +231,6 @@ func ResolvePath(path string) (string, error) {
}
}
- // Convert to absolute path
absPath, err := filepath.Abs(path)
if err != nil {
return "", err
diff --git a/cli/internal/promt_test.go b/cli/internal/promt_test.go
index c522768d6b..cc663f1953 100644
--- a/cli/internal/promt_test.go
+++ b/cli/internal/promt_test.go
@@ -7,13 +7,11 @@ import (
)
func TestResolvePath(t *testing.T) {
- // Get current working directory for testing relative paths
cwd, err := os.Getwd()
if err != nil {
t.Fatalf("Failed to get current working directory: %v", err)
}
- // Get home directory for testing ~ expansion
home, err := os.UserHomeDir()
if err != nil {
t.Fatalf("Failed to get home directory: %v", err)
@@ -109,7 +107,6 @@ func TestResolvePath(t *testing.T) {
return
}
- // Clean both paths for comparison to handle path separator differences
expectedClean := filepath.Clean(tt.expected)
resultClean := filepath.Clean(result)
@@ -117,7 +114,6 @@ func TestResolvePath(t *testing.T) {
t.Errorf("Expected %q, got %q", expectedClean, resultClean)
}
- // Verify the result is an absolute path
if !filepath.IsAbs(result) {
t.Errorf("Result %q is not an absolute path", result)
}
diff --git a/cli/main.go b/cli/main.go
index 49a0eb31c2..2d0e84c174 100644
--- a/cli/main.go
+++ b/cli/main.go
@@ -50,11 +50,9 @@ func main() {
}
}
- // Define a set of commands that do not require KeyHolder or cli initialisation.
skipInitCommands := map[string]struct{}{"version": {}, "docs": {}, "help": {}}
var keyHolder *secrets.KeyHolder
- // Only initialise KeyHolder if the command isn't in the skip list.
shouldInit := len(os.Args) > 1
if len(os.Args) > 1 {
if _, skip := skipInitCommands[os.Args[1]]; skip {
@@ -75,7 +73,6 @@ func main() {
}
if len(os.Args) == 1 {
- // If no arguments are passed, show help
os.Args = append(os.Args, "help")
}
if len(os.Args) == 2 && os.Args[1] == "docs" {
@@ -104,10 +101,10 @@ func main() {
}
func initConfig(cliConfigDir string) {
- viper.SetConfigName("config") // name of config file (without extension)
- viper.SetConfigType("yaml") // REQUIRED if the config file does not have the extension in the name
- viper.AddConfigPath(cliConfigDir + "/") // path to look for the config file in
- viper.AddConfigPath(".") // optionally look for config in the working directory
+ viper.SetConfigName("config")
+ viper.SetConfigType("yaml")
+ viper.AddConfigPath(cliConfigDir + "/")
+ viper.AddConfigPath(".")
viper.SetDefault("endpoint.api", constants.EnteApiUrl)
viper.SetDefault("log.http", false)
@@ -119,21 +116,18 @@ func initConfig(cliConfigDir string) {
}
}
-// GetCLIConfigDir returns the path to the .ente-cli folder and creates it if it doesn't exist.
func GetCLIConfigDir() (string, error) {
var configDir = os.Getenv("ENTE_CLI_CONFIG_DIR")
if configDir == "" {
- // for backward compatibility, check for ENTE_CLI_CONFIG_PATH
+ // ENTE_CLI_CONFIG_PATH is kept for backward compatibility.
configDir = os.Getenv("ENTE_CLI_CONFIG_PATH")
}
if configDir != "" {
- // remove trailing slash (for all OS)
configDir = strings.TrimSuffix(configDir, string(filepath.Separator))
return configDir, nil
}
- // Get the user's home directory
homeDir, err := os.UserHomeDir()
if err != nil {
return "", err
@@ -141,7 +135,6 @@ func GetCLIConfigDir() (string, error) {
cliDBPath := filepath.Join(homeDir, ".ente")
- // Check if the folder already exists, if not, create it
if _, err := os.Stat(cliDBPath); os.IsNotExist(err) {
err := os.MkdirAll(cliDBPath, 0755)
if err != nil {
diff --git a/cli/pkg/account.go b/cli/pkg/account.go
index 2b3a6da293..14be8df177 100644
--- a/cli/pkg/account.go
+++ b/cli/pkg/account.go
@@ -37,8 +37,7 @@ func (c *ClICtrl) AddAccount(cxt context.Context) {
srpAttr, flowErr := c.Client.GetSRPAttributes(cxt, email)
if flowErr != nil {
- // if flowErr type is ApiError and status code is 404, then set verifyEmail to true and continue
- // else return
+ // A 404 starts email verification; other errors end the login.
if apiErr, ok := flowErr.(*api.ApiError); ok && apiErr.StatusCode == 404 {
verifyEmail = true
} else {
@@ -82,7 +81,6 @@ func (c *ClICtrl) AddAccount(cxt context.Context) {
}
func (c *ClICtrl) storeAccount(_ context.Context, email string, userID int64, app api.App, secretInfo *model.AccSecretInfo, exportDir string) error {
- // get password
err := c.DB.Update(func(tx *bolt.Tx) error {
b, err := tx.CreateBucketIfNotExists([]byte(AccBucket))
if err != nil {
diff --git a/cli/pkg/admin_actions.go b/cli/pkg/admin_actions.go
index 069bf246c0..46b1bd2444 100644
--- a/cli/pkg/admin_actions.go
+++ b/cli/pkg/admin_actions.go
@@ -140,7 +140,6 @@ func (c *ClICtrl) UpdateFreeStorage(ctx context.Context, params model.AdminActio
utils.ByteCountDecimalGIB(storageSize), utils.ByteCountDecimalGIB(userDetails.Subscription.Storage),
date.Format("2006-01-02"),
time.UnixMicro(userDetails.Subscription.ExpiryTime).Format("2006-01-02"))
- // press y to confirm
confirmed, _ := internal.ConfirmAction("Are you sure you want to update the storage ('y' or 'n')?")
if !confirmed {
return nil
@@ -211,10 +210,8 @@ func (c *ClICtrl) buildAdminContext(ctx context.Context, adminEmail string) (con
func _parseDateOrDateTime(input string) (time.Time, error) {
var layout string
if strings.Contains(input, " ") {
- // If the input contains a space, assume it's a date-time format
layout = "2006-01-02 15:04:05"
} else {
- // If there's no space, assume it's just a date
layout = "2006-01-02"
}
return time.Parse(layout, input)
diff --git a/cli/pkg/authenticator/decrypt.go b/cli/pkg/authenticator/decrypt.go
index ddbae5909b..ae414fd5c0 100644
--- a/cli/pkg/authenticator/decrypt.go
+++ b/cli/pkg/authenticator/decrypt.go
@@ -29,7 +29,7 @@ func DecryptExport(inputPath string, outputPath string, password string) error {
outputFile, err := internal.ResolvePath(outputPath)
if err != nil {
return fmt.Errorf("error resolving outputFile path (out): %v", err)
- } // Implement your decryption logic here
+ }
data, err := os.ReadFile(exportFile)
if err != nil {
diff --git a/cli/pkg/cli.go b/cli/pkg/cli.go
index 7e737e6dd8..34b37ad5bf 100644
--- a/cli/pkg/cli.go
+++ b/cli/pkg/cli.go
@@ -18,7 +18,6 @@ type ClICtrl struct {
func (c *ClICtrl) Init() error {
tempPath := filepath.Join(GetCLITempPath(), "ente-download")
- // create temp folder if not exists
if _, err := os.Stat(tempPath); os.IsNotExist(err) {
err = os.Mkdir(tempPath, 0755)
if err != nil {
diff --git a/cli/pkg/disk.go b/cli/pkg/disk.go
index bf856a78cb..2cb530ccc8 100644
--- a/cli/pkg/disk.go
+++ b/cli/pkg/disk.go
@@ -19,14 +19,13 @@ const (
type albumDiskInfo struct {
ExportRoot string
AlbumMeta *export.AlbumMetadata
- // FileNames contain the name of the files at root level of the album folder
+ // FileNames tracks files at the root of the album directory.
FileNames *map[string]bool
MetaFileNameToDiskFileMap *map[string]*export.DiskFileMetadata
FileIdToDiskFileMap *map[int64]*export.DiskFileMetadata
}
func (a *albumDiskInfo) IsFilePresent(file model.RemoteFile) bool {
- // check if file.ID is present
_, ok := (*a.FileIdToDiskFileMap)[file.ID]
return ok
}
@@ -74,12 +73,10 @@ func (a *albumDiskInfo) IsMetaFileNamePresent(metaFileName string) bool {
return ok
}
-// GenerateUniqueMetaFileName generates a unique metafile name.
func (a *albumDiskInfo) GenerateUniqueMetaFileName(baseFileName, extension string) string {
potentialDiskFileName := fmt.Sprintf("%s%s.json", baseFileName, extension)
count := 1
for a.IsMetaFileNamePresent(potentialDiskFileName) {
- // separate the file name and extension
fileName := fmt.Sprintf("%s_%d", baseFileName, count)
potentialDiskFileName = fmt.Sprintf("%s%s.json", fileName, extension)
count++
@@ -90,12 +87,10 @@ func (a *albumDiskInfo) GenerateUniqueMetaFileName(baseFileName, extension strin
return potentialDiskFileName
}
-// GenerateUniqueFileName generates a unique file name.
func (a *albumDiskInfo) GenerateUniqueFileName(baseFileName, extension string) string {
fileName := fmt.Sprintf("%s%s", baseFileName, extension)
count := 1
for a.IsFileNamePresent(strings.ToLower(fileName)) {
- // separate the file name and extension
fileName = fmt.Sprintf("%s_%d%s", baseFileName, count, extension)
count++
if !a.IsFileNamePresent(strings.ToLower(fileName)) {
@@ -106,7 +101,6 @@ func (a *albumDiskInfo) GenerateUniqueFileName(baseFileName, extension string) s
}
func (a *albumDiskInfo) GetDiskFileMetadata(file model.RemoteFile) *export.DiskFileMetadata {
- // check if file.ID is present
diskFile, ok := (*a.FileIdToDiskFileMap)[file.ID]
if !ok {
return nil
diff --git a/cli/pkg/disk_test.go b/cli/pkg/disk_test.go
index 62fe8b169e..ccb5e5af1a 100644
--- a/cli/pkg/disk_test.go
+++ b/cli/pkg/disk_test.go
@@ -8,7 +8,7 @@ import (
func TestGenerateUniqueFileName(t *testing.T) {
existingFilenames := make(map[string]bool)
- testFilename := "FullSizeRender.jpg" // what Apple calls shared files
+ testFilename := "FullSizeRender.jpg"
existingFilenames[strings.ToLower(testFilename)] = true
@@ -16,7 +16,6 @@ func TestGenerateUniqueFileName(t *testing.T) {
FileNames: &existingFilenames,
}
- // this is taken from downloadEntry()
extension := filepath.Ext(testFilename)
baseFileName := strings.TrimSuffix(filepath.Clean(filepath.Base(testFilename)), extension)
@@ -25,7 +24,6 @@ func TestGenerateUniqueFileName(t *testing.T) {
if strings.Contains(newFilename, "_1_2") {
t.Fatalf("Filename contained _1_2")
} else {
- // add generated name to existing files
existingFilenames[strings.ToLower(newFilename)] = true
}
}
diff --git a/cli/pkg/download.go b/cli/pkg/download.go
index c004952332..a33ff445a4 100644
--- a/cli/pkg/download.go
+++ b/cli/pkg/download.go
@@ -22,7 +22,6 @@ func (c *ClICtrl) downloadAndDecrypt(
) (*string, error) {
dir := c.tempFolder
downloadPath := fmt.Sprintf("%s/%d", dir, file.ID)
- // check if file exists
if stat, err := os.Stat(downloadPath); err == nil && stat.Size() == file.Info.FileSize {
log.Printf("File already exists %s (%s)", file.GetTitle(), utils.ByteCountDecimal(file.Info.FileSize))
} else {
diff --git a/cli/pkg/mapper/authenticator.go b/cli/pkg/mapper/authenticator.go
index 67e48e0150..4b7b11914d 100644
--- a/cli/pkg/mapper/authenticator.go
+++ b/cli/pkg/mapper/authenticator.go
@@ -14,7 +14,6 @@ func MapRemoteAuthEntityToString(ctx context.Context, authEntity models.AuthEnti
return nil, fmt.Errorf("failed to decrypt auth enityt %s: %v", authEntity.ID, err)
}
decryptedStr := string(decrypted)
- // json decode the string
var jsonDecodedStr string
err = json.Unmarshal([]byte(decryptedStr), &jsonDecodedStr)
if err != nil {
diff --git a/cli/pkg/model/account.go b/cli/pkg/model/account.go
index 86ec45131a..67c25ee347 100644
--- a/cli/pkg/model/account.go
+++ b/cli/pkg/model/account.go
@@ -12,7 +12,6 @@ type Account struct {
App api.App `json:"app" binding:"required"`
MasterKey EncString `json:"masterKey" binding:"required"`
SecretKey EncString `json:"secretKey" binding:"required"`
- // PublicKey corresponding to the secret key
PublicKey string `json:"publicKey" binding:"required"`
Token EncString `json:"token" binding:"required"`
ExportDir string `json:"exportDir"`
diff --git a/cli/pkg/model/export/filter.go b/cli/pkg/model/export/filter.go
index 4ccba7ca91..9ea84063d7 100644
--- a/cli/pkg/model/export/filter.go
+++ b/cli/pkg/model/export/filter.go
@@ -1,16 +1,10 @@
package export
type Filters struct {
- // When true, none of the shared albums are exported
ExcludeShared bool
- // When true, none of the shared files are exported
ExcludeSharedFiles bool
- // When true, hidden albums are not exported
ExcludeHidden bool
- // when album name is provided, only files in those albums are exported
Albums []string
- // when email is provided, only files shared with that email are exported
Emails []string
- // for the listed album names, files in these albums are excluded
ExcludeAlbums []string
}
diff --git a/cli/pkg/model/export/metadata.go b/cli/pkg/model/export/metadata.go
index e96f93dcbf..4723319f04 100644
--- a/cli/pkg/model/export/metadata.go
+++ b/cli/pkg/model/export/metadata.go
@@ -10,18 +10,12 @@ type AlbumMetadata struct {
OwnerID int64 `json:"ownerID"`
AlbumName string `json:"albumName"`
IsDeleted bool `json:"isDeleted"`
- // This is to handle the case where two accounts are exporting to the same directory
- // and a album is shared between them
+ // Shared albums may be exported by multiple accounts into the same directory.
AccountOwnerIDs []int64 `json:"accountOwnerIDs"`
- // Folder name is the name of the disk folder that contains the album data
- // exclude this from json serialization
FolderName string `json:"-"`
}
-// AddAccountOwner adds the given account id to the list of account owners
-// if it is not already present. Returns true if the account id was added
-// and false otherwise
func (a *AlbumMetadata) AddAccountOwner(id int64) bool {
if slices.Contains(a.AccountOwnerIDs, id) {
return false
@@ -30,8 +24,6 @@ func (a *AlbumMetadata) AddAccountOwner(id int64) bool {
return true
}
-// DiskFileMetadata is the metadata for a file when exported to disk
-// For S3 compliant storage, we will introduce a new struct that will contain references to the albums
type DiskFileMetadata struct {
Title string `json:"title"`
Description *string `json:"description"`
@@ -40,7 +32,6 @@ type DiskFileMetadata struct {
ModificationTime time.Time `json:"modificationTime"`
Info *Info `json:"info"`
- // exclude this from json serialization
MetaFileName string `json:"-"`
}
@@ -58,6 +49,6 @@ type Info struct {
ID int64 `json:"id"`
Hash *string `json:"hash"`
OwnerID int64 `json:"ownerID"`
- // A file can contain multiple parts (example: live photos or burst photos)
+ // Live and burst photos can contain multiple files.
FileNames []string `json:"fileNames"`
}
diff --git a/cli/pkg/model/filter.go b/cli/pkg/model/filter.go
index 41e274d6e3..60cd9daff9 100644
--- a/cli/pkg/model/filter.go
+++ b/cli/pkg/model/filter.go
@@ -6,17 +6,11 @@ import (
)
type Filter struct {
- // When true, none of the shared albums are exported
ExcludeShared bool
- // When true, none of the shared files are exported
ExcludeSharedFiles bool
- // When true, hidden albums are not exported
ExcludeHidden bool
- // when album name is provided, only files in those albums are exported
Albums []string
- // when email is provided, only files shared with that email are exported
Emails []string
- // for the listed album names, files in these albums are excluded
ExcludeAlbums []string
}
@@ -54,17 +48,13 @@ func (f Filter) SkipAlbum(album RemoteAlbum, shouldLog bool) bool {
return false
}
-// excludeByName returns true if Albums list is not empty and album name is not in the list,
-// or if album name is in the ExcludeAlbums list
func (f Filter) excludeByName(album RemoteAlbum) bool {
- // Check if album is in the ExcludeAlbums list
for _, a := range f.ExcludeAlbums {
if strings.ToLower(a) == strings.ToLower(strings.TrimSpace(album.AlbumName)) {
return true
}
}
- // Check if Albums filter is set and album is not in the list
if len(f.Albums) > 0 {
for _, a := range f.Albums {
if strings.ToLower(a) == strings.ToLower(strings.TrimSpace(album.AlbumName)) {
diff --git a/cli/pkg/model/remote.go b/cli/pkg/model/remote.go
index 58e31a80be..6ff40cea6d 100644
--- a/cli/pkg/model/remote.go
+++ b/cli/pkg/model/remote.go
@@ -61,7 +61,6 @@ type AlbumFileEntry struct {
SyncedLocally bool `json:"localSync"`
}
-// SortAlbumFileEntry sorts the given entries by isDeleted and then by albumID
func SortAlbumFileEntry(entries []*AlbumFileEntry) {
sort.Slice(entries, func(i, j int) bool {
if entries[i].IsDeleted != entries[j].IsDeleted {
@@ -158,7 +157,6 @@ func (r *RemoteFile) GetModificationTime() time.Time {
func (r *RemoteFile) GetLatlong() *export.Location {
if r.PublicMetadata != nil {
- // check if lat and long key exists
if lat, ok := r.PublicMetadata["lat"]; ok {
if long, ok := r.PublicMetadata["long"]; ok {
if lat.(float64) == 0 && long.(float64) == 0 {
diff --git a/cli/pkg/remote_sync.go b/cli/pkg/remote_sync.go
index 77c1122f9a..9656ae40af 100644
--- a/cli/pkg/remote_sync.go
+++ b/cli/pkg/remote_sync.go
@@ -93,7 +93,7 @@ func (c *ClICtrl) fetchRemoteFiles(ctx context.Context) error {
maxUpdated = file.UpdationTime
}
if isFirstSync && file.IsRemovedFromAlbum() {
- // on first sync, no need to sync delete markers
+ // A first sync has no local album entries to delete.
continue
}
albumEntry := model.AlbumFileEntry{AlbumID: album.ID, FileID: file.ID, IsDeleted: file.IsRemovedFromAlbum(), SyncedLocally: false}
diff --git a/cli/pkg/remote_to_disk_album.go b/cli/pkg/remote_to_disk_album.go
index 97ac7217d1..f4f2667eb2 100644
--- a/cli/pkg/remote_to_disk_album.go
+++ b/cli/pkg/remote_to_disk_album.go
@@ -44,13 +44,11 @@ func (c *ClICtrl) createLocalFolderForRemoteAlbums(ctx context.Context, account
if metaByID != nil {
if strings.EqualFold(metaByID.AlbumName, album.AlbumName) {
- //log.Printf("Skipping album %s as it already exists", album.AlbumName)
continue
}
}
albumFolderName := filepath.Clean(album.AlbumName)
- // replace : with _
albumFolderName = strings.ReplaceAll(albumFolderName, ":", "_")
albumFolderName = strings.ReplaceAll(albumFolderName, "/", "_")
albumFolderName = strings.TrimSpace(albumFolderName)
@@ -66,7 +64,6 @@ func (c *ClICtrl) createLocalFolderForRemoteAlbums(ctx context.Context, account
}
}
}
- // Create album and meta folders if they don't exist
albumPath := filepath.Clean(filepath.Join(path, albumFolderName))
metaPath := filepath.Join(albumPath, ".meta")
if metaByID == nil {
@@ -79,14 +76,12 @@ func (c *ClICtrl) createLocalFolderForRemoteAlbums(ctx context.Context, account
}
}
} else {
- // rename meta.FolderName to albumFolderName
oldAlbumPath := filepath.Join(path, metaByID.FolderName)
log.Printf("Renaming path from %s to %s for album %s", oldAlbumPath, albumPath, album.AlbumName)
if err = os.Rename(oldAlbumPath, albumPath); err != nil {
return err
}
}
- // Handle meta file
metaFilePath := filepath.Join(path, albumFolderName, albumMetaFolder, albumMetaFile)
metaData := export.AlbumMetadata{
ID: album.ID,
@@ -105,12 +100,9 @@ func (c *ClICtrl) createLocalFolderForRemoteAlbums(ctx context.Context, account
return nil
}
-// readFolderMetadata returns a map of folder name to album metadata for all folders in the given path
-// and a map of album ID to album metadata for all albums in the given path.
func readFolderMetadata(path string) (map[string]*export.AlbumMetadata, map[int64]*export.AlbumMetadata, error) {
result := make(map[string]*export.AlbumMetadata)
albumIdToMetadataMap := make(map[int64]*export.AlbumMetadata)
- // Read the top-level directories in the given path
entries, err := os.ReadDir(path)
if err != nil {
return nil, nil, err
@@ -121,7 +113,6 @@ func readFolderMetadata(path string) (map[string]*export.AlbumMetadata, map[int6
metaFilePath := filepath.Join(path, dirName, albumMetaFolder, albumMetaFile)
// Initialize as nil, will remain nil if JSON file is not found or not readable
result[dirName] = nil
- // Read the JSON file if it exists
if _, err := os.Stat(metaFilePath); err == nil {
var metaData export.AlbumMetadata
metaDataBytes, err := os.ReadFile(metaFilePath)
diff --git a/cli/pkg/remote_to_disk_file.go b/cli/pkg/remote_to_disk_file.go
index bffd0f058f..9230d17a5f 100644
--- a/cli/pkg/remote_to_disk_file.go
+++ b/cli/pkg/remote_to_disk_file.go
@@ -98,7 +98,6 @@ func (c *ClICtrl) syncFiles(ctx context.Context, account model.Account) error {
}
}
} else {
- // file metadata is missing in the localDB
if albumFileEntry.IsDeleted {
delErr := c.DeleteAlbumEntry(ctx, albumFileEntry)
if delErr != nil {
@@ -146,7 +145,6 @@ func (c *ClICtrl) downloadEntry(ctx context.Context,
return err
}
fileDiskMetadata := mapper.MapRemoteFileToDiskMetadata(file)
- // Get the extension
extension := filepath.Ext(fileDiskMetadata.Title)
baseFileName := strings.TrimSuffix(filepath.Clean(filepath.Base(fileDiskMetadata.Title)), extension)
diskMetaFileName := diskInfo.GenerateUniqueMetaFileName(baseFileName, extension)
@@ -173,7 +171,6 @@ func (c *ClICtrl) downloadEntry(ctx context.Context,
videoExtn := filepath.Ext(videoPath)
videoFileName := diskInfo.GenerateUniqueFileName(baseFileName, videoExtn)
videoFilePath := filepath.Join(diskInfo.ExportRoot, diskInfo.AlbumMeta.FolderName, videoFileName)
- // move the decrypt file to filePath
moveErr := Move(videoPath, videoFilePath)
if moveErr != nil {
return moveErr
@@ -183,7 +180,6 @@ func (c *ClICtrl) downloadEntry(ctx context.Context,
} else {
fileName := diskInfo.GenerateUniqueFileName(baseFileName, extension)
filePath := filepath.Join(diskInfo.ExportRoot, diskInfo.AlbumMeta.FolderName, fileName)
- // move the decrypt file to filePath
err = Move(*decrypt, filePath)
if err != nil {
return err
@@ -211,7 +207,6 @@ func (c *ClICtrl) downloadEntry(ctx context.Context,
}
func removeDiskFile(diskFileMeta *export.DiskFileMetadata, diskInfo *albumDiskInfo) error {
- // remove the file from disk
log.Printf("Removing file %s from disk", diskFileMeta.MetaFileName)
err := os.Remove(filepath.Join(diskInfo.ExportRoot, diskInfo.AlbumMeta.FolderName, ".meta", diskFileMeta.MetaFileName))
if err != nil && !os.IsNotExist(err) {
@@ -226,13 +221,9 @@ func removeDiskFile(diskFileMeta *export.DiskFileMetadata, diskInfo *albumDiskIn
return diskInfo.RemoveEntry(diskFileMeta)
}
-// readFolderMetadata reads the metadata of the files in the given path
-// For disk export, a particular albums files are stored in a folder named after the album.
-// Inside the folder, the files are stored at top level and its metadata is stored in a .meta folder
func readFilesMetadata(home string, albumMeta *export.AlbumMetadata) (*albumDiskInfo, error) {
albumMetadataFolder := filepath.Join(home, albumMeta.FolderName, albumMetaFolder)
albumPath := filepath.Join(home, albumMeta.FolderName)
- // verify the both the album folder and the .meta folder exist
if _, err := os.Stat(albumMetadataFolder); err != nil {
return nil, err
}
@@ -240,10 +231,8 @@ func readFilesMetadata(home string, albumMeta *export.AlbumMetadata) (*albumDisk
return nil, err
}
result := make(map[string]*export.DiskFileMetadata)
- //fileNameToFileName := make(map[string]*export.DiskFileMetadata)
fileIdToMetadata := make(map[int64]*export.DiskFileMetadata)
claimedFileName := make(map[string]bool)
- // Read the top-level directories in the given path
albumFileEntries, err := os.ReadDir(albumPath)
if err != nil {
return nil, err
@@ -270,7 +259,6 @@ func readFilesMetadata(home string, albumMeta *export.AlbumMetadata) (*albumDisk
fileMetadataPath := filepath.Join(albumMetadataFolder, fileName)
// Initialize as nil, will remain nil if JSON file is not found or not readable
result[strings.ToLower(fileName)] = nil
- // Read the JSON file if it exists
var metaData export.DiskFileMetadata
metaDataBytes, err := os.ReadFile(fileMetadataPath)
if err != nil {
diff --git a/cli/pkg/secrets/key_holder.go b/cli/pkg/secrets/key_holder.go
index fa9330b4e4..c1b41873eb 100644
--- a/cli/pkg/secrets/key_holder.go
+++ b/cli/pkg/secrets/key_holder.go
@@ -11,8 +11,7 @@ import (
)
type KeyHolder struct {
- // DeviceKey is the key used to encrypt/decrypt the data while storing sensitive
- // information on the disk. Usually, it should be stored in OS Keychain.
+ // DeviceKey encrypts secrets stored on disk and normally lives in the OS keychain.
DeviceKey []byte
AccountSecrets map[string]*model.AccSecretInfo
CollectionKeys map[string][]byte
@@ -29,10 +28,6 @@ func NewKeyHolder(deviceKey []byte) *KeyHolder {
}
}
-// LoadSecrets loads the secrets for a given account using the provided CLI key.
-// It decrypts the token key, master key, and secret key using the CLI key.
-// The decrypted keys and the decoded public key are stored in the AccountSecrets map using the account key as the map key.
-// It returns the account secret information or an error if the decryption fails.
func (k *KeyHolder) LoadSecrets(account model.Account) (*model.AccSecretInfo, error) {
tokenKey := account.Token.MustDecrypt(k.DeviceKey)
masterKey := account.MasterKey.MustDecrypt(k.DeviceKey)
@@ -51,11 +46,6 @@ func (k *KeyHolder) GetAccountSecretInfo(ctx context.Context) *model.AccSecretIn
return k.AccountSecrets[accountKey]
}
-// GetCollectionKey retrieves the key for a given collection.
-// It first fetches the account secret information from the context.
-// If the collection owner's ID matches the user ID from the context, it decrypts the collection key using the master key.
-// If the collection is shared (i.e., the owner's ID does not match the user ID), it decrypts the collection key using the public and secret keys.
-// It returns the decrypted collection key or an error if the decryption fails.
func (k *KeyHolder) GetCollectionKey(ctx context.Context, collection api.Collection) ([]byte, error) {
accSecretInfo := k.GetAccountSecretInfo(ctx)
userID := ctx.Value("user_id").(int64)
diff --git a/cli/pkg/secrets/secret.go b/cli/pkg/secrets/secret.go
index 8422155519..5742b5646c 100644
--- a/cli/pkg/secrets/secret.go
+++ b/cli/pkg/secrets/secret.go
@@ -26,7 +26,6 @@ const (
)
func GetOrCreateClISecret() []byte {
- // get password
secret, err := keyring.Get(secretService, secretUser)
if err != nil {
@@ -44,23 +43,20 @@ func GetOrCreateClISecret() []byte {
}
key := make([]byte, keyLength)
rand.Read(key)
- // Store the key as a base64 encoded string
secret = base64.StdEncoding.EncodeToString(key)
keySetErr := keyring.Set(secretService, secretUser, secret)
if keySetErr != nil {
log.Fatal(fmt.Errorf("error setting password in keyring: %w", keySetErr))
}
}
- // Try to decode the secret as base64
decodedSecret, err := base64.StdEncoding.DecodeString(secret)
if err == nil && len(decodedSecret) == keyLength {
- // If successful and the length is correct, return the decoded secret
return decodedSecret
}
- // If decoding fails or the length is incorrect, treat it as a legacy key
+ // Older versions stored the raw key instead of base64.
legacySecret := []byte(secret)
if len(legacySecret) != keyLength {
- // See https://github.com/ente/ente/issues/1510#issuecomment-2331676096 for more information
+ // Invalid legacy keys are regenerated: https://github.com/ente/ente/issues/1510#issuecomment-2331676096
log.Println("Warning: Existing key is not 32 bytes. Deleting it")
delErr := keyring.Delete(secretService, secretUser)
if delErr != nil {
@@ -70,21 +66,15 @@ func GetOrCreateClISecret() []byte {
return GetOrCreateClISecret()
}
}
- // If it's a keyLength-byte legacy key, return it as-is
return legacySecret
}
-// GetSecretFromSecretText reads the scecret from the secret text file.
-// If the file does not exist, it will be created and write random keyLength bytes secret to it.
func GetSecretFromSecretText(secretFilePath string) []byte {
-
- // Check if file exists
_, err := os.Stat(secretFilePath)
if err != nil {
if !errors.Is(err, os.ErrNotExist) {
log.Fatal(fmt.Errorf("error checking secret file: %w", err))
}
- // File does not exist; create and write a random 32-byte secret
key := make([]byte, keyLength)
rand.Read(key)
err = os.WriteFile(secretFilePath, key, 0644)
@@ -93,7 +83,6 @@ func GetSecretFromSecretText(secretFilePath string) []byte {
}
return key
}
- // File exists; read the secret
secret, err := os.ReadFile(secretFilePath)
if err != nil {
log.Fatal(fmt.Errorf("error reading from secret file: %w", err))
diff --git a/cli/pkg/sign_in.go b/cli/pkg/sign_in.go
index 85bfb4a512..09c68da626 100644
--- a/cli/pkg/sign_in.go
+++ b/cli/pkg/sign_in.go
@@ -16,7 +16,6 @@ import (
func (c *ClICtrl) signInViaPassword(ctx context.Context, srpAttr *api.SRPAttributes) (*api.AuthorizationResponse, []byte, error) {
for {
- // CLI prompt for password
password, flowErr := internal.GetSensitiveField("Enter password")
if flowErr != nil {
return nil, nil, flowErr
@@ -51,9 +50,7 @@ func (c *ClICtrl) signInViaPassword(ctx context.Context, srpAttr *api.SRPAttribu
}
}
-// Parameters:
-// - keyEncKey: key encryption key is derived from user's password. During SRP based login, this key is already derived.
-// So, we can pass it to avoid asking for password again.
+// SRP login reuses the password-derived key to avoid another password prompt.
func (c *ClICtrl) decryptAccSecretInfo(
_ context.Context,
authResp *api.AuthorizationResponse,
@@ -65,7 +62,6 @@ func (c *ClICtrl) decryptAccSecretInfo(
var publicKey = encoding.DecodeBase64(authResp.KeyAttributes.PublicKey)
for {
if keyEncKey == nil {
- // CLI prompt for password
password, flowErr := internal.GetSensitiveField("Enter password")
if flowErr != nil {
return nil, flowErr
@@ -126,7 +122,6 @@ func (c *ClICtrl) validateTOTP(ctx context.Context, authResp *api.AuthorizationR
return authResp, nil
}
for {
- // CLI prompt for TOTP
totp, flowErr := internal.GetCode("Enter TOTP", 6)
if flowErr != nil {
return nil, flowErr
@@ -170,7 +165,6 @@ func (c *ClICtrl) validateEmail(ctx context.Context, email string) (*api.Authori
return nil, err
}
for {
- // CLI prompt for OTP
ott, flowErr := internal.GetCode("Enter OTP", 6)
if flowErr != nil {
return nil, flowErr
diff --git a/cli/pkg/store.go b/cli/pkg/store.go
index 589d71b5d1..86b60b50f2 100644
--- a/cli/pkg/store.go
+++ b/cli/pkg/store.go
@@ -92,7 +92,6 @@ func (c *ClICtrl) DeleteValue(ctx context.Context, store model.PhotosStore, key
})
}
-// GetValue
func (c *ClICtrl) GetValue(ctx context.Context, store model.PhotosStore, key []byte) ([]byte, error) {
var value []byte
err := c.DB.View(func(tx *bolt.Tx) error {
diff --git a/cli/pkg/sync_authenticator.go b/cli/pkg/sync_authenticator.go
index f096d8ba60..d9c398de5b 100644
--- a/cli/pkg/sync_authenticator.go
+++ b/cli/pkg/sync_authenticator.go
@@ -37,14 +37,12 @@ func (c *ClICtrl) writeAuthExport(ctx context.Context, account model.Account, da
return fmt.Errorf("export directory not set")
}
outputFile := fmt.Sprintf("%s/ente_auth.txt", exportDir)
- // if outout file exists, create a backup with current datetime
if _, err := os.Stat(outputFile); err == nil {
backupFile := fmt.Sprintf("%s/ente_auth_%s.txt", exportDir, time.Now().Format("2006-01-02_15-04-05"))
if err := os.Rename(outputFile, backupFile); err != nil {
return fmt.Errorf("error creating backup file: %v", err)
}
}
- // write the data to the output file, one line per entity
file, err := os.Create(outputFile)
if err != nil {
return fmt.Errorf("error creating output file: %v", err)
diff --git a/cli/release.sh b/cli/release.sh
index b3946c3810..05f97a0166 100755
--- a/cli/release.sh
+++ b/cli/release.sh
@@ -1,51 +1,39 @@
#!/bin/bash
-# Fetch the latest tag that starts with "cli-"
# shellcheck disable=SC2046
# shellcheck disable=SC2006
LATEST_TAG=$(git describe --tags `git rev-list --tags='cli-*' --max-count=1`)
-# Check if the LATEST_TAG variable is empty
if [ -z "$LATEST_TAG" ]; then
echo "No 'cli-' tag found. Exiting..."
exit 1
fi
VERSION=${LATEST_TAG#cli-}
-# Create a "bin" directory if it doesn't exist
mkdir -p bin
-# List of target operating systems
OS_TARGETS=("windows" "linux" "darwin")
-# Corresponding architectures for each OS
ARCH_TARGETS=("386 amd64" "386 amd64 arm arm64" "amd64 arm64")
export CGO_ENABLED=0
-# Loop through each OS target
for index in "${!OS_TARGETS[@]}"
do
OS=${OS_TARGETS[$index]}
for ARCH in ${ARCH_TARGETS[$index]}
do
- # Set the GOOS environment variable for the current target OS
export GOOS="$OS"
export GOARCH="$ARCH"
- # Set the output binary name to "ente-cli" for the current OS and architecture
BINARY_NAME="ente-$OS-$ARCH"
- # Add .exe extension for Windows
if [ "$OS" == "windows" ]; then
BINARY_NAME="ente-$OS-$ARCH.exe"
fi
- # Build the binary and place it in the "bin" directory
go build -ldflags="-X main.AppVersion=${VERSION} -s -w" -trimpath -o "bin/$BINARY_NAME" main.go
- # Print a message indicating the build is complete for the current OS and architecture
echo "Built for $OS ($ARCH) as bin/$BINARY_NAME"
done
done
-# Print a message indicating the build process is complete
echo "Build process completed for all platforms and architectures. Binaries are in the 'bin' directory."
diff --git a/cli/utils/browser/browser.go b/cli/utils/browser/browser.go
index d31e67c4b2..7a2224b2c1 100644
--- a/cli/utils/browser/browser.go
+++ b/cli/utils/browser/browser.go
@@ -6,8 +6,6 @@ import (
"strings"
)
-// https://stackoverflow.com/questions/39320371/how-start-web-server-to-open-page-in-browser-in-golang
-// openURL opens the specified URL in the default browser of the user.
func OpenURL(url string) error {
var cmd string
var args []string
@@ -20,25 +18,21 @@ func OpenURL(url string) error {
cmd = "open"
args = []string{url}
default: // "linux", "freebsd", "openbsd", "netbsd"
- // Check if running under WSL
if isWSL() {
- // Use 'cmd.exe /c start' to open the URL in the default Windows browser
cmd = "cmd.exe"
args = []string{"/c", "start", url}
} else {
- // Use xdg-open on native Linux environments
cmd = "xdg-open"
args = []string{url}
}
}
if len(args) > 1 {
- // args[0] is used for 'start' command argument, to prevent issues with URLs starting with a quote
+ // start treats its first quoted argument as a window title.
args = append(args[:1], append([]string{""}, args[1:]...)...)
}
return exec.Command(cmd, args...).Start()
}
-// isWSL checks if the Go program is running inside Windows Subsystem for Linux
func isWSL() bool {
releaseData, err := exec.Command("uname", "-r").Output()
if err != nil {