Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add Transmission support #637

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions docs/customservices.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ within Homer:
- [Proxmox](#proxmox)
- [rTorrent](#rtorrent)
- [qBittorrent](#qbittorrent)
- [Transmission](#transmission)
- [CopyToClipboard](#copy-to-clipboard)
- [Speedtest Tracker](#SpeedtestTracker)
- [What's Up Docker](#whats-up-docker)
Expand Down Expand Up @@ -334,6 +335,30 @@ servers can be found at [enable-cors.org](https://enable-cors.org/server.html).
target: "_blank" # optional html a tag target attribute
```

## Transmission

This service displays the global upload and download rates, as well as the number of torrents
listed.
The service communicates with the Transmission RPC interface which needs
to be accessible from the browser.
Please
consult [the instructions](https://github.com/transmission/transmission/blob/main/docs/Editing-Configuration-Files.md#rpc)
for setting up Transmission RPC and make sure the correct CORS-settings are applied.
Examples for various servers can be found at [enable-cors.org](https://enable-cors.org/server.html).

```yaml
- name: "Transmission"
type: "Transmission"
logo: "assets/tools/sample.png"
url: "http://192.168.1.2:9090/transmission/web" # Your Transmission web UI
rpc: "http://192.168.1.2:9090/transmission/rpc" # (required, if your url not ends with /web or you use custom RPC URL) Url to Transmission RPC
updateInterval: 2000 # (optional) Interval for updating the download and upload rates and torrent count
username: "username" # Username for logging into Transmission (required if RPC/WebUI required login/password)
password: "password" # Password for logging into Transmission (required if RPC/WebUI required login/password)
sessionId: "sessionId" # (optional) X-Transmission-Session-Id for logging into Transmission (it set automatically)
target: "_blank" # (optional) html a tag target attribute
```

## Copy to Clipboard

This service displays the same information of a generic one, but shows an icon button on the indicator place (right side) you can click to get the content of the `clipboard` field copied to your clipboard.
Expand Down
24 changes: 24 additions & 0 deletions dummy-data/transmission/transmission/rpc
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
{
"arguments": {
"activeTorrentCount": 16,
"cumulative-stats": {
"downloadedBytes": 95397570485,
"filesAdded": 92,
"secondsActive": 777792,
"sessionCount": 6,
"uploadedBytes": 21985043465
},
"current-stats": {
"downloadedBytes": 790271483,
"filesAdded": 2,
"secondsActive": 645,
"sessionCount": 1,
"uploadedBytes": 386100159
},
"downloadSpeed": 5693440,
"pausedTorrentCount": 0,
"torrentCount": 16,
"uploadSpeed": 1967553
},
"result": "success"
}
221 changes: 221 additions & 0 deletions src/components/services/Transmission.vue
Original file line number Diff line number Diff line change
@@ -0,0 +1,221 @@
<template>
<Generic :item="item">
<template #content>
<p class="title is-4">{{ item.name }}</p>
<p class="subtitle is-6">
<span v-if="error" class="error">An error has occurred.</span>
<template v-else>
<span class="down monospace">
<i class="fas fa-download" aria-hidden="true"></i>
{{ downRate }}
</span>
<span class="up monospace">
<i class="fas fa-upload" aria-hidden="true"></i>
{{ upRate }}
</span>
</template>
</p>
</template>
<template #indicator>
<div class="notifs">
<strong v-if="count > 0" class="notif activity" title="Torrents">
{{ count }}
</strong>
</div>
</template>
</Generic>
</template>

<script>
import service from "@/mixins/service.js";
import Generic from "./Generic.vue";

const units = ["B", "KB", "MB", "GB"];

// Take the rate in bytes and keep dividing it by 1k until the lowest
// value for which we have a unit is determined. Return the value with
// up to two decimals as a string and unit/s appended.
const displayRate = (rate) => {
let i = 0;

while (rate > 1000 && i < units.length) {
rate /= 1000;
i++;
}
return (
Intl.NumberFormat(undefined, { maximumFractionDigits: 2 }).format(
rate || 0
) + ` ${units[i]}/s`
);
};

export default {
name: "Transmission",
mixins: [service],
props: { item: Object },
components: { Generic },
data: () => ({ dl: null, ul: null, count: null, error: null }),
computed: {
downRate: function () {
return displayRate(this.dl);
},
upRate: function () {
return displayRate(this.ul);
},
},
created() {
const updateInterval = parseInt(this.item?.updateInterval, 10) || 0;
if (updateInterval > 0) {
this.interval = setInterval(() => this.fetchData(), updateInterval);
}
if (this.item?.sessionId) {
this.sessionId = this.item.sessionId;
}

this.fetchData();
},
unmounted() {
if (this.interval) {
clearInterval(this.interval);
}
},
methods: {
fetchData: async function () {
try {
const auth = {};
if (this.item?.username && this.item?.password) {
auth.user = this.item.username;
auth.password = this.item.password;
}
const {
arguments: { torrentCount, downloadSpeed, uploadSpeed },
} = await this.transmissionFetch("session-stats", auth);

this.error = false;
this.ul = uploadSpeed;
this.dl = downloadSpeed;
this.count = torrentCount;
} catch (e) {
this.error = true;
console.error(e);
}
},
/**
* @param {string} method
* @param {{user: string, password: string}?} auth
* @returns {Promise<{result: string, arguments: any}>}
*/
transmissionFetch: async function (method, auth) {
/**
* @type {RequestInit}
*/
const options = {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
method: method,
}),
};

if (this.proxy?.useCredentials) {
options.credentials = "include";
}

// Each item can override the credential settings
if (this.item.useCredentials !== undefined) {
options.credentials =
this.item.useCredentials === true ? "include" : "omit";
}
Comment on lines +122 to +130
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

A custom fetch function is available (you already included it using the service mixin), which handle the credential option and more. Could you update your code to use it and avoid code duplication ? Thanks 🙏

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@bastienwirtz

With the existing custom fetch, we don't have access to the response in the event of a non Response.OK result. We would need access to the response in order to obtain the "X-Transmission-Session-Id" after we are sent a 409 status code.

I have hacked it trivially with, but I'm sure there is a better / more correct way.

In service.js

`fetch: function (path, init, json = true, forceResponse = false)`
...
...
        if (!response.ok) {
          if (!forceResponse)
            throw new Error("Not 2xx response");
          else
            return response;
        }


// Add the credentials if they are set
if (auth?.user && auth?.password) {
options.headers["Authorization"] = `Basic ${btoa(
`${auth.user}:${auth.password}`
)}`;
}

// Add the session id if it is set
if (this?.sessionId) {
options.headers["X-Transmission-Session-Id"] = this.sessionId;
}

let url;
if (this.item?.rpc) {
url = this.item.rpc;
} else {
url = this.endpoint;
if (url.endsWith("/")) {
url = url.slice(0, -1);
}
if (url.endsWith("/web")) {
url = url.slice(0, -4);
url += "/rpc";
}
}
Comment on lines +144 to +156
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We don't need another config key for /rpc endpoint. the endpoint config key is made for this. It's supposed to be the url where to fetch the data. You just have to write in the documentation that endpoint should contain the rpc url.


const response = await fetch(url, options);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use this.fetch here.


// If the session id is not set, we need to get it from the response
if (response.status === 409 && !this.sessionId) {
const body = await response.text();
const match = body.match(/X-Transmission-Session-Id: ([a-z0-9]+)/i);
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think the X-Transmission-Session-Id exist in the response headers, it would be easier / cleaner to get it from the headers.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You can use response.headers.get('x-transmission-session-id') to get the session-id

this.sessionId = match[1];
return await this.transmissionFetch(method, auth);
}
if (!response.ok) {
throw new Error("Not 2xx response");
}
return await response.json();
},
},
};
</script>

<style lang="scss" scoped>
.error {
color: #e51111 !important;
}

.down {
margin-right: 1em;
}

.count {
color: var(--text);
font-size: 0.8em;
}

.monospace {
font-weight: 300;
font-family: monospace;
}

.fa-download {
color: #00C853;
}

.fa-upload {
color: #D50000;
}

.notifs {
position: absolute;
color: white;
font-family: sans-serif;
top: 0.3em;
right: 0.5em;
.notif {
display: inline-block;
padding: 0.2em 0.35em;
border-radius: 0.25em;
position: relative;
margin-left: 0.3em;
font-size: 0.8em;
&.activity {
background-color: #4fb5d6;
}
}
}
</style>