<commit_before>package megos

// State represents the JSON from the state.json of a mesos node
type State struct {
	ActivatedSlaves        int         `json:"activated_slaves"`
	BuildDate              string      `json:"build_date"`
	BuildTime              int         `json:"build_time"`
	BuildUser              string      `json:"build_user"`
	Cluster                string      `json:"cluster"`
	CompletedFrameworks    []Framework `json:"completed_frameworks"`
	DeactivatedSlaves      int         `json:"deactivated_slaves"`
	ElectedTime            float32     `json:"elected_time"`
	Flags                  Flags       `json:"flags"`
	Frameworks             []Framework `json:"frameworks"`
	GitSHA                 string      `json:"git_sha"`
	GitBranch              string      `json:"git_branch"`
	GitTag                 string      `json:"git_tag"`
	Hostname               string      `json:"hostname"`
	ID                     string      `json:"id"`
	Leader                 string      `json:"leader"`
	LogDir                 string      `json:"log_dir"`
	ExternalLogFile        string      `json:"external_log_file"`
	OrphanTasks            []Task      `json:"orphan_tasks"`
	PID                    string      `json:"pid"`
	Slaves                 []Slave     `json:"slaves"`
	StartTime              float32     `json:"start_time"`
	UnregisteredFrameworks []string    `json:"unregistered_frameworks"`
	Version                string      `json:"version"`
}

// Flags represents the flags of a mesos state
type Flags struct {
	AllocationInterval          string `json:"allocation_interval"`
	Allocator                   string `json:"allocator"`
	Authenticate                string `json:"authenticate"`
	Authenticatee               string `json:"authenticatee"`
	AuthenticateSlaves          string `json:"authenticate_slaves"`
	Authenticators              string `json:"authenticators"`
	Authorizers                 string `json:"authorizers"`
	CgroupsEnableCfs            string `json:"cgroups_enable_cfs"`
	CgroupsHierarchy            string `json:"cgroups_hierarchy"`
	CgroupsLimitSwap            string `json:"cgroups_limit_swap"`
	CgroupsRoot                 string `json:"cgroups_root"`
	Cluster                     string `json:"cluster"`
	ContainerDiskWatchInterval  string `json:"container_disk_watch_interval"`
	Containerizers              string `json:"containerizers"`
	DefaultRole                 string `json:"default_role"`
	DiskWatchInterval           string `json:"disk_watch_interval"`
	Docker                      string `json:"docker"`
	DockerRemoveDelay           string `json:"docker_remove_delay"`
	DockerSandboxDirectory      string `json:"docker_sandbox_directory"`
	DockerStopTimeout           string `json:"docker_stop_timeout"`
	EnforceContainerDiskQuota   string `json:"enforce_container_disk_quota"`
	ExecutorRegistrationTimeout string `json:"executor_registration_timeout"`
	ExecutorShutdownGracePeriod string `json:"executor_shutdown_grace_period"`
	FrameworksHome              string `json:"frameworks_home"`
	FrameworkSorter             string `json:"framework_sorter"`
	GCDelay                     string `json:"gc_delay"`
	GCDiskHeadroom              string `json:"gc_disk_headroom"`
	HadoopHome                  string `json:"hadoop_home"`
	Help                        string `json:"help"`
	Hostname                    string `json:"hostname"`
	InitializeDriverLogging     string `json:"initialize_driver_logging"`
	IP                          string `json:"ip"`
	Isolation                   string `json:"isolation"`
	LauncherDir                 string `json:"launcher_dir"`
	LogAutoInitialize           string `json:"log_auto_initialize"`
	LogDir                      string `json:"log_dir"`
	Logbufsecs                  string `json:"logbufsecs"`
	LoggingLevel                string `json:"logging_level"`
	MaxSlavePingTimeouts        string `json:"max_slave_ping_timeouts"`
	Master                      string `json:"master"`
	PerfDuration                string `json:"perf_duration"`
	PerfInterval                string `json:"perf_interval"`
	Port                        string `json:"port"`
	Quiet                       string `json:"quiet"`
	Quorum                      string `json:"quorum"`
	Recover                     string `json:"recover"`
	RecoverySlaveRemovalLimit   string `json:"recovery_slave_removal_limit"`
	RecoveryTimeout             string `json:"recovery_timeout"`
	RegistrationBackoffFactor   string `json:"registration_backoff_factor"`
	Registry                    string `json:"registry"`
	RegistryFetchTimeout        string `json:"registry_fetch_timeout"`
	RegistryStoreTimeout        string `json:"registry_store_timeout"`
	RegistryStrict              string `json:"registry_strict"`
	ResourceMonitoringInterval  string `json:"resource_monitoring_interval"`
	RootSubmissions             string `json:"root_submissions"`
	SlavePingTimeout            string `json:"slave_ping_timeout"`
	SlaveReregisterTimeout      string `json:"slave_reregister_timeout"`
	Strict                      string `json:"strict"`
	SwitchUser                  string `json:"switch_user"`
	UserSorter                  string `json:"user_sorter"`
	Version                     string `json:"version"`
	WebuiDir                    string `json:"webui_dir"`
	WorkDir                     string `json:"work_dir"`
	ZK                          string `json:"zk"`
	ZKSessionTimeout            string `json:"zk_session_timeout"`
}

// Framework represent a single framework of a mesos node
type Framework struct {
	Active           bool       `json:"active"`
	Checkpoint       bool       `json:"checkpoint"`
	CompletedTasks   []Task     `json:"completed_tasks"`
	Executors        []Executor `json:"executors"`
	FailoverTimeout  int        `json:"failover_timeout"`
	Hostname         string     `json:"hostname"`
	ID               string     `json:"id"`
	Name             string     `json:"name"`
	OfferedResources Resources  `json:"offered_resources"`
	Offers           []Offer    `json:"offers"`
	RegisteredTime   float32    `json:"registered_time"`
	ReregisteredTime float32    `json:"reregistered_time"`
	Resources        Resources  `json:"resources"`
	Role             string     `json:"role"`
	Tasks            []Task     `json:"tasks"`
	UnregisteredTime float32    `json:"unregistered_time"`
	UsedResources    Resources  `json:"used_resources"`
	User             string     `json:"user"`
	WebuiURL         string     `json:"webui_url"`
	Labels           []Label    `json:"label"`
}

type Offer struct {
	ID          string            `json:"id"`
	FrameworkID string            `json:"framework_id"`
	SlaveID     string            `json:"slave_id"`
	Hostname    string            `json:"hostname"`
	URL         URL               `json:"url"`
	Resources   Resources         `json:"resources"`
	Attributes  map[string]string `json:"attributes"`
}

type URL struct {
	Scheme     string      `json:"scheme"`
	Address    Address     `json:"address"`
	Path       string      `json:"path"`
	Parameters []Parameter `json:"parameters"`
}

type Address struct {
	Hostname string `json:"hostname"`
	IP       string `json:"ip"`
	Port     int    `json:"port"`
}

type Parameter struct {
	Key   string `json:"key"`
	Value string `json:"value"`
}

type Label struct {
	Key   string `json:"key"`
	Value string `json:"value"`
}

// Task represent a single Mesos task
type Task struct {
	// Missing fields
	// TODO: "labels": [],
	ExecutorID  string       `json:"executor_id"`
	FrameworkID string       `json:"framework_id"`
	ID          string       `json:"id"`
	Name        string       `json:"name"`
	Resources   Resources    `json:"resources"`
	SlaveID     string       `json:"slave_id"`
	State       string       `json:"state"`
	Statuses    []TaskStatus `json:"statuses"`
}

// Resources represents a resource type for a task
type Resources struct {
	CPUs  float32 `json:"cpus"`
	Disk  int     `json:"disk"`
	Mem   float64 `json:"mem"`
	Ports string  `json:"ports"`
}

// TaskStatus represents the status of a single task
type TaskStatus struct {
	State     string  `json:"state"`
	Timestamp float32 `json:"timestamp"`
}

// Slave represents a single mesos slave node
type Slave struct {
	Active         bool              `json:"active"`
	Hostname       string            `json:"hostname"`
	ID             string            `json:"id"`
	PID            string            `json:"pid"`
	RegisteredTime float32           `json:"registered_time"`
	Resources      Resources         `json:"resources"`
	Attributes     map[string]string `json:"attributes"`
}

// Executor represents a single executor of a framework
type Executor struct {
	// Missing fields
	// TODO "queued_tasks": [],
	// TODO "tasks": []
	CompletedTasks []Task    `json:"completed_tasks"`
	Container      string    `json:"container"`
	Directory      string    `json:"directory"`
	ID             string    `json:"id"`
	Name           string    `json:"name"`
	Resources      Resources `json:"resources"`
	Source         string    `json:"source"`
}
<commit_msg>Support mesos 0.25.0<commit_after>package megos

// State represents the JSON from the state.json of a mesos node
type State struct {
	ActivatedSlaves        float32     `json:"activated_slaves"`
	BuildDate              string      `json:"build_date"`
	BuildTime              float32     `json:"build_time"`
	BuildUser              string      `json:"build_user"`
	Cluster                string      `json:"cluster"`
	CompletedFrameworks    []Framework `json:"completed_frameworks"`
	DeactivatedSlaves      float32     `json:"deactivated_slaves"`
	ElectedTime            float32     `json:"elected_time"`
	Flags                  Flags       `json:"flags"`
	Frameworks             []Framework `json:"frameworks"`
	GitSHA                 string      `json:"git_sha"`
	GitBranch              string      `json:"git_branch"`
	GitTag                 string      `json:"git_tag"`
	Hostname               string      `json:"hostname"`
	ID                     string      `json:"id"`
	Leader                 string      `json:"leader"`
	LogDir                 string      `json:"log_dir"`
	ExternalLogFile        string      `json:"external_log_file"`
	OrphanTasks            []Task      `json:"orphan_tasks"`
	PID                    string      `json:"pid"`
	Slaves                 []Slave     `json:"slaves"`
	StartTime              float32     `json:"start_time"`
	UnregisteredFrameworks []string    `json:"unregistered_frameworks"`
	Version                string      `json:"version"`
}

// Flags represents the flags of a mesos state
type Flags struct {
	AllocationInterval          string `json:"allocation_interval"`
	Allocator                   string `json:"allocator"`
	Authenticate                string `json:"authenticate"`
	Authenticatee               string `json:"authenticatee"`
	AuthenticateSlaves          string `json:"authenticate_slaves"`
	Authenticators              string `json:"authenticators"`
	Authorizers                 string `json:"authorizers"`
	CgroupsEnableCfs            string `json:"cgroups_enable_cfs"`
	CgroupsHierarchy            string `json:"cgroups_hierarchy"`
	CgroupsLimitSwap            string `json:"cgroups_limit_swap"`
	CgroupsRoot                 string `json:"cgroups_root"`
	Cluster                     string `json:"cluster"`
	ContainerDiskWatchInterval  string `json:"container_disk_watch_interval"`
	Containerizers              string `json:"containerizers"`
	DefaultRole                 string `json:"default_role"`
	DiskWatchInterval           string `json:"disk_watch_interval"`
	Docker                      string `json:"docker"`
	DockerRemoveDelay           string `json:"docker_remove_delay"`
	DockerSandboxDirectory      string `json:"docker_sandbox_directory"`
	DockerStopTimeout           string `json:"docker_stop_timeout"`
	EnforceContainerDiskQuota   string `json:"enforce_container_disk_quota"`
	ExecutorRegistrationTimeout string `json:"executor_registration_timeout"`
	ExecutorShutdownGracePeriod string `json:"executor_shutdown_grace_period"`
	FrameworksHome              string `json:"frameworks_home"`
	FrameworkSorter             string `json:"framework_sorter"`
	GCDelay                     string `json:"gc_delay"`
	GCDiskHeadroom              string `json:"gc_disk_headroom"`
	HadoopHome                  string `json:"hadoop_home"`
	Help                        string `json:"help"`
	Hostname                    string `json:"hostname"`
	InitializeDriverLogging     string `json:"initialize_driver_logging"`
	IP                          string `json:"ip"`
	Isolation                   string `json:"isolation"`
	LauncherDir                 string `json:"launcher_dir"`
	LogAutoInitialize           string `json:"log_auto_initialize"`
	LogDir                      string `json:"log_dir"`
	Logbufsecs                  string `json:"logbufsecs"`
	LoggingLevel                string `json:"logging_level"`
	MaxSlavePingTimeouts        string `json:"max_slave_ping_timeouts"`
	Master                      string `json:"master"`
	PerfDuration                string `json:"perf_duration"`
	PerfInterval                string `json:"perf_interval"`
	Port                        string `json:"port"`
	Quiet                       string `json:"quiet"`
	Quorum                      string `json:"quorum"`
	Recover                     string `json:"recover"`
	RecoverySlaveRemovalLimit   string `json:"recovery_slave_removal_limit"`
	RecoveryTimeout             string `json:"recovery_timeout"`
	RegistrationBackoffFactor   string `json:"registration_backoff_factor"`
	Registry                    string `json:"registry"`
	RegistryFetchTimeout        string `json:"registry_fetch_timeout"`
	RegistryStoreTimeout        string `json:"registry_store_timeout"`
	RegistryStrict              string `json:"registry_strict"`
	ResourceMonitoringInterval  string `json:"resource_monitoring_interval"`
	RootSubmissions             string `json:"root_submissions"`
	SlavePingTimeout            string `json:"slave_ping_timeout"`
	SlaveReregisterTimeout      string `json:"slave_reregister_timeout"`
	Strict                      string `json:"strict"`
	SwitchUser                  string `json:"switch_user"`
	UserSorter                  string `json:"user_sorter"`
	Version                     string `json:"version"`
	WebuiDir                    string `json:"webui_dir"`
	WorkDir                     string `json:"work_dir"`
	ZK                          string `json:"zk"`
	ZKSessionTimeout            string `json:"zk_session_timeout"`
}

// Framework represent a single framework of a mesos node
type Framework struct {
	Active           bool       `json:"active"`
	Checkpoint       bool       `json:"checkpoint"`
	CompletedTasks   []Task     `json:"completed_tasks"`
	Executors        []Executor `json:"executors"`
	FailoverTimeout  float32    `json:"failover_timeout"`
	Hostname         string     `json:"hostname"`
	ID               string     `json:"id"`
	Name             string     `json:"name"`
	OfferedResources Resources  `json:"offered_resources"`
	Offers           []Offer    `json:"offers"`
	RegisteredTime   float32    `json:"registered_time"`
	ReregisteredTime float32    `json:"reregistered_time"`
	Resources        Resources  `json:"resources"`
	Role             string     `json:"role"`
	Tasks            []Task     `json:"tasks"`
	UnregisteredTime float32    `json:"unregistered_time"`
	UsedResources    Resources  `json:"used_resources"`
	User             string     `json:"user"`
	WebuiURL         string     `json:"webui_url"`
	Labels           []Label    `json:"label"`
}

type Offer struct {
	ID          string            `json:"id"`
	FrameworkID string            `json:"framework_id"`
	SlaveID     string            `json:"slave_id"`
	Hostname    string            `json:"hostname"`
	URL         URL               `json:"url"`
	Resources   Resources         `json:"resources"`
	Attributes  map[string]string `json:"attributes"`
}

type URL struct {
	Scheme     string      `json:"scheme"`
	Address    Address     `json:"address"`
	Path       string      `json:"path"`
	Parameters []Parameter `json:"parameters"`
}

type Address struct {
	Hostname string `json:"hostname"`
	IP       string `json:"ip"`
	Port     int    `json:"port"`
}

type Parameter struct {
	Key   string `json:"key"`
	Value string `json:"value"`
}

type Label struct {
	Key   string `json:"key"`
	Value string `json:"value"`
}

// Task represent a single Mesos task
type Task struct {
	// Missing fields
	// TODO: "labels": [],
	ExecutorID  string       `json:"executor_id"`
	FrameworkID string       `json:"framework_id"`
	ID          string       `json:"id"`
	Name        string       `json:"name"`
	Resources   Resources    `json:"resources"`
	SlaveID     string       `json:"slave_id"`
	State       string       `json:"state"`
	Statuses    []TaskStatus `json:"statuses"`
}

// Resources represents a resource type for a task
type Resources struct {
	CPUs  float32 `json:"cpus"`
	Disk  float64 `json:"disk"`
	Mem   float64 `json:"mem"`
	Ports string  `json:"ports"`
}

// TaskStatus represents the status of a single task
type TaskStatus struct {
	State     string  `json:"state"`
	Timestamp float32 `json:"timestamp"`
}

// Slave represents a single mesos slave node
type Slave struct {
	Active         bool              `json:"active"`
	Hostname       string            `json:"hostname"`
	ID             string            `json:"id"`
	PID            string            `json:"pid"`
	RegisteredTime float32           `json:"registered_time"`
	Resources      Resources         `json:"resources"`
	Attributes     map[string]string `json:"attributes"`
}

// Executor represents a single executor of a framework
type Executor struct {
	// Missing fields
	// TODO "queued_tasks": [],
	// TODO "tasks": []
	CompletedTasks []Task    `json:"completed_tasks"`
	Container      string    `json:"container"`
	Directory      string    `json:"directory"`
	ID             string    `json:"id"`
	Name           string    `json:"name"`
	Resources      Resources `json:"resources"`
	Source         string    `json:"source"`
}
<|endoftext|>


<commit_before>package gowfs

import "fmt"
import "net/url"

/*
	Generic container type for FileSystem status information
*/

type HdfsJsonData struct {
	Boolean			bool
	FileStatus 		FileStatus
	FileStatuses 	FileStatuses
	FileChecksum 	FileChecksum
	ContentSummary  ContentSummary
	Token 			Token
	Tokens 			Tokens
	Long			int64
	RemoteException RemoteException
}

type Path struct {
	Name 			string 		// Relative path representation (/root/leaf)
	RefererUrl 		url.URL 	// URL related to path (http://server:port/root/leaf)
}

// Represents HDFS FileStatus (FileSystem.getStatus())
// See http://hadoop.apache.org/docs/r2.2.0/hadoop-project-dist/hadoop-hdfs/WebHDFS.html#FileStatus_JSON_Schema
// Example:
// {
//   "FileStatus":
//   {
//     "accessTime"      : 0, 				// integer
//     "blockSize"       : 0, 				// integer
//     "group"           : "grp",			// string
//     "length"          : 0,             	// integer - zero for directories
//     "modificationTime": 1320173277227,	// integer
//     "owner"           : "webuser",		// string
//     "pathSuffix"      : "",				// string
//     "permission"      : "777",			// string
//     "replication"     : 0,				// integer
//     "type"            : "DIRECTORY"    	// string - enum {FILE, DIRECTORY, SYMLINK}
//   }
// }
type FileStatus struct {
	AccesTime int64
    BlockSize int64
    Group string
    Length int64
    ModificationTime int64
    Owner string
    PathSuffix string
    Permission string
    Replication int64
    Type string
}

// Container type for multiple FileStatus for directory, etc
// (see HDFS FileSystem.listStatus())
// NOTE: the confusing naming and Plurality is to match WebHDFS schema.
type FileStatuses struct {
	FileStatus []FileStatus
}

// 	Type for HDFS FileSystem content summary (FileSystem.getContentSummary())
// 	See http://hadoop.apache.org/docs/r2.2.0/hadoop-project-dist/hadoop-hdfs/WebHDFS.html#ContentSummary_JSON_Schema
//
// Example:
// {
//   "ContentSummary":
//   {
//     "directoryCount": 2,
//     "fileCount"     : 1,
//     "length"        : 24930,
//     "quota"         : -1,
//     "spaceConsumed" : 24930,
//     "spaceQuota"    : -1
//   }
// }
type ContentSummary struct {
    DirectoryCount 	int64
    FileCount 		int64
    Length 			int64
    Quota 			int64
    SpaceConsumed 	int64
    SpaceQuota 		int64
}

// 	Type for HDFS FileSystem.getFileChecksum()
// 	See http://hadoop.apache.org/docs/r2.2.0/hadoop-project-dist/hadoop-hdfs/WebHDFS.html#FileChecksum_JSON_Schema
// Example:
// {
//   "FileChecksum":
//   {
//     "algorithm": "MD5-of-1MD5-of-512CRC32",
//     "bytes"    : "eadb10de24aa315748930df6e185c0d ...",
//     "length"   : 28
//   }
// }
type FileChecksum struct {
    Algorithm 	string
    Bytes 		string
    Length 		int64
}

/*
	Type for HDFS FileSystem delegation token (FileSystem.getDelegationToken())
	See http://hadoop.apache.org/docs/r2.2.0/hadoop-project-dist/hadoop-hdfs/WebHDFS.html#Token_JSON_Schema

Example:
{
  "Token":
  {
    "urlString": "JQAIaG9y..."
  }
}
*/
type Token struct {
	UrlString string
}

/*
	Container type for Token
*/
type Tokens struct {
	Token []Token
}

/*
	Type for returning WebHDFS error/exceptions.
	See http://hadoop.apache.org/docs/r2.2.0/hadoop-project-dist/hadoop-hdfs/WebHDFS.html#RemoteException_JSON_schema

Example:
{
  "RemoteException":
  {
    "exception"    : "FileNotFoundException",
    "javaClassName": "java.io.FileNotFoundException",
    "message"      : "File does not exist: /foo/a.patch"
  }
}
*/
type RemoteException struct {
	Exception 		string
	JavaClassName 	string
	Message 		string
}
// implements Error type
func (re RemoteException) Error() string {
	return fmt.Sprintf("RemoteException: %v [%v]\n[%v]\n", re.Exception, re.JavaClassName, re.Message)
}
<commit_msg>updated type documentation.<commit_after>package gowfs

import "fmt"
import "net/url"

// Root level struct for data JSON data from WebHDFS.
type HdfsJsonData struct {
	Boolean			bool
	FileStatus 		FileStatus
	FileStatuses 	FileStatuses
	FileChecksum 	FileChecksum
	ContentSummary  ContentSummary
	Token 			Token
	Tokens 			Tokens
	Long			int64
	RemoteException RemoteException
}

// Represents a remote webHDFS path
type Path struct {
	Name 			string 		// Relative path representation (/root/leaf)
	RefererUrl 		url.URL 	// URL related to path (http://server:port/root/leaf)
}

// Represents HDFS FileStatus (FileSystem.getStatus())
// See http://hadoop.apache.org/docs/r2.2.0/hadoop-project-dist/hadoop-hdfs/WebHDFS.html#FileStatus_JSON_Schema
//
// Example:
// {
//   "FileStatus":
//   {
//     "accessTime"      : 0, 				// integer
//     "blockSize"       : 0, 				// integer
//     "group"           : "grp",			// string
//     "length"          : 0,             	// integer - zero for directories
//     "modificationTime": 1320173277227,	// integer
//     "owner"           : "webuser",		// string
//     "pathSuffix"      : "",				// string
//     "permission"      : "777",			// string
//     "replication"     : 0,				// integer
//     "type"            : "DIRECTORY"    	// string - enum {FILE, DIRECTORY, SYMLINK}
//   }
// }
type FileStatus struct {
	AccesTime int64
    BlockSize int64
    Group string
    Length int64
    ModificationTime int64
    Owner string
    PathSuffix string
    Permission string
    Replication int64
    Type string
}

// Container type for multiple FileStatus for directory, etc
// (see HDFS FileSystem.listStatus())
// NOTE: the confusing naming and Plurality is to match WebHDFS schema.
type FileStatuses struct {
	FileStatus []FileStatus
}

// 	Type for HDFS FileSystem content summary (FileSystem.getContentSummary())
// 	See http://hadoop.apache.org/docs/r2.2.0/hadoop-project-dist/hadoop-hdfs/WebHDFS.html#ContentSummary_JSON_Schema
//
// Example:
// {
//   "ContentSummary":
//   {
//     "directoryCount": 2,
//     "fileCount"     : 1,
//     "length"        : 24930,
//     "quota"         : -1,
//     "spaceConsumed" : 24930,
//     "spaceQuota"    : -1
//   }
// }
type ContentSummary struct {
    DirectoryCount 	int64
    FileCount 		int64
    Length 			int64
    Quota 			int64
    SpaceConsumed 	int64
    SpaceQuota 		int64
}

// 	Type for HDFS FileSystem.getFileChecksum()
// 	See http://hadoop.apache.org/docs/r2.2.0/hadoop-project-dist/hadoop-hdfs/WebHDFS.html#FileChecksum_JSON_Schema
//
// Example:
// {
//   "FileChecksum":
//   {
//     "algorithm": "MD5-of-1MD5-of-512CRC32",
//     "bytes"    : "eadb10de24aa315748930df6e185c0d ...",
//     "length"   : 28
//   }
// }
type FileChecksum struct {
    Algorithm 	string
    Bytes 		string
    Length 		int64
}

// Type for HDFS FileSystem delegation token (FileSystem.getDelegationToken())
// See http://hadoop.apache.org/docs/r2.2.0/hadoop-project-dist/hadoop-hdfs/WebHDFS.html#Token_JSON_Schema

// Example:
// {
//   "Token":
//   {
//     "urlString": "JQAIaG9y..."
//   }
// }
type Token struct {
	UrlString string
}

/*
	Container type for Token
*/
type Tokens struct {
	Token []Token
}

// Type for returning WebHDFS error/exceptions.
// See http://hadoop.apache.org/docs/r2.2.0/hadoop-project-dist/hadoop-hdfs/WebHDFS.html#RemoteException_JSON_schema

// Example:
// {
//   "RemoteException":
//   {
//     "exception"    : "FileNotFoundException",
//     "javaClassName": "java.io.FileNotFoundException",
//     "message"      : "File does not exist: /foo/a.patch"
//   }
// }
type RemoteException struct {
	Exception 		string
	JavaClassName 	string
	Message 		string
}

// Implementation of error type.  Returns string representation of RemoteException.
func (re RemoteException) Error() string {
	return fmt.Sprintf("RemoteException: %v [%v]\n[%v]\n", re.Exception, re.JavaClassName, re.Message)
}
<|endoftext|>


<commit_before>// All names loose the CK_ prefix
// All names loose the hungarian notation
// All the defines are kept from the C package so: C.CKM_RSA_X_509
// All struct's get a Go variant
//
package pkcs11

/*
#define CK_PTR *
#ifndef NULL_PTR
#define NULL_PTR 0
#endif
#define CK_DEFINE_FUNCTION(returnType, name) returnType name
#define CK_DECLARE_FUNCTION(returnType, name) returnType name
#define CK_DECLARE_FUNCTION_POINTER(returnType, name) returnType (* name)
#define CK_CALLBACK_FUNCTION(returnType, name) returnType (* name)

#include <stdlib.h>
#include "pkcs11.h"

CK_ULONG Index(CK_ULONG_PTR array, CK_ULONG i) {
	return array[i];
}

*/
import "C"

import (
	"fmt"
	"unsafe"
)

// List is used as a "generic" list as all object from PKCS#11 hold a uint (CK_ULONG).
type List []uint

// ToList converts from a C style array to a List.
func toList(clist C.CK_ULONG_PTR, size C.CK_ULONG) List {
	l := make(List, int(size))
	for i := 0; i < len(l); i++ {
		l[i] = uint(C.Index(clist, C.CK_ULONG(i)))
	}
	defer C.free(unsafe.Pointer(clist))
	return l
}

// CBBool converts a bool to a CK_BBOOL.
func cBBool(x bool) C.CK_BBOOL {
	if x {
		return C.CK_BBOOL(C.CK_TRUE)
	}
	return C.CK_BBOOL(C.CK_FALSE)
}

type Error uint

func (e Error) Error() string { return "pkcs11: " + fmt.Sprintf("0x%x", int(e)) }

func toError(e C.CK_RV) error {
	if e == C.CKR_OK {
		return nil
	}
	return Error(e)
}

type SessionHandle uint

type ObjectHandle uint

type Version struct {
	Major byte
	Minor byte
}

type Info struct {
	// TODO
}

type SlotInfo struct {
	SlotDescription [64]byte
	ManufacturerID  [32]byte
	Flags           uint
	HardwareVersion Version
	FirmwareVersion Version
}

type TokenInfo struct {
	Label              [32]byte
	ManufacturerID     [32]byte
	Model              [16]byte
	SerialNumber       [16]byte
	Flags              uint
	MaxSessionCount    uint
	SessionCount       uint
	MaxRwSessionCount  uint
	RwSessionCount     uint
	MaxPinLen          uint
	MinPinLen          uint
	TotalPublicMemory  uint
	FreePublicMemory   uint
	TotalPrivateMemory uint
	FreePrivateMemory  uint
	hardwareVersion    Version
	firmwareVersion    Version
	UTCTime            [16]byte
}

type SessionInfo struct {
	SlotID      uint
	Sate        uint
	Flags       uint
	DeviceError uint
}

type Attribute struct {
	Type  uint
	Value []byte
}

func NewAttribute(typ uint, x interface{}) Attribute {
	var a Attribute
	a.Type = typ
	if x == nil {
		a.Value = nil
		return a
	}
	switch x.(type) {
	case bool: // create bbool
		if x.(bool) {
			a.Value = []byte{1}
			break
		}
		a.Value = []byte{0}
	case uint:
		if x.(uint) <= 1<<16-1 {
			a.Value = make([]byte, 2)
			a.Value[0] = byte(x.(uint) >> 8)
			a.Value[1] = byte(x.(uint))
			break
		}
		if x.(uint) <= 1<<32-1 {
			a.Value = make([]byte, 4)
			a.Value[0] = byte(x.(uint) >> 24)
			a.Value[1] = byte(x.(uint) >> 16)
			a.Value[2] = byte(x.(uint) >> 8)
			a.Value[3] = byte(x.(uint))
		}
	case []byte: // just copy
		a.Value = x.([]byte)
	default:
		panic("pkcs11: unhandled attribute type")
	}
	return a
}

// cAttribute returns the start address and the length of an attribute list.
func cAttributeList(a []Attribute) (C.CK_ATTRIBUTE_PTR, C.CK_ULONG) {
	if len(a) == 0 {
		return nil, 0
	}
	cp := make([]C.CK_ATTRIBUTE, len(a))
	for i := 0; i < len(a); i++ {
		var l C.CK_ATTRIBUTE
		l._type = C.CK_ATTRIBUTE_TYPE(a[i].Type)
		l.pValue = C.CK_VOID_PTR(&(a[i].Value[0]))
		l.ulValueLen = C.CK_ULONG(len(a[i].Value))
	}
	return C.CK_ATTRIBUTE_PTR(&(cp[0])), C.CK_ULONG(len(a))
}

type Date struct {
	// TODO
}

type Mechanism struct {
	Type      uint
	Parameter []byte
}

func NewMechanism(typ uint, x interface{}) Mechanism {
	var m Mechanism
	m.Type = typ
	if x == nil {
		m.Parameter = nil
		return m
	}
	// Add specific types? Ala Attributes?
	return m
}

// cMechanism returns a C pointer to the mechanism m.
func cMechanism(m Mechanism) C.CK_MECHANISM_PTR {
	var m1 C.CK_MECHANISM
	m1.mechanism = C.CK_MECHANISM_TYPE(m.Type)
	if len(m.Parameter) == 0 {
		m1.pParameter = C.CK_VOID_PTR(nil)
	} else {
		m1.pParameter = C.CK_VOID_PTR(&(m.Parameter[0]))
	}
	m1.ulParameterLen = C.CK_ULONG(len(m.Parameter))
	return C.CK_MECHANISM_PTR(&m1)
}

type MechanismInfo struct {
	MinKeySize uint
	MaxKeySize uint
	Flags      uint
}

// stopped after this one
<commit_msg>Rename mechanism.Type to mechanism.Mechanism<commit_after>// All names loose the CK_ prefix
// All names loose the hungarian notation
// All the defines are kept from the C package so: C.CKM_RSA_X_509
// All struct's get a Go variant
//
package pkcs11

/*
#define CK_PTR *
#ifndef NULL_PTR
#define NULL_PTR 0
#endif
#define CK_DEFINE_FUNCTION(returnType, name) returnType name
#define CK_DECLARE_FUNCTION(returnType, name) returnType name
#define CK_DECLARE_FUNCTION_POINTER(returnType, name) returnType (* name)
#define CK_CALLBACK_FUNCTION(returnType, name) returnType (* name)

#include <stdlib.h>
#include "pkcs11.h"

CK_ULONG Index(CK_ULONG_PTR array, CK_ULONG i) {
	return array[i];
}

*/
import "C"

import (
	"fmt"
	"unsafe"
)

// List is used as a "generic" list as all object from PKCS#11 hold a uint (CK_ULONG).
type List []uint

// ToList converts from a C style array to a List.
func toList(clist C.CK_ULONG_PTR, size C.CK_ULONG) List {
	l := make(List, int(size))
	for i := 0; i < len(l); i++ {
		l[i] = uint(C.Index(clist, C.CK_ULONG(i)))
	}
	defer C.free(unsafe.Pointer(clist))
	return l
}

// CBBool converts a bool to a CK_BBOOL.
func cBBool(x bool) C.CK_BBOOL {
	if x {
		return C.CK_BBOOL(C.CK_TRUE)
	}
	return C.CK_BBOOL(C.CK_FALSE)
}

type Error uint

func (e Error) Error() string { return "pkcs11: " + fmt.Sprintf("0x%x", int(e)) }

func toError(e C.CK_RV) error {
	if e == C.CKR_OK {
		return nil
	}
	return Error(e)
}

type SessionHandle uint

type ObjectHandle uint

type Version struct {
	Major byte
	Minor byte
}

type Info struct {
	// TODO
}

type SlotInfo struct {
	SlotDescription [64]byte
	ManufacturerID  [32]byte
	Flags           uint
	HardwareVersion Version
	FirmwareVersion Version
}

type TokenInfo struct {
	Label              [32]byte
	ManufacturerID     [32]byte
	Model              [16]byte
	SerialNumber       [16]byte
	Flags              uint
	MaxSessionCount    uint
	SessionCount       uint
	MaxRwSessionCount  uint
	RwSessionCount     uint
	MaxPinLen          uint
	MinPinLen          uint
	TotalPublicMemory  uint
	FreePublicMemory   uint
	TotalPrivateMemory uint
	FreePrivateMemory  uint
	hardwareVersion    Version
	firmwareVersion    Version
	UTCTime            [16]byte
}

type SessionInfo struct {
	SlotID      uint
	Sate        uint
	Flags       uint
	DeviceError uint
}

type Attribute struct {
	Type  uint
	Value []byte
}

func NewAttribute(typ uint, x interface{}) Attribute {
	var a Attribute
	a.Type = typ
	if x == nil {
		a.Value = nil
		return a
	}
	switch x.(type) {
	case bool: // create bbool
		if x.(bool) {
			a.Value = []byte{1}
			break
		}
		a.Value = []byte{0}
	case uint:
		if x.(uint) <= 1<<16-1 {
			a.Value = make([]byte, 2)
			a.Value[0] = byte(x.(uint) >> 8)
			a.Value[1] = byte(x.(uint))
			break
		}
		if x.(uint) <= 1<<32-1 {
			a.Value = make([]byte, 4)
			a.Value[0] = byte(x.(uint) >> 24)
			a.Value[1] = byte(x.(uint) >> 16)
			a.Value[2] = byte(x.(uint) >> 8)
			a.Value[3] = byte(x.(uint))
		}
	case []byte: // just copy
		a.Value = x.([]byte)
	default:
		panic("pkcs11: unhandled attribute type")
	}
	return a
}

// cAttribute returns the start address and the length of an attribute list.
func cAttributeList(a []Attribute) (C.CK_ATTRIBUTE_PTR, C.CK_ULONG) {
	if len(a) == 0 {
		return nil, 0
	}
	cp := make([]C.CK_ATTRIBUTE, len(a))
	for i := 0; i < len(a); i++ {
		var l C.CK_ATTRIBUTE
		l._type = C.CK_ATTRIBUTE_TYPE(a[i].Type)
		l.pValue = C.CK_VOID_PTR(&(a[i].Value[0]))
		l.ulValueLen = C.CK_ULONG(len(a[i].Value))
	}
	return C.CK_ATTRIBUTE_PTR(&(cp[0])), C.CK_ULONG(len(a))
}

type Date struct {
	// TODO
}

type Mechanism struct {
	Mechanism      uint
	Parameter []byte
}

func NewMechanism(mech uint, x interface{}) Mechanism {
	var m Mechanism
	m.Mechanism = mech
	if x == nil {
		m.Parameter = nil
		return m
	}
	// Add specific types? Ala Attributes?
	return m
}

// cMechanismList

// cMechanism returns a C pointer to the mechanism m.
func cMechanism(m Mechanism) C.CK_MECHANISM_PTR {
	var m1 C.CK_MECHANISM
	m1.mechanism = C.CK_MECHANISM_TYPE(m.Mechanism)
	if len(m.Parameter) == 0 {
		m1.pParameter = C.CK_VOID_PTR(nil)
	} else {
		m1.pParameter = C.CK_VOID_PTR(&(m.Parameter[0]))
	}
	m1.ulParameterLen = C.CK_ULONG(len(m.Parameter))
	return C.CK_MECHANISM_PTR(&m1)
}

//func toMechanismList(clist C.CK_MECHANISM_TYPE_PTR, size C.CK_ULONG) []Mechanism {
//	m := make([]Mechanism, int(size))
//	for i := 0; i < len(m); i++ {
//		cm := C.Index(clist, C.(i))
//		m[i] = Mechanism{Mechanism: uint(cm.mechanism),
//	}
//	defer C.free(unsafe.Pointer(clist))
//	return m
//}

type MechanismInfo struct {
	MinKeySize uint
	MaxKeySize uint
	Flags      uint
}

// stopped after this one
<|endoftext|>


<commit_before>package goinsta

import (
	"fmt"
	"net/http"
)

// ConfigFile is a structure to store the session information so that can be exported or imported.
type ConfigFile struct {
	ID        int64          `json:"id"`
	User      string         `json:"username"`
	DeviceID  string         `json:"device_id"`
	UUID      string         `json:"uuid"`
	RankToken string         `json:"rank_token"`
	Token     string         `json:"token"`
	PhoneID   string         `json:"phone_id"`
	Cookies   []*http.Cookie `json:"cookies"`
}

// School is void structure (yet).
type School struct {
}

// PicURLInfo repre
type PicURLInfo struct {
	Height int    `json:"height"`
	URL    string `json:"url"`
	Width  int    `json:"width"`
}

// ErrorN is general instagram error
type ErrorN struct {
	Message   string `json:"message"`
	Status    string `json:"status"`
	ErrorType string `json:"error_type"`
}

// Error503 is instagram API error
type Error503 struct {
	Message string
}

func (e Error503) Error() string {
	return e.Message
}

func (e ErrorN) Error() string {
	return fmt.Sprintf("%s: %s (%s)", e.Status, e.Message, e.ErrorType)
}

// Error400 is error returned by HTTP 400 status code.
type Error400 struct {
	Action     string `json:"action"`
	StatusCode string `json:"status_code"`
	Payload    struct {
		ClientContext string `json:"client_context"`
		Message       string `json:"message"`
	} `json:"payload"`
	Status string `json:"status"`
}

func (e Error400) Error() string {
	return fmt.Sprintf("%s: %s", e.Status, e.Payload.Message)
}

// Nametag is part of the account information.
type Nametag struct {
	Mode          int64       `json:"mode"`
	Gradient      interface{} `json:"gradient"`
	Emoji         string      `json:"emoji"`
	SelfieSticker interface{} `json:"selfie_sticker"`
}

type friendResp struct {
	Status     string     `json:"status"`
	Friendship Friendship `json:"friendship_status"`
}

// Location stores media location information.
type Location struct {
	Pk               int64   `json:"pk"`
	Name             string  `json:"name"`
	Address          string  `json:"address"`
	City             string  `json:"city"`
	ShortName        string  `json:"short_name"`
	Lng              float64 `json:"lng"`
	Lat              float64 `json:"lat"`
	ExternalSource   string  `json:"external_source"`
	FacebookPlacesID int64   `json:"facebook_places_id"`
}

// SuggestedUsers stores the information about user suggestions.
type SuggestedUsers struct {
	Type        int `json:"type"`
	Suggestions []struct {
		User            User          `json:"user"`
		Algorithm       string        `json:"algorithm"`
		SocialContext   string        `json:"social_context"`
		Icon            string        `json:"icon"`
		Caption         string        `json:"caption"`
		MediaIds        []interface{} `json:"media_ids"`
		ThumbnailUrls   []interface{} `json:"thumbnail_urls"`
		LargeUrls       []interface{} `json:"large_urls"`
		MediaInfos      []interface{} `json:"media_infos"`
		Value           float64       `json:"value"`
		IsNewSuggestion bool          `json:"is_new_suggestion"`
	} `json:"suggestions"`
	LandingSiteType  string `json:"landing_site_type"`
	Title            string `json:"title"`
	ViewAllText      string `json:"view_all_text"`
	LandingSiteTitle string `json:"landing_site_title"`
	NetegoType       string `json:"netego_type"`
	UpsellFbPos      string `json:"upsell_fb_pos"`
	AutoDvance       string `json:"auto_dvance"`
	ID               string `json:"id"`
	TrackingToken    string `json:"tracking_token"`
}

// Friendship stores the details of the relationship between two users.
type Friendship struct {
	IncomingRequest bool `json:"incoming_request"`
	FollowedBy      bool `json:"followed_by"`
	OutgoingRequest bool `json:"outgoing_request"`
	Following       bool `json:"following"`
	Blocking        bool `json:"blocking"`
	IsPrivate       bool `json:"is_private"`
	Muting          bool `json:"muting"`
	IsMutingReel    bool `json:"is_muting_reel"`
}

// SavedMedia stores the information about media being saved before in my account.
type SavedMedia struct {
	Items []struct {
		Media Item `json:"media"`
	} `json:"items"`
	NumResults          int    `json:"num_results"`
	MoreAvailable       bool   `json:"more_available"`
	AutoLoadMoreEnabled bool   `json:"auto_load_more_enabled"`
	Status              string `json:"status"`
}

// Images are different quality images
type Images struct {
	Versions []Candidate `json:"candidates"`
}

// GetBest returns the URL of the image with the best quality.
func (img Images) GetBest() string {
	best := ""
	var mh, mw int
	for _, v := range img.Versions {
		if v.Width > mw || v.Height > mh {
			best = v.URL
			mh, mw = v.Height, v.Width
		}
	}
	return best
}

// Candidate is something that I really have no idea what it is.
type Candidate struct {
	Width  int    `json:"width"`
	Height int    `json:"height"`
	URL    string `json:"url"`
}

// Tag is the information of an user being tagged on any media.
type Tag struct {
	In []struct {
		User                  User        `json:"user"`
		Position              []float64   `json:"position"`
		StartTimeInVideoInSec interface{} `json:"start_time_in_video_in_sec"`
		DurationInVideoInSec  interface{} `json:"duration_in_video_in_sec"`
	} `json:"in"`
}

// Caption is media caption
type Caption struct {
	ID              int64  `json:"pk"`
	UserID          int64  `json:"user_id"`
	Text            string `json:"text"`
	Type            int    `json:"type"`
	CreatedAt       int64  `json:"created_at"`
	CreatedAtUtc    int64  `json:"created_at_utc"`
	ContentType     string `json:"content_type"`
	Status          string `json:"status"`
	BitFlags        int    `json:"bit_flags"`
	User            User   `json:"user"`
	DidReportAsSpam bool   `json:"did_report_as_spam"`
	MediaID         int64  `json:"media_id"`
	HasTranslation  bool   `json:"has_translation"`
}

// Mentions is a user being mentioned on media.
type Mentions struct {
	X        float64 `json:"x"`
	Y        float64 `json:"y"`
	Z        int64   `json:"z"`
	Width    float64 `json:"width"`
	Height   float64 `json:"height"`
	Rotation float64 `json:"rotation"`
	IsPinned int     `json:"is_pinned"`
	User     User    `json:"user"`
}

// Video are different quality videos
type Video struct {
	Type   int    `json:"type"`
	Width  int    `json:"width"`
	Height int    `json:"height"`
	URL    string `json:"url"`
	ID     string `json:"id"`
}

type timeStoryResp struct {
	Status string       `json:"status"`
	Media  []StoryMedia `json:"tray"`
}

type trayResp struct {
	Reels  map[string]StoryMedia `json:"reels"`
	Status string                `json:"status"`
}

// Tray is a set of story media received from timeline calls.
type Tray struct {
	Stories []StoryMedia `json:"tray"`
	Lives   struct {
		LiveItems []LiveItems `json:"post_live_items"`
	} `json:"post_live"`
	StoryRankingToken    string      `json:"story_ranking_token"`
	Broadcasts           []Broadcast `json:"broadcasts"`
	FaceFilterNuxVersion int         `json:"face_filter_nux_version"`
	HasNewNuxStory       bool        `json:"has_new_nux_story"`
	Status               string      `json:"status"`
}

func (tray *Tray) set(inst *Instagram, url string) {
	for i := range tray.Stories {
		tray.Stories[i].inst = inst
		tray.Stories[i].endpoint = url
		tray.Stories[i].setValues()
	}
	for i := range tray.Lives.LiveItems {
		tray.Lives.LiveItems[i].User.inst = inst
		for j := range tray.Lives.LiveItems[i].Broadcasts {
			tray.Lives.LiveItems[i].Broadcasts[j].BroadcastOwner.inst = inst
		}
	}
	for i := range tray.Broadcasts {
		tray.Broadcasts[i].BroadcastOwner.inst = inst
	}
}

// LiveItems are Live media items
type LiveItems struct {
	ID                  string      `json:"pk"`
	User                User        `json:"user"`
	Broadcasts          []Broadcast `json:"broadcasts"`
	LastSeenBroadcastTs float64     `json:"last_seen_broadcast_ts"`
	RankedPosition      int64       `json:"ranked_position"`
	SeenRankedPosition  int64       `json:"seen_ranked_position"`
	Muted               bool        `json:"muted"`
	CanReply            bool        `json:"can_reply"`
	CanReshare          bool        `json:"can_reshare"`
}

// Broadcast is live videos.
type Broadcast struct {
	ID                   int64  `json:"id"`
	BroadcastStatus      string `json:"broadcast_status"`
	DashManifest         string `json:"dash_manifest"`
	ExpireAt             int64  `json:"expire_at"`
	EncodingTag          string `json:"encoding_tag"`
	InternalOnly         bool   `json:"internal_only"`
	NumberOfQualities    int    `json:"number_of_qualities"`
	CoverFrameURL        string `json:"cover_frame_url"`
	BroadcastOwner       User   `json:"broadcast_owner"`
	PublishedTime        int64  `json:"published_time"`
	MediaID              string `json:"media_id"`
	BroadcastMessage     string `json:"broadcast_message"`
	OrganicTrackingToken string `json:"organic_tracking_token"`
}

// BlockedUser stores information about a used that has been blocked before.
type BlockedUser struct {
	// TODO: Convert to user
	UserID        int64  `json:"user_id"`
	Username      string `json:"username"`
	FullName      string `json:"full_name"`
	ProfilePicURL string `json:"profile_pic_url"`
	BlockAt       int64  `json:"block_at"`
}

// Unblock unblocks blocked user.
func (b *BlockedUser) Unblock() error {
	u := User{ID: b.UserID}
	return u.Unblock()
}

type blockedListResp struct {
	BlockedList []BlockedUser `json:"blocked_list"`
	PageSize    int           `json:"page_size"`
	Status      string        `json:"status"`
}

// InboxItemMedia is inbox media item
type InboxItemMedia struct {
	ClientContext              string `json:"client_context"`
	ExpiringMediaActionSummary struct {
		Count     int    `json:"count"`
		Timestamp int64  `json:"timestamp"`
		Type      string `json:"type"`
	} `json:"expiring_media_action_summary"`
	ItemID     string `json:"item_id"`
	ItemType   string `json:"item_type"`
	RavenMedia struct {
		MediaType int64 `json:"media_type"`
	} `json:"raven_media"`
	ReplyChainCount int           `json:"reply_chain_count"`
	SeenUserIds     []interface{} `json:"seen_user_ids"`
	Timestamp       int64         `json:"timestamp"`
	UserID          int64         `json:"user_id"`
	ViewMode        string        `json:"view_mode"`
}

//InboxItemLike is the heart sent during a conversation.
type InboxItemLike struct {
	ItemID    string `json:"item_id"`
	ItemType  string `json:"item_type"`
	Timestamp int64  `json:"timestamp"`
	UserID    int64  `json:"user_id"`
}

type respLikers struct {
	Users     []User `json:"users"`
	UserCount int64  `json:"user_count"`
	Status    string `json:"status"`
}

type threadResp struct {
	Conversation Conversation `json:"thread"`
	Status       string       `json:"status"`
}
<commit_msg>using json number (#202)<commit_after>package goinsta

import (
	"encoding/json"
	"fmt"
	"net/http"
)

// ConfigFile is a structure to store the session information so that can be exported or imported.
type ConfigFile struct {
	ID        int64          `json:"id"`
	User      string         `json:"username"`
	DeviceID  string         `json:"device_id"`
	UUID      string         `json:"uuid"`
	RankToken string         `json:"rank_token"`
	Token     string         `json:"token"`
	PhoneID   string         `json:"phone_id"`
	Cookies   []*http.Cookie `json:"cookies"`
}

// School is void structure (yet).
type School struct {
}

// PicURLInfo repre
type PicURLInfo struct {
	Height int    `json:"height"`
	URL    string `json:"url"`
	Width  int    `json:"width"`
}

// ErrorN is general instagram error
type ErrorN struct {
	Message   string `json:"message"`
	Status    string `json:"status"`
	ErrorType string `json:"error_type"`
}

// Error503 is instagram API error
type Error503 struct {
	Message string
}

func (e Error503) Error() string {
	return e.Message
}

func (e ErrorN) Error() string {
	return fmt.Sprintf("%s: %s (%s)", e.Status, e.Message, e.ErrorType)
}

// Error400 is error returned by HTTP 400 status code.
type Error400 struct {
	Action     string `json:"action"`
	StatusCode string `json:"status_code"`
	Payload    struct {
		ClientContext string `json:"client_context"`
		Message       string `json:"message"`
	} `json:"payload"`
	Status string `json:"status"`
}

func (e Error400) Error() string {
	return fmt.Sprintf("%s: %s", e.Status, e.Payload.Message)
}

// Nametag is part of the account information.
type Nametag struct {
	Mode          int64       `json:"mode"`
	Gradient      json.Number `json:"gradient,Number"`
	Emoji         string      `json:"emoji"`
	SelfieSticker json.Number `json:"selfie_sticker,Number"`
}

type friendResp struct {
	Status     string     `json:"status"`
	Friendship Friendship `json:"friendship_status"`
}

// Location stores media location information.
type Location struct {
	Pk               int64   `json:"pk"`
	Name             string  `json:"name"`
	Address          string  `json:"address"`
	City             string  `json:"city"`
	ShortName        string  `json:"short_name"`
	Lng              float64 `json:"lng"`
	Lat              float64 `json:"lat"`
	ExternalSource   string  `json:"external_source"`
	FacebookPlacesID int64   `json:"facebook_places_id"`
}

// SuggestedUsers stores the information about user suggestions.
type SuggestedUsers struct {
	Type        int `json:"type"`
	Suggestions []struct {
		User            User          `json:"user"`
		Algorithm       string        `json:"algorithm"`
		SocialContext   string        `json:"social_context"`
		Icon            string        `json:"icon"`
		Caption         string        `json:"caption"`
		MediaIds        []interface{} `json:"media_ids"`
		ThumbnailUrls   []interface{} `json:"thumbnail_urls"`
		LargeUrls       []interface{} `json:"large_urls"`
		MediaInfos      []interface{} `json:"media_infos"`
		Value           float64       `json:"value"`
		IsNewSuggestion bool          `json:"is_new_suggestion"`
	} `json:"suggestions"`
	LandingSiteType  string `json:"landing_site_type"`
	Title            string `json:"title"`
	ViewAllText      string `json:"view_all_text"`
	LandingSiteTitle string `json:"landing_site_title"`
	NetegoType       string `json:"netego_type"`
	UpsellFbPos      string `json:"upsell_fb_pos"`
	AutoDvance       string `json:"auto_dvance"`
	ID               string `json:"id"`
	TrackingToken    string `json:"tracking_token"`
}

// Friendship stores the details of the relationship between two users.
type Friendship struct {
	IncomingRequest bool `json:"incoming_request"`
	FollowedBy      bool `json:"followed_by"`
	OutgoingRequest bool `json:"outgoing_request"`
	Following       bool `json:"following"`
	Blocking        bool `json:"blocking"`
	IsPrivate       bool `json:"is_private"`
	Muting          bool `json:"muting"`
	IsMutingReel    bool `json:"is_muting_reel"`
}

// SavedMedia stores the information about media being saved before in my account.
type SavedMedia struct {
	Items []struct {
		Media Item `json:"media"`
	} `json:"items"`
	NumResults          int    `json:"num_results"`
	MoreAvailable       bool   `json:"more_available"`
	AutoLoadMoreEnabled bool   `json:"auto_load_more_enabled"`
	Status              string `json:"status"`
}

// Images are different quality images
type Images struct {
	Versions []Candidate `json:"candidates"`
}

// GetBest returns the URL of the image with the best quality.
func (img Images) GetBest() string {
	best := ""
	var mh, mw int
	for _, v := range img.Versions {
		if v.Width > mw || v.Height > mh {
			best = v.URL
			mh, mw = v.Height, v.Width
		}
	}
	return best
}

// Candidate is something that I really have no idea what it is.
type Candidate struct {
	Width  int    `json:"width"`
	Height int    `json:"height"`
	URL    string `json:"url"`
}

// Tag is the information of an user being tagged on any media.
type Tag struct {
	In []struct {
		User                  User        `json:"user"`
		Position              []float64   `json:"position"`
		StartTimeInVideoInSec interface{} `json:"start_time_in_video_in_sec"`
		DurationInVideoInSec  interface{} `json:"duration_in_video_in_sec"`
	} `json:"in"`
}

// Caption is media caption
type Caption struct {
	ID              int64  `json:"pk"`
	UserID          int64  `json:"user_id"`
	Text            string `json:"text"`
	Type            int    `json:"type"`
	CreatedAt       int64  `json:"created_at"`
	CreatedAtUtc    int64  `json:"created_at_utc"`
	ContentType     string `json:"content_type"`
	Status          string `json:"status"`
	BitFlags        int    `json:"bit_flags"`
	User            User   `json:"user"`
	DidReportAsSpam bool   `json:"did_report_as_spam"`
	MediaID         int64  `json:"media_id"`
	HasTranslation  bool   `json:"has_translation"`
}

// Mentions is a user being mentioned on media.
type Mentions struct {
	X        float64 `json:"x"`
	Y        float64 `json:"y"`
	Z        int64   `json:"z"`
	Width    float64 `json:"width"`
	Height   float64 `json:"height"`
	Rotation float64 `json:"rotation"`
	IsPinned int     `json:"is_pinned"`
	User     User    `json:"user"`
}

// Video are different quality videos
type Video struct {
	Type   int    `json:"type"`
	Width  int    `json:"width"`
	Height int    `json:"height"`
	URL    string `json:"url"`
	ID     string `json:"id"`
}

type timeStoryResp struct {
	Status string       `json:"status"`
	Media  []StoryMedia `json:"tray"`
}

type trayResp struct {
	Reels  map[string]StoryMedia `json:"reels"`
	Status string                `json:"status"`
}

// Tray is a set of story media received from timeline calls.
type Tray struct {
	Stories []StoryMedia `json:"tray"`
	Lives   struct {
		LiveItems []LiveItems `json:"post_live_items"`
	} `json:"post_live"`
	StoryRankingToken    string      `json:"story_ranking_token"`
	Broadcasts           []Broadcast `json:"broadcasts"`
	FaceFilterNuxVersion int         `json:"face_filter_nux_version"`
	HasNewNuxStory       bool        `json:"has_new_nux_story"`
	Status               string      `json:"status"`
}

func (tray *Tray) set(inst *Instagram, url string) {
	for i := range tray.Stories {
		tray.Stories[i].inst = inst
		tray.Stories[i].endpoint = url
		tray.Stories[i].setValues()
	}
	for i := range tray.Lives.LiveItems {
		tray.Lives.LiveItems[i].User.inst = inst
		for j := range tray.Lives.LiveItems[i].Broadcasts {
			tray.Lives.LiveItems[i].Broadcasts[j].BroadcastOwner.inst = inst
		}
	}
	for i := range tray.Broadcasts {
		tray.Broadcasts[i].BroadcastOwner.inst = inst
	}
}

// LiveItems are Live media items
type LiveItems struct {
	ID                  string      `json:"pk"`
	User                User        `json:"user"`
	Broadcasts          []Broadcast `json:"broadcasts"`
	LastSeenBroadcastTs float64     `json:"last_seen_broadcast_ts"`
	RankedPosition      int64       `json:"ranked_position"`
	SeenRankedPosition  int64       `json:"seen_ranked_position"`
	Muted               bool        `json:"muted"`
	CanReply            bool        `json:"can_reply"`
	CanReshare          bool        `json:"can_reshare"`
}

// Broadcast is live videos.
type Broadcast struct {
	ID                   int64  `json:"id"`
	BroadcastStatus      string `json:"broadcast_status"`
	DashManifest         string `json:"dash_manifest"`
	ExpireAt             int64  `json:"expire_at"`
	EncodingTag          string `json:"encoding_tag"`
	InternalOnly         bool   `json:"internal_only"`
	NumberOfQualities    int    `json:"number_of_qualities"`
	CoverFrameURL        string `json:"cover_frame_url"`
	BroadcastOwner       User   `json:"broadcast_owner"`
	PublishedTime        int64  `json:"published_time"`
	MediaID              string `json:"media_id"`
	BroadcastMessage     string `json:"broadcast_message"`
	OrganicTrackingToken string `json:"organic_tracking_token"`
}

// BlockedUser stores information about a used that has been blocked before.
type BlockedUser struct {
	// TODO: Convert to user
	UserID        int64  `json:"user_id"`
	Username      string `json:"username"`
	FullName      string `json:"full_name"`
	ProfilePicURL string `json:"profile_pic_url"`
	BlockAt       int64  `json:"block_at"`
}

// Unblock unblocks blocked user.
func (b *BlockedUser) Unblock() error {
	u := User{ID: b.UserID}
	return u.Unblock()
}

type blockedListResp struct {
	BlockedList []BlockedUser `json:"blocked_list"`
	PageSize    int           `json:"page_size"`
	Status      string        `json:"status"`
}

// InboxItemMedia is inbox media item
type InboxItemMedia struct {
	ClientContext              string `json:"client_context"`
	ExpiringMediaActionSummary struct {
		Count     int    `json:"count"`
		Timestamp int64  `json:"timestamp"`
		Type      string `json:"type"`
	} `json:"expiring_media_action_summary"`
	ItemID     string `json:"item_id"`
	ItemType   string `json:"item_type"`
	RavenMedia struct {
		MediaType int64 `json:"media_type"`
	} `json:"raven_media"`
	ReplyChainCount int           `json:"reply_chain_count"`
	SeenUserIds     []interface{} `json:"seen_user_ids"`
	Timestamp       int64         `json:"timestamp"`
	UserID          int64         `json:"user_id"`
	ViewMode        string        `json:"view_mode"`
}

//InboxItemLike is the heart sent during a conversation.
type InboxItemLike struct {
	ItemID    string `json:"item_id"`
	ItemType  string `json:"item_type"`
	Timestamp int64  `json:"timestamp"`
	UserID    int64  `json:"user_id"`
}

type respLikers struct {
	Users     []User `json:"users"`
	UserCount int64  `json:"user_count"`
	Status    string `json:"status"`
}

type threadResp struct {
	Conversation Conversation `json:"thread"`
	Status       string       `json:"status"`
}
<|endoftext|>


<commit_before>package dockerclient

import (
	"time"
)

type ContainerConfig struct {
	Hostname        string
	Domainname      string
	User            string
	Memory          int64
	MemorySwap      int64
	CpuShares       int64
	Cpuset          string
	AttachStdin     bool
	AttachStdout    bool
	AttachStderr    bool
	PortSpecs       []string
	ExposedPorts    map[string]struct{}
	Tty             bool
	OpenStdin       bool
	StdinOnce       bool
	Env             []string
	Cmd             []string
	Image           string
	Labels          map[string]string
	Volumes         map[string]struct{}
	WorkingDir      string
	Entrypoint      []string
	NetworkDisabled bool
	OnBuild         []string

	// This is used only by the create command
	HostConfig HostConfig
}

type HostConfig struct {
	Binds           []string
	ContainerIDFile string
	LxcConf         []map[string]string
	Privileged      bool
	PortBindings    map[string][]PortBinding
	Links           []string
	PublishAllPorts bool
	Dns             []string
	DnsSearch       []string
	VolumesFrom     []string
	SecurityOpt     []string
	NetworkMode     string
	RestartPolicy   RestartPolicy
}

type ExecConfig struct {
	AttachStdin  bool
	AttachStdout bool
	AttachStderr bool
	Tty          bool
	Cmd          []string
	Container    string
	Detach       bool
}

type LogOptions struct {
	Follow     bool
	Stdout     bool
	Stderr     bool
	Timestamps bool
	Tail       int64
}

type MonitorEventsFilters struct {
	Event     string `json:",omitempty"`
	Image     string `json:",omitempty"`
	Container string `json:",omitempty"`
}

type MonitorEventsOptions struct {
	Since   int
	Until   int
	Filters *MonitorEventsFilters `json:",omitempty"`
}

type RestartPolicy struct {
	Name              string
	MaximumRetryCount int64
}

type PortBinding struct {
	HostIp   string
	HostPort string
}

type ContainerInfo struct {
	Id      string
	Created string
	Path    string
	Name    string
	Args    []string
	ExecIDs []string
	Config  *ContainerConfig
	State   struct {
		Running    bool
		Paused     bool
		Restarting bool
		Pid        int
		ExitCode   int
		StartedAt  time.Time
		FinishedAt time.Time
		Ghost      bool
	}
	Image           string
	NetworkSettings struct {
		IpAddress   string
		IpPrefixLen int
		Gateway     string
		Bridge      string
		Ports       map[string][]PortBinding
	}
	SysInitPath    string
	ResolvConfPath string
	Volumes        map[string]string
	HostConfig     *HostConfig
}

type ContainerChanges struct {
	Path string
	Kind int
}

type Port struct {
	IP          string
	PrivatePort int
	PublicPort  int
	Type        string
}

type Container struct {
	Id         string
	Names      []string
	Image      string
	Command    string
	Created    int64
	Status     string
	Ports      []Port
	SizeRw     int64
	SizeRootFs int64
}

type Event struct {
	Id     string
	Status string
	From   string
	Time   int64
}

type Version struct {
	Version   string
	GitCommit string
	GoVersion string
}

type RespContainersCreate struct {
	Id       string
	Warnings []string
}

type Image struct {
	Created     int64
	Id          string
	ParentId    string
	RepoTags    []string
	Size        int64
	VirtualSize int64
}

type Info struct {
	ID              string
	Containers      int64
	Driver          string
	DriverStatus    [][]string
	ExecutionDriver string
	Images          int64
	KernelVersion   string
	OperatingSystem string
	NCPU            int64
	MemTotal        int64
	Name            string
	Labels          []string
}

type ImageDelete struct {
	Deleted  string
	Untagged string
}

type StatsOrError struct {
	Stats
	Error error
}

type EventOrError struct {
	Event
	Error error
}

type decodingResult struct {
	result interface{}
	err    error
}

// The following are types for the API stats endpoint
type ThrottlingData struct {
	// Number of periods with throttling active
	Periods uint64 `json:"periods"`
	// Number of periods when the container hit its throttling limit.
	ThrottledPeriods uint64 `json:"throttled_periods"`
	// Aggregate time the container was throttled for in nanoseconds.
	ThrottledTime uint64 `json:"throttled_time"`
}

// All CPU stats are aggregated since container inception.
type CpuUsage struct {
	// Total CPU time consumed.
	// Units: nanoseconds.
	TotalUsage uint64 `json:"total_usage"`
	// Total CPU time consumed per core.
	// Units: nanoseconds.
	PercpuUsage []uint64 `json:"percpu_usage"`
	// Time spent by tasks of the cgroup in kernel mode.
	// Units: nanoseconds.
	UsageInKernelmode uint64 `json:"usage_in_kernelmode"`
	// Time spent by tasks of the cgroup in user mode.
	// Units: nanoseconds.
	UsageInUsermode uint64 `json:"usage_in_usermode"`
}

type CpuStats struct {
	CpuUsage       CpuUsage       `json:"cpu_usage"`
	SystemUsage    uint64         `json:"system_cpu_usage"`
	ThrottlingData ThrottlingData `json:"throttling_data,omitempty"`
}

type NetworkStats struct {
	RxBytes   uint64 `json:"rx_bytes"`
	RxPackets uint64 `json:"rx_packets"`
	RxErrors  uint64 `json:"rx_errors"`
	RxDropped uint64 `json:"rx_dropped"`
	TxBytes   uint64 `json:"tx_bytes"`
	TxPackets uint64 `json:"tx_packets"`
	TxErrors  uint64 `json:"tx_errors"`
	TxDropped uint64 `json:"tx_dropped"`
}

type MemoryStats struct {
	Usage    uint64            `json:"usage"`
	MaxUsage uint64            `json:"max_usage"`
	Stats    map[string]uint64 `json:"stats"`
	Failcnt  uint64            `json:"failcnt"`
	Limit    uint64            `json:"limit"`
}

type BlkioStatEntry struct {
	Major uint64 `json:"major"`
	Minor uint64 `json:"minor"`
	Op    string `json:"op"`
	Value uint64 `json:"value"`
}

type BlkioStats struct {
	// number of bytes tranferred to and from the block device
	IoServiceBytesRecursive []BlkioStatEntry `json:"io_service_bytes_recursive"`
	IoServicedRecursive     []BlkioStatEntry `json:"io_serviced_recursive"`
	IoQueuedRecursive       []BlkioStatEntry `json:"io_queue_recursive"`
	IoServiceTimeRecursive  []BlkioStatEntry `json:"io_service_time_recursive"`
	IoWaitTimeRecursive     []BlkioStatEntry `json:"io_wait_time_recursive"`
	IoMergedRecursive       []BlkioStatEntry `json:"io_merged_recursive"`
	IoTimeRecursive         []BlkioStatEntry `json:"io_time_recursive"`
	SectorsRecursive        []BlkioStatEntry `json:"sectors_recursive"`
}

type Stats struct {
	Read         time.Time    `json:"read"`
	NetworkStats NetworkStats `json:"network,omitempty"`
	CpuStats     CpuStats     `json:"cpu_stats,omitempty"`
	MemoryStats  MemoryStats  `json:"memory_stats,omitempty"`
	BlkioStats   BlkioStats   `json:"blkio_stats,omitempty"`
}
<commit_msg>add more fields to Info struct<commit_after>package dockerclient

import (
	"time"
)

type ContainerConfig struct {
	Hostname        string
	Domainname      string
	User            string
	Memory          int64
	MemorySwap      int64
	CpuShares       int64
	Cpuset          string
	AttachStdin     bool
	AttachStdout    bool
	AttachStderr    bool
	PortSpecs       []string
	ExposedPorts    map[string]struct{}
	Tty             bool
	OpenStdin       bool
	StdinOnce       bool
	Env             []string
	Cmd             []string
	Image           string
	Labels          map[string]string
	Volumes         map[string]struct{}
	WorkingDir      string
	Entrypoint      []string
	NetworkDisabled bool
	OnBuild         []string

	// This is used only by the create command
	HostConfig HostConfig
}

type HostConfig struct {
	Binds           []string
	ContainerIDFile string
	LxcConf         []map[string]string
	Privileged      bool
	PortBindings    map[string][]PortBinding
	Links           []string
	PublishAllPorts bool
	Dns             []string
	DnsSearch       []string
	VolumesFrom     []string
	SecurityOpt     []string
	NetworkMode     string
	RestartPolicy   RestartPolicy
}

type ExecConfig struct {
	AttachStdin  bool
	AttachStdout bool
	AttachStderr bool
	Tty          bool
	Cmd          []string
	Container    string
	Detach       bool
}

type LogOptions struct {
	Follow     bool
	Stdout     bool
	Stderr     bool
	Timestamps bool
	Tail       int64
}

type MonitorEventsFilters struct {
	Event     string `json:",omitempty"`
	Image     string `json:",omitempty"`
	Container string `json:",omitempty"`
}

type MonitorEventsOptions struct {
	Since   int
	Until   int
	Filters *MonitorEventsFilters `json:",omitempty"`
}

type RestartPolicy struct {
	Name              string
	MaximumRetryCount int64
}

type PortBinding struct {
	HostIp   string
	HostPort string
}

type ContainerInfo struct {
	Id      string
	Created string
	Path    string
	Name    string
	Args    []string
	ExecIDs []string
	Config  *ContainerConfig
	State   struct {
		Running    bool
		Paused     bool
		Restarting bool
		Pid        int
		ExitCode   int
		StartedAt  time.Time
		FinishedAt time.Time
		Ghost      bool
	}
	Image           string
	NetworkSettings struct {
		IpAddress   string
		IpPrefixLen int
		Gateway     string
		Bridge      string
		Ports       map[string][]PortBinding
	}
	SysInitPath    string
	ResolvConfPath string
	Volumes        map[string]string
	HostConfig     *HostConfig
}

type ContainerChanges struct {
	Path string
	Kind int
}

type Port struct {
	IP          string
	PrivatePort int
	PublicPort  int
	Type        string
}

type Container struct {
	Id         string
	Names      []string
	Image      string
	Command    string
	Created    int64
	Status     string
	Ports      []Port
	SizeRw     int64
	SizeRootFs int64
}

type Event struct {
	Id     string
	Status string
	From   string
	Time   int64
}

type Version struct {
	Version   string
	GitCommit string
	GoVersion string
}

type RespContainersCreate struct {
	Id       string
	Warnings []string
}

type Image struct {
	Created     int64
	Id          string
	ParentId    string
	RepoTags    []string
	Size        int64
	VirtualSize int64
}

type Info struct {
	ID                 string
	Containers         int64
	Driver             string
	DriverStatus       [][]string
	ExecutionDriver    string
	Images             int64
	KernelVersion      string
	OperatingSystem    string
	NCPU               int64
	MemTotal           int64
	Name               string
	Labels             []string
	Debug              interface{} // should be a bool but is sometimes an int
	NFd                int64
	NGoroutines        int64
	SystemTime         time.Time
	NEventsListener    int64
	InitPath           string
	InitSha1           string
	IndexServerAddress string
	MemoryLimit        interface{} // should be a bool but is sometimes an int
	SwapLimit          interface{} // should be a bool but is sometimes an int
	IPv4Forwarding     interface{} // should be a bool but is sometimes an int
	DockerRootDir      string
	HttpProxy          string
	HttpsProxy         string
	NoProxy            string
}

type ImageDelete struct {
	Deleted  string
	Untagged string
}

type StatsOrError struct {
	Stats
	Error error
}

type EventOrError struct {
	Event
	Error error
}

type decodingResult struct {
	result interface{}
	err    error
}

// The following are types for the API stats endpoint
type ThrottlingData struct {
	// Number of periods with throttling active
	Periods uint64 `json:"periods"`
	// Number of periods when the container hit its throttling limit.
	ThrottledPeriods uint64 `json:"throttled_periods"`
	// Aggregate time the container was throttled for in nanoseconds.
	ThrottledTime uint64 `json:"throttled_time"`
}

// All CPU stats are aggregated since container inception.
type CpuUsage struct {
	// Total CPU time consumed.
	// Units: nanoseconds.
	TotalUsage uint64 `json:"total_usage"`
	// Total CPU time consumed per core.
	// Units: nanoseconds.
	PercpuUsage []uint64 `json:"percpu_usage"`
	// Time spent by tasks of the cgroup in kernel mode.
	// Units: nanoseconds.
	UsageInKernelmode uint64 `json:"usage_in_kernelmode"`
	// Time spent by tasks of the cgroup in user mode.
	// Units: nanoseconds.
	UsageInUsermode uint64 `json:"usage_in_usermode"`
}

type CpuStats struct {
	CpuUsage       CpuUsage       `json:"cpu_usage"`
	SystemUsage    uint64         `json:"system_cpu_usage"`
	ThrottlingData ThrottlingData `json:"throttling_data,omitempty"`
}

type NetworkStats struct {
	RxBytes   uint64 `json:"rx_bytes"`
	RxPackets uint64 `json:"rx_packets"`
	RxErrors  uint64 `json:"rx_errors"`
	RxDropped uint64 `json:"rx_dropped"`
	TxBytes   uint64 `json:"tx_bytes"`
	TxPackets uint64 `json:"tx_packets"`
	TxErrors  uint64 `json:"tx_errors"`
	TxDropped uint64 `json:"tx_dropped"`
}

type MemoryStats struct {
	Usage    uint64            `json:"usage"`
	MaxUsage uint64            `json:"max_usage"`
	Stats    map[string]uint64 `json:"stats"`
	Failcnt  uint64            `json:"failcnt"`
	Limit    uint64            `json:"limit"`
}

type BlkioStatEntry struct {
	Major uint64 `json:"major"`
	Minor uint64 `json:"minor"`
	Op    string `json:"op"`
	Value uint64 `json:"value"`
}

type BlkioStats struct {
	// number of bytes tranferred to and from the block device
	IoServiceBytesRecursive []BlkioStatEntry `json:"io_service_bytes_recursive"`
	IoServicedRecursive     []BlkioStatEntry `json:"io_serviced_recursive"`
	IoQueuedRecursive       []BlkioStatEntry `json:"io_queue_recursive"`
	IoServiceTimeRecursive  []BlkioStatEntry `json:"io_service_time_recursive"`
	IoWaitTimeRecursive     []BlkioStatEntry `json:"io_wait_time_recursive"`
	IoMergedRecursive       []BlkioStatEntry `json:"io_merged_recursive"`
	IoTimeRecursive         []BlkioStatEntry `json:"io_time_recursive"`
	SectorsRecursive        []BlkioStatEntry `json:"sectors_recursive"`
}

type Stats struct {
	Read         time.Time    `json:"read"`
	NetworkStats NetworkStats `json:"network,omitempty"`
	CpuStats     CpuStats     `json:"cpu_stats,omitempty"`
	MemoryStats  MemoryStats  `json:"memory_stats,omitempty"`
	BlkioStats   BlkioStats   `json:"blkio_stats,omitempty"`
}
<|endoftext|>


<commit_before>package goslackbot

type SlackUser struct {
	ID           string           `json:"id"`
	Name         string           `json:"name"`
	Profile      SlackUserProfile `json:"profile"`
	IsAdmin      bool             `json:"is_admin"`
	IsOwner      bool             `json:"is_owner"`
	IsRestricted bool             `json:"is_restricted"`
	Has2FA       bool             `json:"has_2fa"`
}

type SlackUserProfile struct {
	FirstName string `json:"first_name"`
	LastName  string `json:"last_name"`
	RealName  string `json:"real_name"`
	Email     string `json:"email"`
	Skype     string `json:"skype"`
	Phone     string `json:"phone"`
}

type SlackChannel struct {
	ID         string `json:"id"`
	Name       string `json:"name"`
	IsArchived bool   `json:"is_archived"`
}

type SlackRTMResponse struct {
	Ok       bool                 `json:"ok"`
	Error    string               `json:"error"`
	Url      string               `json:"url"`
	Self     SlackRTMResponseSelf `json:"self"`
	Users    []SlackUser          `json:"users"`
	Channels []SlackChannel       `json:"channels"`
	MPIMs    []SlackChannel       `jsonL:"mpims"`
	Groups   []SlackChannel       `json:"groups"`
}

type SlackRTMResponseSelf struct {
	Id string `json:"id"`
}

type SlackMessage struct {
	Id        uint64           `json:"id"`
	Type      string           `json:"type"`
	SubType   string           `json:"sub_type"`
	Channel   string           `json:"channel"`
	Text      string           `json:"text"`
	User      string           `json:"user"`
	ReplyTo   uint64           `json:"reply_to, omitempty"`
	TimeStamp string           `json:"ts, omitempty"`
	Item      SlackMessageItem `json:"item, omitempty"`
	Name      string           `json:"name, omitempty"`
	Reaction  string           `json:"reaction, omitempty"`
}

type SlackMessageItem struct {
	Type      string `json:"type"`
	Channel   string `json:"channel"`
	TimeStamp string `json:"ts"`
}
<commit_msg>add SlackTeam to types and Name to field to Self<commit_after>package goslackbot

type SlackUser struct {
	ID           string           `json:"id"`
	Name         string           `json:"name"`
	Profile      SlackUserProfile `json:"profile"`
	IsAdmin      bool             `json:"is_admin"`
	IsOwner      bool             `json:"is_owner"`
	IsRestricted bool             `json:"is_restricted"`
	Has2FA       bool             `json:"has_2fa"`
}

type SlackUserProfile struct {
	FirstName string `json:"first_name"`
	LastName  string `json:"last_name"`
	RealName  string `json:"real_name"`
	Email     string `json:"email"`
	Skype     string `json:"skype"`
	Phone     string `json:"phone"`
}

type SlackChannel struct {
	ID         string `json:"id"`
	Name       string `json:"name"`
	IsArchived bool   `json:"is_archived"`
}

type SlackRTMResponse struct {
	Ok       bool                 `json:"ok"`
	Error    string               `json:"error"`
	Url      string               `json:"url"`
	Self     SlackRTMResponseSelf `json:"self"`
	Users    []SlackUser          `json:"users"`
	Channels []SlackChannel       `json:"channels"`
	MPIMs    []SlackChannel       `jsonL:"mpims"`
	Groups   []SlackChannel       `json:"groups"`
}

type SlackRTMResponseSelf struct {
	Id   string `json:"id"`
	Name string `json:"name"`
}

type SlackMessage struct {
	Id        uint64           `json:"id"`
	Type      string           `json:"type"`
	SubType   string           `json:"sub_type"`
	Channel   string           `json:"channel"`
	Text      string           `json:"text"`
	User      string           `json:"user"`
	ReplyTo   uint64           `json:"reply_to, omitempty"`
	TimeStamp string           `json:"ts, omitempty"`
	Item      SlackMessageItem `json:"item, omitempty"`
	Name      string           `json:"name, omitempty"`
	Reaction  string           `json:"reaction, omitempty"`
}

type SlackMessageItem struct {
	Type      string `json:"type"`
	Channel   string `json:"channel"`
	TimeStamp string `json:"ts"`
}

type SlackTeam struct {
	Id          uint64 `json:"id"`
	Name        string `json:"name"`
	EmailDomain string `json:"email_domain"`
	Domain      string `json:"domain"`
}
<|endoftext|>


<commit_before>// the udger package allow you to load in memory and lookup the user agent database to extract value from the provided user agent
package udger

import (
	"database/sql"
	"errors"
	"os"
	"strings"

	"github.com/glenn-brown/golang-pkg-pcre/src/pkg/pcre"
	_ "github.com/mattn/go-sqlite3"
)

// create a new instance of Udger and load all the database in memory to allow fast lookup
// you need to pass the sqlite database in parameter
func New(dbPath string) (*Udger, error) {
	u := &Udger{
		Browsers:     make(map[int]Browser),
		OS:           make(map[int]OS),
		Devices:      make(map[int]Device),
		browserTypes: make(map[int]string),
		browserOS:    make(map[int]int),
	}
	var err error

	if _, err := os.Stat(dbPath); os.IsNotExist(err) {
		return nil, err
	}

	u.db, err = sql.Open("sqlite3", dbPath)
	if err != nil {
		return nil, err
	}
	defer u.db.Close()

	err = u.init()
	if err != nil {
		return nil, err
	}

	return u, nil
}

// lookup one user agent and return a Info struct who contains all the metadata possible for the UA.
func (this *Udger) Lookup(ua string) (*Info, error) {
	info := &Info{}

	browserId, err := this.findData(ua, this.rexBrowsers)
	if err != nil {
		return nil, err
	}

	info.Browser = this.Browsers[browserId]
	info.Browser.Type = this.browserTypes[info.Browser.typ]

	if val, ok := this.browserOS[browserId]; ok {
		info.OS = this.OS[val]
	} else {
		osId, err := this.findData(ua, this.rexOS)
		if err != nil {
			return nil, err
		}
		info.OS = this.OS[osId]
	}

	deviceId, err := this.findData(ua, this.rexDevices)
	if err != nil {
		return nil, err
	}
	if val, ok := this.Devices[deviceId]; ok {
		info.Device = val
	} else if info.Browser.typ == 3 { // if browser if mobile, we can guess its a mobile
		info.Device = Device{
			Name: "Smartphone",
			Icon: "phone.png",
		}
	}

	return info, nil
}

func (this *Udger) cleanRegex(r string) string {
	if strings.HasSuffix(r, "/si") {
		r = r[:len(r)-3]
	}
	if strings.HasPrefix(r, "/") {
		r = r[1:]
	}

	return r
}

func (this *Udger) findData(ua string, data []rexData) (int, error) {
	for i := 0; i < len(data); i++ {
		data[i].Regex = this.cleanRegex(data[i].Regex)
		r, err := pcre.Compile(data[i].Regex, pcre.CASELESS)
		if err != nil {
			return -1, errors.New(err.String())
		}
		matcher := r.MatcherString(ua, 0)
		match := matcher.MatchString(ua, 0)
		if !match {
			continue
		}
		return data[i].Id, nil
	}

	return -1, nil
}

func (this *Udger) init() error {
	rows, err := this.db.Query("SELECT browser, regstring FROM reg_browser ORDER by sequence ASC")
	if err != nil {
		return err
	}
	for rows.Next() {
		var d rexData
		rows.Scan(&d.Id, &d.Regex)
		this.rexBrowsers = append(this.rexBrowsers, d)
	}
	rows.Close()

	rows, err = this.db.Query("SELECT device, regstring FROM reg_device ORDER by sequence ASC")
	if err != nil {
		return err
	}
	for rows.Next() {
		var d rexData
		rows.Scan(&d.Id, &d.Regex)
		this.rexDevices = append(this.rexDevices, d)
	}
	rows.Close()

	rows, err = this.db.Query("SELECT os, regstring FROM reg_os ORDER by sequence ASC")
	if err != nil {
		return err
	}
	for rows.Next() {
		var d rexData
		rows.Scan(&d.Id, &d.Regex)
		this.rexOS = append(this.rexOS, d)
	}
	rows.Close()

	rows, err = this.db.Query("SELECT id,type,name,engine,company,icon FROM c_browser")
	if err != nil {
		return err
	}
	for rows.Next() {
		var d Browser
		var id int
		rows.Scan(&id, &d.typ, &d.Name, &d.Engine, &d.Company, &d.Icon)
		this.Browsers[id] = d
	}
	rows.Close()

	rows, err = this.db.Query("SELECT id, name, family, company, icon FROM c_os")
	if err != nil {
		return err
	}
	for rows.Next() {
		var d OS
		var id int
		rows.Scan(&id, &d.Name, &d.Family, &d.Company, &d.Icon)
		this.OS[id] = d
	}
	rows.Close()

	rows, err = this.db.Query("SELECT id, name, icon FROM c_device")
	if err != nil {
		return err
	}
	for rows.Next() {
		var d Device
		var id int
		rows.Scan(&id, &d.Name, &d.Icon)
		this.Devices[id] = d
	}
	rows.Close()

	rows, err = this.db.Query("SELECT type, name FROM c_browser_type")
	if err != nil {
		return err
	}
	for rows.Next() {
		var d string
		var id int
		rows.Scan(&id, &d)
		this.browserTypes[id] = d
	}
	rows.Close()

	rows, err = this.db.Query("SELECT browser, os FROM c_browser_os")
	if err != nil {
		return err
	}
	for rows.Next() {
		var browser int
		var os int
		rows.Scan(&browser, &os)
		this.browserOS[browser] = os
	}
	rows.Close()

	return nil
}
<commit_msg>add gestion of the device type in case of personal computer<commit_after>// the udger package allow you to load in memory and lookup the user agent database to extract value from the provided user agent
package udger

import (
	"database/sql"
	"errors"
	"os"
	"strings"

	"github.com/glenn-brown/golang-pkg-pcre/src/pkg/pcre"
	_ "github.com/mattn/go-sqlite3"
)

// create a new instance of Udger and load all the database in memory to allow fast lookup
// you need to pass the sqlite database in parameter
func New(dbPath string) (*Udger, error) {
	u := &Udger{
		Browsers:     make(map[int]Browser),
		OS:           make(map[int]OS),
		Devices:      make(map[int]Device),
		browserTypes: make(map[int]string),
		browserOS:    make(map[int]int),
	}
	var err error

	if _, err := os.Stat(dbPath); os.IsNotExist(err) {
		return nil, err
	}

	u.db, err = sql.Open("sqlite3", dbPath)
	if err != nil {
		return nil, err
	}
	defer u.db.Close()

	err = u.init()
	if err != nil {
		return nil, err
	}

	return u, nil
}

// lookup one user agent and return a Info struct who contains all the metadata possible for the UA.
func (this *Udger) Lookup(ua string) (*Info, error) {
	info := &Info{}

	browserId, err := this.findData(ua, this.rexBrowsers)
	if err != nil {
		return nil, err
	}

	info.Browser = this.Browsers[browserId]
	info.Browser.Type = this.browserTypes[info.Browser.typ]

	if val, ok := this.browserOS[browserId]; ok {
		info.OS = this.OS[val]
	} else {
		osId, err := this.findData(ua, this.rexOS)
		if err != nil {
			return nil, err
		}
		info.OS = this.OS[osId]
	}

	deviceId, err := this.findData(ua, this.rexDevices)
	if err != nil {
		return nil, err
	}
	if val, ok := this.Devices[deviceId]; ok {
		info.Device = val
	} else if info.Browser.typ == 3 { // if browser is mobile, we can guess its a mobile
		info.Device = Device{
			Name: "Smartphone",
			Icon: "phone.png",
		}
	} else {
		//nothing so personal computer
		info.Device = Device{
			Name: "Personal computer",
			Icon: "desktop.png",
		}
	}

	return info, nil
}

func (this *Udger) cleanRegex(r string) string {
	if strings.HasSuffix(r, "/si") {
		r = r[:len(r)-3]
	}
	if strings.HasPrefix(r, "/") {
		r = r[1:]
	}

	return r
}

func (this *Udger) findData(ua string, data []rexData) (int, error) {
	for i := 0; i < len(data); i++ {
		data[i].Regex = this.cleanRegex(data[i].Regex)
		r, err := pcre.Compile(data[i].Regex, pcre.CASELESS)
		if err != nil {
			return -1, errors.New(err.String())
		}
		matcher := r.MatcherString(ua, 0)
		match := matcher.MatchString(ua, 0)
		if !match {
			continue
		}
		return data[i].Id, nil
	}

	return -1, nil
}

func (this *Udger) init() error {
	rows, err := this.db.Query("SELECT browser, regstring FROM reg_browser ORDER by sequence ASC")
	if err != nil {
		return err
	}
	for rows.Next() {
		var d rexData
		rows.Scan(&d.Id, &d.Regex)
		this.rexBrowsers = append(this.rexBrowsers, d)
	}
	rows.Close()

	rows, err = this.db.Query("SELECT device, regstring FROM reg_device ORDER by sequence ASC")
	if err != nil {
		return err
	}
	for rows.Next() {
		var d rexData
		rows.Scan(&d.Id, &d.Regex)
		this.rexDevices = append(this.rexDevices, d)
	}
	rows.Close()

	rows, err = this.db.Query("SELECT os, regstring FROM reg_os ORDER by sequence ASC")
	if err != nil {
		return err
	}
	for rows.Next() {
		var d rexData
		rows.Scan(&d.Id, &d.Regex)
		this.rexOS = append(this.rexOS, d)
	}
	rows.Close()

	rows, err = this.db.Query("SELECT id,type,name,engine,company,icon FROM c_browser")
	if err != nil {
		return err
	}
	for rows.Next() {
		var d Browser
		var id int
		rows.Scan(&id, &d.typ, &d.Name, &d.Engine, &d.Company, &d.Icon)
		this.Browsers[id] = d
	}
	rows.Close()

	rows, err = this.db.Query("SELECT id, name, family, company, icon FROM c_os")
	if err != nil {
		return err
	}
	for rows.Next() {
		var d OS
		var id int
		rows.Scan(&id, &d.Name, &d.Family, &d.Company, &d.Icon)
		this.OS[id] = d
	}
	rows.Close()

	rows, err = this.db.Query("SELECT id, name, icon FROM c_device")
	if err != nil {
		return err
	}
	for rows.Next() {
		var d Device
		var id int
		rows.Scan(&id, &d.Name, &d.Icon)
		this.Devices[id] = d
	}
	rows.Close()

	rows, err = this.db.Query("SELECT type, name FROM c_browser_type")
	if err != nil {
		return err
	}
	for rows.Next() {
		var d string
		var id int
		rows.Scan(&id, &d)
		this.browserTypes[id] = d
	}
	rows.Close()

	rows, err = this.db.Query("SELECT browser, os FROM c_browser_os")
	if err != nil {
		return err
	}
	for rows.Next() {
		var browser int
		var os int
		rows.Scan(&browser, &os)
		this.browserOS[browser] = os
	}
	rows.Close()

	return nil
}
<|endoftext|>


<commit_before>package main

import (
	"flag"
	"fmt"
	"log"
	"os"
	"strconv"
)

import (
	"github.com/sternix/commands/lib/sysctl"
)

const (
	MFLAG = 1 << iota
	NFLAG
	PFLAG
	RFLAG
	SFLAG
	VFLAG
	IFLAG
	KFLAG
)

var (
	allFlag      = flag.Bool("a", false, "Behave as though the options -m, -n, -r, -s, and -v were specified.")
	identFlag    = flag.Bool("i", false, "Write the kernel ident to standard output.")
	platformFlag = flag.Bool("m", false, "Write the type of the current hardware platform to standard output.")
	hostnameFlag = flag.Bool("n", false, "Write the name of the system to standard output.")
	osnameFlag   = flag.Bool("o", false, "This is a synonym for the -s option, for compatibility with other systems.")
	archFlag     = flag.Bool("p", false, "Write the type of the machine processor architecture to standard output.")
	releaseFlag  = flag.Bool("r", false, "Write the current release level of the operating system to standard output.")
	sysnameFlag  = flag.Bool("s", false, "Write the name of the operating system implementation to standard output.")
	versionFlag  = flag.Bool("v", false, "Write the version level of this release of the operating system to standard output.")
	kernversFlag = flag.Bool("K", false, "Write the FreeBSD version of the kernel.")
)

func init() {
	log.SetFlags(0)
	log.SetOutput(os.Stderr)
}

func main() {
	flag.Usage = usage
	flag.Parse()

	var flags int

	if *allFlag {
		flags |= (MFLAG | NFLAG | RFLAG | SFLAG | VFLAG)
	}

	if *identFlag {
		flags |= IFLAG
	}

	if *osnameFlag || *sysnameFlag {
		flags |= SFLAG
	}

	if *platformFlag {
		flags |= MFLAG
	}

	if *hostnameFlag {
		flags |= NFLAG
	}

	if *archFlag {
		flags |= PFLAG
	}

	if *releaseFlag {
		flags |= RFLAG
	}

	if *versionFlag {
		flags |= VFLAG
	}

	if *kernversFlag {
		flags |= KFLAG
	}

	if flags == 0 {
		flags |= SFLAG
	}

	printUname(flags)
}

var isPrinted bool

func printFlag(flags, flg int, envVar, sysctlName string, fn func(string, string) string) {
	if flags&flg == flg {
		if isPrinted {
			fmt.Print(" ")
		}

		fmt.Print(fn(envVar, sysctlName))
		isPrinted = true
	}
}

func printUname(flags int) {
	printFlag(flags, SFLAG, "s", "kern.ostype", getValue)
	printFlag(flags, NFLAG, "n", "kern.hostname", getValue)
	printFlag(flags, RFLAG, "r", "kern.osrelease", getValue)
	printFlag(flags, VFLAG, "v", "kern.version", getVersion)
	printFlag(flags, MFLAG, "m", "hw.machine", getValue)
	printFlag(flags, PFLAG, "p", "hw.machine_arch", getValue)
	printFlag(flags, IFLAG, "i", "kern.ident", getValue)
	printFlag(flags, KFLAG, "K", "kern.osreldate", getIntValue)

	fmt.Println()
}

func isEnvSet(flg string) (bool, string) {
	if val := os.Getenv("UNAME_" + flg); val != "" {
		return true, val
	} else {
		return false, ""
	}
}

func getSysctl(sysctlName string) string {
	if val, err := sysctl.ByName(sysctlName); err != nil {
		log.Fatalf("%s - %v\n", sysctlName, err)
		return "" //NOTREACHED
	} else {
		return val
	}
}

func getSysctlUint32AsString(sysctlName string) string {
	if ret, err := sysctl.Uint32(sysctlName); err != nil {
		log.Fatalf("%s - %v", sysctlName, err)
		return "" //NOTREACHED
	} else {
		return strconv.FormatUint(uint64(ret), 10)
	}
}

func getValue(envVar, sysctlName string) string {
	if yes, envVal := isEnvSet(envVar); yes {
		return envVal
	} else {
		return getSysctl(sysctlName)
	}
}

func getIntValue(envVar, sysctlName string) string {
	if yes, envVal := isEnvSet(envVar); yes {
		return envVal
	} else {
		return getSysctlUint32AsString(sysctlName)
	}
}

func getVersion(envVar, sysctlName string) string {
	if yes, envVal := isEnvSet(envVar); yes {
		return envVal
	} else {
		version := []byte(getSysctl(sysctlName))
		for i, r := range version {
			if r == '\n' || r == '\t' {
				version[i] = ' '
			}
		}

		return string(version)
	}
}

func usage() {
	log.Fatalln("usage: uname [-aiKmnoprsUv]")
}
<commit_msg>use sysctl.Raw<commit_after>package main

import (
	"flag"
	"fmt"
	"log"
	"os"
	"strconv"
)

import (
	"github.com/sternix/commands/lib/sysctl"
)

const (
	MFLAG = 1 << iota
	NFLAG
	PFLAG
	RFLAG
	SFLAG
	VFLAG
	IFLAG
	KFLAG
)

var (
	allFlag      = flag.Bool("a", false, "Behave as though the options -m, -n, -r, -s, and -v were specified.")
	identFlag    = flag.Bool("i", false, "Write the kernel ident to standard output.")
	platformFlag = flag.Bool("m", false, "Write the type of the current hardware platform to standard output.")
	hostnameFlag = flag.Bool("n", false, "Write the name of the system to standard output.")
	osnameFlag   = flag.Bool("o", false, "This is a synonym for the -s option, for compatibility with other systems.")
	archFlag     = flag.Bool("p", false, "Write the type of the machine processor architecture to standard output.")
	releaseFlag  = flag.Bool("r", false, "Write the current release level of the operating system to standard output.")
	sysnameFlag  = flag.Bool("s", false, "Write the name of the operating system implementation to standard output.")
	versionFlag  = flag.Bool("v", false, "Write the version level of this release of the operating system to standard output.")
	kernversFlag = flag.Bool("K", false, "Write the FreeBSD version of the kernel.")
)

func init() {
	log.SetFlags(0)
	log.SetOutput(os.Stderr)
}

func main() {
	flag.Usage = usage
	flag.Parse()

	var flags int

	if *allFlag {
		flags |= (MFLAG | NFLAG | RFLAG | SFLAG | VFLAG)
	}

	if *identFlag {
		flags |= IFLAG
	}

	if *osnameFlag || *sysnameFlag {
		flags |= SFLAG
	}

	if *platformFlag {
		flags |= MFLAG
	}

	if *hostnameFlag {
		flags |= NFLAG
	}

	if *archFlag {
		flags |= PFLAG
	}

	if *releaseFlag {
		flags |= RFLAG
	}

	if *versionFlag {
		flags |= VFLAG
	}

	if *kernversFlag {
		flags |= KFLAG
	}

	if flags == 0 {
		flags |= SFLAG
	}

	printUname(flags)
}

var isPrinted bool

func printFlag(flags, flg int, envVar, sysctlName string, fn func(string, string) string) {
	if flags&flg == flg {
		if isPrinted {
			fmt.Print(" ")
		}

		fmt.Print(fn(envVar, sysctlName))
		isPrinted = true
	}
}

func printUname(flags int) {
	printFlag(flags, SFLAG, "s", "kern.ostype", getValue)
	printFlag(flags, NFLAG, "n", "kern.hostname", getValue)
	printFlag(flags, RFLAG, "r", "kern.osrelease", getValue)
	printFlag(flags, VFLAG, "v", "kern.version", getVersion)
	printFlag(flags, MFLAG, "m", "hw.machine", getValue)
	printFlag(flags, PFLAG, "p", "hw.machine_arch", getValue)
	printFlag(flags, IFLAG, "i", "kern.ident", getValue)
	printFlag(flags, KFLAG, "K", "kern.osreldate", getIntValue)

	fmt.Println()
}

func isEnvSet(flg string) (bool, string) {
	if val := os.Getenv("UNAME_" + flg); val != "" {
		return true, val
	} else {
		return false, ""
	}
}

func getSysctl(sysctlName string) string {
	if val, err := sysctl.ByName(sysctlName); err != nil {
		log.Fatalf("%s - %v\n", sysctlName, err)
		return "" //NOTREACHED
	} else {
		return val
	}
}

func getSysctlUint32AsString(sysctlName string) string {
	if ret, err := sysctl.Uint32(sysctlName); err != nil {
		log.Fatalf("%s - %v\n", sysctlName, err)
		return "" //NOTREACHED
	} else {
		return strconv.FormatUint(uint64(ret), 10)
	}
}

func getValue(envVar, sysctlName string) string {
	if yes, envVal := isEnvSet(envVar); yes {
		return envVal
	} else {
		return getSysctl(sysctlName)
	}
}

func getIntValue(envVar, sysctlName string) string {
	if yes, envVal := isEnvSet(envVar); yes {
		return envVal
	} else {
		return getSysctlUint32AsString(sysctlName)
	}
}

func getVersion(envVar, sysctlName string) string {
	if yes, envVal := isEnvSet(envVar); yes {
		return envVal
	} else {
		version, err := sysctl.Raw(sysctlName)
		if err != nil {
			log.Fatalf("%s - %v\n", sysctlName, err)
		}

		for i, r := range version {
			if r == '\n' || r == '\t' {
				version[i] = ' '
			}
		}

		return string(version)
	}
}

func usage() {
	log.Fatalln("usage: uname [-aiKmnoprsUv]")
}
<|endoftext|>