so://phie

verbal

A mobile app for listening to radio stations from around the globe
git clone git://soophie.de/verbal

blob: 467f86fa118c1852771109fd6f8e946dc715d224 (5594 bytes)[doc][blame][raw]

1use async_std::io::ReadExt;

2use regex::Regex;

3use sqlx::Acquire;

4use sqlx::Postgres;

5use tide_sqlx::SQLxRequestExt;

6

7use crate::model;

8use crate::unwrap_option_or_throw;

9use crate::unwrap_result_or_throw;

10use crate::Response;

11use crate::ToSql;

12

13pub async fn do_prefetch(_: tide::Request<()>) -> tide::Result {

14 Ok(tide::Response::new(200))

15}

16

17pub async fn get_account(req: tide::Request<()>) -> tide::Result {

18 let account =

19 unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");

20 Response::with(account)

21}

22

23pub async fn do_search(req: tide::Request<()>) -> tide::Result {

24 let query = req.query::<model::Query>()?;

25 let account =

26 unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");

27 let sql = format!(

28 r#"

29 SELECT

30 station.*,

31 station_status.is_restricted,

32 station_status.is_broken,

33 station_status.is_no_track_info,

34 CASE

35 WHEN favorite.id IS NULL OR favorite.account_id != {account_id}

36 THEN false

37 ELSE true

38 END AS is_favorite

39 FROM station

40 LEFT JOIN favorite

41 ON station.id = favorite.station_id

42 LEFT JOIN station_status

43 ON station.id = station_status.station_id

44 {conditions}

45 OFFSET {offset}

46 LIMIT 10

47 "#,

48 account_id = account.id,

49 offset = query.page.unwrap_or_default() * 10,

50 conditions = unwrap_result_or_throw!(query.to_sql(), "cannot parse sql statement!"),

51 );

52 let mut conn = req.sqlx_conn::<Postgres>().await;

53 let result = sqlx::query_as::<_, model::Station>(&sql)

54 .fetch_all(conn.acquire().await?)

55 .await?;

56 Response::with(result)

57}

58

59pub async fn get_song(req: tide::Request<()>) -> tide::Result {

60 let station = req.query::<model::Station>()?;

61 let mut response = surf::get(&station.url).header("icy-metadata", "1").await?;

62 let meta_int = match response.header("icy-metaint") {

63 Some(header) => header.as_str(),

64 None => return Response::throw("no icy metadata header found!"),

65 };

66 let interval = match meta_int.parse::<usize>() {

67 Ok(interval) => interval * 2,

68 Err(_) => return Response::throw("icy metadata interval is not a number!"),

69 };

70 let mut total = 0;

71 let mut bytes = Vec::new();

72 let mut buf = [0; 10000];

73 let mut title = None;

74 loop {

75 let len =

76 unwrap_result_or_throw!(response.read(&mut buf).await, "cannot read stream data!");

77 bytes.extend_from_slice(&buf);

78 if total + len > interval {

79 let metadata = String::from_utf8_lossy(&bytes);

80 if let Some(cap) =

81 unwrap_result_or_throw!(Regex::new("StreamTitle='([^;]*)';"), "cannot parse regex!")

82 .captures_iter(&metadata)

83 .next()

84 {

85 title = Some(cap[1].to_string());

86 }

87 break;

88 }

89 if total > interval * 2 {

90 warn!("too many iterations while acquiring song title!");

91 break;

92 }

93 total += len;

94 }

95 Response::with(title)

96}

97

98pub async fn get_favorites(req: tide::Request<()>) -> tide::Result {

99 let account =

100 unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");

101 let sql = format!(

102 r#"

103 SELECT

104 station.*,

105 station_status.is_restricted,

106 station_status.is_broken,

107 station_status.is_no_track_info,

108 true as is_favorite

109 FROM station

110 LEFT JOIN favorite

111 ON station.id = favorite.station_id

112 LEFT JOIN station_status

113 ON station.id = station_status.station_id

114 WHERE favorite.account_id = {account_id}

115 "#,

116 account_id = account.id,

117 );

118 let mut conn = req.sqlx_conn::<Postgres>().await;

119 let result = sqlx::query_as::<_, model::Station>(&sql)

120 .fetch_all(conn.acquire().await?)

121 .await?;

122 Response::with(result)

123}

124

125pub async fn add_favorite(mut req: tide::Request<()>) -> tide::Result {

126 let station_id = req.body_json::<i32>().await?;

127 let account =

128 unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");

129 let sql = format!(

130 r#"

131 INSERT INTO

132 favorite

133 (account_id, station_id)

134 VALUES

135 ({account_id}, {station_id})

136 "#,

137 account_id = account.id,

138 station_id = station_id,

139 );

140 let mut conn = req.sqlx_conn::<Postgres>().await;

141 sqlx::query(&sql).execute(conn.acquire().await?).await?;

142 Response::with(())

143}

144

145pub async fn delete_favorite(mut req: tide::Request<()>) -> tide::Result {

146 let station_id = req.body_json::<i32>().await?;

147 let account =

148 unwrap_option_or_throw!(req.ext::<model::Account>(), "no account in request found!");

149 let sql = format!(

150 r#"

151 DELETE FROM

152 favorite

153 WHERE account_id = {account_id}

154 AND station_id = {station_id}

155 "#,

156 account_id = account.id,

157 station_id = station_id,

158 );

159 let mut conn = req.sqlx_conn::<Postgres>().await;

160 sqlx::query(&sql).execute(conn.acquire().await?).await?;

161 Response::with(())

162}