Skip to content

Commit

Permalink
feat: GetAppPreferences and more methods (#18)
Browse files Browse the repository at this point in the history
* AppPreferences

* add AppPreferences method

* flip apps

* implement torrentProperties

* implement GetTorrentProperties

* never forget the s

* buildfix

* Update domain.go

* properly close multipartWriter
  • Loading branch information
KyleSanderson authored Dec 14, 2023
1 parent a65a609 commit afb56af
Show file tree
Hide file tree
Showing 3 changed files with 277 additions and 2 deletions.
220 changes: 220 additions & 0 deletions domain.go
Original file line number Diff line number Diff line change
Expand Up @@ -342,3 +342,223 @@ type TorrentFilterOptions struct {
Offset int
Hashes []string
}

type TorrentProperties struct {
AdditionDate int `json:"addition_date"`
Comment string `json:"comment"`
CompletionDate int `json:"completion_date"`
CreatedBy string `json:"created_by"`
CreationDate int `json:"creation_date"`
DlLimit int `json:"dl_limit"`
DlSpeed int `json:"dl_speed"`
DlSpeedAvg int `json:"dl_speed_avg"`
DownloadPath string `json:"download_path"`
Eta int `json:"eta"`
Hash string `json:"hash"`
InfohashV1 string `json:"infohash_v1"`
InfohashV2 string `json:"infohash_v2"`
IsPrivate bool `json:"is_private"`
LastSeen int `json:"last_seen"`
Name string `json:"name"`
NbConnections int `json:"nb_connections"`
NbConnectionsLimit int `json:"nb_connections_limit"`
Peers int `json:"peers"`
PeersTotal int `json:"peers_total"`
PieceSize int `json:"piece_size"`
PiecesHave int `json:"pieces_have"`
PiecesNum int `json:"pieces_num"`
Reannounce int `json:"reannounce"`
SavePath string `json:"save_path"`
SeedingTime int `json:"seeding_time"`
Seeds int `json:"seeds"`
SeedsTotal int `json:"seeds_total"`
ShareRatio float64 `json:"share_ratio"`
TimeElapsed int `json:"time_elapsed"`
TotalDownloaded int64 `json:"total_downloaded"`
TotalDownloadedSession int64 `json:"total_downloaded_session"`
TotalSize int64 `json:"total_size"`
TotalUploaded int64 `json:"total_uploaded"`
TotalUploadedSession int64 `json:"total_uploaded_session"`
TotalWasted int64 `json:"total_wasted"`
UpLimit int `json:"up_limit"`
UpSpeed int `json:"up_speed"`
UpSpeedAvg int `json:"up_speed_avg"`
}

type AppPreferences struct {
AddTrackers string `json:"add_trackers"`
AddTrackersEnabled bool `json:"add_trackers_enabled"`
AltDlLimit int `json:"alt_dl_limit"`
AltUpLimit int `json:"alt_up_limit"`
AlternativeWebuiEnabled bool `json:"alternative_webui_enabled"`
AlternativeWebuiPath string `json:"alternative_webui_path"`
AnnounceIP string `json:"announce_ip"`
AnnounceToAllTiers bool `json:"announce_to_all_tiers"`
AnnounceToAllTrackers bool `json:"announce_to_all_trackers"`
AnonymousMode bool `json:"anonymous_mode"`
AsyncIoThreads int `json:"async_io_threads"`
AutoDeleteMode int `json:"auto_delete_mode"`
AutoTmmEnabled bool `json:"auto_tmm_enabled"`
AutorunEnabled bool `json:"autorun_enabled"`
AutorunOnTorrentAddedEnabled bool `json:"autorun_on_torrent_added_enabled"`
AutorunOnTorrentAddedProgram string `json:"autorun_on_torrent_added_program"`
AutorunProgram string `json:"autorun_program"`
BannedIPs string `json:"banned_IPs"`
BittorrentProtocol int `json:"bittorrent_protocol"`
BlockPeersOnPrivilegedPorts bool `json:"block_peers_on_privileged_ports"`
BypassAuthSubnetWhitelist string `json:"bypass_auth_subnet_whitelist"`
BypassAuthSubnetWhitelistEnabled bool `json:"bypass_auth_subnet_whitelist_enabled"`
BypassLocalAuth bool `json:"bypass_local_auth"`
CategoryChangedTmmEnabled bool `json:"category_changed_tmm_enabled"`
CheckingMemoryUse int `json:"checking_memory_use"`
ConnectionSpeed int `json:"connection_speed"`
CurrentInterfaceAddress string `json:"current_interface_address"`
CurrentNetworkInterface string `json:"current_network_interface"`
Dht bool `json:"dht"`
DiskCache int `json:"disk_cache"`
DiskCacheTTL int `json:"disk_cache_ttl"`
DiskIoReadMode int `json:"disk_io_read_mode"`
DiskIoType int `json:"disk_io_type"`
DiskIoWriteMode int `json:"disk_io_write_mode"`
DiskQueueSize int `json:"disk_queue_size"`
DlLimit int `json:"dl_limit"`
DontCountSlowTorrents bool `json:"dont_count_slow_torrents"`
DyndnsDomain string `json:"dyndns_domain"`
DyndnsEnabled bool `json:"dyndns_enabled"`
DyndnsPassword string `json:"dyndns_password"`
DyndnsService int `json:"dyndns_service"`
DyndnsUsername string `json:"dyndns_username"`
EmbeddedTrackerPort int `json:"embedded_tracker_port"`
EmbeddedTrackerPortForwarding bool `json:"embedded_tracker_port_forwarding"`
EnableCoalesceReadWrite bool `json:"enable_coalesce_read_write"`
EnableEmbeddedTracker bool `json:"enable_embedded_tracker"`
EnableMultiConnectionsFromSameIP bool `json:"enable_multi_connections_from_same_ip"`
EnablePieceExtentAffinity bool `json:"enable_piece_extent_affinity"`
EnableUploadSuggestions bool `json:"enable_upload_suggestions"`
Encryption int `json:"encryption"`
ExcludedFileNames string `json:"excluded_file_names"`
ExcludedFileNamesEnabled bool `json:"excluded_file_names_enabled"`
ExportDir string `json:"export_dir"`
ExportDirFin string `json:"export_dir_fin"`
FilePoolSize int `json:"file_pool_size"`
HashingThreads int `json:"hashing_threads"`
IdnSupportEnabled bool `json:"idn_support_enabled"`
IncompleteFilesExt bool `json:"incomplete_files_ext"`
IPFilterEnabled bool `json:"ip_filter_enabled"`
IPFilterPath string `json:"ip_filter_path"`
IPFilterTrackers bool `json:"ip_filter_trackers"`
LimitLanPeers bool `json:"limit_lan_peers"`
LimitTCPOverhead bool `json:"limit_tcp_overhead"`
LimitUtpRate bool `json:"limit_utp_rate"`
ListenPort int `json:"listen_port"`
Locale string `json:"locale"`
Lsd bool `json:"lsd"`
MailNotificationAuthEnabled bool `json:"mail_notification_auth_enabled"`
MailNotificationEmail string `json:"mail_notification_email"`
MailNotificationEnabled bool `json:"mail_notification_enabled"`
MailNotificationPassword string `json:"mail_notification_password"`
MailNotificationSender string `json:"mail_notification_sender"`
MailNotificationSMTP string `json:"mail_notification_smtp"`
MailNotificationSslEnabled bool `json:"mail_notification_ssl_enabled"`
MailNotificationUsername string `json:"mail_notification_username"`
MaxActiveCheckingTorrents int `json:"max_active_checking_torrents"`
MaxActiveDownloads int `json:"max_active_downloads"`
MaxActiveTorrents int `json:"max_active_torrents"`
MaxActiveUploads int `json:"max_active_uploads"`
MaxConcurrentHTTPAnnounces int `json:"max_concurrent_http_announces"`
MaxConnec int `json:"max_connec"`
MaxConnecPerTorrent int `json:"max_connec_per_torrent"`
MaxRatio int `json:"max_ratio"`
MaxRatioAct int `json:"max_ratio_act"`
MaxRatioEnabled bool `json:"max_ratio_enabled"`
MaxSeedingTime int `json:"max_seeding_time"`
MaxSeedingTimeEnabled bool `json:"max_seeding_time_enabled"`
MaxUploads int `json:"max_uploads"`
MaxUploadsPerTorrent int `json:"max_uploads_per_torrent"`
MemoryWorkingSetLimit int `json:"memory_working_set_limit"`
OutgoingPortsMax int `json:"outgoing_ports_max"`
OutgoingPortsMin int `json:"outgoing_ports_min"`
PeerTos int `json:"peer_tos"`
PeerTurnover int `json:"peer_turnover"`
PeerTurnoverCutoff int `json:"peer_turnover_cutoff"`
PeerTurnoverInterval int `json:"peer_turnover_interval"`
PerformanceWarning bool `json:"performance_warning"`
Pex bool `json:"pex"`
PreallocateAll bool `json:"preallocate_all"`
ProxyAuthEnabled bool `json:"proxy_auth_enabled"`
ProxyHostnameLookup bool `json:"proxy_hostname_lookup"`
ProxyIP string `json:"proxy_ip"`
ProxyPassword string `json:"proxy_password"`
ProxyPeerConnections bool `json:"proxy_peer_connections"`
ProxyPort int `json:"proxy_port"`
ProxyTorrentsOnly bool `json:"proxy_torrents_only"`
ProxyType int `json:"proxy_type"`
ProxyUsername string `json:"proxy_username"`
QueueingEnabled bool `json:"queueing_enabled"`
RandomPort bool `json:"random_port"`
ReannounceWhenAddressChanged bool `json:"reannounce_when_address_changed"`
RecheckCompletedTorrents bool `json:"recheck_completed_torrents"`
RefreshInterval int `json:"refresh_interval"`
RequestQueueSize int `json:"request_queue_size"`
ResolvePeerCountries bool `json:"resolve_peer_countries"`
ResumeDataStorageType string `json:"resume_data_storage_type"`
RssAutoDownloadingEnabled bool `json:"rss_auto_downloading_enabled"`
RssDownloadRepackProperEpisodes bool `json:"rss_download_repack_proper_episodes"`
RssMaxArticlesPerFeed int `json:"rss_max_articles_per_feed"`
RssProcessingEnabled bool `json:"rss_processing_enabled"`
RssRefreshInterval int `json:"rss_refresh_interval"`
RssSmartEpisodeFilters string `json:"rss_smart_episode_filters"`
SavePath string `json:"save_path"`
SavePathChangedTmmEnabled bool `json:"save_path_changed_tmm_enabled"`
SaveResumeDataInterval int `json:"save_resume_data_interval"`
ScanDirs struct {
} `json:"scan_dirs"`
ScheduleFromHour int `json:"schedule_from_hour"`
ScheduleFromMin int `json:"schedule_from_min"`
ScheduleToHour int `json:"schedule_to_hour"`
ScheduleToMin int `json:"schedule_to_min"`
SchedulerDays int `json:"scheduler_days"`
SchedulerEnabled bool `json:"scheduler_enabled"`
SendBufferLowWatermark int `json:"send_buffer_low_watermark"`
SendBufferWatermark int `json:"send_buffer_watermark"`
SendBufferWatermarkFactor int `json:"send_buffer_watermark_factor"`
SlowTorrentDlRateThreshold int `json:"slow_torrent_dl_rate_threshold"`
SlowTorrentInactiveTimer int `json:"slow_torrent_inactive_timer"`
SlowTorrentUlRateThreshold int `json:"slow_torrent_ul_rate_threshold"`
SocketBacklogSize int `json:"socket_backlog_size"`
SsrfMitigation bool `json:"ssrf_mitigation"`
StartPausedEnabled bool `json:"start_paused_enabled"`
StopTrackerTimeout int `json:"stop_tracker_timeout"`
TempPath string `json:"temp_path"`
TempPathEnabled bool `json:"temp_path_enabled"`
TorrentChangedTmmEnabled bool `json:"torrent_changed_tmm_enabled"`
TorrentContentLayout string `json:"torrent_content_layout"`
TorrentStopCondition string `json:"torrent_stop_condition"`
UpLimit int `json:"up_limit"`
UploadChokingAlgorithm int `json:"upload_choking_algorithm"`
UploadSlotsBehavior int `json:"upload_slots_behavior"`
Upnp bool `json:"upnp"`
UpnpLeaseDuration int `json:"upnp_lease_duration"`
UseCategoryPathsInManualMode bool `json:"use_category_paths_in_manual_mode"`
UseHTTPS bool `json:"use_https"`
UtpTCPMixedMode int `json:"utp_tcp_mixed_mode"`
ValidateHTTPSTrackerCertificate bool `json:"validate_https_tracker_certificate"`
WebUIAddress string `json:"web_ui_address"`
WebUIBanDuration int `json:"web_ui_ban_duration"`
WebUIClickjackingProtectionEnabled bool `json:"web_ui_clickjacking_protection_enabled"`
WebUICsrfProtectionEnabled bool `json:"web_ui_csrf_protection_enabled"`
WebUICustomHTTPHeaders string `json:"web_ui_custom_http_headers"`
WebUIDomainList string `json:"web_ui_domain_list"`
WebUIHostHeaderValidationEnabled bool `json:"web_ui_host_header_validation_enabled"`
WebUIHTTPSCertPath string `json:"web_ui_https_cert_path"`
WebUIHTTPSKeyPath string `json:"web_ui_https_key_path"`
WebUIMaxAuthFailCount int `json:"web_ui_max_auth_fail_count"`
WebUIPort int `json:"web_ui_port"`
WebUIReverseProxiesList string `json:"web_ui_reverse_proxies_list"`
WebUIReverseProxyEnabled bool `json:"web_ui_reverse_proxy_enabled"`
WebUISecureCookieEnabled bool `json:"web_ui_secure_cookie_enabled"`
WebUISessionTimeout int `json:"web_ui_session_timeout"`
WebUIUpnp bool `json:"web_ui_upnp"`
WebUIUseCustomHTTPHeadersEnabled bool `json:"web_ui_use_custom_http_headers_enabled"`
WebUIUsername string `json:"web_ui_username"`
}
5 changes: 3 additions & 2 deletions http.go
Original file line number Diff line number Diff line change
Expand Up @@ -150,7 +150,8 @@ func (c *Client) postFileCtx(ctx context.Context, endpoint string, fileName stri
}

// Close multipart writer
defer multiPartWriter.Close()
contentType := multiPartWriter.FormDataContentType()
multiPartWriter.Close()

reqUrl := c.buildUrl(endpoint, nil)
req, err := http.NewRequestWithContext(ctx, http.MethodPost, reqUrl, &requestBody)
Expand All @@ -163,7 +164,7 @@ func (c *Client) postFileCtx(ctx context.Context, endpoint string, fileName stri
}

// Set correct content type
req.Header.Set("Content-Type", multiPartWriter.FormDataContentType())
req.Header.Set("Content-Type", contentType)

cookieURL, _ := url.Parse(c.buildUrl("/", nil))
if len(c.http.Jar.Cookies(cookieURL)) == 0 {
Expand Down
54 changes: 54 additions & 0 deletions methods.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,31 @@ func (c *Client) LoginCtx(ctx context.Context) error {
return nil
}

func (c *Client) GetAppPreferences() (AppPreferences, error) {
return c.GetAppPreferencesCtx(context.Background())
}

func (c *Client) GetAppPreferencesCtx(ctx context.Context) (AppPreferences, error) {
var app AppPreferences
resp, err := c.getCtx(ctx, "app/preferences", nil)
if err != nil {
return app, errors.Wrap(err, "could not get app preferences")
}

defer resp.Body.Close()

body, err := io.ReadAll(resp.Body)
if err != nil {
return app, errors.Wrap(err, "could not read body")
}

if err := json.Unmarshal(body, &app); err != nil {
return app, errors.Wrap(err, "could not unmarshal body")
}

return app, nil
}

func (c *Client) GetTorrents(o TorrentFilterOptions) ([]Torrent, error) {
return c.GetTorrentsCtx(context.Background(), o)
}
Expand Down Expand Up @@ -147,6 +172,35 @@ func (c *Client) GetTorrentsActiveDownloadsCtx(ctx context.Context) ([]Torrent,
return res, nil
}

func (c *Client) GetTorrentProperties(hash string) (TorrentProperties, error) {
return c.GetTorrentPropertiesCtx(context.Background(), hash)
}

func (c *Client) GetTorrentPropertiesCtx(ctx context.Context, hash string) (TorrentProperties, error) {
opts := map[string]string{
"hash": hash,
}

var prop TorrentProperties
resp, err := c.getCtx(ctx, "torrents/properties", opts)
if err != nil {
return prop, errors.Wrap(err, "could not get app preferences")
}

defer resp.Body.Close()

body, err := io.ReadAll(resp.Body)
if err != nil {
return prop, errors.Wrap(err, "could not read body")
}

if err := json.Unmarshal(body, &prop); err != nil {
return prop, errors.Wrap(err, "could not unmarshal body")
}

return prop, nil
}

func (c *Client) GetTorrentsRaw() (string, error) {
return c.GetTorrentsRawCtx(context.Background())
}
Expand Down

0 comments on commit afb56af

Please sign in to comment.