Skip to content

armgit / ente

Public Imported from GitHub
0

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

Prune server repository comments

Manav Rathi127dc8cee53c
diff --git a/server/ente/billing.go b/server/ente/billing.go
index a6ccdc6af3..98b09f46dd 100644
--- a/server/ente/billing.go
+++ b/server/ente/billing.go
@@ -10,21 +10,14 @@ import (
)
const (
- // FreePlanStorage is the amount of storage in free plan
- FreePlanStorage int64 = 10 * 1024 * 1024 * 1024
- // FreePlanProductID is the product ID of free plan
- FreePlanProductID = "free"
- // FreePlanTransactionID is the dummy transaction ID for the free plan
- FreePlanTransactionID = "none"
- // TrialPeriodDuration is the duration (in years) of the free trial
- TrialPeriodDuration = 100
- // TrialPeriod is the unit for the duration of the free trial
- TrialPeriod = "days"
-
- // PeriodYear is the unit for the duration of the yearly plan
+ FreePlanStorage int64 = 10 * 1024 * 1024 * 1024
+ FreePlanProductID = "free"
+ FreePlanTransactionID = "none"
+ TrialPeriodDuration = 100
+ TrialPeriod = "days"
+
PeriodYear = "year"
- // PeriodMonth is the unit for the duration of the monthly plan
PeriodMonth = "month"
Period3Years = "3"
@@ -33,42 +26,27 @@ const (
Period10Years = "10"
- // FamilyPlanProductID is the product ID of family (internal employees & their friends & family) plan
FamilyPlanProductID = "family"
- // StripeSignature is the header send by the stripe webhook to verify authenticity
StripeSignature = "Stripe-Signature"
- // OnHoldTemplate is the template for the email
- // that is to be sent out when an account enters the hold stage
OnHoldTemplate = "on_hold.html"
- // AccountOnHoldEmailSubject is the subject of account on hold email
AccountOnHoldEmailSubject = "Ente account on hold"
- // Template for the email we send out when the user's subscription ends,
- // either because the user cancelled their subscription, or because it
- // expired.
SubscriptionEndedEmailTemplate = "subscription_ended.html"
- // Subject for `SubscriptionEndedEmailTemplate`.
SubscriptionEndedEmailSubject = "Your subscription to Ente Photos has ended"
)
-// PaymentProvider represents the payment provider via which a purchase was made
type PaymentProvider string
const (
- // PlayStore was the payment provider
PlayStore PaymentProvider = "playstore"
- // AppStore was the payment provider
- AppStore PaymentProvider = "appstore"
- // Stripe was the payment provider
- Stripe PaymentProvider = "stripe"
- // Paypal was the payment provider
- Paypal PaymentProvider = "paypal"
- // BitPay was the payment provider
- BitPay PaymentProvider = "bitpay"
+ AppStore PaymentProvider = "appstore"
+ Stripe PaymentProvider = "stripe"
+ Paypal PaymentProvider = "paypal"
+ BitPay PaymentProvider = "bitpay"
)
type StripeAccountCountry string
@@ -86,21 +64,17 @@ const (
const DefaultStripeAccountCountry = StripeUS
-// AndroidNotification represents a notification received from PlayStore
type AndroidNotification struct {
Message AndroidNotificationMessage `json:"message"`
Subscription string `json:"subscription"`
}
-// AndroidNotificationMessage represents the message within the notification received from
-// PlayStore
type AndroidNotificationMessage struct {
Attributes map[string]string `json:"attributes"`
Data string `json:"data"`
MessageID string `json:"messageId"`
}
-// BillingPlan represents a billing plan
type BillingPlan struct {
ID string `json:"id"`
AndroidID string `json:"androidID"`
@@ -117,11 +91,9 @@ type FreePlan struct {
Period string `json:"period"`
}
-// Subscription represents a user's subscription to a billing plan
type Subscription struct {
- ID int64 `json:"id"`
- UserID int64 `json:"userID"`
- // Identifier of the product on respective stores that the user has subscribed to
+ ID int64 `json:"id"`
+ UserID int64 `json:"userID"`
ProductID string `json:"productID"`
Storage int64 `json:"storage"`
// LinkedPurchaseToken on PlayStore , OriginalTransactionID on AppStore and SubscriptionID on Stripe
@@ -134,26 +106,17 @@ type Subscription struct {
Period string `json:"period"`
}
-// SubscriptionAttributes represents a subscription's paymentProvider specific attributes
type SubscriptionAttributes struct {
- // IsCancelled represents if subscription's renewal have been cancelled
- IsCancelled bool `json:"isCancelled,omitempty"`
- // CustomerID represents the stripe customerID
- CustomerID string `json:"customerID,omitempty"`
- // LatestVerificationData is the the latestTransactionReceipt received
- LatestVerificationData string `json:"latestVerificationData,omitempty"`
- // StripeAccountCountry is the identifier for the account in which the subscription is created.
- StripeAccountCountry StripeAccountCountry `json:"stripeAccountCountry,omitempty"`
+ IsCancelled bool `json:"isCancelled,omitempty"`
+ CustomerID string `json:"customerID,omitempty"`
+ LatestVerificationData string `json:"latestVerificationData,omitempty"`
+ StripeAccountCountry StripeAccountCountry `json:"stripeAccountCountry,omitempty"`
}
-// Value implements the driver.Valuer interface. This method
-// simply returns the JSON-encoded representation of the struct.
func (ca SubscriptionAttributes) Value() (driver.Value, error) {
return json.Marshal(ca)
}
-// Scan implements the sql.Scanner interface. This method
-// simply decodes a JSON-encoded value into the struct fields.
func (ca *SubscriptionAttributes) Scan(value interface{}) error {
b, ok := value.([]byte)
if !ok {
@@ -163,14 +126,12 @@ func (ca *SubscriptionAttributes) Scan(value interface{}) error {
return json.Unmarshal(b, &ca)
}
-// SubscriptionVerificationRequest represents a request to verify a subscription done via a paymentProvider
type SubscriptionVerificationRequest struct {
PaymentProvider PaymentProvider `json:"paymentProvider"`
ProductID string `json:"productID"`
VerificationData string `json:"verificationData"`
}
-// StripeUpdateRequest represents a request to modify the stripe subscription
type StripeUpdateRequest struct {
ProductID string `json:"productID"`
}
diff --git a/server/ente/collection.go b/server/ente/collection.go
index 1e0f67d77a..4846549696 100644
--- a/server/ente/collection.go
+++ b/server/ente/collection.go
@@ -9,7 +9,6 @@ import (
var ValidCollectionTypes = []string{"album", "folder", "favorites", "uncategorized"}
-// Collection represents a collection
type Collection struct {
ID int64 `json:"id"`
Owner CollectionUser `json:"owner"`
@@ -33,8 +32,6 @@ type Collection struct {
SharedMagicMetadata *MagicMetadata `json:"sharedMagicMetadata,omitempty"`
}
-// AllowSharing indicates if this particular collection type can be shared
-// or not
func (c *Collection) AllowSharing() bool {
if c == nil {
return false
@@ -45,14 +42,10 @@ func (c *Collection) AllowSharing() bool {
return true
}
-// AllowParticipantSharing indicates whether a collection can be shared
-// directly with a participant in the given role.
func (c *Collection) AllowParticipantSharing(role CollectionParticipantRole) bool {
return c != nil && (c.Type != "uncategorized" || role == VIEWER)
}
-// AllowDelete indicates if this particular collection type can be deleted by the user
-// or not
func (c *Collection) AllowDelete() bool {
if c == nil {
return false
@@ -63,7 +56,6 @@ func (c *Collection) AllowDelete() bool {
return true
}
-// CollectionUser represents the owner of a collection
type CollectionUser struct {
ID int64 `json:"id"`
Email string `json:"email"`
@@ -72,21 +64,16 @@ type CollectionUser struct {
Role CollectionParticipantRole `json:"role"`
}
-// CollectionAttributes represents a collection's attribtues
type CollectionAttributes struct {
EncryptedPath string `json:"encryptedPath,omitempty"`
PathDecryptionNonce string `json:"pathDecryptionNonce,omitempty"`
Version int `json:"version"`
}
-// Value implements the driver.Valuer interface. This method
-// simply returns the JSON-encoded representation of the struct.
func (ca CollectionAttributes) Value() (driver.Value, error) {
return json.Marshal(ca)
}
-// Scan implements the sql.Scanner interface. This method
-// simply decodes a JSON-encoded value into the struct fields.
func (ca *CollectionAttributes) Scan(value interface{}) error {
b, ok := value.([]byte)
if !ok {
@@ -96,7 +83,6 @@ func (ca *CollectionAttributes) Scan(value interface{}) error {
return json.Unmarshal(b, &ca)
}
-// AlterShareRequest represents a share/unshare request
type AlterShareRequest struct {
CollectionID int64 `json:"collectionID" binding:"required"`
Email string `json:"email" binding:"required"`
@@ -158,13 +144,11 @@ type JoinCollectionViaLinkRequest struct {
EncryptedKey string `json:"encryptedKey" binding:"required"`
}
-// AddFilesRequest represents a request to add files to a collection
type AddFilesRequest struct {
CollectionID int64 `json:"collectionID" binding:"required"`
Files []CollectionFileItem `json:"files" binding:"required"`
}
-// CopyFileSyncRequest is request object for creating copy of CollectionFileItems, and those copy to the destination collection
type CopyFileSyncRequest struct {
SrcCollectionID int64 `json:"srcCollectionID" binding:"required"`
DstCollection int64 `json:"dstCollectionID" binding:"required"`
@@ -175,7 +159,6 @@ type CopyResponse struct {
OldToNewFileIDMap map[int64]int64 `json:"oldToNewFileIDMap"`
}
-// RemoveFilesRequest represents a request to remove files from a collection
type RemoveFilesRequest struct {
CollectionID int64 `json:"collectionID" binding:"required"`
// OtherFileIDs represents the files which don't belong the user trying to remove files
@@ -205,20 +188,17 @@ type RenameRequest struct {
NameDecryptionNonce string `json:"nameDecryptionNonce" binding:"required"`
}
-// UpdateCollectionMagicMetadata payload for updating magic metadata for single file
type UpdateCollectionMagicMetadata struct {
ID int64 `json:"id" binding:"required"`
MagicMetadata MagicMetadata `json:"magicMetadata" 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"`
KeyDecryptionNonce string `json:"keyDecryptionNonce" binding:"required"`
}
-// MoveFilesRequest represents movement of file between two collections
type MoveFilesRequest struct {
FromCollectionID int64 `json:"fromCollectionID" binding:"required"`
ToCollectionID int64 `json:"toCollectionID" binding:"required"`
diff --git a/server/ente/embedding.go b/server/ente/embedding.go
index cbbbb5574a..44d276f023 100644
--- a/server/ente/embedding.go
+++ b/server/ente/embedding.go
@@ -10,7 +10,6 @@ type Embedding struct {
Size *int64
}
-// IndexedFile ...
type IndexedFile struct {
FileID int64 `json:"fileID"`
UpdatedAt int64 `json:"updatedAt"`
diff --git a/server/ente/errors.go b/server/ente/errors.go
index 32c7792aef..ac30f4f094 100644
--- a/server/ente/errors.go
+++ b/server/ente/errors.go
@@ -6,22 +6,14 @@ import (
"net/http"
)
-// ErrPermissionDenied is returned when a user has insufficient permissions to
-// perform an action
var ErrPermissionDenied = errors.New("insufficient permissions to perform this action")
-// ErrIncorrectOTT is returned when a user tries to validate an email with an
-// incorrect OTT
var ErrIncorrectOTT = errors.New("incorrect OTT")
-// ErrExpiredOTT is returned when a user tries to validate an email but there's no active ott
var ErrExpiredOTT = errors.New("no active OTT")
-// ErrIncorrectTOTP is returned when a user tries to validate an two factor with an
-// incorrect TOTP
var ErrIncorrectTOTP = errors.New("incorrect TOTP")
-// ErrNotFound is returned when the requested resource was not found
var ErrNotFound = errors.New("not found")
var ErrCollectionDeleted = &ApiError{
@@ -36,75 +28,52 @@ var ErrFileLimitReached = ApiError{
HttpStatusCode: http.StatusForbidden,
}
-// ErrBadRequest is returned when a bad request is encountered
var ErrBadRequest = errors.New("bad request")
-// ErrTooManyBadRequest is returned when user send many bad requests, especailly for authentication
var ErrTooManyBadRequest = errors.New("too many bad request")
-// ErrUnexpectedState is returned when certain assumption/assets fails
var ErrUnexpectedState = errors.New("unexpected state")
-// ErrCannotDowngrade is thrown when a user tries to downgrade to a plan whose
-// limits are lower than current consumption
var ErrCannotDowngrade = errors.New("usage is greater than selected plan, cannot downgrade")
-// ErrCannotSwitchPaymentProvider is thrown when a user attempts to renew a subscription from a different payment provider
var ErrCannotSwitchPaymentProvider = errors.New("cannot switch payment provider")
-// ErrNoActiveSubscription is returned when user's doesn't has any active plans
var ErrNoActiveSubscription = errors.New("no Active Subscription")
-// ErrStorageLimitExceeded is thrown when user exceed the plan's data Storage limit
var ErrStorageLimitExceeded = errors.New("storage Limit exceeded")
-// ErrFileTooLarge thrown when an uploaded file is too large for the storage plan
var ErrFileTooLarge = errors.New("file too large")
-// ErrSharingDisabledForFreeAccounts is thrown when free subscription user tries to share files
var ErrSharingDisabledForFreeAccounts = errors.New("sharing Feature is disabled for free accounts")
-// ErrDuplicateFileObjectFound is thrown when another file with the same objectKey is detected
var ErrDuplicateFileObjectFound = errors.New("file object already exists")
var ErrFavoriteCollectionAlreadyExist = errors.New("favorites collection already exists")
var ErrUncategorizeCollectionAlreadyExists = errors.New("uncategorized collection already exists")
-// ErrDuplicateThumbnailObjectFound is thrown when another thumbnail with the same objectKey is detected
var ErrDuplicateThumbnailObjectFound = errors.New("thumbnail object already exists")
-// ErrVersionMismatch is thrown when for versioned updates, client is sending incorrect version to server
var ErrVersionMismatch = errors.New("client version is out of sync")
-// ErrCanNotInviteUserWithPaidPlan is thrown when a family admin tries to invite another user with active paid plan
var ErrCanNotInviteUserWithPaidPlan = errors.New("can not invite user with active paid plan")
-// ErrBatchSizeTooLarge is thrown when api request batch size is greater than API limit
var ErrBatchSizeTooLarge = errors.New("batch size greater than API limit")
-// ErrAuthenticationRequired is thrown when authentication vector is missing
var ErrAuthenticationRequired = errors.New("authentication required")
-// ErrInvalidPassword is thrown when incorrect password is provided by user
var ErrInvalidPassword = errors.New("invalid password")
-// ErrCanNotInviteUserAlreadyInFamily is thrown when a family admin tries to invite another user with active paid plan
var ErrCanNotInviteUserAlreadyInFamily = errors.New("can not invite user who is already part of a family")
-// ErrFamilySizeLimitReached is thrown when a family admin tries to invite more than max allowed members for family plan
var ErrFamilySizeLimitReached = errors.New("can't invite new member, family already at max allowed size")
-// ErrUserDeleted is thrown when Get user is called for a deleted account
var ErrUserDeleted = errors.New("user account has been deleted")
-// ErrLockUnavailable is thrown when a lock could not be acquired
var ErrLockUnavailable = errors.New("could not acquire lock")
-// ErrActiveLinkAlreadyExists is thrown when an active link already exists for entity
var ErrActiveLinkAlreadyExists = errors.New("link already exists for this entity")
-// ErrAccessTokenInUse is thrown when an access token is already active
var ErrAccessTokenInUse = errors.New("access token already in use")
// ErrNotImplemented indicates that the action that we tried to perform is not
@@ -270,7 +239,6 @@ var ErrLockerRollOutLimit = &ApiError{
type ErrorCode string
const (
- // Standard, generic error codes
BadRequest ErrorCode = "BAD_REQUEST"
CONFLICT ErrorCode = "CONFLICT"
AlreadyExists ErrorCode = "ALREADY_EXISTS"
@@ -279,56 +247,40 @@ const (
NotFoundError ErrorCode = "NOT_FOUND"
- // Business specific error codes
FamiliySizeLimitExceeded ErrorCode = "FAMILY_SIZE_LIMIT_EXCEEDED"
- // UserSignupIncomplete indicates that account exists but signup is not fully completed
UserSignupIncomplete ErrorCode = "USER_SIGNUP_INCOMPLETE"
- // Subscription Already Associted with different account
SubscriptionAlreadyClaimed ErrorCode = "SUBSCRIPTION_ALREADY_CLAIMED"
FileNotFoundInAlbum ErrorCode = "FILE_NOT_FOUND_IN_ALBUM"
AuthKeyNotCreated ErrorCode = "AUTH_KEY_NOT_CREATED"
- // PublicCollectDisabled error code indicates that the user has not enabled public collect
PublicCollectDisabled ErrorCode = "PUBLIC_COLLECT_DISABLED"
- // PublicCommentDisabled error code indicates that the user has not enabled public comments
PublicCommentDisabled ErrorCode = "PUBLIC_COMMENT_DISABLED"
- // PublicCommentTooLong indicates that comment text exceeded allowed limit
PublicCommentTooLong ErrorCode = "PUBLIC_COMMENT_TOO_LONG"
- // AnonNameTooLong indicates that anonymous display name exceeded allowed limit
AnonNameTooLong ErrorCode = "ANON_NAME_TOO_LONG"
- // CollectionNotEmpty is thrown when user attempts to delete a collection but keep files but all files from that
- // collections have been moved yet.
CollectionNotEmpty ErrorCode = "COLLECTION_NOT_EMPTY"
- // MaxPasskeysReached is thrown when user attempts to create more than max allowed passkeys
MaxPasskeysReached ErrorCode = "MAX_PASSKEYS_REACHED"
- // LockerRegistrationDisabled indicates that locker registration is currently disabled
LockerRegistrationDisabled ErrorCode = "LOCKER_REGISTRATION_DISABLED"
LockerRolloutLimit ErrorCode = "LOCKER_ROLLOUT_LIMIT"
- // FileLimitReached indicates the user hit the maximum number of files allowed
FileLimitReached ErrorCode = "FILE_LIMIT_REACHED"
- // FileInTrash indicates files are present in trash and cannot be added to collection
FileInTrash ErrorCode = "FILE_IN_TRASH"
SessionExpired ErrorCode = "SESSION_EXPIRED"
- // LinkEditNotAllowed indicates that the user cannot change link settings
LinkEditNotAllowed ErrorCode = "LINK_EDIT_NOT_ALLOWED"
- // LinkDeviceLimitExceeded indicates that the public link has exhausted its
- // allowed unique device accesses.
LinkDeviceLimitExceeded ErrorCode = "LINK_DEVICE_LIMIT_EXCEEDED"
)
diff --git a/server/ente/file.go b/server/ente/file.go
index c48f38c7af..b80cc75cb9 100644
--- a/server/ente/file.go
+++ b/server/ente/file.go
@@ -7,7 +7,6 @@ import (
"github.com/ente/stacktrace"
)
-// File represents an encrypted file in the system
type File struct {
ID int64 `json:"id"`
OwnerID int64 `json:"ownerID"`
@@ -44,20 +43,15 @@ type MetaFile struct {
PubicMagicMetadata *MagicMetadata `json:"pubMagicMetadata,omitempty"`
}
-// 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"`
}
-// Value implements the driver.Valuer interface. This method
-// simply returns the JSON-encoded representation of the struct.
func (fi FileInfo) Value() (driver.Value, error) {
return json.Marshal(fi)
}
-// Scan implements the sql.Scanner interface. This method
-// simply decodes a JSON-encoded value into the struct fields.
func (fi *FileInfo) Scan(value interface{}) error {
if value == nil {
return nil
@@ -69,13 +63,11 @@ func (fi *FileInfo) Scan(value interface{}) error {
return json.Unmarshal(b, &fi)
}
-// UpdateFileResponse represents a response to the UpdateFileRequest
type UpdateFileResponse struct {
ID int64 `json:"id" binding:"required"`
UpdationTime int64 `json:"updationTime" binding:"required"`
}
-// FileIDsRequest represents a request where we just pass fileIDs as payload
type FileIDsRequest struct {
FileIDs []int64 `json:"fileIDs" binding:"required"`
}
@@ -93,19 +85,16 @@ type TrashRequest struct {
TrashItems []TrashItemRequest `json:"items" binding:"required"`
}
-// TrashItemRequest represents the request payload for deleting one file
type TrashItemRequest struct {
FileID int64 `json:"fileID" binding:"required"`
// collectionID belonging to same owner
CollectionID int64 `json:"collectionID" binding:"required"`
}
-// GetSizeRequest represents a request to get the size of files
type GetSizeRequest struct {
FileIDs []int64 `json:"fileIDs" binding:"required"`
}
-// FileAttributes represents a file item
type FileAttributes struct {
ObjectKey string `json:"objectKey,omitempty"`
EncryptedData string `json:"encryptedData,omitempty"`
@@ -124,14 +113,10 @@ type MagicMetadata struct {
Header string `json:"header,omitempty" binding:"required"`
}
-// Value implements the driver.Valuer interface. This method
-// simply returns the JSON-encoded representation of the struct.
func (mmd MagicMetadata) Value() (driver.Value, error) {
return json.Marshal(mmd)
}
-// Scan implements the sql.Scanner interface. This method
-// simply decodes a JSON-encoded value into the struct fields.
func (mmd *MagicMetadata) Scan(value interface{}) error {
if value == nil {
return nil
@@ -143,38 +128,32 @@ func (mmd *MagicMetadata) Scan(value interface{}) error {
return json.Unmarshal(b, &mmd)
}
-// UpdateMagicMetadata payload for updating magic metadata for single file
type UpdateMagicMetadata struct {
ID int64 `json:"id" binding:"required"`
MagicMetadata MagicMetadata `json:"magicMetadata" binding:"required"`
}
-// UpdateMultipleMagicMetadataRequest request payload for updating magic metadata for list of files
type UpdateMultipleMagicMetadataRequest struct {
MetadataList []UpdateMagicMetadata `json:"metadataList" binding:"required"`
SkipVersion *bool `json:"skipVersion"`
}
-// UploadURL represents the upload url for a specific object
type UploadURL struct {
ObjectKey string `json:"objectKey"`
URL string `json:"url"`
}
-// UploadURLRequest represents the inputs necessary to mint a single upload URL
type UploadURLRequest struct {
ContentLength int64 `json:"contentLength" binding:"required"`
ContentMD5 string `json:"contentMD5" binding:"required"`
}
-// MultipartUploadURLs represents the part upload url for a specific object
type MultipartUploadURLs struct {
ObjectKey string `json:"objectKey"`
PartURLs []string `json:"partURLs"`
CompleteURL string `json:"completeURL"`
}
-// MultipartUploadURLRequest encapsulates the metadata needed to mint a multipart upload URL set
type MultipartUploadURLRequest struct {
ContentLength int64 `json:"contentLength" binding:"required"`
PartLength int64 `json:"partLength" binding:"required"`
@@ -191,7 +170,6 @@ const (
MlData ObjectType = "mldata"
)
-// S3ObjectKey represents the s3 object key and corresponding fileID for it
type S3ObjectKey struct {
FileID int64
ObjectKey string
@@ -199,10 +177,6 @@ type S3ObjectKey struct {
Type ObjectType
}
-// ObjectCopies represents a row from the object_copies table.
-//
-// It contains information about which replicas a given object key should be and
-// has been replicated to.
type ObjectCopies struct {
ObjectKey string
WantB2 bool
@@ -213,22 +187,12 @@ type ObjectCopies struct {
SCW *int64
}
-// ObjectState represents details about an object that are needed for
-// pre-flights checks during replication.
-//
-// This information is obtained by joining various tables.
type ObjectState struct {
- // true if the file corresponding to this object has been deleted (or cannot
- // be found)
IsFileDeleted bool
- // true if the owner of the file corresponding to this object has deleted
- // their account (or cannot be found).
IsUserDeleted bool
- // Size of the object, in bytes.
- Size int64
+ Size int64
}
-// TempObject represents a entry in tempObjects table
type TempObject struct {
ObjectKey string
IsMultipart bool
@@ -236,7 +200,6 @@ type TempObject struct {
BucketId string
}
-// DuplicateFiles represents duplicate files
type DuplicateFiles struct {
FileIDs []int64 `json:"fileIDs"`
Size int64 `json:"size"`
diff --git a/server/ente/file_link.go b/server/ente/file_link.go
index 6c5a5f5950..5f990b3458 100644
--- a/server/ente/file_link.go
+++ b/server/ente/file_link.go
@@ -5,7 +5,6 @@ import (
"github.com/ente/museum/pkg/utils/time"
)
-// CreateFileUrl represents an encrypted file in the system
type CreateFileUrl struct {
FileID int64 `json:"fileID" binding:"required"`
App App `json:"app" binding:"required"`
@@ -17,7 +16,6 @@ type CreateFileUrl struct {
EncryptedShareKey *string `json:"encryptedShareKey,omitempty"`
}
-// UpdateFileUrl ..
type UpdateFileUrl struct {
LinkID string `json:"linkID" binding:"required"`
FileID int64 `json:"fileID" binding:"required"`
diff --git a/server/ente/filedata/filedata.go b/server/ente/filedata/filedata.go
index 68ec616661..234c9cc4d1 100644
--- a/server/ente/filedata/filedata.go
+++ b/server/ente/filedata/filedata.go
@@ -82,8 +82,6 @@ type GetFilesDataResponse struct {
ErrFileIDs []int64 `json:"errFileIDs"`
}
-// S3FileMetadata stuck represents the metadata that is stored in the S3 bucket for non-file type metadata
-// that is stored in the S3 bucket.
type S3FileMetadata struct {
Version int `json:"v"`
EncryptedData string `json:"encryptedData"`
@@ -134,7 +132,6 @@ func (g *PreviewUploadUrlRequest) Validate() error {
return nil
}
-// Row represents the data that is stored in the file_data table.
type Row struct {
FileID int64
UserID int64
@@ -160,7 +157,6 @@ type Row struct {
UpdatedAt int64
}
-// S3FileMetadataObjectKey returns the object key for the metadata stored in the S3 bucket.
func (r *Row) S3FileMetadataObjectKey() string {
if r.Type == ente.MlData || r.Type == ente.PreviewVideo {
return ObjectMetadataKey(r.FileID, r.UserID, r.Type, r.ObjectID)
@@ -168,7 +164,6 @@ func (r *Row) S3FileMetadataObjectKey() string {
panic(fmt.Sprintf("S3FileMetadata should not be written for %s type", r.Type))
}
-// GetS3FileObjectKey returns the object key for the file data stored in the S3 bucket.
func (r *Row) GetS3FileObjectKey() string {
if r.Type == ente.PreviewVideo || r.Type == ente.PreviewImage {
return ObjectKey(r.FileID, r.UserID, r.Type, r.ObjectID)
diff --git a/server/ente/filedata/path.go b/server/ente/filedata/path.go
index 8781b2b921..e7b78a30f8 100644
--- a/server/ente/filedata/path.go
+++ b/server/ente/filedata/path.go
@@ -19,7 +19,6 @@ func AllObjects(fileID int64, ownerID int64, oType ente.ObjectType) []string {
return []string{derivedMetaPath(fileID, ownerID)}
default:
- // throw panic saying current object type is not supported
panic(fmt.Sprintf("object type %s is not supported", oType))
}
}
diff --git a/server/ente/memory_share.go b/server/ente/memory_share.go
index 7fdbc53b8a..0ea32daed7 100644
--- a/server/ente/memory_share.go
+++ b/server/ente/memory_share.go
@@ -1,16 +1,12 @@
package ente
-// MemoryShareType represents the type of memory share
type MemoryShareType string
const (
- // MemoryShareTypeShare is a user-curated memory share with selected files
MemoryShareTypeShare MemoryShareType = "share"
- // MemoryShareTypeLane is an auto-generated memory lane
- MemoryShareTypeLane MemoryShareType = "lane"
+ MemoryShareTypeLane MemoryShareType = "lane"
)
-// MemoryShare represents a shared memory with its encrypted metadata
type MemoryShare struct {
ID int64 `json:"id"`
UserID int64 `json:"-"`
@@ -27,7 +23,6 @@ type MemoryShare struct {
URL string `json:"url,omitempty"`
}
-// MemoryShareFile represents a file within a memory share
type MemoryShareFile struct {
ID int64 `json:"id"`
MemoryShareID int64 `json:"-"`
@@ -39,7 +34,6 @@ type MemoryShareFile struct {
CreatedAt int64 `json:"createdAt"`
}
-// CreateMemoryShareRequest is the request body for creating a memory share
type CreateMemoryShareRequest struct {
Type MemoryShareType `json:"type,omitempty"`
MemoryHash string `json:"memoryHash,omitempty"`
@@ -50,7 +44,6 @@ type CreateMemoryShareRequest struct {
Files []MemoryShareFileItem `json:"files" binding:"required,min=1"`
}
-// MemoryShareFileItem represents a file in the create request
type MemoryShareFileItem struct {
FileID int64 `json:"fileID" binding:"required"`
Position *int64 `json:"position,omitempty"`
@@ -58,22 +51,18 @@ type MemoryShareFileItem struct {
KeyDecryptionNonce string `json:"keyDecryptionNonce" binding:"required"`
}
-// CreateMemoryShareResponse is the response for creating a memory share
type CreateMemoryShareResponse struct {
MemoryShare MemoryShare `json:"memoryShare"`
}
-// ListMemorySharesResponse is the response for listing memory shares
type ListMemorySharesResponse struct {
MemoryShares []MemoryShare `json:"memoryShares"`
}
-// PublicMemoryShareResponse is the response for public memory share access
type PublicMemoryShareResponse struct {
MemoryShare MemoryShare `json:"memoryShare"`
}
-// PublicMemoryShareFile combines file data with its re-encrypted key for public access
type PublicMemoryShareFile struct {
File File `json:"file"`
Position int64 `json:"position"`
@@ -81,12 +70,10 @@ type PublicMemoryShareFile struct {
KeyDecryptionNonce string `json:"keyDecryptionNonce"`
}
-// PublicMemoryShareFilesResponse is the response for listing files in a public memory share
type PublicMemoryShareFilesResponse struct {
Files []PublicMemoryShareFile `json:"files"`
}
-// MemoryShareAccessContext represents the context for public memory share access
type MemoryShareAccessContext struct {
ID int64
ShareID int64
diff --git a/server/ente/public_collection.go b/server/ente/public_collection.go
index 5ca89cdd89..000bb6ce85 100644
--- a/server/ente/public_collection.go
+++ b/server/ente/public_collection.go
@@ -8,7 +8,6 @@ import (
"github.com/ente/stacktrace"
)
-// CreatePublicAccessTokenRequest payload for creating accessToken for public albums
type CreatePublicAccessTokenRequest struct {
CollectionID int64 `json:"collectionID" binding:"required"`
EnableCollect bool `json:"enableCollect"`
@@ -74,7 +73,6 @@ type VerifyPasswordResponse struct {
JWTToken string `json:"jwtToken"`
}
-// CollectionLinkRow represents row entity for public_collection_token table
type CollectionLinkRow struct {
ID int64
CollectionID int64
@@ -109,16 +107,14 @@ func (p CollectionLinkRow) CanJoin() error {
return nil
}
-// PublicURL represents information about non-disabled public url for a collection
type PublicURL struct {
- URL string `json:"url"`
- DeviceLimit int `json:"deviceLimit"`
- ValidTill int64 `json:"validTill"`
- EnableDownload bool `json:"enableDownload"`
- // Enable collect indicates whether folks can upload files in a publicly shared url
- EnableCollect bool `json:"enableCollect"`
- EnableComment bool `json:"enableComment"`
- PasswordEnabled bool `json:"passwordEnabled"`
+ URL string `json:"url"`
+ DeviceLimit int `json:"deviceLimit"`
+ ValidTill int64 `json:"validTill"`
+ EnableDownload bool `json:"enableDownload"`
+ EnableCollect bool `json:"enableCollect"`
+ EnableComment bool `json:"enableComment"`
+ PasswordEnabled bool `json:"passwordEnabled"`
// Nonce contains the nonce value for the password if the link is password protected.
Nonce *string `json:"nonce,omitempty"`
MemLimit *int64 `json:"memLimit,omitempty"`
@@ -148,7 +144,6 @@ func FilterPublicURLsForRole(urls []PublicURL, role CollectionParticipantRole) [
return result
}
-// PublicCollectionSummary represents an information about a public collection
type PublicCollectionSummary struct {
ID int64
CollectionID int64
@@ -188,14 +183,10 @@ type ReporterAddress struct {
Phone string `json:"phone" binding:"required"`
}
-// Value implements the driver.Valuer interface. This method
-// simply returns the JSON-encoded representation of the struct.
func (ca AbuseReportDetails) Value() (driver.Value, error) {
return json.Marshal(ca)
}
-// Scan implements the sql.Scanner interface. This method
-// simply decodes a JSON-encoded value into the struct fields.
func (ca *AbuseReportDetails) Scan(value interface{}) error {
b, ok := value.([]byte)
if !ok {
@@ -205,14 +196,10 @@ func (ca *AbuseReportDetails) Scan(value interface{}) error {
return json.Unmarshal(b, &ca)
}
-// Value implements the driver.Valuer interface. This method
-// simply returns the JSON-encoded representation of the struct.
func (ca ReporterAddress) Value() (driver.Value, error) {
return json.Marshal(ca)
}
-// Scan implements the sql.Scanner interface. This method
-// simply decodes a JSON-encoded value into the struct fields.
func (ca *ReporterAddress) Scan(value interface{}) error {
b, ok := value.([]byte)
if !ok {
diff --git a/server/ente/remotestore.go b/server/ente/remotestore.go
index 5d53c06fee..a8a3ee6c43 100644
--- a/server/ente/remotestore.go
+++ b/server/ente/remotestore.go
@@ -31,8 +31,7 @@ type AdminUpdateKeyValueRequest struct {
}
type FeatureFlagResponse struct {
- EnableStripe bool `json:"enableStripe"`
- // If true, the mobile client will stop using CF worker to download files
+ EnableStripe bool `json:"enableStripe"`
DisableCFWorker bool `json:"disableCFWorker"`
MapEnabled bool `json:"mapEnabled"`
FaceSearchEnabled bool `json:"faceSearchEnabled"`
@@ -49,19 +48,14 @@ type FeatureFlagResponse struct {
}
const (
- // UploadV2 marks availability of the upload v2 APIs in the binary.
- UploadV2 int64 = 1 << 0
- // Comments marks availability of the comments feature.
- Comments int64 = 1 << 1
- // BackupOptions marks availability of backup option features for older clients.
- BackupOptions int64 = 1 << 2
- // VideoStreaming gates video streaming feature.
+ UploadV2 int64 = 1 << 0
+ Comments int64 = 1 << 1
+ BackupOptions int64 = 1 << 2
VideoStreaming int64 = 1 << 3
// 1 << 4 previously gated CastSessionsV2 for released clients. Reuse it
// only when those clients no longer need to be isolated from a new flag.
// CastSessionsV2 gates cast sessions v2 support.
- CastSessionsV2 int64 = 1 << 5
- // DeferredMultipartChecksums gates multipart URLs without precomputed checksums.
+ CastSessionsV2 int64 = 1 << 5
DeferredMultipartChecksums int64 = 1 << 6
)
@@ -96,7 +90,6 @@ func (k FlagKey) String() string {
return string(k)
}
-// UserEditable returns true if the key is user editable
func (k FlagKey) UserEditable() bool {
switch k {
case RecoveryKeyVerified, MapEnabled, FaceSearchEnabled, PassKeyEnabled, CustomDomain:
@@ -132,7 +125,7 @@ func (k FlagKey) IsBoolType() bool {
case CustomDomain:
return false
default:
- return false // Explicitly handle unexpected cases
+ return false
}
}
@@ -188,7 +181,6 @@ func ParseFamilyCustomDomainPointer(value string) (int64, string, bool, error) {
return memberID, domain, true, nil
}
-// ResolveCustomDomainValue returns the effective domain for a custom domain value.
func ResolveCustomDomainValue(value string) (string, error) {
if value == "" {
return "", nil
@@ -215,13 +207,11 @@ func isValidDomainWithoutScheme(input string) error {
return NewBadRequestWithMessage("domain should not contain scheme (e.g., http:// or https://)")
}
- // Convert IDN to ASCII (Punycode) for validation
asciiDomain, err := idna.ToASCII(trimmed)
if err != nil {
return NewBadRequestWithMessage(fmt.Sprintf("invalid idn domain format: %s", trimmed))
}
- // Validate the ASCII version
if !domainRegex.MatchString(asciiDomain) {
return NewBadRequestWithMessage(fmt.Sprintf("invalid domain format: %s", trimmed))
}
diff --git a/server/ente/trash.go b/server/ente/trash.go
index 52bb2c758b..437d075f82 100644
--- a/server/ente/trash.go
+++ b/server/ente/trash.go
@@ -1,6 +1,5 @@
package ente
-// Trash indicates a trashed file in the system.
type Trash struct {
File File `json:"file"`
IsDeleted bool `json:"isDeleted"`
@@ -10,14 +9,12 @@ type Trash struct {
UpdatedAt int64 `json:"updatedAt"`
}
-// DeleteTrashFilesRequest represents a request to delete a trashed files
type DeleteTrashFilesRequest struct {
FileIDs []int64 `json:"fileIDs" binding:"required"`
// OwnerID will be set based on the authenticated user
OwnerID int64
}
-// EmptyTrashRequest represents a request to empty items from user's trash
type EmptyTrashRequest struct {
// LastUpdatedAt timestamp will be used to delete trashed files with updatedAt timestamp <= LastUpdatedAt
// User's trash will be cleaned up in an async manner. The timestamp is used to ensure that newly trashed files
diff --git a/server/ente/user.go b/server/ente/user.go
index 91cabfaa8e..ded0712a55 100644
--- a/server/ente/user.go
+++ b/server/ente/user.go
@@ -15,7 +15,6 @@ const (
ExpectedKDFStrength = int64(1073741824 * 4)
)
-// User represents a user in the system
type User struct {
ID int64
Email string `json:"email"`
@@ -27,20 +26,16 @@ type User struct {
IsEmailMFAEnabled *bool `json:"isEmailMFAEnabled"`
}
-// A request to generate and send a verification code (OTT)
type SendOTTRequest struct {
Email string `json:"email"`
Client string `json:"client"`
Purpose string `json:"purpose"`
- // Mobile indicates whether the request is coming from a mobile client`
- Mobile bool `json:"mobile"`
+ Mobile bool `json:"mobile"`
}
-// EmailVerificationRequest represents an email verification request
type EmailVerificationRequest struct {
- Email string `json:"email"`
- OTT string `json:"ott"`
- // Indicates where the source form where the user heard about the service
+ Email string `json:"email"`
+ OTT string `json:"ott"`
Source *string `json:"source"`
}
@@ -71,7 +66,6 @@ type EmailAuthorizationResponse struct {
SrpM2 *string `json:"srpM2,omitempty"`
}
-// KeyAttributes stores the key related attributes for a user
type KeyAttributes struct {
KEKSalt string `json:"kekSalt" binding:"required"`
KEKHash string `json:"kekHash"`
@@ -88,7 +82,6 @@ type KeyAttributes struct {
RecoveryKeyDecryptionNonce string `json:"recoveryKeyDecryptionNonce"`
}
-// SetUserAttributesRequest represents an incoming request to set UA
type SetUserAttributesRequest struct {
KeyAttributes KeyAttributes `json:"keyAttributes" binding:"required"`
}
@@ -104,12 +97,10 @@ func (sk *SetUserAttributesRequest) Validate() error {
return nil
}
-// UpdateEmailMFA ..
type UpdateEmailMFA struct {
IsEnabled *bool `json:"isEnabled" binding:"required"`
}
-// UpdateKeysRequest represents a request to set user keys
type UpdateKeysRequest struct {
KEKSalt string `json:"kekSalt" binding:"required"`
EncryptedKey string `json:"encryptedKey" binding:"required"`
@@ -146,7 +137,6 @@ type EncryptionResult struct {
}
type DeleteChallengeResponse struct {
- // AllowDelete indicates whether the user is allowed to delete their account via app
AllowDelete bool `json:"allowDelete"`
EncryptedChallenge *string `json:"encryptedChallenge,omitempty"`
Apps []App `json:"apps"`
@@ -194,26 +184,22 @@ type AccountRecoveryResponse struct {
Status AccountRecoveryStatus `json:"status"`
}
-// TwoFactorSecret represents the two factor secret generator value, user enters in his authenticator app
type TwoFactorSecret struct {
SecretCode string `json:"secretCode"`
QRCode string `json:"qrCode"`
}
-// TwoFactorEnableRequest represent the user request to enable two factor after initial setup
type TwoFactorEnableRequest struct {
Code string `json:"code"`
EncryptedTwoFactorSecret string `json:"encryptedTwoFactorSecret"`
TwoFactorSecretDecryptionNonce string `json:"twoFactorSecretDecryptionNonce"`
}
-// TwoFactorVerificationRequest represents a two factor verification request
type TwoFactorVerificationRequest struct {
SessionID string `json:"sessionID" binding:"required"`
Code string `json:"code" binding:"required"`
}
-// TwoFactorBeginAuthenticationCeremonyRequest represents the request to begin the passkey authentication ceremony
type PasskeyTwoFactorBeginAuthenticationCeremonyRequest struct {
SessionID string `json:"sessionID" binding:"required"`
}
@@ -223,20 +209,17 @@ type PasskeyTwoFactorFinishAuthenticationCeremonyRequest struct {
CeremonySessionID string `form:"ceremonySessionID" binding:"required"`
}
-// TwoFactorAuthorizationResponse represents the response after two factor authentication
type TwoFactorAuthorizationResponse struct {
ID int64 `json:"id"`
KeyAttributes *KeyAttributes `json:"keyAttributes,omitempty"`
EncryptedToken string `json:"encryptedToken,omitempty"`
}
-// TwoFactorRecoveryResponse represents the two factor secret encrypted with user's recovery key sent for user to make removal request
type TwoFactorRecoveryResponse struct {
EncryptedSecret string `json:"encryptedSecret"`
SecretDecryptionNonce string `json:"secretDecryptionNonce"`
}
-// TwoFactorRemovalRequest represents the the body of two factor removal request consist of decrypted two factor secret and sessionID
type TwoFactorRemovalRequest struct {
Secret string `json:"secret"`
SessionID string `json:"sessionID"`
@@ -244,7 +227,6 @@ type TwoFactorRemovalRequest struct {
}
type ProfileData struct {
- // CanDisableEmailMFA is used to decide if client should show disable email MFA option
CanDisableEmailMFA bool `json:"canDisableEmailMFA"`
IsEmailMFAEnabled bool `json:"isEmailMFAEnabled"`
IsTwoFactorEnabled bool `json:"isTwoFactorEnabled"`
diff --git a/server/ente/userentity/entity.go b/server/ente/userentity/entity.go
index 06072e4bc0..a27bd6c8df 100644
--- a/server/ente/userentity/entity.go
+++ b/server/ente/userentity/entity.go
@@ -50,7 +50,6 @@ type EntityKey struct {
CreatedAt int64 `json:"createdAt" binding:"required"`
}
-// EntityData represents a single UserEntity
type EntityData struct {
ID string `json:"id" binding:"required"`
UserID int64 `json:"userID" binding:"required"`
@@ -62,19 +61,16 @@ type EntityData struct {
UpdatedAt int64 `json:"updatedAt" binding:"required"`
}
-// EntityKeyRequest represents a request to create entity data encryption key for a given EntityType
type EntityKeyRequest struct {
Type EntityType `json:"type" binding:"required"`
EncryptedKey string `json:"encryptedKey" binding:"required"`
Header string `json:"header" binding:"required"`
}
-// GetEntityKeyRequest represents a request to get entity key for given EntityType
type GetEntityKeyRequest struct {
Type EntityType `form:"type" binding:"required"`
}
-// EntityDataRequest is used to create a new entity data of given EntityType
type EntityDataRequest struct {
Type EntityType `json:"type" binding:"required"`
EncryptedData string `json:"encryptedData" binding:"required"`
@@ -91,7 +87,6 @@ func (edr *EntityDataRequest) IsValid(userID int64) error {
if edr.ID == nil {
return ente.NewBadRequestWithMessage("ID is required for SmartAlbum entity type")
}
- // check if ID starts with sa_userid_ or not
if !strings.HasPrefix(*edr.ID, fmt.Sprintf("sa_%d_", userID)) {
return ente.NewBadRequestWithMessage(fmt.Sprintf("ID %s is not valid for SmartAlbum entity type", *edr.ID))
}
@@ -101,7 +96,6 @@ func (edr *EntityDataRequest) IsValid(userID int64) error {
}
}
-// UpdateEntityDataRequest updates the current entity
type UpdateEntityDataRequest struct {
ID string `json:"id" binding:"required"`
Type EntityType `json:"type" binding:"required"`
@@ -109,7 +103,6 @@ type UpdateEntityDataRequest struct {
Header string `json:"header" binding:"required"`
}
-// GetEntityDiffRequest returns the diff of entities since the given time
type GetEntityDiffRequest struct {
Type EntityType `form:"type" binding:"required"`
// SinceTime *int64. Pointer allows us to pass 0 value otherwise binding fails for zero Value.
diff --git a/server/pkg/repo/collection.go b/server/pkg/repo/collection.go
index b4b826aa17..723fcd618b 100644
--- a/server/pkg/repo/collection.go
+++ b/server/pkg/repo/collection.go
@@ -21,8 +21,6 @@ import (
"github.com/lib/pq"
)
-// CollectionRepository defines the methods for inserting, updating and
-// retrieving collection entities from the underlying repository
type CollectionRepository struct {
DB *sql.DB
FileRepo *FileRepository
@@ -39,10 +37,8 @@ type SharedCollection struct {
FromUserID int64
}
-// Create creates a collection
func (repo *CollectionRepository) Create(c ente.Collection) (ente.Collection, error) {
- // Check if the app type can create collection
if !ente.App(c.App).IsValidForCollection() {
return ente.Collection{}, ente.ErrInvalidApp
}
@@ -61,7 +57,6 @@ func (repo *CollectionRepository) Create(c ente.Collection) (ente.Collection, er
return c, stacktrace.Propagate(err, "")
}
-// Get returns a collection identified by the collectionID
func (repo *CollectionRepository) Get(collectionID int64) (ente.Collection, error) {
row := repo.DB.QueryRow(`SELECT collection_id, app, owner_id, encrypted_key, key_decryption_nonce, name, encrypted_name, name_decryption_nonce, type, attributes, updation_time, is_deleted, magic_metadata, pub_magic_metadata
FROM collections
@@ -254,8 +249,6 @@ pct.access_token, pct.valid_till, pct.device_limit, pct.created_at, pct.updated_
return result, nil
}
-// GetCollectionsSharedWithUser returns the list of collections that are shared
-// with a user
func (repo *CollectionRepository) GetCollectionsSharedWithUser(userID int64, updationTime int64, app ente.App, limit *int64) ([]ente.Collection, error) {
query := `
SELECT collections.collection_id, collections.owner_id, users.encrypted_email, users.email_decryption_nonce, collection_shares.encrypted_key, collections.name, collections.encrypted_name, collections.name_decryption_nonce, collections.type, collections.app, collections.pub_magic_metadata, collection_shares.magic_metadata, collections.updation_time, collection_shares.is_deleted, collection_shares.role_type, collection_shares.shared_at
@@ -355,7 +348,6 @@ func (repo *CollectionRepository) GetCollectionsSharedWithUser(userID int64, upd
return collections, nil
}
-// GetCollectionIDsSharedWithUser returns the list of collections that a user has access to
func (repo *CollectionRepository) GetCollectionIDsSharedWithUser(userID int64) ([]int64, error) {
rows, err := repo.DB.Query(`
SELECT collection_id
@@ -378,7 +370,6 @@ func (repo *CollectionRepository) GetCollectionIDsSharedWithUser(userID int64) (
return cIDs, nil
}
-// FilterNonDeletedCollectionIDs returns collection IDs that are not deleted and match the provided app.
func (repo *CollectionRepository) FilterNonDeletedCollectionIDs(collectionIDs []int64, app ente.App) ([]int64, error) {
if len(collectionIDs) == 0 {
return nil, nil
@@ -432,7 +423,6 @@ func (repo *CollectionRepository) GetCollectionsSharedWithOrByUser(userID int64)
}
-// GetCollectionIDsOwnedByUser returns the map of collectionID (owned by user) to collection deletion status
func (repo *CollectionRepository) GetCollectionIDsOwnedByUser(userID int64) (map[int64]bool, error) {
rows, err := repo.DB.Query(`
SELECT collection_id, is_deleted
@@ -457,7 +447,6 @@ func (repo *CollectionRepository) GetCollectionIDsOwnedByUser(userID int64) (map
return result, nil
}
-// GetAllSharedCollections returns list of SharedCollection in which the given user is involed
func (repo *CollectionRepository) GetAllSharedCollections(ctx context.Context, userID int64) ([]SharedCollection, error) {
rows, err := repo.DB.QueryContext(ctx, `SELECT collection_id, to_user_id, from_user_id
FROM collection_shares
@@ -480,7 +469,6 @@ func (repo *CollectionRepository) GetAllSharedCollections(ctx context.Context, u
return result, nil
}
-// GetCollectionShareeRole returns true if the collection is shared with the user
func (repo *CollectionRepository) GetCollectionShareeRole(cID int64, userID int64) (*ente.CollectionParticipantRole, error) {
var role *ente.CollectionParticipantRole
err := repo.DB.QueryRow(`(SELECT role_type FROM collection_shares WHERE collection_id = $1 AND to_user_id = $2 AND is_deleted = $3)`,
@@ -495,7 +483,6 @@ func (repo *CollectionRepository) GetOwnerID(collectionID int64) (int64, error)
return ownerID, stacktrace.Propagate(err, "failed to get collection owner")
}
-// Share shares a collection with a userID
func (repo *CollectionRepository) Share(
collectionID int64,
fromUserID int64,
@@ -594,7 +581,6 @@ func (repo *CollectionRepository) ShareAutomatically(
return ente.CollectionShared, nil
}
-// UpdateShareeMetadata shares a collection with a userID
func (repo *CollectionRepository) UpdateShareeMetadata(
collectionID int64,
ownerUserID int64,
@@ -606,14 +592,12 @@ func (repo *CollectionRepository) UpdateShareeMetadata(
if err != nil {
return stacktrace.Propagate(err, "")
}
- // Update collection_shares metadata if the collection is not deleted
sqlResult, err := tx.ExecContext(context, `UPDATE collection_shares SET magic_metadata = $1, updation_time = $2 WHERE collection_id = $3 AND from_user_id = $4 AND to_user_id = $5 AND is_deleted = $6`,
metadata, updationTime, collectionID, ownerUserID, shareeUserID, false)
if err != nil {
tx.Rollback()
return stacktrace.Propagate(err, "")
}
- // verify that only one row is affected
affected, err := sqlResult.RowsAffected()
if err != nil {
tx.Rollback()
@@ -634,13 +618,11 @@ func (repo *CollectionRepository) UpdateShareeMetadata(
return stacktrace.Propagate(err, "")
}
-// UnShare un-shares a collection from a userID
func (repo *CollectionRepository) UnShare(collectionID int64, toUserID int64) error {
_, err := repo.UnShareContext(context.Background(), collectionID, toUserID)
return err
}
-// UnShareContext revokes access to a collection.
func (repo *CollectionRepository) UnShareContext(
ctx context.Context,
collectionID int64,
@@ -693,7 +675,6 @@ func (repo *CollectionRepository) UnShareContext(
return status, nil
}
-// AddFiles adds files to a collection
func (repo *CollectionRepository) AddFiles(
collectionID int64,
collectionOwnerID int64,
@@ -742,7 +723,6 @@ func (repo *CollectionRepository) RestoreFiles(ctx context.Context, userID int64
for _, newFile := range newCollectionFiles {
fileIDs = append(fileIDs, newFile.ID)
}
- // verify that all files are restorable
_, canRestoreAllFiles, err := repo.TrashRepo.GetFilesInTrashState(ctx, userID, fileIDs)
if err != nil {
return stacktrace.Propagate(err, "")
@@ -807,8 +787,6 @@ func (repo *CollectionRepository) RemoveFilesV3(context context.Context, collect
return errors.New("can not remove files owned by album owner")
}
- // check if there are files owned by collection owner
-
tx, err := repo.DB.BeginTx(context, nil)
if err != nil {
return stacktrace.Propagate(err, "")
@@ -857,7 +835,6 @@ func (repo *CollectionRepository) SuggestAction(ctx context.Context, collectionI
return tx.Commit()
}
-// MoveFiles move files from one collection to another collection
func (repo *CollectionRepository) MoveFiles(ctx context.Context,
toCollectionID int64, fromCollectionID int64,
fileItems []ente.CollectionFileItem,
@@ -920,8 +897,6 @@ func (repo *CollectionRepository) MoveFiles(ctx context.Context,
return tx.Commit()
}
-// GetDiff returns the diff of files added or modified within a collection since
-// the specified time
func (repo *CollectionRepository) GetDiff(collectionID int64, sinceTime int64, limit int) ([]ente.File, error) {
startTime := t.Now()
defer func() {
@@ -994,7 +969,6 @@ func (repo *CollectionRepository) GetFile(collectionID int64, fileID int64) ([]e
return files, nil
}
-// GetSharees returns the list of users a collection has been shared with
func (repo *CollectionRepository) GetSharees(cID int64) ([]ente.CollectionUser, error) {
rows, err := repo.DB.Query(`
SELECT users.user_id, users.encrypted_email, users.email_decryption_nonce, collection_shares.role_type
@@ -1037,7 +1011,6 @@ func convertRowsToFileId(rows *sql.Rows) ([]int64, error) {
return fileIDs, nil
}
-// TrashV3 move the files belonging to the collection owner to the trash
func (repo *CollectionRepository) TrashV3(ctx context.Context, collectionID int64) error {
log := logrus.WithFields(logrus.Fields{
"deleting_collection": collectionID,
@@ -1075,7 +1048,6 @@ func (repo *CollectionRepository) TrashV3(ctx context.Context, collectionID int6
return stacktrace.Propagate(err, "")
}
}
- // Verify that all files are processed in the collection.
count, err := repo.GetCollectionsFilesCount(collectionID)
if err != nil {
return stacktrace.Propagate(err, "")
@@ -1155,7 +1127,6 @@ func (repo *CollectionRepository) ScheduleDelete(collectionID int64) error {
return stacktrace.Propagate(err, "")
}
-// Rename updates the collection's name by updating the encrypted_name and name_decryption_nonce of the collection
func (repo *CollectionRepository) Rename(collectionID int64, encryptedName string, nameDecryptionNonce string) error {
updationTime := time.Microseconds()
_, err := repo.DB.Exec(`UPDATE collections
@@ -1167,7 +1138,6 @@ func (repo *CollectionRepository) Rename(collectionID int64, encryptedName strin
return stacktrace.Propagate(err, "")
}
-// UpdateMagicMetadata updates the magic metadata for the given collection
func (repo *CollectionRepository) UpdateMagicMetadata(ctx context.Context,
collectionID int64,
magicMetadata ente.MagicMetadata,
diff --git a/server/pkg/repo/file.go b/server/pkg/repo/file.go
index 8fe86d95c8..d52808c07f 100644
--- a/server/pkg/repo/file.go
+++ b/server/pkg/repo/file.go
@@ -17,8 +17,6 @@ import (
"github.com/lib/pq"
)
-// FileRepository is an implementation of the FileRepo that
-// persists and retrieves data from disk.
type FileRepository struct {
DB *sql.DB
S3Config *s3config.S3Config
@@ -29,7 +27,6 @@ type FileRepository struct {
UsageRepo *UsageRepository
}
-// Create creates an entry in the database for the given file
func (repo *FileRepository) Create(
file ente.File,
fileSize int64,
@@ -126,7 +123,6 @@ func (repo *FileRepository) Create(
return file, usage, stacktrace.Propagate(err, "")
}
-// CreateMetaFile creates an entry in the database for the given file
func (repo *FileRepository) CreateMetaFile(
metaFile ente.MetaFile,
collectionOwnerID int64,
@@ -220,8 +216,6 @@ func (repo *FileRepository) markAsNeedingReplication(ctx context.Context, tx *sq
err = repo.ObjectCopiesRepo.CreateNewWasabiObject(ctx, tx, file.Thumbnail.ObjectKey, true, false)
return stacktrace.Propagate(err, "")
} else {
- // Bail out if we're trying to add a new entry for a file but the
- // primary hot DC is not one of the known types.
err := fmt.Errorf("only B2 and Wasabi DCs can be used for as the primary hot storage; instead, it was %s", hotDC)
return stacktrace.Propagate(err, "")
}
@@ -236,14 +230,11 @@ func (repo *FileRepository) markThumbnailAsNeedingReplication(ctx context.Contex
err := repo.ObjectCopiesRepo.CreateNewWasabiObject(ctx, tx, thumbnailObjectKey, true, false)
return stacktrace.Propagate(err, "")
} else {
- // Bail out if we're trying to add a new entry for a file but the
- // primary hot DC is not one of the known types.
err := fmt.Errorf("only B2 and Wasabi DCs can be used for as the primary hot storage; instead, it was %s", hotDC)
return stacktrace.Propagate(err, "")
}
}
-// ResetNeedsReplication resets the replication status for an existing file
func (repo *FileRepository) ResetNeedsReplication(file ente.File, hotDC string) error {
if hotDC == repo.S3Config.GetHotBackblazeDC() {
err := repo.ObjectCopiesRepo.ResetNeedsWasabiReplication(file.File.ObjectKey)
@@ -270,14 +261,11 @@ func (repo *FileRepository) ResetNeedsReplication(file ente.File, hotDC string)
err = repo.ObjectCopiesRepo.ResetNeedsB2Replication(file.Thumbnail.ObjectKey)
return stacktrace.Propagate(err, "")
} else {
- // Bail out if we're trying to update the replication flags but the
- // primary hot DC is not one of the known types.
err := fmt.Errorf("only B2 and Wasabi DCs can be used for as the primary hot storage; instead, it was %s", hotDC)
return stacktrace.Propagate(err, "")
}
}
-// Update updates the entry in the database for the given file
func (repo *FileRepository) Update(file ente.File, fileSize int64, thumbnailSize int64, usageDiff int64, oldObjects []string, isDuplicateRequest bool) error {
hotDC := repo.S3Config.GetHotDataCenter()
dcsForNewEntry := pq.StringArray{hotDC}
@@ -444,7 +432,6 @@ func (repo *FileRepository) UpdateMagicAttributes(
return tx.Commit()
}
-// Update updates the entry in the database for the given file
func (repo *FileRepository) UpdateThumbnail(ctx context.Context, fileID int64, userID int64, thumbnail ente.FileAttributes, thumbnailSize int64, usageDiff int64, oldThumbnailObject *string) error {
hotDC := repo.S3Config.GetHotDataCenter()
dcsForNewEntry := pq.StringArray{hotDC}
@@ -527,7 +514,6 @@ func (repo *FileRepository) UpdateThumbnail(ctx context.Context, fileID int64, u
return stacktrace.Propagate(err, "")
}
-// GetOwnerID returns the ownerID for a file
func (repo *FileRepository) GetOwnerID(fileID int64) (int64, error) {
row := repo.DB.QueryRow(`SELECT owner_id FROM files WHERE file_id = $1`,
fileID)
@@ -536,7 +522,6 @@ func (repo *FileRepository) GetOwnerID(fileID int64) (int64, error) {
return ownerID, stacktrace.Propagate(err, "failed to get file owner")
}
-// GetOwnerToFileCountMap will return a map of ownerId & number of files owned by that owner
func (repo *FileRepository) GetOwnerToFileCountMap(ctx context.Context, fileIDs []int64) (map[int64]int64, error) {
rows, err := repo.DB.QueryContext(ctx, `SELECT owner_id, count(*) FROM files WHERE file_id = ANY($1) group by owner_id`,
pq.Array(fileIDs))
@@ -555,7 +540,6 @@ func (repo *FileRepository) GetOwnerToFileCountMap(ctx context.Context, fileIDs
return result, nil
}
-// GetOwnerToFileIDsMap will return a map of ownerId & number of files owned by that owner
func (repo *FileRepository) GetOwnerToFileIDsMap(ctx context.Context, fileIDs []int64) (map[int64][]int64, error) {
rows, err := repo.DB.QueryContext(ctx, `SELECT owner_id, file_id FROM files WHERE file_id = ANY($1)`,
pq.Array(fileIDs))
@@ -607,7 +591,6 @@ func (repo *FileRepository) VerifyFileOwner(ctx context.Context, fileIDs []int64
}
}
-// GetOwnerAndMagicMetadata returns the ownerID and magicMetadata for given file id
func (repo *FileRepository) GetOwnerAndMagicMetadata(fileID int64, publicMetadata bool) (int64, *ente.MagicMetadata, error) {
var row *sql.Row
if publicMetadata {
@@ -623,7 +606,6 @@ func (repo *FileRepository) GetOwnerAndMagicMetadata(fileID int64, publicMetadat
return ownerID, magicMetadata, stacktrace.Propagate(err, "")
}
-// GetSize returns the size of files indicated by fileIDs that are owned by the given userID.
func (repo *FileRepository) GetSize(userID int64, fileIDs []int64) (int64, error) {
row := repo.DB.QueryRow(`
SELECT COALESCE(SUM(size), 0) FROM object_keys WHERE o_type = 'file' AND is_deleted = false AND file_id = ANY(SELECT file_id FROM files WHERE (file_id = ANY($1) AND owner_id = $2))`,
@@ -636,7 +618,6 @@ func (repo *FileRepository) GetSize(userID int64, fileIDs []int64) (int64, error
return size, nil
}
-// GetFileCountForUser returns the total number of files in the system for a given user.
func (repo *FileRepository) GetFileCountForUser(userID int64, app ente.App) (int64, error) {
row := repo.DB.QueryRow(`SELECT count(distinct files.file_id)
FROM collection_files
@@ -715,7 +696,6 @@ func (repo *FileRepository) GetFileAttributes(fileID int64) (*ente.File, error)
return &file, nil
}
-// GetUsage gets the Storage usage of a user
// Deprecated: GetUsage is deprecated, use UsageRepository.GetUsage
func (repo *FileRepository) GetUsage(userID int64) (int64, error) {
return repo.UsageRepo.GetUsage(userID)
@@ -752,7 +732,6 @@ func (repo *FileRepository) DropFilesMetadata(ctx context.Context, fileIDs []int
return stacktrace.Propagate(err, "")
}
-// GetDuplicateFiles returns the list of files for a user that are of the same size
func (repo *FileRepository) GetDuplicateFiles(userID int64) ([]ente.DuplicateFiles, error) {
rows, err := repo.DB.Query(`SELECT string_agg(o.file_id::character varying, ','), o.size FROM object_keys o JOIN files f ON f.file_id = o.file_id
WHERE f.owner_id = $1 AND o.o_type = 'file' AND o.is_deleted = false
@@ -830,7 +809,6 @@ func convertRowsToFiles(rows *sql.Rows) ([]ente.File, error) {
return files, nil
}
-// scheduleDeletion added a list of files's object ids to delete queue for deletion from datastore
func (repo *FileRepository) scheduleDeletion(ctx context.Context, tx *sql.Tx, fileIDs []int64, userID int64) error {
diff := int64(0)
@@ -847,7 +825,6 @@ func (repo *FileRepository) scheduleDeletion(ctx context.Context, tx *sql.Tx, fi
return stacktrace.Propagate(err, "")
}
-// updateUsage updates the storage usage of a user and returns the updated value
func (repo *FileRepository) updateUsage(ctx context.Context, tx *sql.Tx, userID int64, diff int64) (int64, error) {
row := tx.QueryRowContext(ctx, `SELECT storage_consumed FROM usage WHERE user_id = $1 FOR UPDATE`, userID)
var usage int64
diff --git a/server/pkg/repo/object.go b/server/pkg/repo/object.go
index 1326853be7..801e2216f7 100644
--- a/server/pkg/repo/object.go
+++ b/server/pkg/repo/object.go
@@ -67,7 +67,6 @@ func (repo *ObjectRepository) GetObjectsForFileIDs(fileIDs []int64) ([]ente.S3Ob
return convertRowsToObjectKeys(rows)
}
-// GetObject returns the ente.S3ObjectKey key for a file id and type
func (repo *ObjectRepository) GetObject(fileID int64, objType ente.ObjectType) (ente.S3ObjectKey, error) {
// todo: handling of deleted objects
row := repo.objectLookupDB().QueryRow(`SELECT object_key, size, o_type FROM object_keys WHERE file_id = $1 AND o_type = $2 AND is_deleted=false`,
@@ -298,7 +297,6 @@ func (repo *ObjectRepository) RemoveDataCenterFromObject(objectKey string, datac
return stacktrace.Propagate(err, "")
}
-// RemoveObjectsForKey removes the keys of a deleted object from our tables
func (repo *ObjectRepository) RemoveObjectsForKey(objectKey string) error {
_, err := repo.DB.Exec(`DELETE FROM object_keys WHERE object_key = $1 AND is_deleted = TRUE`,
objectKey)
@@ -369,7 +367,6 @@ func convertRowsToObjectKeys(rows *sql.Rows) ([]ente.S3ObjectKey, error) {
return fileObjectKeys, nil
}
-// DoesObjectExist returns the true if there is an entry for the object key.
func (repo *ObjectRepository) DoesObjectExist(tx *sql.Tx, objectKey string) (bool, error) {
var exists bool
err := tx.QueryRow(
@@ -378,8 +375,6 @@ func (repo *ObjectRepository) DoesObjectExist(tx *sql.Tx, objectKey string) (boo
return exists, stacktrace.Propagate(err, "")
}
-// DoesObjectOrTempObjectExist returns the true if there is an entry for the object key in
-// either the object_keys or in temp_objects table.
func (repo *ObjectRepository) DoesObjectOrTempObjectExist(objectKey string) (bool, error) {
var exists bool
err := repo.DB.QueryRow(
diff --git a/server/pkg/repo/object_copies.go b/server/pkg/repo/object_copies.go
index 3796473a4b..4d198cd522 100644
--- a/server/pkg/repo/object_copies.go
+++ b/server/pkg/repo/object_copies.go
@@ -11,8 +11,6 @@ import (
log "github.com/sirupsen/logrus"
)
-// ObjectCopiesRepository wraps over our interaction with the database related
-// to the object_copies table.
type ObjectCopiesRepository struct {
DB *sql.DB
}
@@ -53,9 +51,9 @@ func (repo *ObjectCopiesRepository) GetAndLockUnreplicatedObject(ctx context.Con
&r.WantSCW, &r.SCW)
if err != nil {
- rollback() // Rollback transaction on any error
+ rollback()
if errors.Is(err, sql.ErrNoRows) {
- return nil, err // Return sql.ErrNoRows without committing the transaction
+ return nil, err
}
return nil, stacktrace.Propagate(err, "")
}
@@ -120,32 +118,24 @@ func (repo *ObjectCopiesRepository) DelayNextAttemptByDays(ctx context.Context,
return stacktrace.Propagate(err, "")
}
-// ResetNeedsB2Replication modifies the db to indicate that objectKey should be
-// re-replicated to Backblaze even if it has already been replicated there.
func (repo *ObjectCopiesRepository) ResetNeedsB2Replication(objectKey string) error {
_, err := repo.DB.Exec(`UPDATE object_copies SET b2 = null WHERE object_key = $1`,
objectKey)
return stacktrace.Propagate(err, "")
}
-// ResetNeedsWasabiReplication modifies the db to indicate that objectKey should
-// be re-replicated to Wasabi even if it has already been replicated there.
func (repo *ObjectCopiesRepository) ResetNeedsWasabiReplication(objectKey string) error {
_, err := repo.DB.Exec(`UPDATE object_copies SET wasabi = null WHERE object_key = $1`,
objectKey)
return stacktrace.Propagate(err, "")
}
-// ResetNeedsScalewayReplication modifies the db to indicate that objectKey
-// should be re-replicated to Scaleway even if it has already been replicated there.
func (repo *ObjectCopiesRepository) ResetNeedsScalewayReplication(objectKey string) error {
_, err := repo.DB.Exec(`UPDATE object_copies SET scw = null WHERE object_key = $1`,
objectKey)
return stacktrace.Propagate(err, "")
}
-// UnmarkFromReplication clears the want_* flags so that this objectKey is
-// marked as not requiring further replication.
func (repo *ObjectCopiesRepository) UnmarkFromReplication(objectKey string) error {
_, err := repo.DB.Exec(`
UPDATE object_copies
@@ -155,8 +145,6 @@ func (repo *ObjectCopiesRepository) UnmarkFromReplication(objectKey string) erro
return stacktrace.Propagate(err, "")
}
-// MarkObjectReplicatedB2 sets the time when `objectKey` was replicated to
-// Wasabi to the current timestamp.
func (repo *ObjectCopiesRepository) MarkObjectReplicatedWasabi(objectKey string) error {
return repo.markObjectReplicated(`
UPDATE object_copies SET wasabi = now_utc_micro_seconds()
@@ -164,8 +152,6 @@ func (repo *ObjectCopiesRepository) MarkObjectReplicatedWasabi(objectKey string)
`, objectKey)
}
-// MarkObjectReplicatedScaleway sets the time when `objectKey` was replicated to
-// Wasabi to the current timestamp.
func (repo *ObjectCopiesRepository) MarkObjectReplicatedScaleway(objectKey string) error {
return repo.markObjectReplicated(`
UPDATE object_copies SET scw = now_utc_micro_seconds()
diff --git a/server/pkg/repo/storagebonus/repo.go b/server/pkg/repo/storagebonus/repo.go
index 361cd365da..4a00a84ce7 100644
--- a/server/pkg/repo/storagebonus/repo.go
+++ b/server/pkg/repo/storagebonus/repo.go
@@ -4,13 +4,10 @@ import (
"database/sql"
)
-// Repository defines the methods for inserting, updating and retrieving
-// authenticator related keys and entities from the underlying repository
type Repository struct {
DB *sql.DB
}
-// NewRepository returns a new instance of Repository
func NewRepository(db *sql.DB) *Repository {
return &Repository{
DB: db,
diff --git a/server/pkg/repo/trash.go b/server/pkg/repo/trash.go
index 5556150e30..df3d97c344 100644
--- a/server/pkg/repo/trash.go
+++ b/server/pkg/repo/trash.go
@@ -16,11 +16,8 @@ import (
)
const (
- // TrashDurationInDays number of days after which file will be removed from trash
TrashDurationInDays = 30
- // TrashDiffLimit is the default limit for number of items server will attempt to return when clients
- // ask for changes.
- TrashDiffLimit = 2500
+ TrashDiffLimit = 2500
TrashBatchSize = 1000
@@ -167,7 +164,6 @@ func (t *TrashRepository) TrashFiles(fileIDs []int64, userID int64, trash ente.T
return stacktrace.Propagate(err, "")
}
-// CleanUpDeletedFilesFromCollection deletes the files from the collection if the files are deleted from the trash
func (t *TrashRepository) CleanUpDeletedFilesFromCollection(ctx context.Context, fileIDs []int64, userID int64) error {
err := t.verifyFilesAreDeleted(ctx, userID, fileIDs)
if err != nil {
@@ -213,8 +209,6 @@ func (t *TrashRepository) Delete(ctx context.Context, userID int64, fileIDs []in
if len(fileIDs) > TrashDiffLimit {
return fmt.Errorf("can not delete more than %d in one go", TrashDiffLimit)
}
- // find file_ids from the trash which belong to the user and can be deleted
- // skip restored and already deleted files
fileIDsInTrash, _, err := t.GetFilesInTrashState(ctx, userID, fileIDs)
if err != nil {
return err
@@ -289,7 +283,6 @@ func (t *TrashRepository) GetFilesInTrashOrDeleted(ctx context.Context, userID i
return fileIDsInTrash, nil
}
-// verifyFilesAreDeleted for a given userID and fileIDs, this method verifies that given files are actually deleted
func (t *TrashRepository) verifyFilesAreDeleted(ctx context.Context, userID int64, fileIDs []int64) error {
rows, err := t.DB.QueryContext(ctx, `SELECT file_id FROM trash
WHERE user_id = $1 AND file_id = ANY ($2)
@@ -312,7 +305,6 @@ func (t *TrashRepository) verifyFilesAreDeleted(ctx context.Context, userID int6
return stacktrace.NewError("all file ids are not deleted from trash")
}
- // get the size of file from object_keys table
row := t.DB.QueryRowContext(ctx, `SELECT coalesce(sum(size),0) FROM object_keys WHERE file_id = ANY($1) and is_deleted = FALSE`,
pq.Array(fileIDs))
var totalUsage int64
@@ -336,8 +328,6 @@ func (t *TrashRepository) verifyFilesAreDeleted(ctx context.Context, userID int6
return nil
}
-// GetFilesIDsForDeletion for given userID and lastUpdateAt timestamp, returns the fileIDs which are in trash and
-// where last updated_at before lastUpdateAt timestamp.
func (t *TrashRepository) GetFilesIDsForDeletion(userID int64, lastUpdatedAt int64, app ente.App) ([]int64, error) {
rows, err := t.DB.Query(`SELECT t.file_id FROM trash t
JOIN collections c ON c.collection_id = t.collection_id
@@ -352,7 +342,6 @@ func (t *TrashRepository) GetFilesIDsForDeletion(userID int64, lastUpdatedAt int
return fileIDs, nil
}
-// GetTimeStampForLatestNonDeletedEntry returns the updated at timestamp for the latest,non-deleted entry in the trash
func (t *TrashRepository) GetTimeStampForLatestNonDeletedEntry(userID int64) (*int64, error) {
row := t.DB.QueryRow(`SELECT max(updated_at) FROM trash WHERE user_id = $1 AND is_deleted = FALSE AND is_restored = FALSE`, userID)
var updatedAt *int64
@@ -363,7 +352,6 @@ func (t *TrashRepository) GetTimeStampForLatestNonDeletedEntry(userID int64) (*i
return updatedAt, stacktrace.Propagate(err, "")
}
-// HasItems returns true if the user has any entries in trash.
func (t *TrashRepository) HasItems(ctx context.Context, userID int64) (bool, error) {
row := t.DB.QueryRowContext(ctx, `
SELECT exists(
@@ -378,7 +366,6 @@ func (t *TrashRepository) HasItems(ctx context.Context, userID int64) (bool, err
return hasItems, stacktrace.Propagate(err, "")
}
-// GetUserIDToFileIDsMapForDeletion returns map of userID to fileIds, where the file ids which should be deleted by now
func (t *TrashRepository) GetUserIDToFileIDsMapForDeletion() (map[int64][]int64, error) {
rows, err := t.DB.Query(`SELECT user_id, file_id FROM trash
WHERE delete_by <= $1 AND is_deleted IS FALSE AND is_restored IS FALSE limit $2`,
@@ -453,7 +440,6 @@ order by updated_at ASC limit $2
var i = len(fileWithUpdatedAt) - 1
for ; i >= 0; i-- {
if fileWithUpdatedAt[i].UpdatedAt != lastUpdatedAt {
- // found index (from end) where file's version is different from given version
break
}
}
diff --git a/server/pkg/repo/user.go b/server/pkg/repo/user.go
index 7748572909..36a825330b 100644
--- a/server/pkg/repo/user.go
+++ b/server/pkg/repo/user.go
@@ -20,12 +20,9 @@ import (
)
const (
- // Format for updated email_hash once the account is deleted
DELETED_EMAIL_HASH_FORMAT = "deleted+%[email protected]"
)
-// UserRepository defines the methods for inserting, updating and retrieving
-// user entities from the underlying repository
type UserRepository struct {
DB *sql.DB
SecretEncryptionKey []byte
@@ -34,8 +31,6 @@ type UserRepository struct {
PasskeysRepository *passkey.Repository
}
-// UserInactivityCandidate captures the latest known activity timestamp for an
-// active (non-deleted) user account.
type UserInactivityCandidate struct {
UserID int64
LastActivity int64
@@ -45,7 +40,6 @@ type userMutationExecutor interface {
ExecContext(context.Context, string, ...any) (sql.Result, error)
}
-// Get returns a user indicated by the userID
func (repo *UserRepository) Get(userID int64) (ente.User, error) {
var user ente.User
var encryptedEmail, nonce []byte
@@ -115,7 +109,6 @@ func deleteUser(ctx context.Context, executor userMutationExecutor, userID int64
return stacktrace.Propagate(err, "")
}
-// GetFamilyAdminID returns the *familyAdminID for the given userID
func (repo *UserRepository) GetFamilyAdminID(userID int64) (*int64, error) {
row := repo.DB.QueryRow(`SELECT family_admin_id FROM users WHERE user_id = $1`, userID)
var familyAdminID *int64
@@ -139,7 +132,6 @@ func (repo *UserRepository) AreUsersInSameFamily(ctx context.Context, firstUserI
return sameFamily, stacktrace.Propagate(err, "")
}
-// GetUserByEmailHash returns a user indicated by the emailHash
func (repo *UserRepository) GetUserByEmailHash(emailHash string) (ente.User, error) {
var user ente.User
row := repo.DB.QueryRow(`SELECT user_id, email_hash, creation_time FROM users WHERE email_hash = $1`, emailHash)
@@ -150,7 +142,6 @@ func (repo *UserRepository) GetUserByEmailHash(emailHash string) (ente.User, err
return user, nil
}
-// GetAll returns all users between sinceTime and tillTime (exclusive).
func (repo *UserRepository) GetAll(sinceTime int64, tillTime int64) ([]ente.User, error) {
rows, err := repo.DB.Query(`SELECT user_id, encrypted_email, email_decryption_nonce, email_hash, creation_time FROM users WHERE creation_time > $1 AND creation_time < $2 AND encrypted_email IS NOT NULL ORDER BY creation_time`, sinceTime, tillTime)
if err != nil {
@@ -288,8 +279,6 @@ func (repo *UserRepository) GetLatestActivity(userID int64) (int64, bool, error)
return lastActivity, true, nil
}
-// GetUserUsageWithSubData will return current storage usage & basic information about subscription for given list
-// of users. It's primarily used for fetching storage utilisation for a family/group of users
func (repo *UserRepository) GetUserUsageWithSubData(ctx context.Context, userIds []int64) ([]ente.UserUsageWithSubData, error) {
rows, err := repo.DB.QueryContext(ctx, `select encrypted_email, email_decryption_nonce, u.user_id, coalesce(storage_consumed , 0) as storage_used, storage, expiry_time
from users as u
@@ -322,8 +311,6 @@ func (repo *UserRepository) GetUserUsageWithSubData(ctx context.Context, userIds
return result, nil
}
-// Create creates a user with a given email address and returns the generated
-// userID
func (repo *UserRepository) Create(encryptedEmail ente.EncryptionResult, emailHash string, source *string) (int64, error) {
var userID int64
err := repo.DB.QueryRow(`INSERT INTO users(encrypted_email, email_decryption_nonce, email_hash, creation_time, source) VALUES($1, $2, $3, $4, $5) RETURNING user_id`,
@@ -334,19 +321,15 @@ func (repo *UserRepository) Create(encryptedEmail ente.EncryptionResult, emailHa
return userID, nil
}
-// UpdateDeleteFeedback for a given user in the delete_feedback column of type jsonb
func (repo *UserRepository) UpdateDeleteFeedback(userID int64, feedback map[string]string) error {
- // Convert the feedback map into JSON
feedbackJSON, err := json.Marshal(feedback)
if err != nil {
return stacktrace.Propagate(err, "Failed to marshal feedback into JSON")
}
- // Execute the update query with the JSON
_, err = repo.DB.Exec(`UPDATE users SET delete_feedback = $1 WHERE user_id = $2`, feedbackJSON, userID)
return stacktrace.Propagate(err, "Failed to update delete feedback")
}
-// UpdateEmail updates the email address of a user
func (repo *UserRepository) UpdateEmail(userID int64, encryptedEmail ente.EncryptionResult, emailHash string) error {
return updateEmail(context.Background(), repo.DB, userID, encryptedEmail, emailHash)
}
@@ -378,7 +361,6 @@ func (repo *UserRepository) GetUserIDWithEmailUnrestricted(email string) (int64,
return userID, nil
}
-// GetKeyAttributes gets the key attributes for a given user
func (repo *UserRepository) GetKeyAttributes(userID int64) (ente.KeyAttributes, error) {
row := repo.DB.QueryRow(`SELECT kek_salt, kek_hash_bytes, encrypted_key, key_decryption_nonce, public_key, encrypted_secret_key, secret_key_decryption_nonce, mem_limit, ops_limit, master_key_encrypted_with_recovery_key, master_key_decryption_nonce, recovery_key_encrypted_with_master_key, recovery_key_decryption_nonce FROM key_attributes WHERE user_id = $1`, userID)
var (
@@ -423,7 +405,6 @@ func (repo *UserRepository) GetKeyAttributes(userID int64) (ente.KeyAttributes,
return keyAttributes, nil
}
-// SetKeyAttributes sets the key attributes for a given user
func (repo *UserRepository) SetKeyAttributes(userID int64, keyAttributes ente.KeyAttributes) error {
_, err := repo.DB.Exec(`INSERT INTO key_attributes(user_id, kek_salt, kek_hash_bytes, encrypted_key, key_decryption_nonce, public_key, encrypted_secret_key, secret_key_decryption_nonce, mem_limit, ops_limit, master_key_encrypted_with_recovery_key, master_key_decryption_nonce, recovery_key_encrypted_with_master_key, recovery_key_decryption_nonce) VALUES($1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11, $12, $13, $14)`,
userID, keyAttributes.KEKSalt, []byte(keyAttributes.KEKHash),
@@ -435,14 +416,12 @@ func (repo *UserRepository) SetKeyAttributes(userID int64, keyAttributes ente.Ke
return stacktrace.Propagate(err, "")
}
-// SetRecoveryKeyAttributes sets the recovery key and related attributes for a user
func (repo *UserRepository) SetRecoveryKeyAttributes(userID int64, keys ente.SetRecoveryKeyRequest) error {
_, err := repo.DB.Exec(`UPDATE key_attributes SET master_key_encrypted_with_recovery_key = $1, master_key_decryption_nonce = $2, recovery_key_encrypted_with_master_key = $3, recovery_key_decryption_nonce = $4 WHERE user_id = $5`,
keys.MasterKeyEncryptedWithRecoveryKey, keys.MasterKeyDecryptionNonce, keys.RecoveryKeyEncryptedWithMasterKey, keys.RecoveryKeyDecryptionNonce, userID)
return stacktrace.Propagate(err, "")
}
-// GetPublicKey returns the public key of a user
func (repo *UserRepository) GetPublicKey(userID int64) (string, error) {
row := repo.DB.QueryRow(`SELECT public_key FROM key_attributes WHERE user_id = $1`, userID)
var publicKey string
@@ -450,8 +429,6 @@ func (repo *UserRepository) GetPublicKey(userID int64) (string, error) {
return publicKey, stacktrace.Propagate(err, "")
}
-// GetUsersWithIndividualPlanWhoHaveExceededStorageQuota returns list of users who have consumed their storage quota
-// and they are not part of any family plan
func (repo *UserRepository) GetUsersWithIndividualPlanWhoHaveExceededStorageQuota() ([]ente.User, error) {
rows, err := repo.DB.Query(`
SELECT users.user_id, users.encrypted_email, users.email_decryption_nonce, users.email_hash, usage.storage_consumed, subscriptions.storage
@@ -531,7 +508,6 @@ func (repo *UserRepository) GetUsersWhoUpgradedNDaysAgo(days int) ([]ente.User,
return users, nil
}
-// SetTwoFactorSecret sets the two factor secret for a user
func (repo *UserRepository) SetTwoFactorSecret(userID int64, secret ente.EncryptionResult, secretHash string, recoveryEncryptedTwoFactorSecret string, recoveryTwoFactorSecretDecryptionNonce string) error {
_, err := repo.DB.Exec(`INSERT INTO two_factor(user_id,encrypted_two_factor_secret,two_factor_secret_decryption_nonce,two_factor_secret_hash,recovery_encrypted_two_factor_secret,recovery_two_factor_secret_decryption_nonce)
VALUES($1, $2, $3, $4, $5, $6)
@@ -546,7 +522,6 @@ func (repo *UserRepository) SetTwoFactorSecret(userID int64, secret ente.Encrypt
return stacktrace.Propagate(err, "")
}
-// IsTwoFactorEnabled checks if a user's two factor is enabled or not
func (repo *UserRepository) IsTwoFactorEnabled(userID int64) (bool, error) {
var twoFAStatus bool
row := repo.DB.QueryRow(`SELECT is_two_factor_enabled FROM users WHERE user_id = $1`, userID)
@@ -589,8 +564,6 @@ func (repo *UserRepository) GetEmailsFromHashes(hashes []string) ([]string, erro
return emails, nil
}
-// CountActiveUsersByEmailHashes returns count of active users matching any of
-// the provided hashes.
func (repo *UserRepository) CountActiveUsersByEmailHashes(hashes []string) (int, error) {
if len(hashes) == 0 {
return 0, nil
@@ -608,8 +581,6 @@ func (repo *UserRepository) CountActiveUsersByEmailHashes(hashes []string) (int,
return count, nil
}
-// GetActiveUserEmailHashes returns active user email hashes present in the
-// provided list of hashes.
func (repo *UserRepository) GetActiveUserEmailHashes(hashes []string) ([]string, error) {
if len(hashes) == 0 {
return []string{}, nil
@@ -639,7 +610,6 @@ func (repo *UserRepository) GetActiveUserEmailHashes(hashes []string) ([]string,
return matchedHashes, nil
}
-// GetActiveUsersForIds returns a map of users by their IDs, similar to GetUserByID
func (repo *UserRepository) GetActiveUsersForIds(id []int64) (map[int64]*ente.User, error) {
result := make(map[int64]*ente.User)
rows, err := repo.DB.Query(`SELECT user_id, encrypted_email, email_decryption_nonce, email_hash, creation_time FROM users WHERE encrypted_email IS NOT NULL and user_id = ANY($1)`, pq.Array(id))