github.com/artpar/rclone@v1.67.3/backend/filefabric/api/types.go (about)

     1  // Package api has type definitions for filefabric
     2  //
     3  // Converted from the API responses with help from https://mholt.github.io/json-to-go/
     4  package api
     5  
     6  import (
     7  	"bytes"
     8  	"encoding/json"
     9  	"fmt"
    10  	"reflect"
    11  	"strings"
    12  	"time"
    13  )
    14  
    15  const (
    16  	// TimeFormat for parameters (UTC)
    17  	timeFormatParameters = `2006-01-02 15:04:05`
    18  	// "2020-08-11 10:10:04" for JSON parsing
    19  	timeFormatJSON = `"` + timeFormatParameters + `"`
    20  )
    21  
    22  // Time represents date and time information for the
    23  // filefabric API
    24  type Time time.Time
    25  
    26  // MarshalJSON turns a Time into JSON (in UTC)
    27  func (t *Time) MarshalJSON() (out []byte, err error) {
    28  	timeString := (*time.Time)(t).UTC().Format(timeFormatJSON)
    29  	return []byte(timeString), nil
    30  }
    31  
    32  var zeroTime = []byte(`"0000-00-00 00:00:00"`)
    33  
    34  // UnmarshalJSON turns JSON into a Time (in UTC)
    35  func (t *Time) UnmarshalJSON(data []byte) error {
    36  	// Set a Zero time.Time if we receive a zero time input
    37  	if bytes.Equal(data, zeroTime) {
    38  		*t = Time(time.Time{})
    39  		return nil
    40  	}
    41  	newT, err := time.Parse(timeFormatJSON, string(data))
    42  	if err != nil {
    43  		return err
    44  	}
    45  	*t = Time(newT)
    46  	return nil
    47  }
    48  
    49  // String turns a Time into a string in UTC suitable for the API
    50  // parameters
    51  func (t Time) String() string {
    52  	return time.Time(t).UTC().Format(timeFormatParameters)
    53  }
    54  
    55  // Int represents an integer which can be represented in JSON as a
    56  // quoted integer or an integer.
    57  type Int int
    58  
    59  // MarshalJSON turns a Int into JSON
    60  func (i *Int) MarshalJSON() (out []byte, err error) {
    61  	return json.Marshal((*int)(i))
    62  }
    63  
    64  // UnmarshalJSON turns JSON into a Int
    65  func (i *Int) UnmarshalJSON(data []byte) error {
    66  	if len(data) >= 2 && data[0] == '"' && data[len(data)-1] == '"' {
    67  		data = data[1 : len(data)-1]
    68  	}
    69  	return json.Unmarshal(data, (*int)(i))
    70  }
    71  
    72  // String represents an string which can be represented in JSON as a
    73  // quoted string or an integer.
    74  type String string
    75  
    76  // MarshalJSON turns a String into JSON
    77  func (s *String) MarshalJSON() (out []byte, err error) {
    78  	return json.Marshal((*string)(s))
    79  }
    80  
    81  // UnmarshalJSON turns JSON into a String
    82  func (s *String) UnmarshalJSON(data []byte) error {
    83  	err := json.Unmarshal(data, (*string)(s))
    84  	if err != nil {
    85  		*s = String(data)
    86  	}
    87  	return nil
    88  }
    89  
    90  // Status return returned in all status responses
    91  type Status struct {
    92  	Code    string `json:"status"`
    93  	Message string `json:"statusmessage"`
    94  	TaskID  String `json:"taskid"`
    95  	// Warning string `json:"warning"` // obsolete
    96  }
    97  
    98  // Status satisfies the error interface
    99  func (e *Status) Error() string {
   100  	return fmt.Sprintf("%s (%s)", e.Message, e.Code)
   101  }
   102  
   103  // OK returns true if the status is all good
   104  func (e *Status) OK() bool {
   105  	return e.Code == "ok"
   106  }
   107  
   108  // GetCode returns the status code if any
   109  func (e *Status) GetCode() string {
   110  	return e.Code
   111  }
   112  
   113  // OKError defines an interface for items which can be OK or be an error
   114  type OKError interface {
   115  	error
   116  	OK() bool
   117  	GetCode() string
   118  }
   119  
   120  // Check Status satisfies the OKError interface
   121  var _ OKError = (*Status)(nil)
   122  
   123  // EmptyResponse is response which just returns the error condition
   124  type EmptyResponse struct {
   125  	Status
   126  }
   127  
   128  // GetTokenByAuthTokenResponse is the response to getTokenByAuthToken
   129  type GetTokenByAuthTokenResponse struct {
   130  	Status
   131  	Token              string `json:"token"`
   132  	UserID             string `json:"userid"`
   133  	AllowLoginRemember string `json:"allowloginremember"`
   134  	LastLogin          Time   `json:"lastlogin"`
   135  	AutoLoginCode      string `json:"autologincode"`
   136  }
   137  
   138  // ApplianceInfo is the response to getApplianceInfo
   139  type ApplianceInfo struct {
   140  	Status
   141  	Sitetitle            string `json:"sitetitle"`
   142  	OauthLoginSupport    string `json:"oauthloginsupport"`
   143  	IsAppliance          string `json:"isappliance"`
   144  	SoftwareVersion      string `json:"softwareversion"`
   145  	SoftwareVersionLabel string `json:"softwareversionlabel"`
   146  }
   147  
   148  // GetFolderContentsResponse is returned from getFolderContents
   149  type GetFolderContentsResponse struct {
   150  	Status
   151  	Total  int    `json:"total,string"`
   152  	Items  []Item `json:"filelist"`
   153  	Folder Item   `json:"folder"`
   154  	From   Int    `json:"from"`
   155  	//Count         int    `json:"count"`
   156  	Pid           string `json:"pid"`
   157  	RefreshResult Status `json:"refreshresult"`
   158  	// Curfolder         Item              `json:"curfolder"` - sometimes returned as "ROOT"?
   159  	Parents           []Item            `json:"parents"`
   160  	CustomPermissions CustomPermissions `json:"custompermissions"`
   161  }
   162  
   163  // ItemType determine whether it is a file or a folder
   164  type ItemType uint8
   165  
   166  // Types of things in Item
   167  const (
   168  	ItemTypeFile   ItemType = 0
   169  	ItemTypeFolder ItemType = 1
   170  )
   171  
   172  // Item ia a File or a Folder
   173  type Item struct {
   174  	ID  string `json:"fi_id"`
   175  	PID string `json:"fi_pid"`
   176  	// UID             string   `json:"fi_uid"`
   177  	Name string `json:"fi_name"`
   178  	// S3Name          string   `json:"fi_s3name"`
   179  	// Extension       string   `json:"fi_extension"`
   180  	// Description     string   `json:"fi_description"`
   181  	Type ItemType `json:"fi_type,string"`
   182  	// Created         Time     `json:"fi_created"`
   183  	Size        int64  `json:"fi_size,string"`
   184  	ContentType string `json:"fi_contenttype"`
   185  	// Tags            string   `json:"fi_tags"`
   186  	// MainCode        string   `json:"fi_maincode"`
   187  	// Public          int      `json:"fi_public,string"`
   188  	// Provider        string   `json:"fi_provider"`
   189  	// ProviderFolder  string   `json:"fi_providerfolder"` // folder
   190  	// Encrypted       int      `json:"fi_encrypted,string"`
   191  	// StructType      string   `json:"fi_structtype"`
   192  	// Bname           string   `json:"fi_bname"` // folder
   193  	// OrgID           string   `json:"fi_orgid"`
   194  	// Favorite        int      `json:"fi_favorite,string"`
   195  	// IspartOf        string   `json:"fi_ispartof"` // folder
   196  	Modified Time `json:"fi_modified"`
   197  	// LastAccessed    Time     `json:"fi_lastaccessed"`
   198  	// Hits            int64    `json:"fi_hits,string"`
   199  	// IP              string   `json:"fi_ip"` // folder
   200  	// BigDescription  string   `json:"fi_bigdescription"`
   201  	LocalTime Time `json:"fi_localtime"`
   202  	// OrgfolderID     string   `json:"fi_orgfolderid"`
   203  	// StorageIP       string   `json:"fi_storageip"` // folder
   204  	// RemoteTime      Time     `json:"fi_remotetime"`
   205  	// ProviderOptions string   `json:"fi_provideroptions"`
   206  	// Access          string   `json:"fi_access"`
   207  	// Hidden          string   `json:"fi_hidden"` // folder
   208  	// VersionOf       string   `json:"fi_versionof"`
   209  	Trash bool `json:"trash"`
   210  	// Isbucket        string   `json:"isbucket"` // filelist
   211  	SubFolders int64 `json:"subfolders"` // folder
   212  }
   213  
   214  // ItemFields is a | separated list of fields in Item
   215  var ItemFields = mustFields(Item{})
   216  
   217  // fields returns the JSON fields in use by opt as a | separated
   218  // string.
   219  func fields(opt interface{}) (pipeTags string, err error) {
   220  	var tags []string
   221  	def := reflect.ValueOf(opt)
   222  	defType := def.Type()
   223  	for i := 0; i < def.NumField(); i++ {
   224  		field := defType.Field(i)
   225  		tag, ok := field.Tag.Lookup("json")
   226  		if !ok {
   227  			continue
   228  		}
   229  		if comma := strings.IndexRune(tag, ','); comma >= 0 {
   230  			tag = tag[:comma]
   231  		}
   232  		if tag == "" {
   233  			continue
   234  		}
   235  		tags = append(tags, tag)
   236  	}
   237  	return strings.Join(tags, "|"), nil
   238  }
   239  
   240  // mustFields returns the JSON fields in use by opt as a | separated
   241  // string. It panics on failure.
   242  func mustFields(opt interface{}) string {
   243  	tags, err := fields(opt)
   244  	if err != nil {
   245  		panic(err)
   246  	}
   247  	return tags
   248  }
   249  
   250  // CustomPermissions is returned as part of GetFolderContentsResponse
   251  type CustomPermissions struct {
   252  	Upload            string `json:"upload"`
   253  	CreateSubFolder   string `json:"createsubfolder"`
   254  	Rename            string `json:"rename"`
   255  	Delete            string `json:"delete"`
   256  	Move              string `json:"move"`
   257  	ManagePermissions string `json:"managepermissions"`
   258  	ListOnly          string `json:"listonly"`
   259  	VisibleInTrash    string `json:"visibleintrash"`
   260  }
   261  
   262  // DoCreateNewFolderResponse is response from foCreateNewFolder
   263  type DoCreateNewFolderResponse struct {
   264  	Status
   265  	Item Item `json:"file"`
   266  }
   267  
   268  // DoInitUploadResponse is response from doInitUpload
   269  type DoInitUploadResponse struct {
   270  	Status
   271  	ProviderID          string `json:"providerid"`
   272  	UploadCode          string `json:"uploadcode"`
   273  	FileType            string `json:"filetype"`
   274  	DirectUploadSupport string `json:"directuploadsupport"`
   275  	ResumeAllowed       string `json:"resumeallowed"`
   276  }
   277  
   278  // UploaderResponse is returned from /cgi-bin/uploader/uploader1.cgi
   279  //
   280  // Sometimes the response is returned as XML and sometimes as JSON
   281  type UploaderResponse struct {
   282  	FileSize int64  `xml:"filesize" json:"filesize,string"`
   283  	MD5      string `xml:"md5" json:"md5"`
   284  	Success  string `xml:"success" json:"success"`
   285  }
   286  
   287  // UploadStatus is returned from getUploadStatus
   288  type UploadStatus struct {
   289  	Status
   290  	UploadCode     string `json:"uploadcode"`
   291  	Metafile       string `json:"metafile"`
   292  	Percent        int    `json:"percent,string"`
   293  	Uploaded       int64  `json:"uploaded,string"`
   294  	Size           int64  `json:"size,string"`
   295  	Filename       string `json:"filename"`
   296  	Nofile         string `json:"nofile"`
   297  	Completed      string `json:"completed"`
   298  	Completsuccess string `json:"completsuccess"`
   299  	Completerror   string `json:"completerror"`
   300  }
   301  
   302  // DoCompleteUploadResponse is the response to doCompleteUpload
   303  type DoCompleteUploadResponse struct {
   304  	Status
   305  	UploadedSize int64  `json:"uploadedsize,string"`
   306  	StorageIP    string `json:"storageip"`
   307  	UploadedName string `json:"uploadedname"`
   308  	// Versioned    []interface{} `json:"versioned"`
   309  	// VersionedID  int           `json:"versionedid"`
   310  	// Comment      interface{}           `json:"comment"`
   311  	File Item `json:"file"`
   312  	// UsSize       string        `json:"us_size"`
   313  	// PaSize       string        `json:"pa_size"`
   314  	// SpaceInfo    SpaceInfo     `json:"spaceinfo"`
   315  }
   316  
   317  // Providers is returned as part of UploadResponse
   318  type Providers struct {
   319  	Max     string `json:"max"`
   320  	Used    string `json:"used"`
   321  	ID      string `json:"id"`
   322  	Private string `json:"private"`
   323  	Limit   string `json:"limit"`
   324  	Percent int    `json:"percent"`
   325  }
   326  
   327  // Total is returned as part of UploadResponse
   328  type Total struct {
   329  	Max        string `json:"max"`
   330  	Used       string `json:"used"`
   331  	ID         string `json:"id"`
   332  	Priused    string `json:"priused"`
   333  	Primax     string `json:"primax"`
   334  	Limit      string `json:"limit"`
   335  	Percent    int    `json:"percent"`
   336  	Pripercent int    `json:"pripercent"`
   337  }
   338  
   339  // UploadResponse is returned as part of SpaceInfo
   340  type UploadResponse struct {
   341  	Providers []Providers `json:"providers"`
   342  	Total     Total       `json:"total"`
   343  }
   344  
   345  // SpaceInfo is returned as part of DoCompleteUploadResponse
   346  type SpaceInfo struct {
   347  	Response UploadResponse `json:"response"`
   348  	Status   string         `json:"status"`
   349  }
   350  
   351  // DeleteResponse is returned from doDeleteFile
   352  type DeleteResponse struct {
   353  	Status
   354  	Deleted        []string      `json:"deleted"`
   355  	Errors         []interface{} `json:"errors"`
   356  	ID             string        `json:"fi_id"`
   357  	BackgroundTask int           `json:"backgroundtask"`
   358  	UsSize         string        `json:"us_size"`
   359  	PaSize         string        `json:"pa_size"`
   360  	//SpaceInfo      SpaceInfo     `json:"spaceinfo"`
   361  }
   362  
   363  // FileResponse is returned from doRenameFile
   364  type FileResponse struct {
   365  	Status
   366  	Item   Item   `json:"file"`
   367  	Exists string `json:"exists"`
   368  }
   369  
   370  // MoveFilesResponse is returned from doMoveFiles
   371  type MoveFilesResponse struct {
   372  	Status
   373  	Filesleft         string   `json:"filesleft"`
   374  	Addedtobackground string   `json:"addedtobackground"`
   375  	Moved             string   `json:"moved"`
   376  	Item              Item     `json:"file"`
   377  	IDs               []string `json:"fi_ids"`
   378  	Length            int      `json:"length"`
   379  	DirID             string   `json:"dir_id"`
   380  	MovedObjects      []Item   `json:"movedobjects"`
   381  	// FolderTasks       []interface{}  `json:"foldertasks"`
   382  }
   383  
   384  // TasksResponse is the response to getUserBackgroundTasks
   385  type TasksResponse struct {
   386  	Status
   387  	Tasks []Task `json:"tasks"`
   388  	Total string `json:"total"`
   389  }
   390  
   391  // BtData is part of TasksResponse
   392  type BtData struct {
   393  	Callback string `json:"callback"`
   394  }
   395  
   396  // Task describes a task returned in TasksResponse
   397  type Task struct {
   398  	BtID             string `json:"bt_id"`
   399  	UsID             string `json:"us_id"`
   400  	BtType           string `json:"bt_type"`
   401  	BtData           BtData `json:"bt_data"`
   402  	BtStatustext     string `json:"bt_statustext"`
   403  	BtStatusdata     string `json:"bt_statusdata"`
   404  	BtMessage        string `json:"bt_message"`
   405  	BtProcent        string `json:"bt_procent"`
   406  	BtAdded          string `json:"bt_added"`
   407  	BtStatus         string `json:"bt_status"`
   408  	BtCompleted      string `json:"bt_completed"`
   409  	BtTitle          string `json:"bt_title"`
   410  	BtCredentials    string `json:"bt_credentials"`
   411  	BtHidden         string `json:"bt_hidden"`
   412  	BtAutoremove     string `json:"bt_autoremove"`
   413  	BtDevsite        string `json:"bt_devsite"`
   414  	BtPriority       string `json:"bt_priority"`
   415  	BtReport         string `json:"bt_report"`
   416  	BtSitemarker     string `json:"bt_sitemarker"`
   417  	BtExecuteafter   string `json:"bt_executeafter"`
   418  	BtCompletestatus string `json:"bt_completestatus"`
   419  	BtSubtype        string `json:"bt_subtype"`
   420  	BtCanceled       string `json:"bt_canceled"`
   421  	Callback         string `json:"callback"`
   422  	CanBeCanceled    bool   `json:"canbecanceled"`
   423  	CanBeRestarted   bool   `json:"canberestarted"`
   424  	Type             string `json:"type"`
   425  	Status           string `json:"status"`
   426  	Settings         string `json:"settings"`
   427  }