pikpak

package module
v0.0.0-...-99b56ba Latest Latest
Warning

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

Go to latest
Published: Jan 13, 2026 License: AGPL-3.0 Imports: 18 Imported by: 0

README

PikPak-Go

A complete Go SDK for the PikPak cloud storage API.

PikPak is a cloud storage service that supports file storage, offline downloads (including magnet links and torrents), and media streaming.

Features

  • 🔐 Authentication - Login with email/password or refresh tokens
  • 📁 File Operations - List, download, rename, move, copy, delete files
  • 📂 Folder Operations - Create, list, navigate folders
  • 🔗 Offline Downloads - Add magnet links, torrent URLs, direct URLs
  • ⬆️ Uploads - Upload files with progress tracking and resumable uploads
  • 🔍 Search - Search files by name
  • 🗑️ Trash - Manage trash (list, restore, empty)
  • Favorites - Star/unstar files
  • 🔗 Sharing - Create and manage share links
  • 💾 Account - Get quota, storage usage, VIP info

Installation

go get github.com/akshardp/pikpak-go

Quick Start

package main

import (
    "fmt"
    "log"
    
    "github.com/akshardp/pikpak-go"
)

func main() {
    // Create a new client
    client := pikpak.NewClient(
        pikpak.WithCredentials("[email protected]", "your-password"),
        pikpak.WithPlatform(pikpak.PlatformWeb),
    )

    // Initialize and authenticate
    if err := client.Init(); err != nil {
        log.Fatal(err)
    }

    fmt.Println("Successfully authenticated!")

    // List files in root directory
    files, err := client.GetRootFiles()
    if err != nil {
        log.Fatal(err)
    }

    for _, f := range files.Files {
        fmt.Printf("%s: %s\n", f.Name, f.ID)
    }
}

Usage Examples

Authentication Options
// Option 1: Username and password
client := pikpak.NewClient(
    pikpak.WithCredentials("[email protected]", "password"),
)

// Option 2: Refresh token (for persistent sessions)
client := pikpak.NewClient(
    pikpak.WithRefreshToken("your-saved-refresh-token"),
)

// Option 3: With token refresh callback
client := pikpak.NewClient(
    pikpak.WithCredentials("[email protected]", "password"),
    pikpak.WithTokenRefreshCallback(func(accessToken, refreshToken string) {
        // Save tokens for later use
    }),
)

// Initialize the client
if err := client.Init(); err != nil {
    log.Fatal(err)
}
File Operations
// List files in a folder
files, err := client.ListFiles("folder-id", nil)

// List all files (handles pagination)
allFiles, err := client.ListAllFiles("folder-id")

// Get file details
file, err := client.GetFile("file-id")

// Get download URL
downloadURL, err := client.GetDownloadURL("file-id")

// Get media streaming URL
mediaURL, err := client.GetMediaURL("file-id")

// Rename file
err := client.Rename("file-id", "new-name.txt")

// Move file
err := client.MoveFile("file-id", "destination-folder-id")

// Copy file
err := client.CopyFile("file-id", "destination-folder-id")

// Move to trash
err := client.TrashFile("file-id")

// Permanently delete
err := client.DeleteFile("file-id")

// Search files
results, err := client.Search("query", "", 100)
Folder Operations
// Create a folder
folder, err := client.CreateFolder("parent-id", "New Folder")

// Create nested folder path
folderID, err := client.CreateFolderPath("path/to/folder", "")

// Get folder by path
folder, err := client.GetFolderByPath("path/to/folder")

// Get folder contents
files, err := client.GetFolderContents("folder-id")
Offline Downloads
// Add a magnet link
task, err := client.OfflineDownloadMagnet("magnet:?xt=urn:btih:...", "parent-id")

// Add a direct URL
task, err := client.OfflineDownload("https://example.com/file.zip", "", "filename.zip")

// List offline tasks
tasks, err := client.ListAllOfflineTasks(nil)

// Get running tasks only
runningTasks, err := client.GetRunningTasks()

// Delete a task
err := client.DeleteOfflineTask("task-id", false) // false = keep downloaded files
Uploading Files
import "context"

// Upload a file
file, err := os.Open("myfile.txt")
stat, _ := file.Stat()

uploadedFile, err := client.UploadFile(
    context.Background(),
    "",           // parent folder ID
    stat.Name(),  // filename
    file,         // reader
    stat.Size(),  // file size
    func(uploaded, total int64) {
        fmt.Printf("Progress: %d%%\n", uploaded*100/total)
    },
)

// Rapid upload (instant upload if file exists on server)
file, err := client.RapidUpload("parent-id", "filename.txt", "gcid-hash", fileSize)
Account Information
// Get storage usage
usage, err := client.GetStorageUsage()
fmt.Printf("Used: %s / %s\n", 
    pikpak.FormatBytes(usage.Used),
    pikpak.FormatBytes(usage.Total),
)

// Get quota
used, total, err := client.GetQuota()

// Get VIP info
vip, err := client.GetVIPInfo()
Sharing
// Create a share link
share, err := client.ShareFile("file-id")
fmt.Println(share.ShareURL)

// Create share with password
share, err := client.ShareFileWithPassword("file-id", "password123")

// Create share with expiration
share, err := client.ShareFileWithExpiration("file-id", 7) // 7 days

// Save shared file to your drive
err := client.SaveSharedFile("share-id", "file-id", "parent-id", "")
Trash Management
// List trash
files, err := client.ListTrash("", 100)

// Restore from trash
err := client.UntrashFile("file-id")

// Empty trash
err := client.EmptyTrash()

Platform Options

The SDK supports three platforms:

pikpak.PlatformWeb     // Web client (default)
pikpak.PlatformAndroid // Android client
pikpak.PlatformPC      // Desktop PC client

Client Options

client := pikpak.NewClient(
    // Authentication
    pikpak.WithCredentials("email", "password"),
    pikpak.WithRefreshToken("refresh-token"),
    pikpak.WithAccessToken("access-token"),
    
    // Platform
    pikpak.WithPlatform(pikpak.PlatformWeb),
    
    // Custom settings
    pikpak.WithDeviceID("custom-device-id"),
    pikpak.WithUserAgent("custom-user-agent"),
    pikpak.WithTimeout(60 * time.Second),
    pikpak.WithProxy("http://proxy:8080"),
    
    // Callbacks
    pikpak.WithTokenRefreshCallback(func(access, refresh string) {
        // Handle token refresh
    }),
)

Error Handling

err := client.TrashFile("file-id")
if err != nil {
    if pikpak.IsAuthError(err) {
        // Handle authentication error
    } else if pikpak.IsRateLimitError(err) {
        // Handle rate limit
    } else if pikpak.IsNotFoundError(err) {
        // Handle not found
    }
}

API Coverage

Category Feature Status
Auth Login with credentials
Auth Refresh token
Auth Captcha handling
Files List files
Files Get file details
Files Download URL
Files Media streaming URL
Files Rename
Files Move
Files Copy
Files Delete
Files Trash
Files Untrash
Files Star/Unstar
Files Search
Folders Create
Folders Create path
Folders Find by path
Offline Add download
Offline List tasks
Offline Delete tasks
Offline Retry tasks
Upload Simple upload
Upload Resumable upload
Upload Rapid upload
Account Quota info
Account VIP info
Sharing Create share
Sharing Get share
Sharing Save shared file

Disclaimer

This is an unofficial SDK and is not affiliated with PikPak. Use at your own risk and comply with PikPak's terms of service.

Credits

This SDK is based on the PikPak driver implementation from OpenList.

Documentation

Overview

Package pikpak provides a complete Go SDK for the PikPak cloud storage API.

PikPak is a cloud storage service that supports file storage, offline downloads (including magnet links and torrents), and media streaming.

Basic Usage

Create a new client and authenticate:

client := pikpak.NewClient(
	pikpak.WithCredentials("[email protected]", "your-password"),
	pikpak.WithPlatform(pikpak.PlatformWeb),
)

if err := client.Init(); err != nil {
	log.Fatal(err)
}

File Operations

List files in root directory:

files, err := client.GetRootFiles()
if err != nil {
	log.Fatal(err)
}

for _, f := range files.Files {
	fmt.Printf("%s: %s\n", f.Name, f.ID)
}

Offline Downloads

Add a magnet link for offline download:

task, err := client.OfflineDownload(
	"magnet:?xt=urn:btih:...",
	"", // parent folder ID (empty for root)
	"", // filename (auto-detected for magnets)
)
if err != nil {
	log.Fatal(err)
}
fmt.Printf("Download started: %s\n", task.ID)

Uploading Files

Upload a file:

file, err := os.Open("myfile.txt")
if err != nil {
	log.Fatal(err)
}
defer file.Close()

stat, _ := file.Stat()
uploadedFile, err := client.UploadFile(
	context.Background(),
	"", // parent folder ID
	stat.Name(),
	file,
	stat.Size(),
	func(uploaded, total int64) {
		fmt.Printf("Progress: %d/%d\n", uploaded, total)
	},
)

Token Persistence

Save and restore tokens for persistent sessions:

// Save tokens after login
client := pikpak.NewClient(
	pikpak.WithCredentials(email, password),
	pikpak.WithTokenRefreshCallback(func(access, refresh string) {
		// Save to database or file
		saveTokens(access, refresh)
	}),
)

// Restore tokens on next run
client := pikpak.NewClient(
	pikpak.WithRefreshToken(savedRefreshToken),
	pikpak.WithAccessToken(savedAccessToken),
)
client.Init()

Package pikpak provides a Go SDK for the PikPak cloud storage API.

Index

Constants

View Source
const (
	AndroidClientID      = "YNxT9w7GMdWvEOKa"
	AndroidClientSecret  = "dbw2OtmVEeuUvIptb1Coyg"
	AndroidClientVersion = "1.53.2"
	AndroidPackageName   = "com.pikcloud.pikpak"
	AndroidSdkVersion    = "2.0.6.206003"
)

Android client constants

View Source
const (
	WebClientID      = "YUMx5nI8ZU8Ap8pm"
	WebClientSecret  = "dbw2OtmVEeuUvIptb1Coyg"
	WebClientVersion = "2.0.0"
	WebPackageName   = "mypikpak.com"
	WebSdkVersion    = "8.0.3"
)

Web client constants

View Source
const (
	PCClientID      = "YvtoWO6GNHiuCl7x"
	PCClientSecret  = "1NIH5R1IEe2pAxZE3hv3uA"
	PCClientVersion = "undefined"
	PCPackageName   = "mypikpak.com"
	PCSdkVersion    = "8.0.3"
)

PC client constants

View Source
const (
	APIBaseURL  = "https://api-drive.mypikpak.net"
	UserBaseURL = "https://user.mypikpak.net"
)

API base URLs

View Source
const (
	EndpointFiles          = "/drive/v1/files"
	EndpointAbout          = "/drive/v1/about"
	EndpointTasks          = "/drive/v1/tasks"
	EndpointAuth           = "/v1/auth"
	EndpointCaptcha        = "/v1/shield/captcha/init"
	EndpointShare          = "/drive/v1/share"
	EndpointShareDetail    = "/drive/v1/share/detail"
	EndpointFileBatchTrash = "/drive/v1/files:batchTrash"
	EndpointFileBatchMove  = "/drive/v1/files:batchMove"
	EndpointFileBatchCopy  = "/drive/v1/files:batchCopy"
)

API endpoints

View Source
const (
	OSSUserAgent               = "aliyun-sdk-android/2.9.13(Linux/Android 14/M2004j7ac;UKQ1.231108.001)"
	OSSSecurityTokenHeaderName = "X-OSS-Security-Token"
)

OSS constants

View Source
const (
	DefaultWebUserAgent = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36"
	DefaultPCUserAgent  = "" /* 158-byte string literal not displayed */
)

Default user agents

View Source
const (
	ErrorCodeAccessTokenExpired  = 4122
	ErrorCodeAccessTokenInvalid  = 4121
	ErrorCodeUnauthorized        = 16
	ErrorCodeCaptchaTokenExpired = 9
	ErrorCodeTooManyRequests     = 10
	ErrorCodeRefreshTokenInvalid = 4126
)

Error codes

View Source
const (
	KindFile   = "drive#file"
	KindFolder = "drive#folder"
)

File kinds

View Source
const (
	UploadTypeResumable = "UPLOAD_TYPE_RESUMABLE"
	UploadTypeURL       = "UPLOAD_TYPE_URL"
)

Upload types

View Source
const (
	ThumbnailSizeLarge  = "SIZE_LARGE"
	ThumbnailSizeMedium = "SIZE_MEDIUM"
	ThumbnailSizeSmall  = "SIZE_SMALL"
)

Thumbnail sizes

View Source
const (
	PhaseTypeRunning  = "PHASE_TYPE_RUNNING"
	PhaseTypeError    = "PHASE_TYPE_ERROR"
	PhaseTypeComplete = "PHASE_TYPE_COMPLETE"
	PhaseTypePending  = "PHASE_TYPE_PENDING"
)

OfflinePhase constants for offline task phases.

View Source
const (
	CaptchaRedirectURI = "xlaccsdk01://xbase.cloud/callback?state=harbor"
)

Captcha redirect URI

Variables

View Source
var (
	ErrNotAuthenticated    = errors.New("client is not authenticated")
	ErrInvalidCredentials  = errors.New("invalid username or password")
	ErrTokenExpired        = errors.New("access token has expired")
	ErrRefreshTokenInvalid = errors.New("refresh token is invalid")
	ErrCaptchaRequired     = errors.New("captcha verification required")
	ErrRateLimited         = errors.New("rate limited, please try again later")
	ErrFileNotFound        = errors.New("file not found")
	ErrFolderNotFound      = errors.New("folder not found")
	ErrTaskNotFound        = errors.New("task not found")
	ErrUploadFailed        = errors.New("upload failed")
	ErrDownloadFailed      = errors.New("download failed")
	ErrInvalidPath         = errors.New("invalid path")
	ErrInvalidFileID       = errors.New("invalid file ID")
	ErrOperationNotAllowed = errors.New("operation not allowed")
	ErrQuotaExceeded       = errors.New("storage quota exceeded")
	ErrFileTooLarge        = errors.New("file too large")
	ErrInvalidHash         = errors.New("invalid file hash")
	ErrNetworkError        = errors.New("network error")
	ErrServerError         = errors.New("server error")
)

Common errors

View Source
var AndroidAlgorithms = []string{
	"SOP04dGzk0TNO7t7t9ekDbAmx+eq0OI1ovEx",
	"nVBjhYiND4hZ2NCGyV5beamIr7k6ifAsAbl",
	"Ddjpt5B/Cit6ED2a6cXgxY9lkEIOw4yC1GDF28KrA",
	"VVCogcmSNIVvgV6U+AochorydiSymi68YVNGiz",
	"u5uj5sM62gpJOsB/1Gu/zsfgfZO",
	"dXYIiBOAHZgzSruaQ2Nhrqc2im",
	"z5jUTBSIpBN9g4qSJGlidNAutX6",
	"KJE2oveZ34du/g1tiimm",
}

AndroidAlgorithms contains the algorithms for Android client signature

View Source
var PCAlgorithms = []string{
	"KHBJ07an7ROXDoK7Db",
	"G6n399rSWkl7WcQmw5rpQInurc1DkLmLqE",
	"JZD1A3M4x+jBFN62hkr7VDhkkZxb9g3rWqRZqFAAb",
	"fQnw/AmSlbbI91Ik15gpddGgyU7U",
	"/Dv9JdPYSj3sHiWjouR95NTQff",
	"yGx2zuTjbWENZqecNI+edrQgqmZKP",
	"ljrbSzdHLwbqcRn",
	"lSHAsqCkGDGxQqqwrVu",
	"TsWXI81fD1",
	"vk7hBjawK/rOSrSWajtbMk95nfgf3",
}

PCAlgorithms contains the algorithms for PC client signature

View Source
var WebAlgorithms = []string{
	"C9qPpZLN8uRTaTiUMWYS9cQvWOE",
	"+r6CQVxjzJV6LCV",
	"F",
	"pFJRC",
	"9WXYIDGrwTCz2OiVlgZa9qpECPD6olt",
	"/750aCr4lm/Sly/c",
	"RB+DT/gZCrbV",
	"",
	"CyLsf7hdkIRxRm215hl",
	"7xHvLi2tOYP0Y92b",
	"ZGTXXxu8E/MIWaEDB+Sm/",
	"1UI3",
	"E7fP5Pfijd+7K+t6Tg/NhuLq0eEUVChpJSkrKxpO",
	"ihtqpG6FMt65+Xk+tWUH2",
	"NhXXU9rg4XXdzo7u5o",
}

WebAlgorithms contains the algorithms for Web client signature

Functions

func BuildAndroidUserAgent

func BuildAndroidUserAgent(deviceID, clientID, appName, sdkVersion, clientVersion, packageName, userID string) string

BuildAndroidUserAgent builds the user agent string for Android client.

func CalculateGCID

func CalculateGCID(reader io.Reader, size int64) (string, error)

CalculateGCID calculates the GCID hash for a file. GCID is a custom hash used by PikPak for file deduplication.

func FormatBytes

func FormatBytes(bytes int64) string

FormatBytes formats bytes into human readable string.

func GenerateDeviceID

func GenerateDeviceID(username, password string) string

GenerateDeviceID generates a device ID from username and password.

func GenerateDeviceSign

func GenerateDeviceSign(deviceID, packageName string) string

GenerateDeviceSign generates a device signature for the API.

func GetAction

func GetAction(method, url string) string

GetAction extracts the action from a URL for captcha purposes.

func GetCaptchaSign

func GetCaptchaSign(clientID, clientVersion, packageName, deviceID string, algorithms []string) (timestamp, sign string)

GetCaptchaSign generates a captcha signature.

func GetMD5

func GetMD5(s string) string

GetMD5 returns the MD5 hash of the input string.

func GetSHA1

func GetSHA1(s string) string

GetSHA1 returns the SHA1 hash of the input string.

func IsAuthError

func IsAuthError(err error) bool

IsAuthError returns true if the error is an authentication error.

func IsCaptchaError

func IsCaptchaError(err error) bool

IsCaptchaError returns true if the error is a captcha verification error.

func IsNotFoundError

func IsNotFoundError(err error) bool

IsNotFoundError returns true if the error is a not found error.

func IsRateLimitError

func IsRateLimitError(err error) bool

IsRateLimitError returns true if the error is a rate limit error.

func IsValidEmail

func IsValidEmail(s string) bool

IsValidEmail checks if the string is a valid email format.

func IsValidPhoneNumber

func IsValidPhoneNumber(s string) bool

IsValidPhoneNumber checks if the string looks like a phone number.

func ParseTime

func ParseTime(s string) (time.Time, error)

ParseTime parses a time string in RFC3339 format.

Types

type AboutResponse

type AboutResponse struct {
	Quota struct {
		Limit         string `json:"limit"`
		Usage         string `json:"usage"`
		UsageInTrash  string `json:"usage_in_trash"`
		IsUnlimited   bool   `json:"is_unlimited"`
		Complimentary string `json:"complimentary"`
	} `json:"quota"`
	ExpiresAt string `json:"expires_at"`
	UserType  int    `json:"user_type"`
}

AboutResponse represents account quota information.

func (*AboutResponse) GetQuotaLimit

func (a *AboutResponse) GetQuotaLimit() int64

GetQuotaLimit returns the quota limit as int64 bytes.

func (*AboutResponse) GetQuotaUsage

func (a *AboutResponse) GetQuotaUsage() int64

GetQuotaUsage returns the quota usage as int64 bytes.

func (*AboutResponse) GetQuotaUsageInTrash

func (a *AboutResponse) GetQuotaUsageInTrash() int64

GetQuotaUsageInTrash returns the trash usage as int64 bytes.

type BatchResponse

type BatchResponse struct {
	TaskID string `json:"task_id"`
}

BatchResponse represents a batch operation response.

type CaptchaTokenRequest

type CaptchaTokenRequest struct {
	Action       string            `json:"action"`
	CaptchaToken string            `json:"captcha_token"`
	ClientID     string            `json:"client_id"`
	DeviceID     string            `json:"device_id"`
	Meta         map[string]string `json:"meta"`
	RedirectURI  string            `json:"redirect_uri"`
}

CaptchaTokenRequest represents a captcha token request.

type CaptchaTokenResponse

type CaptchaTokenResponse struct {
	CaptchaToken string `json:"captcha_token"`
	ExpiresIn    int64  `json:"expires_in"`
	URL          string `json:"url"`
}

CaptchaTokenResponse represents a captcha token response.

type Client

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

func MustNewClient

func MustNewClient(opts ...ClientOption) *Client

MustNewClient creates a new PikPak client and panics on error.

func NewClient

func NewClient(opts ...ClientOption) (*Client, error)

NewClient creates a new PikPak client with the given options. Returns an error if credentials are provided but invalid (empty username or password).

func (*Client) CancelOfflineTask

func (c *Client) CancelOfflineTask(taskID string) error

CancelOfflineTask cancels an offline download task (same as delete without deleting files).

func (*Client) Copy

func (c *Client) Copy(fileIDs []string, destParentID string) error

Copy copies files to a new parent folder.

func (*Client) CopyFile

func (c *Client) CopyFile(fileID, destParentID string) error

CopyFile copies a single file to a new parent folder.

func (*Client) CopyFolder

func (c *Client) CopyFolder(folderID, destParentID string) error

CopyFolder copies a folder to a new parent.

func (*Client) CreateFolder

func (c *Client) CreateFolder(parentID, name string) (*File, error)

CreateFolder creates a new folder.

func (*Client) CreateFolderPath

func (c *Client) CreateFolderPath(path string, parentID string) (string, error)

CreateFolderPath creates folders recursively based on path. Returns the ID of the final folder.

func (*Client) CreateShare

func (c *Client) CreateShare(fileIDs []string, password string, expirationDays int) (*ShareInfo, error)

CreateShare creates a share link for files.

func (*Client) CreateUploadTask

func (c *Client) CreateUploadTask(parentID, name, gcidHash string, size int64) (*UploadTaskData, error)

CreateUploadTask creates an upload task (for resumable upload).

func (*Client) Delete

func (c *Client) Delete(fileIDs []string) error

Delete permanently deletes files.

func (*Client) DeleteFile

func (c *Client) DeleteFile(fileID string) error

DeleteFile permanently deletes a single file.

func (*Client) DeleteFolder

func (c *Client) DeleteFolder(folderID string) error

DeleteFolder permanently deletes a folder.

func (*Client) DeleteOfflineTask

func (c *Client) DeleteOfflineTask(taskID string, deleteFiles bool) error

DeleteOfflineTask deletes a single offline download task.

func (*Client) DeleteOfflineTasks

func (c *Client) DeleteOfflineTasks(taskIDs []string, deleteFiles bool) error

DeleteOfflineTasks deletes offline download tasks.

func (*Client) DeleteShare

func (c *Client) DeleteShare(shareID string) error

DeleteShare deletes a share link.

func (*Client) EmptyTrash

func (c *Client) EmptyTrash() error

EmptyTrash empties the trash.

func (*Client) GetAbout

func (c *Client) GetAbout() (*AboutResponse, error)

GetAbout gets account quota and usage information.

func (*Client) GetAccessToken

func (c *Client) GetAccessToken() string

GetAccessToken returns the current access token.

func (*Client) GetAllRootFiles

func (c *Client) GetAllRootFiles() ([]File, error)

GetAllRootFiles lists all files in the root directory, handling pagination.

func (*Client) GetCompletedTasks

func (c *Client) GetCompletedTasks() ([]OfflineTask, error)

GetCompletedTasks gets all completed offline tasks.

func (*Client) GetDownloadURL

func (c *Client) GetDownloadURL(fileID string) (string, error)

GetDownloadURL gets the download URL for a file.

func (*Client) GetFailedTasks

func (c *Client) GetFailedTasks() ([]OfflineTask, error)

GetFailedTasks gets all failed offline tasks.

func (*Client) GetFile

func (c *Client) GetFile(fileID string) (*File, error)

GetFile gets a single file by ID.

func (c *Client) GetFileWithMediaLink(fileID string) (*File, error)

GetFileWithMediaLink gets a file with its media streaming link.

func (*Client) GetFolderByPath

func (c *Client) GetFolderByPath(path string) (*File, error)

GetFolderByPath finds a folder by its path from root.

func (*Client) GetFolderContents

func (c *Client) GetFolderContents(folderID string) ([]File, error)

GetFolderContents gets all contents of a folder by ID.

func (*Client) GetInvites

func (c *Client) GetInvites() ([]Invite, error)

GetInvites gets invite codes (placeholder).

func (*Client) GetMediaURL

func (c *Client) GetMediaURL(fileID string) (string, error)

GetMediaURL gets the media streaming URL for a file.

func (*Client) GetOfflineTask

func (c *Client) GetOfflineTask(taskID string) (*OfflineTask, error)

GetOfflineTask gets a specific offline task by ID.

func (*Client) GetPendingTasks

func (c *Client) GetPendingTasks() ([]OfflineTask, error)

GetPendingTasks gets all pending offline tasks.

func (*Client) GetQuota

func (c *Client) GetQuota() (used, total int64, err error)

GetQuota returns the storage quota information.

func (*Client) GetRefreshToken

func (c *Client) GetRefreshToken() string

GetRefreshToken returns the current refresh token.

func (*Client) GetRootFiles

func (c *Client) GetRootFiles() (*Files, error)

GetRootFiles lists files in the root directory.

func (*Client) GetRunningTasks

func (c *Client) GetRunningTasks() ([]OfflineTask, error)

GetRunningTasks gets all running offline tasks.

func (*Client) GetShare

func (c *Client) GetShare(shareID string) (*ShareResp, error)

GetShare gets share information.

func (*Client) GetStorageUsage

func (c *Client) GetStorageUsage() (*StorageUsage, error)

GetStorageUsage returns detailed storage usage information.

func (*Client) GetUserID

func (c *Client) GetUserID() string

GetUserID returns the current user ID.

func (*Client) GetUserInfo

func (c *Client) GetUserInfo() (*UserInfo, error)

GetUserInfo gets user information (placeholder - implement based on API).

func (*Client) GetVIPInfo

func (c *Client) GetVIPInfo() (*VIPInfo, error)

GetVIPInfo gets VIP subscription information.

func (*Client) Init

func (c *Client) Init() error

Init initializes the client by refreshing or obtaining tokens.

func (*Client) IsAuthenticated

func (c *Client) IsAuthenticated() bool

IsAuthenticated returns true if the client has authentication tokens.

func (*Client) ListAllFiles

func (c *Client) ListAllFiles(parentID string) ([]File, error)

ListAllFiles lists all files in a directory, handling pagination automatically.

func (*Client) ListAllOfflineTasks

func (c *Client) ListAllOfflineTasks(phases []string) ([]OfflineTask, error)

ListAllOfflineTasks lists all offline download tasks, handling pagination.

func (*Client) ListFiles

func (c *Client) ListFiles(parentID string, opts *ListOptions) (*Files, error)

ListFiles lists files in a directory.

func (*Client) ListOfflineTasks

func (c *Client) ListOfflineTasks(opts *OfflineListOptions) ([]OfflineTask, error)

ListOfflineTasks lists offline download tasks.

func (*Client) ListStarred

func (c *Client) ListStarred(pageToken string, pageSize int) (*Files, error)

ListStarred lists starred files.

func (*Client) ListTrash

func (c *Client) ListTrash(pageToken string, pageSize int) (*Files, error)

ListTrash lists files in trash.

func (*Client) Login

func (c *Client) Login() error

Login authenticates with username and password.

func (*Client) Move

func (c *Client) Move(fileIDs []string, destParentID string) error

Move moves files to a new parent folder.

func (*Client) MoveFile

func (c *Client) MoveFile(fileID, destParentID string) error

MoveFile moves a single file to a new parent folder.

func (*Client) MoveFolder

func (c *Client) MoveFolder(folderID, destParentID string) error

MoveFolder moves a folder to a new parent.

func (*Client) OfflineDownload

func (c *Client) OfflineDownload(url, parentID, fileName string) (*OfflineTask, error)

OfflineDownload adds a URL to be downloaded by PikPak.

func (*Client) OfflineDownloadMagnet

func (c *Client) OfflineDownloadMagnet(magnetLink, parentID string) (*OfflineTask, error)

OfflineDownloadMagnet adds a magnet link to be downloaded.

func (*Client) OfflineDownloadTorrent

func (c *Client) OfflineDownloadTorrent(torrentURL, parentID string) (*OfflineTask, error)

OfflineDownloadTorrent adds a torrent by URL to be downloaded.

func (*Client) RapidUpload

func (c *Client) RapidUpload(parentID, name, gcidHash string, size int64) (*File, error)

RapidUpload attempts to rapid upload (秒传) a file using its GCID hash. If the file already exists on PikPak servers, it will be instantly available.

func (*Client) RefreshToken

func (c *Client) RefreshToken() error

RefreshToken refreshes the access token using the refresh token.

func (*Client) Rename

func (c *Client) Rename(fileID, newName string) error

Rename renames a file or folder.

func (*Client) RenameFolder

func (c *Client) RenameFolder(folderID, newName string) error

RenameFolder renames a folder.

func (*Client) RetryOfflineTask

func (c *Client) RetryOfflineTask(taskID string) error

RetryOfflineTask retries a failed offline download task.

func (*Client) SaveSharedFile

func (c *Client) SaveSharedFile(shareID, fileID, parentID string, passCodeToken string) error

SaveSharedFile saves a shared file to your drive.

func (*Client) Search

func (c *Client) Search(query string, pageToken string, pageSize int) (*Files, error)

Search searches for files by name.

func (*Client) SetUserID

func (c *Client) SetUserID(userID string)

SetUserID sets the user ID.

func (*Client) ShareFile

func (c *Client) ShareFile(fileID string) (*ShareInfo, error)

ShareFile creates a share link for a single file.

func (*Client) ShareFileWithExpiration

func (c *Client) ShareFileWithExpiration(fileID string, expirationDays int) (*ShareInfo, error)

ShareFileWithExpiration creates a share link with expiration.

func (*Client) ShareFileWithPassword

func (c *Client) ShareFileWithPassword(fileID, password string) (*ShareInfo, error)

ShareFileWithPassword creates a password-protected share link.

func (*Client) Star

func (c *Client) Star(fileIDs []string) error

Star stars files.

func (*Client) StarFile

func (c *Client) StarFile(fileID string) error

StarFile stars a single file.

func (*Client) Trash

func (c *Client) Trash(fileIDs []string) error

Trash moves files to trash.

func (*Client) TrashFile

func (c *Client) TrashFile(fileID string) error

TrashFile moves a single file to trash.

func (*Client) TrashFolder

func (c *Client) TrashFolder(folderID string) error

TrashFolder moves a folder to trash.

func (*Client) Unstar

func (c *Client) Unstar(fileIDs []string) error

Unstar unstars files.

func (*Client) UnstarFile

func (c *Client) UnstarFile(fileID string) error

UnstarFile unstars a single file.

func (*Client) Untrash

func (c *Client) Untrash(fileIDs []string) error

Untrash restores files from trash.

func (*Client) UntrashFile

func (c *Client) UntrashFile(fileID string) error

UntrashFile restores a single file from trash.

func (*Client) UploadFile

func (c *Client) UploadFile(ctx context.Context, parentID, name string, reader io.Reader, size int64, progress UploadProgressFunc) (*File, error)

UploadFile uploads a file to PikPak. If the file already exists (based on GCID), it will be instantly uploaded.

func (*Client) UploadFileWithRetry

func (c *Client) UploadFileWithRetry(ctx context.Context, parentID, name string, reader io.ReadSeeker, size int64, progress UploadProgressFunc, maxRetries int) (*File, error)

UploadFileWithRetry uploads a file with automatic retry on failure.

func (*Client) UploadFromURL

func (c *Client) UploadFromURL(url, parentID, fileName string) (*OfflineTask, error)

UploadFromURL uploads a file from a URL (essentially offline download to a specific folder).

func (*Client) WaitForTask

func (c *Client) WaitForTask(taskID string, checkInterval int) (*OfflineTask, error)

WaitForTask waits for an offline task to complete. Returns the completed task or an error if it fails.

type ClientOption

type ClientOption func(*Client)

ClientOption is a function that configures a Client.

func WithAccessToken

func WithAccessToken(accessToken string) ClientOption

WithAccessToken sets an existing access token.

func WithCaptchaToken

func WithCaptchaToken(captchaToken string) ClientOption

func WithCredentials

func WithCredentials(username, password string) ClientOption

WithCredentials sets username and password for authentication.

func WithDeviceID

func WithDeviceID(deviceID string) ClientOption

WithDeviceID sets a custom device ID.

func WithPlatform

func WithPlatform(platform Platform) ClientOption

WithPlatform sets the platform for the client.

func WithProxy

func WithProxy(proxyURL string) ClientOption

WithProxy sets a proxy for HTTP requests.

func WithRefreshToken

func WithRefreshToken(refreshToken string) ClientOption

WithRefreshToken sets an existing refresh token.

func WithTimeout

func WithTimeout(timeout time.Duration) ClientOption

WithTimeout sets the HTTP client timeout.

func WithTokenRefreshCallback

func WithTokenRefreshCallback(callback func(accessToken, refreshToken string)) ClientOption

WithTokenRefreshCallback sets a callback for when tokens are refreshed.

func WithUserAgent

func WithUserAgent(userAgent string) ClientOption

WithUserAgent sets a custom user agent.

type DownloadOptions

type DownloadOptions struct {
	FileID        string
	UseMediaLink  bool
	ThumbnailSize string
}

DownloadOptions represents options for downloading files.

type ErrResp

type ErrResp struct {
	ErrorCode        int64  `json:"error_code"`
	ErrorMsg         string `json:"error"`
	ErrorDescription string `json:"error_description"`
}

ErrResp represents an error response from PikPak API.

func (*ErrResp) Error

func (e *ErrResp) Error() string

Error implements the error interface.

func (*ErrResp) IsError

func (e *ErrResp) IsError() bool

IsError returns true if this is an error response.

type File

type File struct {
	ID             string    `json:"id"`
	Kind           string    `json:"kind"`
	Name           string    `json:"name"`
	CreatedTime    time.Time `json:"created_time"`
	ModifiedTime   time.Time `json:"modified_time"`
	Hash           string    `json:"hash"`
	Size           string    `json:"size"`
	ParentID       string    `json:"parent_id"`
	MimeType       string    `json:"mime_type"`
	ThumbnailLink  string    `json:"thumbnail_link"`
	WebContentLink string    `json:"web_content_link"`
	Medias         []Media   `json:"medias"`
	Trashed        bool      `json:"trashed"`
	Phase          string    `json:"phase"`
}

File represents a file or folder in PikPak.

func (*File) GetSize

func (f *File) GetSize() int64

GetSize returns the file size as int64.

func (*File) IsFolder

func (f *File) IsFolder() bool

IsFolder returns true if this file is a folder.

type Files

type Files struct {
	Files         []File `json:"files"`
	NextPageToken string `json:"next_page_token"`
}

Files represents a paginated list of files.

type Invite

type Invite struct {
	Code      string `json:"code"`
	Used      bool   `json:"used"`
	ExpiresAt string `json:"expires_at"`
}

Invite represents an invite.

type InviteInfo

type InviteInfo struct {
	Code      string `json:"code"`
	ExpiresAt string `json:"expires_at"`
}

InviteInfo represents invite code information.

type ListOptions

type ListOptions struct {
	ParentID      string
	PageToken     string
	PageSize      int
	Filters       map[string]interface{}
	ThumbnailSize string
	WithAudit     bool
}

ListOptions represents options for listing files.

func DefaultListOptions

func DefaultListOptions() *ListOptions

DefaultListOptions returns default list options.

type Media

type Media struct {
	MediaID   string `json:"media_id"`
	MediaName string `json:"media_name"`
	Video     struct {
		Height     int    `json:"height"`
		Width      int    `json:"width"`
		Duration   int    `json:"duration"`
		BitRate    int    `json:"bit_rate"`
		FrameRate  int    `json:"frame_rate"`
		VideoCodec string `json:"video_codec"`
		AudioCodec string `json:"audio_codec"`
		VideoType  string `json:"video_type"`
	} `json:"video"`
	Link struct {
		URL    string    `json:"url"`
		Token  string    `json:"token"`
		Expire time.Time `json:"expire"`
	} `json:"link"`
	NeedMoreQuota  bool          `json:"need_more_quota"`
	VipTypes       []interface{} `json:"vip_types"`
	RedirectLink   string        `json:"redirect_link"`
	IconLink       string        `json:"icon_link"`
	IsDefault      bool          `json:"is_default"`
	Priority       int           `json:"priority"`
	IsOrigin       bool          `json:"is_origin"`
	ResolutionName string        `json:"resolution_name"`
	IsVisible      bool          `json:"is_visible"`
	Category       string        `json:"category"`
}

Media represents media information for a file.

type OfflineDownloadOptions

type OfflineDownloadOptions struct {
	URL      string
	ParentID string
	FileName string
}

OfflineDownloadOptions represents options for offline download.

type OfflineDownloadResp

type OfflineDownloadResp struct {
	File       *string     `json:"file"`
	Task       OfflineTask `json:"task"`
	UploadType string      `json:"upload_type"`
	URL        struct {
		Kind string `json:"kind"`
	} `json:"url"`
}

OfflineDownloadResp represents offline download response.

type OfflineListOptions

type OfflineListOptions struct {
	PageToken string
	PageSize  int
	Phases    []string // e.g., ["PHASE_TYPE_RUNNING", "PHASE_TYPE_COMPLETE"]
}

OfflineListOptions represents options for listing offline tasks.

func DefaultOfflineListOptions

func DefaultOfflineListOptions() *OfflineListOptions

DefaultOfflineListOptions returns default offline list options.

type OfflineListResp

type OfflineListResp struct {
	ExpiresIn     int64         `json:"expires_in"`
	NextPageToken string        `json:"next_page_token"`
	Tasks         []OfflineTask `json:"tasks"`
}

OfflineListResp represents offline download list response.

type OfflineParams

type OfflineParams struct {
	Age         string  `json:"age"`
	MIMEType    *string `json:"mime_type,omitempty"`
	PredictType string  `json:"predict_type"`
	URL         string  `json:"url"`
}

OfflineParams represents offline task parameters.

type OfflineTask

type OfflineTask struct {
	Callback          string            `json:"callback"`
	CreatedTime       string            `json:"created_time"`
	FileID            string            `json:"file_id"`
	FileName          string            `json:"file_name"`
	FileSize          string            `json:"file_size"`
	IconLink          string            `json:"icon_link"`
	ID                string            `json:"id"`
	Kind              string            `json:"kind"`
	Message           string            `json:"message"`
	Name              string            `json:"name"`
	Params            OfflineParams     `json:"params"`
	Phase             string            `json:"phase"` // PHASE_TYPE_RUNNING, PHASE_TYPE_ERROR, PHASE_TYPE_COMPLETE, PHASE_TYPE_PENDING
	Progress          int64             `json:"progress"`
	ReferenceResource ReferenceResource `json:"reference_resource"`
	Space             string            `json:"space"`
	StatusSize        int64             `json:"status_size"`
	Statuses          []string          `json:"statuses"`
	ThirdTaskID       string            `json:"third_task_id"`
	Type              string            `json:"type"`
	UpdatedTime       string            `json:"updated_time"`
	UserID            string            `json:"user_id"`
}

OfflineTask represents an offline download task.

func (*OfflineTask) GetFileSize

func (t *OfflineTask) GetFileSize() int64

GetFileSize returns the file size as int64.

func (*OfflineTask) IsComplete

func (t *OfflineTask) IsComplete() bool

IsComplete returns true if the task is complete.

func (*OfflineTask) IsError

func (t *OfflineTask) IsError() bool

IsError returns true if the task has an error.

func (*OfflineTask) IsPending

func (t *OfflineTask) IsPending() bool

IsPending returns true if the task is pending.

func (*OfflineTask) IsRunning

func (t *OfflineTask) IsRunning() bool

IsRunning returns true if the task is running.

type Platform

type Platform string

Platform constants

const (
	PlatformAndroid Platform = "android"
	PlatformWeb     Platform = "web"
	PlatformPC      Platform = "pc"
)

type ReferenceResource

type ReferenceResource struct {
	Type          string                 `json:"@type"`
	Audit         interface{}            `json:"audit"`
	Hash          string                 `json:"hash"`
	IconLink      string                 `json:"icon_link"`
	ID            string                 `json:"id"`
	Kind          string                 `json:"kind"`
	Medias        []Media                `json:"medias"`
	MIMEType      string                 `json:"mime_type"`
	Name          string                 `json:"name"`
	Params        map[string]interface{} `json:"params"`
	ParentID      string                 `json:"parent_id"`
	Phase         string                 `json:"phase"`
	Size          string                 `json:"size"`
	Space         string                 `json:"space"`
	Starred       bool                   `json:"starred"`
	Tags          []string               `json:"tags"`
	ThumbnailLink string                 `json:"thumbnail_link"`
}

ReferenceResource represents referenced resource in offline task.

type S3Params

type S3Params struct {
	AccessKeyID     string    `json:"access_key_id"`
	AccessKeySecret string    `json:"access_key_secret"`
	Bucket          string    `json:"bucket"`
	Endpoint        string    `json:"endpoint"`
	Expiration      time.Time `json:"expiration"`
	Key             string    `json:"key"`
	SecurityToken   string    `json:"security_token"`
}

S3Params represents S3/OSS upload parameters.

type ShareInfo

type ShareInfo struct {
	ShareID       string `json:"share_id"`
	ShareURL      string `json:"share_url"`
	SharePassword string `json:"share_password"`
	ExpiresAt     string `json:"expires_at"`
}

ShareInfo represents share information.

type ShareResp

type ShareResp struct {
	ShareStatus     string `json:"share_status"`
	ShareStatusText string `json:"share_status_text"`
	FileInfo        File   `json:"file_info"`
	Files           []File `json:"files"`
	NextPageToken   string `json:"next_page_token"`
	PassCodeToken   string `json:"pass_code_token"`
}

ShareResp represents a share response.

type StorageUsage

type StorageUsage struct {
	Total       int64
	Used        int64
	UsedInTrash int64
	Free        int64
	IsUnlimited bool
}

GetStorageUsage returns storage usage statistics.

type TokenResponse

type TokenResponse struct {
	TokenType    string `json:"token_type"`
	AccessToken  string `json:"access_token"`
	RefreshToken string `json:"refresh_token"`
	ExpiresIn    int64  `json:"expires_in"`
	Sub          string `json:"sub"`
	UserID       string `json:"user_id"`
}

TokenResponse represents an authentication token response.

type TrashResponse

type TrashResponse struct {
	TaskID string `json:"task_id"`
}

TrashResponse represents a trash operation response.

type UploadOptions

type UploadOptions struct {
	ParentID string
	Name     string
	Hash     string // GCID hash
	Size     int64
}

UploadOptions represents options for uploading files.

type UploadProgressFunc

type UploadProgressFunc func(uploaded, total int64)

UploadProgressFunc is a callback function for upload progress.

type UploadTaskData

type UploadTaskData struct {
	UploadType string `json:"upload_type"`
	Resumable  *struct {
		Kind     string   `json:"kind"`
		Params   S3Params `json:"params"`
		Provider string   `json:"provider"`
	} `json:"resumable"`
	File File `json:"file"`
}

UploadTaskData represents upload task response.

type UserInfo

type UserInfo struct {
	Sub       string `json:"sub"`
	Name      string `json:"name"`
	Email     string `json:"email"`
	Picture   string `json:"picture"`
	CreatedAt string `json:"created_at"`
}

UserInfo represents user account information.

type VIPInfo

type VIPInfo struct {
	Type      string `json:"type"`
	Status    string `json:"status"`
	ExpiresAt string `json:"expires_at"`
}

VIPInfo represents VIP subscription information.

Directories

Path Synopsis
examples
basic command

Jump to

Keyboard shortcuts

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