address some no-op clippy warnings

This commit is contained in:
Scott Lamb
2021-05-17 14:31:50 -07:00
parent 603f02b686
commit 54bd068706
32 changed files with 185 additions and 241 deletions

View File

@@ -40,13 +40,13 @@ impl From<&'static str> for Chunk {
impl From<String> for Chunk {
fn from(r: String) -> Self {
Chunk(ARefss::new(r.into_bytes()).map(|v| &v[..]))
Chunk(ARefss::new(r.into_bytes()))
}
}
impl From<Vec<u8>> for Chunk {
fn from(r: Vec<u8>) -> Self {
Chunk(ARefss::new(r).map(|v| &v[..]))
Chunk(ARefss::new(r))
}
}

View File

@@ -279,7 +279,7 @@ fn lower_retention(
db: &Arc<db::Database>,
zero_limits: BTreeMap<i32, Vec<writer::NewLimit>>,
) -> Result<(), Error> {
let dirs_to_open: Vec<_> = zero_limits.keys().map(|id| *id).collect();
let dirs_to_open: Vec<_> = zero_limits.keys().copied().collect();
db.lock().open_sample_file_dirs(&dirs_to_open[..])?;
for (&dir_id, l) in &zero_limits {
writer::lower_retention(db.clone(), dir_id, &l)?;
@@ -358,7 +358,7 @@ fn edit_camera_dialog(db: &Arc<db::Database>, siv: &mut Cursive, item: &Option<i
.child(
"sample file dir",
views::SelectView::<Option<i32>>::new()
.with_all(dirs.iter().map(|d| d.clone()))
.with_all(dirs.iter().cloned())
.popup()
.with_name(format!("{}_sample_file_dir", type_.as_str())),
)

View File

@@ -408,10 +408,7 @@ fn edit_dir_dialog(db: &Arc<db::Database>, siv: &mut Cursive, dir_id: i32) {
.child(views::DummyView {}.fixed_width(20))
.child(views::TextView::new(encode_size(model.borrow().fs_capacity)).fixed_width(25)),
);
let mut change_button = views::Button::new("Change", {
let model = model.clone();
move |siv| press_change(&model, siv)
});
let mut change_button = views::Button::new("Change", move |siv| press_change(&model, siv));
change_button.set_enabled(!over);
let mut buttons = views::LinearLayout::horizontal().child(views::DummyView.full_width());
buttons.add_child(change_button.with_name("change"));

View File

@@ -10,7 +10,6 @@
use base::clock;
use cursive::views;
use cursive::Cursive;
use db;
use failure::Error;
use std::path::PathBuf;
use std::sync::Arc;
@@ -43,10 +42,7 @@ pub fn run(args: &Args) -> Result<i32, Error> {
siv.add_layer(
views::Dialog::around(
views::SelectView::<fn(&Arc<db::Database>, &mut Cursive)>::new()
.on_submit({
let db = db.clone();
move |siv, item| item(&db, siv)
})
.on_submit(move |siv, item| item(&db, siv))
.item("Cameras and streams".to_string(), cameras::top_dialog)
.item("Directories and retention".to_string(), dirs::top_dialog)
.item("Users".to_string(), users::top_dialog),

View File

@@ -126,12 +126,12 @@ fn edit_user_dialog(db: &Arc<db::Database>, siv: &mut Cursive, item: Option<i32>
{
let l = db.lock();
let u = item.map(|id| l.users_by_id().get(&id).unwrap());
username = u.map(|u| u.username.clone()).unwrap_or(String::new());
id_str = item.map(|id| id.to_string()).unwrap_or("<new>".to_string());
username = u.map(|u| u.username.clone()).unwrap_or_default();
id_str = item
.map(|id| id.to_string())
.unwrap_or_else(|| "<new>".to_string());
has_password = u.map(|u| u.has_password()).unwrap_or(false);
permissions = u
.map(|u| u.permissions.clone())
.unwrap_or(db::Permissions::default());
permissions = u.map(|u| u.permissions.clone()).unwrap_or_default();
}
let top_list = views::ListView::new()
.child("id", views::TextView::new(id_str))

View File

@@ -56,7 +56,7 @@ pub struct Args {
pub fn run(args: &Args) -> Result<i32, Error> {
let clocks = clock::RealClocks {};
let (_db_dir, conn) = super::open_conn(&args.db_dir, super::OpenMode::ReadWrite)?;
let db = std::sync::Arc::new(db::Database::new(clocks.clone(), conn, true).unwrap());
let db = std::sync::Arc::new(db::Database::new(clocks, conn, true).unwrap());
let mut l = db.lock();
let u = l
.get_user(&args.username)
@@ -72,7 +72,6 @@ pub fn run(args: &Args) -> Result<i32, Error> {
flags |= *f as i32;
}
let uid = u.id;
drop(u);
let (sid, _) = l.make_session(
creation,
uid,

View File

@@ -6,7 +6,6 @@ use db::dir;
use failure::{Error, Fail};
use log::info;
use nix::fcntl::FlockArg;
use rusqlite;
use std::path::Path;
pub mod check;

View File

@@ -17,7 +17,6 @@ use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use std::thread;
use structopt::StructOpt;
use tokio;
use tokio::signal::unix::{signal, SignalKind};
#[derive(StructOpt)]
@@ -76,20 +75,20 @@ pub struct Args {
// These are used in a hack to get the name of the current time zone (e.g. America/Los_Angeles).
// They seem to be correct for Linux and macOS at least.
const LOCALTIME_PATH: &'static str = "/etc/localtime";
const TIMEZONE_PATH: &'static str = "/etc/timezone";
const ZONEINFO_PATHS: [&'static str; 2] = [
const LOCALTIME_PATH: &str = "/etc/localtime";
const TIMEZONE_PATH: &str = "/etc/timezone";
const ZONEINFO_PATHS: [&str; 2] = [
"/usr/share/zoneinfo/", // Linux, macOS < High Sierra
"/var/db/timezone/zoneinfo/", // macOS High Sierra
];
fn trim_zoneinfo(p: &str) -> &str {
fn trim_zoneinfo(path: &str) -> &str {
for zp in &ZONEINFO_PATHS {
if p.starts_with(zp) {
return &p[zp.len()..];
if let Some(p) = path.strip_prefix(zp) {
return p;
}
}
return p;
path
}
/// Attempt to resolve the timezone of the server.
@@ -145,7 +144,7 @@ fn resolve_zone() -> Result<String, Error> {
// If `TIMEZONE_PATH` is a file, use its contents as the zone name.
match ::std::fs::read_to_string(TIMEZONE_PATH) {
Ok(z) => return Ok(z),
Ok(z) => Ok(z),
Err(e) => {
bail!(
"Unable to resolve timezone from TZ env, {}, or {}. Last error: {}",
@@ -174,7 +173,7 @@ pub async fn run(args: &Args) -> Result<i32, Error> {
super::OpenMode::ReadWrite
},
)?;
let db = Arc::new(db::Database::new(clocks.clone(), conn, !args.read_only).unwrap());
let db = Arc::new(db::Database::new(clocks, conn, !args.read_only).unwrap());
info!("Database is loaded.");
let object_detector = match args.object_detection {
@@ -260,7 +259,7 @@ pub async fn run(args: &Args) -> Result<i32, Error> {
let rotate_offset_sec = streamer::ROTATE_INTERVAL_SEC * i as i64 / streams as i64;
let syncer = syncers.get(&sample_file_dir_id).unwrap();
let object_detector = match stream.type_ {
db::StreamType::SUB => object_detector.clone(),
db::StreamType::Sub => object_detector.clone(),
_ => None,
};
let mut streamer = streamer::Streamer::new(

View File

@@ -45,10 +45,7 @@ pub fn run(args: &Args) -> Result<i32, Error> {
db::upgrade::run(
&db::upgrade::Args {
sample_file_dir: args
.sample_file_dir
.as_ref()
.map(std::path::PathBuf::as_path),
sample_file_dir: args.sample_file_dir.as_deref(),
preset_journal: &args.preset_journal,
no_vacuum: args.no_vacuum,
},

View File

@@ -208,7 +208,7 @@ impl<'a> Camera<'a> {
{
let mut map = serializer.serialize_map(Some(streams.len()))?;
for (i, s) in streams.iter().enumerate() {
if let &Some(ref s) = s {
if let Some(ref s) = *s {
map.serialize_key(
db::StreamType::from_index(i)
.expect("invalid stream type index")
@@ -397,10 +397,9 @@ impl<'a> TopLevel<'a> {
let (db, include_days, include_config) = *cameras;
let cs = db.cameras_by_id();
let mut seq = serializer.serialize_seq(Some(cs.len()))?;
for (_, c) in cs {
for c in cs.values() {
seq.serialize_element(
&Camera::wrap(c, db, include_days, include_config)
.map_err(|e| S::Error::custom(e))?,
&Camera::wrap(c, db, include_days, include_config).map_err(S::Error::custom)?,
)?;
}
seq.end()
@@ -417,7 +416,7 @@ impl<'a> TopLevel<'a> {
let (db, include_days) = *signals;
let ss = db.signals_by_id();
let mut seq = serializer.serialize_seq(Some(ss.len()))?;
for (_, s) in ss {
for s in ss.values() {
seq.serialize_element(&Signal::wrap(s, db, include_days))?;
}
seq.end()

View File

@@ -160,7 +160,7 @@ fn main() {
.and_then(|s| mylog::ColorMode::from_str(&s))
.unwrap_or(mylog::ColorMode::Auto),
)
.set_spec(&::std::env::var("MOONFIRE_LOG").unwrap_or("info".to_owned()))
.set_spec(&::std::env::var("MOONFIRE_LOG").unwrap_or_else(|_| "info".to_owned()))
.build();
h.clone().install().unwrap();

View File

@@ -63,12 +63,9 @@ use db::dir;
use db::recording::{self, rescale, TIME_UNITS_PER_SEC};
use futures::stream;
use futures::Stream;
use http;
use http::header::HeaderValue;
use http_serve;
use hyper::body::Buf;
use log::{debug, error, trace, warn};
use memmap;
use parking_lot::Once;
use reffers::ARefss;
use smallvec::SmallVec;
@@ -88,7 +85,7 @@ use std::time::SystemTime;
const FORMAT_VERSION: [u8; 1] = [0x08];
/// An `ftyp` (ISO/IEC 14496-12 section 4.3 `FileType`) box.
const NORMAL_FTYP_BOX: &'static [u8] = &[
const NORMAL_FTYP_BOX: &[u8] = &[
0x00, 0x00, 0x00, 0x20, // length = 32, sizeof(NORMAL_FTYP_BOX)
b'f', b't', b'y', b'p', // type
b'i', b's', b'o', b'm', // major_brand
@@ -105,7 +102,7 @@ const NORMAL_FTYP_BOX: &'static [u8] = &[
/// (8.8.7.1) cannot be set where a file is marked with [the avc1 brand]."
/// Note that Safari insists there be a compatible brand set in this list. The
/// major brand is not enough.
const INIT_SEGMENT_FTYP_BOX: &'static [u8] = &[
const INIT_SEGMENT_FTYP_BOX: &[u8] = &[
0x00, 0x00, 0x00, 0x14, // length = 20, sizeof(INIT_SEGMENT_FTYP_BOX)
b'f', b't', b'y', b'p', // type
b'i', b's', b'o', b'5', // major_brand
@@ -114,7 +111,7 @@ const INIT_SEGMENT_FTYP_BOX: &'static [u8] = &[
];
/// An `hdlr` (ISO/IEC 14496-12 section 8.4.3 `HandlerBox`) box suitable for video.
const VIDEO_HDLR_BOX: &'static [u8] = &[
const VIDEO_HDLR_BOX: &[u8] = &[
0x00, 0x00, 0x00, 0x21, // length == sizeof(kHdlrBox)
b'h', b'd', b'l', b'r', // type == hdlr, ISO/IEC 14496-12 section 8.4.3.
0x00, 0x00, 0x00, 0x00, // version + flags
@@ -127,7 +124,7 @@ const VIDEO_HDLR_BOX: &'static [u8] = &[
];
/// An `hdlr` (ISO/IEC 14496-12 section 8.4.3 `HandlerBox`) box suitable for subtitles.
const SUBTITLE_HDLR_BOX: &'static [u8] = &[
const SUBTITLE_HDLR_BOX: &[u8] = &[
0x00, 0x00, 0x00, 0x21, // length == sizeof(kHdlrBox)
b'h', b'd', b'l', b'r', // type == hdlr, ISO/IEC 14496-12 section 8.4.3.
0x00, 0x00, 0x00, 0x00, // version + flags
@@ -141,7 +138,7 @@ const SUBTITLE_HDLR_BOX: &'static [u8] = &[
/// Part of an `mvhd` (`MovieHeaderBox` version 0, ISO/IEC 14496-12 section 8.2.2), used from
/// `append_mvhd`.
const MVHD_JUNK: &'static [u8] = &[
const MVHD_JUNK: &[u8] = &[
0x00, 0x01, 0x00, 0x00, // rate
0x01, 0x00, // volume
0x00, 0x00, // reserved
@@ -166,7 +163,7 @@ const MVHD_JUNK: &'static [u8] = &[
/// Part of a `tkhd` (`TrackHeaderBox` version 0, ISO/IEC 14496-12 section 8.3.2), used from
/// `append_video_tkhd` and `append_subtitle_tkhd`.
const TKHD_JUNK: &'static [u8] = &[
const TKHD_JUNK: &[u8] = &[
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // reserved
0x00, 0x00, 0x00, 0x00, // layer + alternate_group
@@ -184,7 +181,7 @@ const TKHD_JUNK: &'static [u8] = &[
/// Part of a `minf` (`MediaInformationBox`, ISO/IEC 14496-12 section 8.4.4), used from
/// `append_video_minf`.
const VIDEO_MINF_JUNK: &'static [u8] = &[
const VIDEO_MINF_JUNK: &[u8] = &[
b'm', b'i', b'n', b'f', // type = minf, ISO/IEC 14496-12 section 8.4.4.
// A vmhd box; the "graphicsmode" and "opcolor" values don't have any
// meaningful use.
@@ -208,7 +205,7 @@ const VIDEO_MINF_JUNK: &'static [u8] = &[
/// Part of a `minf` (`MediaInformationBox`, ISO/IEC 14496-12 section 8.4.4), used from
/// `append_subtitle_minf`.
const SUBTITLE_MINF_JUNK: &'static [u8] = &[
const SUBTITLE_MINF_JUNK: &[u8] = &[
b'm', b'i', b'n', b'f', // type = minf, ISO/IEC 14496-12 section 8.4.4.
// A nmhd box.
0x00, 0x00, 0x00, 0x0c, // length == sizeof(kNmhdBox)
@@ -230,7 +227,7 @@ const SUBTITLE_MINF_JUNK: &'static [u8] = &[
/// Part of a `stbl` (`SampleTableBox`, ISO/IEC 14496 section 8.5.1) used from
/// `append_subtitle_stbl`.
#[rustfmt::skip]
const SUBTITLE_STBL_JUNK: &'static [u8] = &[
const SUBTITLE_STBL_JUNK: &[u8] = &[
b's', b't', b'b', b'l', // type = stbl, ISO/IEC 14496-12 section 8.5.1.
// A stsd box.
0x00, 0x00, 0x00, 0x54, // length
@@ -270,7 +267,7 @@ const SUBTITLE_STBL_JUNK: &'static [u8] = &[
/// Pointers to each static bytestrings.
/// The order here must match the `StaticBytestring` enum.
const STATIC_BYTESTRINGS: [&'static [u8]; 9] = [
const STATIC_BYTESTRINGS: [&[u8]; 9] = [
NORMAL_FTYP_BOX,
INIT_SEGMENT_FTYP_BOX,
VIDEO_HDLR_BOX,
@@ -301,7 +298,7 @@ enum StaticBytestring {
/// The template fed into strtime for a timestamp subtitle. This must produce fixed-length output
/// (see `SUBTITLE_LENGTH`) to allow quick calculation of the total size of the subtitles for
/// a given time range.
const SUBTITLE_TEMPLATE: &'static str = "%Y-%m-%d %H:%M:%S %z";
const SUBTITLE_TEMPLATE: &str = "%Y-%m-%d %H:%M:%S %z";
/// The length of the output of `SUBTITLE_TEMPLATE`.
const SUBTITLE_LENGTH: usize = 25; // "2015-07-02 17:10:00 -0700".len();
@@ -419,7 +416,7 @@ impl Segment {
});
let index: &'a _ = unsafe { &*self.index.get() };
match *index {
Ok(ref b) => return Ok(f(&b[..], self.lens())),
Ok(ref b) => Ok(f(&b[..], self.lens())),
Err(()) => bail_t!(Unknown, "Unable to build index; see previous error."),
}
}
@@ -562,6 +559,7 @@ impl Segment {
if is_key {
// first_sample_flags. See trex (8.8.3.1).
#[allow(clippy::identity_op)]
v.write_u32::<BigEndian>(
// As defined by the Independent and Disposable Samples Box
// (sdp, 8.6.4).
@@ -571,8 +569,7 @@ impl Segment {
(2 << 20) | // sample_has_redundancy: no redundant coding
// As defined by the sample padding bits (padb, 8.7.6).
(0 << 17) | // no padding
(0 << 16) | // sample_is_non_sync_sample=0
0,
(0 << 16), // sample_is_non_sync_sample=0
)?; // TODO: sample_degradation_priority
}
RunInfo {
@@ -767,7 +764,7 @@ impl slices::Slice for Slice {
type Chunk = Chunk;
fn end(&self) -> u64 {
return self.0 & 0xFF_FF_FF_FF_FF;
self.0 & 0xFF_FF_FF_FF_FF
}
fn get_range(
&self,
@@ -809,7 +806,7 @@ impl slices::Slice for Slice {
SliceType::Truns => self.wrap_truns(f, range.clone(), len as usize),
};
Box::new(stream::once(futures::future::ready(
res.map_err(|e| wrap_error(e)).and_then(move |c| {
res.map_err(wrap_error).and_then(move |c| {
if c.remaining() != (range.end - range.start) as usize {
return Err(wrap_error(format_err_t!(
Internal,
@@ -884,7 +881,7 @@ impl FileBuilder {
buf: Vec::new(),
unflushed_buf_pos: 0,
},
type_: type_,
type_,
include_timestamp_subtitle_track: false,
content_disposition: None,
prev_media_duration_and_cur_runs: None,
@@ -1822,7 +1819,7 @@ impl FileInner {
Ok(ARefss::new(mmap).map(|m| m.deref()).into())
}
fn get_subtitle_sample_data(&self, i: usize, r: Range<u64>, l: u64) -> Result<Chunk, Error> {
fn get_subtitle_sample_data(&self, i: usize, r: Range<u64>, len: u64) -> Result<Chunk, Error> {
let s = &self.segments[i];
let md = &s.rel_media_range_90k;
let wd = s.wall(md.start)..s.wall(md.end);
@@ -1831,8 +1828,8 @@ impl FileInner {
let end_sec = (s.recording_start
+ recording::Duration(i64::from(wd.end) + TIME_UNITS_PER_SEC - 1))
.unix_seconds();
let l = usize::try_from(l).unwrap();
let mut v = Vec::with_capacity(l);
let len = usize::try_from(len).unwrap();
let mut v = Vec::with_capacity(len);
// TODO(slamb): is this right?!? might have an off-by-one here.
for ts in start_sec..end_sec {
v.write_u16::<BigEndian>(SUBTITLE_LENGTH as u16)
@@ -1847,7 +1844,7 @@ impl FileInner {
)
.expect("Vec write shouldn't fail");
}
assert_eq!(l, v.len());
assert_eq!(len, v.len());
Ok(ARefss::new(v)
.map(|v| &v[r.start as usize..r.end as usize])
.into())
@@ -2471,7 +2468,7 @@ mod tests {
testutil::init();
let db = TestDb::new(RealClocks {});
let mut r = db::RecordingToInsert::default();
let mut encoder = recording::SampleIndexEncoder::new();
let mut encoder = recording::SampleIndexEncoder::default();
for i in 1..6 {
let duration_90k = 2 * i;
let bytes = 3 * i;
@@ -2531,7 +2528,7 @@ mod tests {
testutil::init();
let db = TestDb::new(RealClocks {});
let mut r = db::RecordingToInsert::default();
let mut encoder = recording::SampleIndexEncoder::new();
let mut encoder = recording::SampleIndexEncoder::default();
for i in 1..6 {
let duration_90k = 2 * i;
let bytes = 3 * i;
@@ -2617,13 +2614,13 @@ mod tests {
let db = TestDb::new(RealClocks {});
let mut encoders = Vec::new();
let mut r = db::RecordingToInsert::default();
let mut encoder = recording::SampleIndexEncoder::new();
let mut encoder = recording::SampleIndexEncoder::default();
encoder.add_sample(1, 1, true, &mut r);
encoder.add_sample(2, 2, false, &mut r);
encoder.add_sample(3, 3, true, &mut r);
encoders.push(r);
let mut r = db::RecordingToInsert::default();
let mut encoder = recording::SampleIndexEncoder::new();
let mut encoder = recording::SampleIndexEncoder::default();
encoder.add_sample(4, 4, true, &mut r);
encoder.add_sample(5, 5, false, &mut r);
encoders.push(r);
@@ -2656,12 +2653,12 @@ mod tests {
let db = TestDb::new(RealClocks {});
let mut encoders = Vec::new();
let mut r = db::RecordingToInsert::default();
let mut encoder = recording::SampleIndexEncoder::new();
let mut encoder = recording::SampleIndexEncoder::default();
encoder.add_sample(2, 1, true, &mut r);
encoder.add_sample(3, 2, false, &mut r);
encoders.push(r);
let mut r = db::RecordingToInsert::default();
let mut encoder = recording::SampleIndexEncoder::new();
let mut encoder = recording::SampleIndexEncoder::default();
encoder.add_sample(0, 3, true, &mut r);
encoders.push(r);
@@ -2708,7 +2705,7 @@ mod tests {
testutil::init();
let db = TestDb::new(RealClocks {});
let mut r = db::RecordingToInsert::default();
let mut encoder = recording::SampleIndexEncoder::new();
let mut encoder = recording::SampleIndexEncoder::default();
for i in 1..6 {
let duration_90k = 2 * i;
let bytes = 3 * i;
@@ -2762,7 +2759,7 @@ mod tests {
testutil::init();
let db = TestDb::new(RealClocks {});
let mut r = db::RecordingToInsert::default();
let mut encoder = recording::SampleIndexEncoder::new();
let mut encoder = recording::SampleIndexEncoder::default();
for i in 1..6 {
let duration_90k = 2 * i;
let bytes = 3 * i;

View File

@@ -129,6 +129,7 @@ where
ctx: &S::Ctx,
range: Range<u64>,
) -> Box<dyn Stream<Item = Result<S::Chunk, BoxedError>> + Sync + Send> {
#[allow(clippy::suspicious_operation_groupings)]
if range.start > range.end || range.end > self.len {
return Box::new(stream::once(futures::future::err(wrap_error(
format_err_t!(

View File

@@ -5,7 +5,6 @@
use crate::h264;
use cstr::cstr;
use failure::{bail, Error};
use ffmpeg;
use lazy_static::lazy_static;
use log::{debug, warn};
use std::convert::TryFrom;
@@ -34,7 +33,7 @@ pub trait Opener<S: Stream>: Sync {
pub trait Stream {
fn get_video_codecpar(&self) -> ffmpeg::avcodec::InputCodecParameters<'_>;
fn get_extra_data(&self) -> Result<h264::ExtraData, Error>;
fn get_next<'p>(&'p mut self) -> Result<ffmpeg::avcodec::Packet<'p>, ffmpeg::Error>;
fn get_next(&mut self) -> Result<ffmpeg::avcodec::Packet, ffmpeg::Error>;
}
pub struct Ffmpeg {}
@@ -166,7 +165,7 @@ impl Stream for FfmpegStream {
)
}
fn get_next<'i>(&'i mut self) -> Result<ffmpeg::avcodec::Packet<'i>, ffmpeg::Error> {
fn get_next(&mut self) -> Result<ffmpeg::avcodec::Packet, ffmpeg::Error> {
loop {
let p = self.input.read_frame()?;
if p.stream_index() == self.video_i {

View File

@@ -11,7 +11,6 @@ use log::{debug, info, trace, warn};
use std::result::Result;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
use time;
use url::Url;
pub static ROTATE_INTERVAL_SEC: i64 = 60;
@@ -359,7 +358,7 @@ mod tests {
fn get_frames(db: &db::LockedDatabase, id: CompositeId) -> Vec<Frame> {
db.with_recording_playback(id, &mut |rec| {
let mut it = recording::SampleIndexIterator::new();
let mut it = recording::SampleIndexIterator::default();
let mut frames = Vec::new();
while it.next(&rec.video_index).unwrap() {
frames.push(Frame {

View File

@@ -479,7 +479,7 @@ impl Service {
std::time::Duration::new(30, 0),
));
let mut combo = futures::stream::select(
sub_rx.map(|s| Either::Left(s)),
sub_rx.map(Either::Left),
keepalive.map(|_| Either::Right(())),
);
@@ -644,10 +644,10 @@ impl Service {
req: Request<::hyper::Body>,
) -> Result<Response<Body>, std::convert::Infallible> {
let p = Path::decode(req.uri().path());
let always_allow_unauthenticated = match p {
Path::NotFound | Path::Request | Path::Login | Path::Logout | Path::Static => true,
_ => false,
};
let always_allow_unauthenticated = matches!(
p,
Path::NotFound | Path::Request | Path::Login | Path::Logout | Path::Static
);
debug!("request on: {}: {:?}", req.uri(), p);
let caller = match self.authenticate(&req, always_allow_unauthenticated) {
Ok(c) => c,
@@ -673,10 +673,8 @@ impl Service {
}
}
if camera_configs {
if !caller.permissions.read_camera_configs {
bail_t!(PermissionDenied, "read_camera_configs required");
}
if camera_configs && !caller.permissions.read_camera_configs {
bail_t!(PermissionDenied, "read_camera_configs required");
}
let db = self.db.lock();
@@ -954,7 +952,7 @@ impl Service {
sec: start.unix_seconds(),
nsec: 0,
});
let stream_abbrev = if stream_type == db::StreamType::MAIN {
let stream_abbrev = if stream_type == db::StreamType::Main {
"main"
} else {
"sub"
@@ -1247,11 +1245,7 @@ impl Service {
if let Some(sid) = extract_sid(req) {
let authreq = self.authreq(req);
match self
.db
.lock()
.authenticate_session(authreq.clone(), &sid.hash())
{
match self.db.lock().authenticate_session(authreq, &sid.hash()) {
Ok((s, u)) => {
return Ok(Caller {
permissions: s.permissions.clone(),
@@ -1319,7 +1313,7 @@ struct StaticFileRequest<'a> {
impl<'a> StaticFileRequest<'a> {
fn parse(path: &'a str) -> Option<Self> {
if !path.starts_with("/") || path == "/index.html" {
if !path.starts_with('/') || path == "/index.html" {
return None;
}
@@ -1492,11 +1486,11 @@ mod tests {
assert_eq!(Path::decode("/api/cameras/asdf/"), Path::NotFound);
assert_eq!(
Path::decode("/api/cameras/35144640-ff1e-4619-b0d5-4c74c185741c/main/recordings"),
Path::StreamRecordings(cam_uuid, db::StreamType::MAIN)
Path::StreamRecordings(cam_uuid, db::StreamType::Main)
);
assert_eq!(
Path::decode("/api/cameras/35144640-ff1e-4619-b0d5-4c74c185741c/sub/recordings"),
Path::StreamRecordings(cam_uuid, db::StreamType::SUB)
Path::StreamRecordings(cam_uuid, db::StreamType::Sub)
);
assert_eq!(
Path::decode("/api/cameras/35144640-ff1e-4619-b0d5-4c74c185741c/junk/recordings"),
@@ -1504,23 +1498,23 @@ mod tests {
);
assert_eq!(
Path::decode("/api/cameras/35144640-ff1e-4619-b0d5-4c74c185741c/main/view.mp4"),
Path::StreamViewMp4(cam_uuid, db::StreamType::MAIN, false)
Path::StreamViewMp4(cam_uuid, db::StreamType::Main, false)
);
assert_eq!(
Path::decode("/api/cameras/35144640-ff1e-4619-b0d5-4c74c185741c/main/view.mp4.txt"),
Path::StreamViewMp4(cam_uuid, db::StreamType::MAIN, true)
Path::StreamViewMp4(cam_uuid, db::StreamType::Main, true)
);
assert_eq!(
Path::decode("/api/cameras/35144640-ff1e-4619-b0d5-4c74c185741c/main/view.m4s"),
Path::StreamViewMp4Segment(cam_uuid, db::StreamType::MAIN, false)
Path::StreamViewMp4Segment(cam_uuid, db::StreamType::Main, false)
);
assert_eq!(
Path::decode("/api/cameras/35144640-ff1e-4619-b0d5-4c74c185741c/main/view.m4s.txt"),
Path::StreamViewMp4Segment(cam_uuid, db::StreamType::MAIN, true)
Path::StreamViewMp4Segment(cam_uuid, db::StreamType::Main, true)
);
assert_eq!(
Path::decode("/api/cameras/35144640-ff1e-4619-b0d5-4c74c185741c/main/live.m4s"),
Path::StreamLiveMp4Segments(cam_uuid, db::StreamType::MAIN)
Path::StreamLiveMp4Segments(cam_uuid, db::StreamType::Main)
);
assert_eq!(
Path::decode("/api/cameras/35144640-ff1e-4619-b0d5-4c74c185741c/main/junk"),