disk

package module
v1.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jan 13, 2026 License: MIT Imports: 17 Imported by: 0

README

Yandex Disk Go Client Library

🇷🇺 Русская версия

Go Version License

A comprehensive, production-ready Go client library for the Yandex Disk REST API. This library provides a clean, idiomatic Go interface to interact with Yandex Disk cloud storage service.

🌟 Features

Core Functionality
  • Complete API Coverage - Full support for all Yandex Disk REST API endpoints
  • 🔐 OAuth2 Authentication - Simple token-based authentication
  • 📁 File Operations - Upload, download, copy, move, and delete files
  • 📊 Metadata Management - Get and update file/folder metadata
  • 🗑️ Trash Management - Move to trash, restore, and permanently delete
  • 🌐 Public Links - Create and manage public links to files and folders
  • 📦 Disk Information - Get disk space, quota, and system folders info
Advanced Features
  • 🔄 Pagination Support - Multiple pagination strategies (offset-based and iterator pattern)
  • 📦 Batch Operations - Process multiple files efficiently with concurrent execution
  • 📤 Smart Upload - Automatic handling of large files with progress tracking
  • Context Support - Full context.Context integration for timeouts and cancellation
  • 📝 Comprehensive Logging - Built-in structured logging with multiple severity levels
  • 🔒 Security - Path validation and sanitization to prevent attacks
  • ⚙️ Configurable - Extensive configuration options for timeouts, retries, and more
  • 🧪 Well-Tested - High test coverage with comprehensive unit tests

📋 Table of Contents

📦 Installation

go get github.com/ilyabrin/disk

Requirements:

  • Go 1.20 or higher

🚀 Quick Start

package main

import (
    "context"
    "fmt"
    "log"
    "time"

    "github.com/ilyabrin/disk"
)

func main() {
    // Create a new client with your OAuth token
    client := disk.NewClient("YOUR_OAUTH_TOKEN")

    // Create a context with timeout
    ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
    defer cancel()

    // Get disk information
    diskInfo, err := client.GetDisk(ctx)
    if err != nil {
        log.Fatalf("Failed to get disk info: %v", err)
    }

    fmt.Printf("Total Space: %d bytes\n", diskInfo.TotalSpace)
    fmt.Printf("Used Space: %d bytes\n", diskInfo.UsedSpace)
    fmt.Printf("Available: %d bytes\n", diskInfo.TotalSpace-diskInfo.UsedSpace)
}

🔐 Authentication

To use this library, you need an OAuth token from Yandex. Here's how to get one:

  1. Go to Yandex OAuth
  2. Register your application
  3. Request access to cloud_api:disk.read and cloud_api:disk.write scopes
  4. Obtain your OAuth token
// Create a client with your token
client := disk.NewClient("YOUR_OAUTH_TOKEN")

// Or with custom configuration
config := disk.DefaultClientConfig()
config.DefaultTimeout = 60 * time.Second
client = disk.NewClientWithConfig("YOUR_OAUTH_TOKEN", config)

💡 Basic Usage

Disk Information
// Get disk information
diskInfo, err := client.GetDisk(ctx)
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Total Space: %d\n", diskInfo.TotalSpace)
fmt.Printf("Used Space: %d\n", diskInfo.UsedSpace)
fmt.Printf("Trash Size: %d\n", diskInfo.TrashSize)
fmt.Printf("Is Paid: %t\n", diskInfo.IsPaid)
File Operations
Get File Metadata
// Get metadata for a file or folder
resource, errResp := client.GetMetadata(ctx, "/path/to/file.txt")
if errResp != nil {
    log.Fatalf("Error: %s", errResp.Error)
}

fmt.Printf("Name: %s\n", resource.Name)
fmt.Printf("Size: %d bytes\n", resource.Size)
fmt.Printf("Type: %s\n", resource.Type)
fmt.Printf("Modified: %s\n", resource.Modified)
Copy File
// Copy a file or folder
link, err := client.CopyResource(ctx, "/source/file.txt", "/destination/file.txt", false)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Copy operation link: %s\n", link.Href)
Move/Rename File
// Move or rename a file
link, err := client.MoveResource(ctx, "/old/path/file.txt", "/new/path/file.txt", false)
if err != nil {
    log.Fatal(err)
}
Delete File
// Delete a file (move to trash)
err := client.DeleteResource(ctx, "/path/to/file.txt", false)
if err != nil {
    log.Fatal(err)
}

// Permanently delete a file
err = client.DeleteResource(ctx, "/path/to/file.txt", true)
Folder Operations
Create Folder
// Create a new folder
link, err := client.CreateFolder(ctx, "/path/to/new/folder")
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Folder created: %s\n", link.Href)
List Folder Contents
// Get folder contents
resource, errResp := client.GetMetadata(ctx, "/path/to/folder")
if errResp != nil {
    log.Fatal(errResp.Error)
}

// Iterate through items
if resource.Embedded != nil {
    for _, item := range resource.Embedded.Items {
        fmt.Printf("- %s (%s)\n", item.Name, item.Type)
    }
}
Upload Files
Simple Upload
// Upload a small file
options := &disk.UploadOptions{
    Overwrite: true,
    Progress: func(progress disk.UploadProgress) {
        fmt.Printf("Uploaded: %.2f%%\n", progress.Percentage)
    },
}

resource, err := client.UploadFileFromPath(ctx, "local/file.txt", "/disk/file.txt", options)
if err != nil {
    log.Fatal(err)
}
fmt.Printf("File uploaded: %s\n", resource.Name)
Upload Large File
// Upload a large file with automatic chunking
resource, err := client.UploadLargeFileFromPath(ctx, "large-file.zip", "/disk/large-file.zip", nil)
if err != nil {
    log.Fatal(err)
}
Upload from Reader
// Upload from io.Reader
file, _ := os.Open("file.txt")
defer file.Close()

resource, err := client.UploadFile(ctx, file, "/disk/file.txt", options)
Download Files
// Download a file
err := client.DownloadFile(ctx, "/disk/file.txt", "local/file.txt")
if err != nil {
    log.Fatal(err)
}

// Or get download URL
link, errResp := client.GetDownloadURL(ctx, "/disk/file.txt")
if errResp != nil {
    log.Fatal(errResp.Error)
}
fmt.Printf("Download URL: %s\n", link.Href)
Public Resources
Publish a Resource
// Make a file or folder public
link, err := client.PublishResource(ctx, "/path/to/file.txt")
if err != nil {
    log.Fatal(err)
}
fmt.Printf("Public URL: %s\n", link.Href)
Unpublish a Resource
// Remove public access
link, err := client.UnpublishResource(ctx, "/path/to/file.txt")
if err != nil {
    log.Fatal(err)
}
Access Public Resource
// Get metadata for a public resource
resource, errResp := client.GetMetadataForPublicResource(ctx, "public-key")
if errResp != nil {
    log.Fatal(errResp.Error)
}

// Download public resource
link, errResp := client.GetDownloadURLForPublicResource(ctx, "public-key")
List Public Resources
// Get all public resources
options := &disk.PaginationOptions{Limit: 20}
pagedResources, errResp := client.GetPublicResourcesPaged(ctx, options)
if errResp != nil {
    log.Fatal(errResp.Error)
}

for _, resource := range pagedResources.Items {
    fmt.Printf("Public: %s (%s)\n", resource.Name, resource.PublicURL)
}
Trash Management
Move to Trash
// Delete file (moves to trash)
err := client.DeleteResource(ctx, "/path/to/file.txt", false)
List Trash Contents
// List items in trash
trashList, err := client.ListTrashResources(ctx, "", 20, 0)
if err != nil {
    log.Fatal(err)
}

for _, item := range trashList.Embedded.Items {
    fmt.Printf("Trash: %s (deleted: %s)\n", item.Name, item.Deleted)
}
Restore from Trash
// Restore a file from trash
link, err := client.RestoreFromTrash(ctx, "/path/to/file.txt", false, "")
if err != nil {
    log.Fatal(err)
}
Empty Trash
// Permanently delete all trash
link, err := client.EmptyTrash(ctx)
if err != nil {
    log.Fatal(err)
}
Permanently Delete from Trash
// Delete specific item from trash permanently
link, err := client.DeleteFromTrash(ctx, "/path/to/file.txt")

🔥 Advanced Features

Pagination

The library provides comprehensive pagination support with multiple strategies. See PAGINATION.md for detailed documentation.

Basic Pagination
// Get files with pagination
options := &disk.PaginationOptions{
    Limit:  20,
    Offset: 0,
}
files, errResp := client.GetSortedFilesWithPagination(ctx, options)
Enhanced Pagination with Metadata
// Get pagination info
pagedFiles, errResp := client.GetSortedFilesPaged(ctx, options)
if errResp == nil {
    fmt.Printf("Total items: %d\n", len(pagedFiles.Items))
    fmt.Printf("Has more: %t\n", pagedFiles.Pagination.HasMore)
    if pagedFiles.Pagination.HasMore {
        fmt.Printf("Next offset: %d\n", pagedFiles.Pagination.NextOffset)
    }
}
Iterator Pattern
// Use iterator for automatic pagination
iterator := client.GetSortedFilesIterator(&disk.PaginationOptions{Limit: 50})

for iterator.HasNext() {
    page, err := iterator.Next(ctx)
    if err != nil {
        log.Printf("Error: %v", err)
        break
    }
    
    for _, file := range page.FilesResourceList.Items {
        fmt.Printf("File: %s (%d bytes)\n", file.Name, file.Size)
    }
    
    // Rate limiting
    time.Sleep(200 * time.Millisecond)
}
Batch Operations

Process multiple files efficiently with concurrent execution.

Batch Delete
paths := []string{
    "/file1.txt",
    "/file2.txt",
    "/folder/file3.txt",
}

options := &disk.BatchDeleteOptions{
    BatchOptions: disk.BatchOptions{
        MaxConcurrency:  5,
        ContinueOnError: true,
        Progress: func(status disk.BatchOperationStatus) {
            fmt.Printf("Progress: %d/%d (%.1f%%)\n", 
                status.Completed, status.Total, status.Percentage)
        },
    },
    Permanently: false,
}

status, err := client.BatchDeleteFiles(ctx, paths, options)
if err != nil {
    log.Fatal(err)
}

fmt.Printf("Successful: %d, Failed: %d\n", status.Successful, status.Failed)
Batch Copy
sourceDestMap := map[string]string{
    "/source/file1.txt": "/backup/file1.txt",
    "/source/file2.txt": "/backup/file2.txt",
}

options := &disk.BatchCopyMoveOptions{
    BatchOptions: disk.BatchOptions{
        MaxConcurrency: 3,
    },
    Overwrite: false,
}

status, err := client.BatchCopyFiles(ctx, sourceDestMap, options)
Batch Move
status, err := client.BatchMoveFiles(ctx, sourceDestMap, options)
Progress Tracking

Track upload/download progress in real-time.

options := &disk.UploadOptions{
    Progress: func(progress disk.UploadProgress) {
        percentage := progress.Percentage
        bytes := progress.BytesUploaded
        total := progress.TotalBytes
        
        fmt.Printf("\rUploading: %.2f%% (%d/%d bytes)", 
            percentage, bytes, total)
    },
}

resource, err := client.UploadFileFromPath(ctx, localPath, remotePath, options)
Custom Configuration
// Create custom configuration
config := &disk.ClientConfig{
    DefaultTimeout:     60 * time.Second,
    MaxRetries:         3,
    EnableDebugLogging: true,
    Logger: &disk.LoggerConfig{
        Enabled:      true,
        Level:        disk.LogLevelInfo,
        IncludeTime:  true,
        ColorEnabled: true,
    },
}

client := disk.NewClientWithConfig("YOUR_TOKEN", config)
Logging

The library includes comprehensive logging capabilities.

// Access the logger
client.Logger.Info("Operation started")
client.Logger.Debug("Debug information: %v", data)
client.Logger.Error("An error occurred: %v", err)

// Change log level
client.Logger.SetLevel(disk.LogLevelDebug)

// Enable/disable logging
client.Logger.SetEnabled(true)

// Enable colored output
client.Logger.SetColorEnabled(true)

Available Log Levels:

  • LogLevelDebug - Detailed debugging information
  • LogLevelInfo - General informational messages
  • LogLevelWarn - Warning messages
  • LogLevelError - Error messages

⚠️ Error Handling

The library provides detailed error information through structured error responses.

resource, errResp := client.GetMetadata(ctx, "/path/to/file")
if errResp != nil {
    fmt.Printf("Error: %s\n", errResp.Error)
    fmt.Printf("Description: %s\n", errResp.Description)
    fmt.Printf("Message: %s\n", errResp.Message)
    
    // Handle specific errors
    switch errResp.Error {
    case "DiskNotFoundError":
        fmt.Println("File or folder not found")
    case "UnauthorizedError":
        fmt.Println("Invalid or expired token")
    case "DiskPathPointsToExistentDirectoryError":
        fmt.Println("Path already exists")
    default:
        fmt.Printf("Unknown error: %s\n", errResp.Error)
    }
    return
}

Common Error Types:

  • UnauthorizedError - Invalid or expired OAuth token
  • DiskNotFoundError - Resource not found
  • DiskPathPointsToExistentDirectoryError - Path already exists
  • FieldValidationError - Invalid input parameters
  • LockedError - Resource is locked
  • LimitExceededError - Rate limit exceeded

📚 Examples

Complete working examples are available in the examples/ directory:

Run an example:

cd examples/upload
go run main.go

📖 API Reference

Client Methods
Disk Information
  • GetDisk(ctx) (*Disk, error) - Get disk information
File & Folder Operations
  • GetMetadata(ctx, path) (*Resource, *ErrorResponse) - Get resource metadata
  • CreateFolder(ctx, path) (*Link, error) - Create a folder
  • CopyResource(ctx, from, to, overwrite) (*Link, error) - Copy resource
  • MoveResource(ctx, from, to, overwrite) (*Link, error) - Move resource
  • DeleteResource(ctx, path, permanently) error - Delete resource
Upload & Download
  • UploadFileFromPath(ctx, local, remote, options) (*Resource, error) - Upload file
  • UploadLargeFileFromPath(ctx, local, remote, options) (*Resource, error) - Upload large file
  • UploadFile(ctx, reader, remote, options) (*Resource, error) - Upload from reader
  • DownloadFile(ctx, remote, local) error - Download file
  • GetDownloadURL(ctx, path) (*Link, *ErrorResponse) - Get download URL
Public Resources
  • PublishResource(ctx, path) (*Link, error) - Publish resource
  • UnpublishResource(ctx, path) (*Link, error) - Unpublish resource
  • GetMetadataForPublicResource(ctx, publicKey) (*PublicResource, *ErrorResponse)
  • GetDownloadURLForPublicResource(ctx, publicKey) (*Link, *ErrorResponse)
  • GetPublicResources(ctx) (*PublicResourcesList, *ErrorResponse)
  • GetPublicResourcesPaged(ctx, options) (*PagedPublicResourcesList, *ErrorResponse)
  • GetPublicResourcesIterator(options) *OffsetPaginationIterator[*PublicResourcesList]
Trash Operations
  • ListTrashResources(ctx, path, limit, offset) (*TrashResourceList, error)
  • RestoreFromTrash(ctx, path, overwrite, name) (*Link, error)
  • DeleteFromTrash(ctx, path) (*Link, error)
  • EmptyTrash(ctx) (*Link, error)
Batch Operations
  • BatchDeleteFiles(ctx, paths, options) (*BatchOperationStatus, error)
  • BatchCopyFiles(ctx, sourceDestMap, options) (*BatchOperationStatus, error)
  • BatchMoveFiles(ctx, sourceDestMap, options) (*BatchOperationStatus, error)
Pagination
  • GetSortedFiles(ctx) (*FilesResourceList, *ErrorResponse)
  • GetSortedFilesWithPagination(ctx, options) (*FilesResourceList, *ErrorResponse)
  • GetSortedFilesPaged(ctx, options) (*PagedFilesResourceList, *ErrorResponse)
  • GetSortedFilesIterator(options) *OffsetPaginationIterator[*FilesResourceList]
  • GetLastUploadedResources(ctx) (*LastUploadedResourceList, *ErrorResponse)
  • GetLastUploadedResourcesWithPagination(ctx, options) (*LastUploadedResourceList, *ErrorResponse)
  • GetLastUploadedResourcesPaged(ctx, options) (*PagedLastUploadedResourceList, *ErrorResponse)
  • GetLastUploadedResourcesIterator(options) *OffsetPaginationIterator[*LastUploadedResourceList]
Operations
  • OperationStatus(ctx, operationID) (any, *http.Response, error) - Check async operation status

For detailed pagination API documentation, see PAGINATION.md.

🧪 Testing

The library includes comprehensive unit tests.

# Run all tests
go test -v

# Run with coverage
go test -v -cover

# Generate coverage report
go test -coverprofile=coverage.out
go tool cover -html=coverage.out

# Run specific tests
go test -v -run TestPagination
go test -v -run TestBatch

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request. For major changes, please open an issue first to discuss what you would like to change.

Development Setup
  1. Clone the repository:
git clone https://github.com/ilyabrin/disk.git
cd disk
  1. Install dependencies:
go mod download
  1. Run tests:
go test -v
Guidelines
  • Write tests for new features
  • Follow Go best practices and idioms
  • Update documentation for API changes
  • Ensure all tests pass before submitting PR

📄 License

This project is licensed under the MIT License - see the LICENSE file for details.

📝 Changelog

Recent Updates
  • ✅ Comprehensive pagination support with multiple strategies
  • ✅ Batch operations for efficient multi-file processing
  • ✅ Enhanced upload functionality with progress tracking
  • ✅ Improved error handling and logging
  • ✅ Full context.Context support
  • ✅ Security enhancements with path validation

💬 Support

If you have questions or need help:

⭐ Acknowledgments

Built with ❤️ for the Go community. If you find this library helpful, please consider giving it a star on GitHub!


Note: This library is not officially affiliated with Yandex. It's a community-maintained client library for the Yandex Disk API.

Documentation

Index

Constants

View Source
const API_URL = "https://cloud-api.yandex.net/v1/disk/"

Variables

This section is empty.

Functions

func FormatFileSize added in v1.1.0

func FormatFileSize(bytes int64) string

FormatFileSize formats a file size in bytes to a human-readable string

func GetFileSize added in v1.1.0

func GetFileSize(filePath string) (int64, error)

GetFileSize returns the size of a local file

func ValidateFilePath added in v1.1.0

func ValidateFilePath(path string) error

ValidateFilePath checks if a file path is valid for upload

func WithCancel added in v1.1.0

func WithCancel() (context.Context, context.CancelFunc)

WithCancel creates a cancellable context

func WithDeadline added in v1.1.0

func WithDeadline(deadline time.Time) (context.Context, context.CancelFunc)

WithDeadline creates a context with the specified deadline

func WithTimeout added in v1.1.0

func WithTimeout(timeout time.Duration) (context.Context, context.CancelFunc)

WithTimeout creates a context with the specified timeout duration

Types

type BatchCopyMoveOptions added in v1.1.0

type BatchCopyMoveOptions struct {
	BatchOptions
	DestinationPrefix string // Prefix to add to destination paths
	Overwrite         bool   // Whether to overwrite existing files
}

BatchCopyMoveOptions contains options specific to batch copy/move operations

type BatchDeleteOptions added in v1.1.0

type BatchDeleteOptions struct {
	BatchOptions
	Permanently bool // Whether to delete files permanently or move to trash
}

BatchDeleteOptions contains options specific to batch deletion

type BatchOperationResult added in v1.1.0

type BatchOperationResult struct {
	Path      string        `json:"path"`
	Success   bool          `json:"success"`
	Error     error         `json:"error,omitempty"`
	Operation string        `json:"operation"`
	Duration  time.Duration `json:"duration"`
	Link      *Link         `json:"link,omitempty"`     // For async operations
	Resource  *Resource     `json:"resource,omitempty"` // For operations that return resources
}

BatchOperationResult represents the result of a single operation in a batch

type BatchOperationStatus added in v1.1.0

type BatchOperationStatus struct {
	Total      int                     `json:"total"`
	Completed  int                     `json:"completed"`
	Successful int                     `json:"successful"`
	Failed     int                     `json:"failed"`
	InProgress int                     `json:"in_progress"`
	Results    []*BatchOperationResult `json:"results"`
	StartTime  time.Time               `json:"start_time"`
	EndTime    *time.Time              `json:"end_time,omitempty"`
	Duration   time.Duration           `json:"duration"`
	Percentage float64                 `json:"percentage"`
}

BatchOperationStatus represents the overall status of a batch operation

func (*BatchOperationStatus) GetFailedOperations added in v1.1.0

func (status *BatchOperationStatus) GetFailedOperations() []*BatchOperationResult

GetFailedOperations returns only the failed operations from a batch

func (*BatchOperationStatus) GetSuccessfulOperations added in v1.1.0

func (status *BatchOperationStatus) GetSuccessfulOperations() []*BatchOperationResult

GetSuccessfulOperations returns only the successful operations from a batch

func (*BatchOperationStatus) GetSummary added in v1.1.0

func (status *BatchOperationStatus) GetSummary() map[string]interface{}

GetBatchOperationsSummary provides a summary of batch operation results

type BatchOptions added in v1.1.0

type BatchOptions struct {
	MaxConcurrency  int                   // Maximum number of concurrent operations (default: 5)
	ContinueOnError bool                  // Whether to continue processing if some operations fail
	Progress        BatchProgressCallback // Optional progress callback
	Timeout         time.Duration         // Timeout for individual operations
}

BatchOptions contains configuration options for batch operations

type BatchProgressCallback added in v1.1.0

type BatchProgressCallback func(status BatchOperationStatus)

BatchProgressCallback is called during batch operations to report progress

type BatchUpdateMetadataOptions added in v1.1.0

type BatchUpdateMetadataOptions struct {
	BatchOptions
	CustomProperties map[string]map[string]string // Properties to set on all files
	Fields           []string                     // Specific fields to update
}

BatchUpdateMetadataOptions contains options for batch metadata updates

type Client

type Client struct {
	AccessToken string
	HTTPClient  *http.Client
	Logger      *DiskLogger
	Config      *ClientConfig
}

func New

func New(token ...string) (*Client, error)

New(token ...string) fetch token from OS env var if has not direct defined Uses default configuration for backward compatibility

func NewWithConfig added in v1.1.0

func NewWithConfig(config *ClientConfig, token ...string) (*Client, error)

NewWithConfig creates a new Client with custom configuration

func (*Client) BatchCopyFiles added in v1.1.0

func (c *Client) BatchCopyFiles(ctx context.Context, operations map[string]string, options *BatchCopyMoveOptions) (*BatchOperationStatus, error)

BatchCopyFiles copies multiple files in parallel

func (*Client) BatchCopyFilesSimple added in v1.1.0

func (c *Client) BatchCopyFilesSimple(ctx context.Context, operations map[string]string) (*BatchOperationStatus, error)

BatchCopyFilesSimple is a simplified version of BatchCopyFiles with basic options

func (*Client) BatchCopyToDirectory added in v1.1.0

func (c *Client) BatchCopyToDirectory(ctx context.Context, paths []string, targetDir string, options *BatchCopyMoveOptions) (*BatchOperationStatus, error)

BatchCopyToDirectory copies multiple files to a target directory

func (*Client) BatchDeleteFiles added in v1.1.0

func (c *Client) BatchDeleteFiles(ctx context.Context, paths []string, options *BatchDeleteOptions) (*BatchOperationStatus, error)

BatchDeleteFiles deletes multiple files in parallel

func (*Client) BatchDeleteFilesSimple added in v1.1.0

func (c *Client) BatchDeleteFilesSimple(ctx context.Context, paths []string, permanently bool) (*BatchOperationStatus, error)

BatchDeleteFilesSimple is a simplified version of BatchDeleteFiles with basic options

func (*Client) BatchMoveFiles added in v1.1.0

func (c *Client) BatchMoveFiles(ctx context.Context, operations map[string]string, options *BatchCopyMoveOptions) (*BatchOperationStatus, error)

BatchMoveFiles moves multiple files in parallel

func (*Client) BatchMoveFilesSimple added in v1.1.0

func (c *Client) BatchMoveFilesSimple(ctx context.Context, operations map[string]string) (*BatchOperationStatus, error)

BatchMoveFilesSimple is a simplified version of BatchMoveFiles with basic options

func (*Client) BatchMoveToDirectory added in v1.1.0

func (c *Client) BatchMoveToDirectory(ctx context.Context, paths []string, targetDir string, options *BatchCopyMoveOptions) (*BatchOperationStatus, error)

BatchMoveToDirectory moves multiple files to a target directory

func (*Client) BatchRenameFiles added in v1.1.0

func (c *Client) BatchRenameFiles(ctx context.Context, paths []string, prefix, suffix string, options *BatchCopyMoveOptions) (*BatchOperationStatus, error)

BatchRenameFiles renames multiple files by adding a prefix or suffix

func (*Client) BatchUpdateMetadata added in v1.1.0

func (c *Client) BatchUpdateMetadata(ctx context.Context, paths []string, customProperties map[string]map[string]string, options *BatchUpdateMetadataOptions) (*BatchOperationStatus, error)

BatchUpdateMetadata updates metadata for multiple files in parallel

func (*Client) CopyResource added in v1.1.0

func (c *Client) CopyResource(ctx context.Context, from, path string) (*Link, *ErrorResponse)

func (*Client) CreateDir added in v1.1.0

func (c *Client) CreateDir(ctx context.Context, path string) (*Link, *ErrorResponse)

CreateDir creates a new directory with the specified 'path' name. todo: can't create nested dirs like newDir/subDir/anotherDir

func (*Client) DeleteResource added in v1.1.0

func (c *Client) DeleteResource(ctx context.Context, path string, permanently bool) error

todo: add *ErrorResponse to return

func (*Client) DetectMimeType added in v1.1.0

func (c *Client) DetectMimeType(filePath string) (string, error)

DetectMimeType attempts to detect the MIME type of a file

func (*Client) DiskInfo added in v1.1.0

func (c *Client) DiskInfo(ctx context.Context) (*Disk, error)

func (*Client) EmptyTrash added in v1.1.0

func (c *Client) EmptyTrash(ctx context.Context, path string, force bool) error

EmptyTrash permanently deletes all resources from trash or a specific path in trash

func (*Client) GetDownloadURL added in v1.1.0

func (c *Client) GetDownloadURL(ctx context.Context, path string) (*Link, *ErrorResponse)

func (*Client) GetDownloadURLForPublicResource added in v1.1.0

func (c *Client) GetDownloadURLForPublicResource(ctx context.Context, public_key string) (*Link, *ErrorResponse)

func (*Client) GetLastUploadedResources added in v1.1.0

func (c *Client) GetLastUploadedResources(ctx context.Context) (*LastUploadedResourceList, *ErrorResponse)

get | sortBy = [name = default, uploadDate]

func (*Client) GetLastUploadedResourcesIterator added in v1.1.0

func (c *Client) GetLastUploadedResourcesIterator(options *PaginationOptions) *PaginationIterator[*PagedLastUploadedResourceList]

GetLastUploadedResourcesIterator returns an iterator for paginated access to last uploaded resources

func (*Client) GetLastUploadedResourcesPaged added in v1.1.0

func (c *Client) GetLastUploadedResourcesPaged(ctx context.Context, options *PaginationOptions) (*PagedLastUploadedResourceList, *ErrorResponse)

GetLastUploadedResourcesPaged returns a paginated wrapper with pagination info

func (*Client) GetLastUploadedResourcesWithPagination added in v1.1.0

func (c *Client) GetLastUploadedResourcesWithPagination(ctx context.Context, options *PaginationOptions) (*LastUploadedResourceList, *ErrorResponse)

GetLastUploadedResourcesWithPagination gets last uploaded resources with pagination support

func (*Client) GetLinkForUpload added in v1.1.0

func (c *Client) GetLinkForUpload(ctx context.Context, path string) (*ResourceUploadLink, *ErrorResponse)

func (*Client) GetMetadata added in v1.1.0

func (c *Client) GetMetadata(ctx context.Context, path string) (*Resource, *ErrorResponse)

func (*Client) GetMetadataForPublicResource added in v1.1.0

func (c *Client) GetMetadataForPublicResource(ctx context.Context, public_key string) (*PublicResource, *ErrorResponse)

func (*Client) GetPublicResources added in v1.1.0

func (c *Client) GetPublicResources(ctx context.Context) (*PublicResourcesList, *ErrorResponse)

func (*Client) GetPublicResourcesIterator added in v1.1.0

func (c *Client) GetPublicResourcesIterator(options *PaginationOptions) *PaginationIterator[*PagedPublicResourcesList]

GetPublicResourcesIterator returns an iterator for paginated access to public resources

func (*Client) GetPublicResourcesPaged added in v1.1.0

func (c *Client) GetPublicResourcesPaged(ctx context.Context, options *PaginationOptions) (*PagedPublicResourcesList, *ErrorResponse)

GetPublicResourcesPaged returns a paginated wrapper with pagination info

func (*Client) GetPublicResourcesWithPagination added in v1.1.0

func (c *Client) GetPublicResourcesWithPagination(ctx context.Context, options *PaginationOptions) (*PublicResourcesList, *ErrorResponse)

GetPublicResourcesWithPagination gets public resources with pagination support

func (*Client) GetSortedFiles added in v1.1.0

func (c *Client) GetSortedFiles(ctx context.Context) (*FilesResourceList, *ErrorResponse)

func (*Client) GetSortedFilesIterator added in v1.1.0

func (c *Client) GetSortedFilesIterator(options *PaginationOptions) *PaginationIterator[*PagedFilesResourceList]

GetSortedFilesIterator returns an iterator for paginated access to sorted files

func (*Client) GetSortedFilesPaged added in v1.1.0

func (c *Client) GetSortedFilesPaged(ctx context.Context, options *PaginationOptions) (*PagedFilesResourceList, *ErrorResponse)

GetSortedFilesPaged returns a paginated wrapper with pagination info

func (*Client) GetSortedFilesWithPagination added in v1.1.0

func (c *Client) GetSortedFilesWithPagination(ctx context.Context, options *PaginationOptions) (*FilesResourceList, *ErrorResponse)

GetSortedFilesWithPagination gets a sorted list of files with pagination support

func (*Client) GetTimeout added in v1.1.0

func (c *Client) GetTimeout() time.Duration

GetTimeout returns the current default timeout for the client

func (*Client) GetTrashResourceMetadata added in v1.1.0

func (c *Client) GetTrashResourceMetadata(ctx context.Context, path string, fields []string) (*TrashResource, error)

GetTrashResourceMetadata retrieves metadata for a specific resource in trash

func (*Client) ListTrashResources added in v1.1.0

func (c *Client) ListTrashResources(ctx context.Context, path string, limit int, offset int) (*TrashResourceList, error)

ListTrashResources lists resources in the trash, optionally filtered by path

func (*Client) MoveResource added in v1.1.0

func (c *Client) MoveResource(ctx context.Context, from, path string) (*Link, *ErrorResponse)

func (*Client) OperationStatus added in v1.1.0

func (c *Client) OperationStatus(ctx context.Context, operationID string) (any, *http.Response, error)

TODO: add tests and use generics instead of interface{}

func (*Client) PublishResource added in v1.1.0

func (c *Client) PublishResource(ctx context.Context, path string) (*Link, *ErrorResponse)

func (*Client) RestoreFromTrash added in v1.1.0

func (c *Client) RestoreFromTrash(ctx context.Context, path string, overwrite bool, name string) (*Link, error)

RestoreFromTrash restores a resource from trash to its original location or a new path

func (*Client) RetryFailedOperations added in v1.1.0

func (c *Client) RetryFailedOperations(ctx context.Context, status *BatchOperationStatus, maxRetries int) (*BatchOperationStatus, error)

RetryFailedOperations retries only the failed operations from a previous batch

func (*Client) SavePublicResource added in v1.1.0

func (c *Client) SavePublicResource(ctx context.Context, public_key string) (*Link, *ErrorResponse)

func (*Client) SetLogLevel added in v1.1.0

func (c *Client) SetLogLevel(level LogLevel)

SetLogLevel sets the minimum log level for the client

func (*Client) SetLogOutput added in v1.1.0

func (c *Client) SetLogOutput(output io.Writer)

SetLogOutput changes the log output destination

func (*Client) SetTimeout added in v1.1.0

func (c *Client) SetTimeout(timeout time.Duration)

SetTimeout updates the default timeout for the client

func (*Client) SetVerbose added in v1.1.0

func (c *Client) SetVerbose(verbose bool)

SetVerbose enables or disables verbose logging

func (*Client) UnpublishResource added in v1.1.0

func (c *Client) UnpublishResource(ctx context.Context, path string) (*Link, *ErrorResponse)

func (*Client) UpdateMetadata added in v1.1.0

func (c *Client) UpdateMetadata(ctx context.Context, path string, custom_properties map[string]map[string]string) (*Resource, *ErrorResponse)

todo: add examples to README

newMeta := map[string]map[string]string{
	"custom_properties": {
		"key_01": "value_01",
		"key_02": "value_02",
		"key_07": "value_07",
	},
}

func (*Client) UploadFile added in v1.1.0

func (c *Client) UploadFile(ctx context.Context, path, uploadURL string) (*Link, *ErrorResponse)

todo: empty resonses - fix it

func (*Client) UploadFileFromPath added in v1.1.0

func (c *Client) UploadFileFromPath(ctx context.Context, localPath string, remotePath string, options *UploadOptions) (*Resource, error)

UploadFileFromPath uploads a file from the local filesystem to Yandex Disk

func (*Client) UploadFileFromPathWithProgress added in v1.1.0

func (c *Client) UploadFileFromPathWithProgress(ctx context.Context, localPath string, remotePath string, overwrite bool, callback ProgressCallback) (*Resource, error)

UploadFileFromPathWithProgress is a convenience method for uploads with progress tracking

func (*Client) UploadLargeFileFromPath added in v1.1.0

func (c *Client) UploadLargeFileFromPath(ctx context.Context, localPath string, remotePath string, chunkSizeMB int, callback ProgressCallback) (*Resource, error)

UploadLargeFileFromPath is a convenience method for large file uploads with chunking

func (*Client) WaitForBatchOperation added in v1.1.0

func (c *Client) WaitForBatchOperation(ctx context.Context, status *BatchOperationStatus, pollInterval time.Duration) error

WaitForBatchOperation waits for asynchronous batch operations to complete This is useful when operations return Links for asynchronous processing

type ClientConfig added in v1.1.0

type ClientConfig struct {
	DefaultTimeout     time.Duration // Default timeout for requests
	MaxRetries         int           // Maximum number of retries (future use)
	EnableDebugLogging bool          // Enable debug logging (future use)
	Logger             *LoggerConfig // Logger configuration
}

ClientConfig holds configuration options for the Client

func DefaultClientConfig added in v1.1.0

func DefaultClientConfig() *ClientConfig

DefaultClientConfig returns a ClientConfig with sensible defaults

type CommentIds

type CommentIds struct {
	PrivateResource string `json:"private_resource,omitempty"`
	PublicResource  string `json:"public_resource,omitempty"`
}

type CursorPaginationIterator added in v1.1.0

type CursorPaginationIterator[T any] struct {
	// contains filtered or unexported fields
}

CursorPaginationIterator provides cursor-based pagination iterator

func NewCursorPaginationIterator added in v1.1.0

func NewCursorPaginationIterator[T any](
	client *Client,
	fetcher func(ctx context.Context, cursor string, limit int) (T, string, error),
	limit int,
) *CursorPaginationIterator[T]

NewCursorPaginationIterator creates a new cursor-based pagination iterator

func (*CursorPaginationIterator[T]) GetNextCursor added in v1.1.0

func (c *CursorPaginationIterator[T]) GetNextCursor() string

GetNextCursor returns the cursor for the next page

func (*CursorPaginationIterator[T]) GetPageSize added in v1.1.0

func (c *CursorPaginationIterator[T]) GetPageSize() int

GetPageSize returns the current page size

func (*CursorPaginationIterator[T]) HasNext added in v1.1.0

func (c *CursorPaginationIterator[T]) HasNext() bool

HasNext returns true if there are more pages available

func (*CursorPaginationIterator[T]) Next added in v1.1.0

func (c *CursorPaginationIterator[T]) Next(ctx context.Context) (T, error)

Next fetches the next page using cursor-based pagination

func (*CursorPaginationIterator[T]) Reset added in v1.1.0

func (c *CursorPaginationIterator[T]) Reset()

Reset resets the iterator to the beginning

func (*CursorPaginationIterator[T]) SetPageSize added in v1.1.0

func (c *CursorPaginationIterator[T]) SetPageSize(size int)

SetPageSize sets the page size for future requests

type Disk

type Disk struct {
	UnlimitedAutouploadEnabled bool           `json:"unlimited_autoupload_enabled,omitempty"` // boolean, optional:
	MaxFileSize                int            `json:"max_file_size,omitempty"`                // integer, optional:
	TotalSpace                 int            `json:"total_space,omitempty"`                  // integer, optional:
	TrashSize                  int            `json:"trash_size,omitempty"`                   // integer, optional:
	IsPaid                     bool           `json:"is_paid,omitempty"`                      // boolean, optional:
	UsedSpace                  int            `json:"used_space,omitempty"`                   // integer, optional:
	SystemFolders              *SystemFolders `json:"system_folders,omitempty"`               // (SystemFolders, optional)
	User                       *User          `json:"user,omitempty"`                         // (User, optional)
	Revision                   int            `json:"revision,omitempty"`                     // (integer, optional):
}

GET /v1/disk

type DiskLogger added in v1.1.0

type DiskLogger struct {
	// contains filtered or unexported fields
}

DiskLogger provides structured logging with multiple levels

func NewLogger added in v1.1.0

func NewLogger(config *LoggerConfig) *DiskLogger

NewLogger creates a new DiskLogger with the given configuration

func (*DiskLogger) Debug added in v1.1.0

func (l *DiskLogger) Debug(format string, args ...interface{})

Debug logs a debug message

func (*DiskLogger) Error added in v1.1.0

func (l *DiskLogger) Error(format string, args ...interface{})

Error logs an error message

func (*DiskLogger) Info added in v1.1.0

func (l *DiskLogger) Info(format string, args ...interface{})

Info logs an info message

func (*DiskLogger) LogError added in v1.1.0

func (l *DiskLogger) LogError(operation string, err error)

LogError logs an error with context

func (*DiskLogger) LogRequest added in v1.1.0

func (l *DiskLogger) LogRequest(method, url string, headers map[string]string)

LogRequest logs HTTP request details

func (*DiskLogger) LogResponse added in v1.1.0

func (l *DiskLogger) LogResponse(statusCode int, contentLength int64, duration time.Duration)

LogResponse logs HTTP response details

func (*DiskLogger) SanitizeValue added in v1.1.0

func (l *DiskLogger) SanitizeValue(key, value string) string

SanitizeValue sanitizes sensitive information for logging

func (*DiskLogger) SetLevel added in v1.1.0

func (l *DiskLogger) SetLevel(level LogLevel)

SetLevel updates the minimum log level

func (*DiskLogger) SetOutput added in v1.1.0

func (l *DiskLogger) SetOutput(output io.Writer)

SetOutput changes the output destination for logs

func (*DiskLogger) SetVerbose added in v1.1.0

func (l *DiskLogger) SetVerbose(verbose bool)

SetVerbose enables or disables verbose mode

func (*DiskLogger) Warn added in v1.1.0

func (l *DiskLogger) Warn(format string, args ...interface{})

Warn logs a warning message

type ErrorResponse

type ErrorResponse struct {
	Message     string `json:"message"`
	Description string `json:"description"`
	Error       string `json:"error"`
}

type Exif

type Exif struct {
	DateTime string `json:"date_time,omitempty"`
}

type FilesResourceList

type FilesResourceList struct {
	Items  []*Resource `json:"items"`            // (Array[Resource]): <Элементы списка>,
	Limit  int         `json:"limit,omitempty"`  //(integer, optional): <Количество элементов на странице>,
	Offset int         `json:"offset,omitempty"` // (integer, optional): <Смещение от начала списка>
}

type HttpMethod added in v1.1.0

type HttpMethod string
const (
	GET    HttpMethod = "GET"
	POST   HttpMethod = "POST"
	PUT    HttpMethod = "PUT"
	PATCH  HttpMethod = "PATCH"
	DELETE HttpMethod = "DELETE"
)

type LastUploadedResourceList

type LastUploadedResourceList struct {
	Items []*Resource `json:"items"`           //(Array[Resource]): <Элементы списка>,
	Limit int         `json:"limit,omitempty"` // (integer, optional): <Количество элементов на странице>
}
type Link struct {
	Href      string `json:"href"`
	Method    string `json:"method"`
	Templated bool   `json:"templated,omitempty"`
}

type LogLevel added in v1.1.0

type LogLevel int

LogLevel represents the severity level of a log message

const (
	DEBUG LogLevel = iota
	INFO
	WARN
	ERROR
	SILENT // No logging
)

func (LogLevel) String added in v1.1.0

func (l LogLevel) String() string

String returns the string representation of a LogLevel

type LoggerConfig added in v1.1.0

type LoggerConfig struct {
	Level        LogLevel  // Minimum log level to output
	Output       io.Writer // Where to write logs (default: os.Stdout)
	Prefix       string    // Prefix for log messages
	TimeFormat   string    // Time format for timestamps
	Structured   bool      // Enable structured logging
	Verbose      bool      // Enable verbose mode (includes DEBUG level)
	SanitizeAuth bool      // Sanitize authorization headers in logs
}

LoggerConfig holds configuration for the logger

func DefaultLoggerConfig added in v1.1.0

func DefaultLoggerConfig() *LoggerConfig

DefaultLoggerConfig returns a LoggerConfig with sensible defaults

type Operation

type Operation struct {
	Status string `json:"status"`
}

type PagedFilesResourceList added in v1.1.0

type PagedFilesResourceList struct {
	*FilesResourceList
	Pagination *PaginationInfo `json:"pagination"`
}

PagedFilesResourceList contains paginated files with pagination info

type PagedLastUploadedResourceList added in v1.1.0

type PagedLastUploadedResourceList struct {
	*LastUploadedResourceList
	Pagination *PaginationInfo `json:"pagination"`
}

PagedLastUploadedResourceList contains paginated last uploaded resources with pagination info

type PagedPublicResourcesList added in v1.1.0

type PagedPublicResourcesList struct {
	*PublicResourcesList
	Pagination *PaginationInfo `json:"pagination"`
}

PagedPublicResourcesList contains paginated public resources with pagination info

type PaginationInfo added in v1.1.0

type PaginationInfo struct {
	Limit      int    // Number of items requested
	Offset     int    // Number of items skipped
	Total      int    // Total number of items available (when available)
	HasMore    bool   // Whether there are more items available
	NextOffset int    // Offset for the next page
	NextCursor string // Cursor for the next page (cursor-based pagination)
	PrevCursor string // Cursor for the previous page (cursor-based pagination)
}

PaginationInfo contains pagination metadata from the response

type PaginationIterator added in v1.1.0

type PaginationIterator[T any] struct {
	// contains filtered or unexported fields
}

PaginationIterator provides an iterator interface for paginated results

func NewPaginationIterator added in v1.1.0

func NewPaginationIterator[T any](
	client *Client,
	fetcher func(ctx context.Context, options *PaginationOptions) (T, error),
	options *PaginationOptions,
) *PaginationIterator[T]

NewPaginationIterator creates a new pagination iterator

func (*PaginationIterator[T]) GetCurrentOffset added in v1.1.0

func (p *PaginationIterator[T]) GetCurrentOffset() int

GetCurrentOffset returns the current offset

func (*PaginationIterator[T]) GetPageSize added in v1.1.0

func (p *PaginationIterator[T]) GetPageSize() int

GetPageSize returns the current page size

func (*PaginationIterator[T]) HasNext added in v1.1.0

func (p *PaginationIterator[T]) HasNext() bool

HasNext returns true if there are more pages available

func (*PaginationIterator[T]) Next added in v1.1.0

func (p *PaginationIterator[T]) Next(ctx context.Context) (T, error)

Next fetches the next page of results

func (*PaginationIterator[T]) Reset added in v1.1.0

func (p *PaginationIterator[T]) Reset()

Reset resets the iterator to the beginning

func (*PaginationIterator[T]) SetPageSize added in v1.1.0

func (p *PaginationIterator[T]) SetPageSize(size int)

SetPageSize sets the page size for future requests

type PaginationOptions added in v1.1.0

type PaginationOptions struct {
	Limit  int    // Maximum number of items to return (default: 20, max: 10000)
	Offset int    // Number of items to skip from the beginning (default: 0)
	Cursor string // Cursor for cursor-based pagination (optional)
}

PaginationOptions contains options for paginated requests

func ValidatePaginationOptions added in v1.1.0

func ValidatePaginationOptions(options *PaginationOptions) *PaginationOptions

ValidatePaginationOptions validates and normalizes pagination options

type ProgressCallback added in v1.1.0

type ProgressCallback func(progress UploadProgress)

ProgressCallback is called during upload to report progress

type PublicResource

type PublicResource struct {
	Resource
	Owner      *UserPublicInformation `json:"owner,omitempty"`
	ViewsCount int                    `json:"views_count,omitempty"`
}

type PublicResourcesList

type PublicResourcesList struct {
	Items  []*Resource `json:"items"`  // (Array[Resource]): <Элементы списка>,
	Type   string      `json:"type"`   // (string, optional): <Значение фильтра по типу ресурсов>,
	Limit  int         `json:"limit"`  // (integer, optional): <Количество элементов на странице>,
	Offset int         `json:"offset"` // (integer, optional): <Смещение от начала списка>
}

type Resource

type Resource struct {
	AntivirusStatus  string        `json:"antivirus_status,omitempty"`  // (object, optional): <Статус проверки антивирусом>,
	ResourceID       string        `json:"resource_id,omitempty"`       // (string, optional): <Идентификатор ресурса>,
	Share            *ShareInfo    `json:"share,omitempty"`             // (ShareInfo, optional),
	File             string        `json:"file,omitempty"`              // (string, optional): <URL для скачивания файла>,
	Size             int           `json:"size,omitempty"`              // (integer, optional): <Размер файла>,
	PhotosliceTime   string        `json:"photoslice_time,omitempty"`   // (string, optional): <Дата создания фото или видео файла>,
	Embedded         *ResourceList `json:"_embedded,omitempty"`         // (ResourceList, optional),
	Exif             *Exif         `json:"exif,omitempty"`              // (Exif, optional),
	CustomProperties interface{}   `json:"custom_properties,omitempty"` // (object, optional): <Пользовательские атрибуты ресурса>,
	MediaType        string        `json:"media_type,omitempty"`        // (string, optional): <Определённый Диском тип файла>,
	Preview          string        `json:"preview,omitempty"`           // (string, optional): <URL превью файла>,
	Type             string        `json:"type"`                        // (string): <Тип>,
	MimeType         string        `json:"mime_type,omitempty"`         // (string, optional): <MIME-тип файла>,
	Revision         int           `json:"revision,omitempty"`          // (integer, optional): <Ревизия Диска в которой этот ресурс был изменён последний раз>,
	PublicURL        string        `json:"public_url,omitempty"`        // (string, optional): <Публичный URL>,
	Path             string        `json:"path"`                        // (string): <Путь к ресурсу>,
	Md5              string        `json:"md5,omitempty"`               // (string, optional): <MD5-хэш>,
	PublicKey        string        `json:"public_key,omitempty"`        // (string, optional): <Ключ опубликованного ресурса>,
	Sha256           string        `json:"sha256,omitempty"`            // (string, optional): <SHA256-хэш>,
	Name             string        `json:"name"`                        // (string): <Имя>,
	Created          string        `json:"created"`                     // (string): <Дата создания>,
	Modified         string        `json:"modified"`                    // (string): <Дата изменения>,
	CommentIDs       *CommentIds   `json:"comment_ids,omitempty"`       // (CommentIds, optional)
}

type ResourceList

type ResourceList struct {
	Sort   string      `json:"sort,omitempty"`   //  (string, optional): <Поле, по которому отсортирован список>,
	Items  []*Resource `json:"items"`            //  (Array[Resource]): <Элементы списка>,
	Limit  int         `json:"limit,omitempty"`  //  (integer, optional): <Количество элементов на странице>,
	Offset int         `json:"offset,omitempty"` //  (integer, optional): <Смещение от начала списка>,
	Path   string      `json:"path"`             //  (string): <Путь к ресурсу, для которого построен список>,
	Total  int         `json:"total,omitempty"`  //  (integer, optional): <Общее количество элементов в списке>}
}
type ResourceUploadLink struct {
	OperationID string `json:"operation_id"`        // (string): <Идентификатор операции загрузки файла>,
	Href        string `json:"href"`                // (string): <URL>,
	Method      string `json:"method"`              // (string): <HTTP-метод>,
	Templated   bool   `json:"templated,omitempty"` // (boolean, optional): <Признак шаблонизированного URL>
}

type ShareInfo

type ShareInfo struct {
	IsRoot  bool   `json:"is_root,omitempty"`
	IsOwned bool   `json:"is_owned,omitempty"`
	Rights  string `json:"rights"`
}

type SystemFolders

type SystemFolders struct {
	Odnoklassniki string `json:"odnoklassniki,omitempty"`
	Google        string `json:"google,omitempty"`
	Instagram     string `json:"instagram,omitempty"`
	Vkontakte     string `json:"vkontakte,omitempty"`
	Mailru        string `json:"mailru,omitempty"`
	Downloads     string `json:"downloads,omitempty"`
	Applications  string `json:"applications,omitempty"`
	Facebook      string `json:"facebook,omitempty"`
	Social        string `json:"social,omitempty"`
	Screenshots   string `json:"screenshots,omitempty"`
	Photostream   string `json:"photostream,omitempty"`
}

type TrashResource

type TrashResource struct {
	Resource
	OriginPath string `json:"origin_path,omitempty"` // Original path before deletion
	Deleted    string `json:"deleted,omitempty"`     // Deletion timestamp
}

TrashResource represents a resource in the trash

type TrashResourceList added in v1.1.0

type TrashResourceList struct {
	Items  []*TrashResource `json:"items"`            // List of trash resources
	Limit  int              `json:"limit,omitempty"`  // Number of items per page
	Offset int              `json:"offset,omitempty"` // Offset from the beginning of the list
	Path   string           `json:"path"`             // Path in trash
}

TrashResourceList represents a list of resources in trash

type UploadOptions added in v1.1.0

type UploadOptions struct {
	Overwrite        bool             // Whether to overwrite existing files
	Progress         ProgressCallback // Optional progress callback
	ChunkSize        int64            // Size of chunks for multipart upload (0 = no chunking)
	ValidateChecksum bool             // Whether to validate file checksum after upload
}

UploadOptions contains options for file upload operations

type UploadProgress added in v1.1.0

type UploadProgress struct {
	BytesUploaded int64
	TotalBytes    int64
	Percentage    float64
}

UploadProgress represents the progress of an upload operation

type User

type User struct {
	Country     string `json:"country,omitempty"`      // string, optional: <Страна>,
	Login       string `json:"login,omitempty"`        // string, optional: <Логин>,
	DisplayName string `json:"display_name,omitempty"` // string, optional: <Отображаемое имя>,
	Uid         string `json:"uid,omitempty"`          // string, optional: <Идентификатор пользователя>
}

type UserPublicInformation

type UserPublicInformation struct {
	Login       string `json:"login,omitempty"`        // (string, optional): <Логин.>,
	DisplayName string `json:"display_name,omitempty"` // (string, optional): <Отображаемое имя пользователя.>,
	Uid         string `json:"uid,omitempty"`          // (string, optional): <Идентификатор пользователя.>
}

Directories

Path Synopsis
examples
demo command
pagination command
upload command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL