aboutsummaryrefslogtreecommitdiff
path: root/server/src/routes/stream.rs
blob: 6b268e42ba4e9994f9dc390b1840490d1674f355 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
/*
    This file is part of jellything (https://codeberg.org/metamuffin/jellything)
    which is licensed under the GNU Affero General Public License (version 3); see /COPYING.
    Copyright (C) 2023 metamuffin <metamuffin.org>
*/
use super::ui::{account::session::Session, error::MyError};
use crate::{database::Database, federation::Federation};
use anyhow::{anyhow, Result};
use jellybase::CONF;
use jellycommon::{stream::StreamSpec, MediaSource};
use log::{info, warn};
use rocket::{
    get,
    http::{ContentType, Header, Status},
    request::{self, FromRequest},
    response::{self, Redirect, Responder},
    Either, Request, Response, State,
};
use std::{ops::Range, time::Duration};
use tokio::io::DuplexStream;

#[get("/n/<id>/stream?<spec>")]
pub async fn r_stream(
    _sess: Session,
    federation: &State<Federation>,
    db: &State<Database>,
    id: String,
    range: Option<RequestRange>,
    spec: StreamSpec,
) -> Result<Either<StreamResponse, Redirect>, MyError> {
    let node = db.node.get(&id)?.ok_or(anyhow!("node does not exist"))?;
    let source = node
        .private
        .source
        .as_ref()
        .ok_or(anyhow!("item does not contain media"))?;

    if let MediaSource::Remote { host, remote_id } = source {
        let (username, password, _) = CONF
            .remote_credentials
            .get(host)
            .ok_or(anyhow!("no credentials on the server-side"))?;

        let instance = federation.get_instance(&host)?.to_owned();
        let session = instance
            .login(
                username.to_owned(),
                password.to_owned(),
                Duration::from_secs(60),
            )
            .await?;

        let uri = session.stream(&remote_id, &spec);
        return Ok(Either::Right(Redirect::found(uri)));
    }

    info!(
        "stream request (range={})",
        range
            .as_ref()
            .map(|r| r.to_cr_hv())
            .unwrap_or(format!("none"))
    );

    let urange = match &range {
        Some(r) => {
            let r = r.0.get(0).unwrap_or(&(None..None));
            r.start.unwrap_or(0)..r.end.unwrap_or(isize::MAX as usize)
        }
        None => 0..(isize::MAX as usize),
    };

    match jellystream::stream(node, spec, urange).await {
        Ok(stream) => Ok(Either::Left(StreamResponse { stream, range })),
        Err(e) => {
            warn!("stream error: {e}");
            Err(MyError(e))
        }
    }
}

pub struct StreamResponse {
    stream: DuplexStream,
    range: Option<RequestRange>,
}

#[rocket::async_trait]
impl<'r> Responder<'r, 'static> for StreamResponse {
    fn respond_to(self, _: &'r Request<'_>) -> response::Result<'static> {
        let mut b = Response::build();
        if let Some(range) = self.range {
            b.status(Status::PartialContent);
            b.header(Header::new("content-range", range.to_cr_hv()));
        }
        b.header(Header::new("accept-ranges", "bytes"))
            .header(ContentType::WEBM)
            .streamed_body(self.stream)
            .ok()
    }
}

#[derive(Debug)]
pub struct RequestRange(Vec<Range<Option<usize>>>);

impl RequestRange {
    pub fn to_cr_hv(&self) -> String {
        assert_eq!(self.0.len(), 1);
        format!(
            "bytes {}-{}/*",
            self.0[0]
                .start
                .map(|e| format!("{e}"))
                .unwrap_or(String::new()),
            self.0[0]
                .end
                .map(|e| format!("{e}"))
                .unwrap_or(String::new())
        )
    }
    pub fn from_hv(s: &str) -> Result<Self> {
        Ok(Self(
            s.strip_prefix("bytes=")
                .ok_or(anyhow!("prefix expected"))?
                .split(',')
                .map(|s| {
                    let (l, r) = s
                        .split_once('-')
                        .ok_or(anyhow!("range delimeter missing"))?;
                    let km = |s: &str| {
                        if s.is_empty() {
                            Ok::<_, anyhow::Error>(None)
                        } else {
                            Ok(Some(s.parse()?))
                        }
                    };
                    Ok(km(l)?..km(r)?)
                })
                .collect::<Result<Vec<_>>>()?,
        ))
    }
}

#[rocket::async_trait]
impl<'r> FromRequest<'r> for RequestRange {
    type Error = anyhow::Error;

    async fn from_request(req: &'r Request<'_>) -> request::Outcome<Self, Self::Error> {
        match req.headers().get("range").next() {
            Some(v) => match Self::from_hv(v) {
                Ok(v) => rocket::outcome::Outcome::Success(v),
                Err(e) => rocket::outcome::Outcome::Failure((Status::BadRequest, e)),
            },
            None => rocket::outcome::Outcome::Forward(Status::Ok),
        }
    }
}