so://phie

verbal

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

blob: 2242288f9834f3dfdd3e9f7319898a2c72fd546e (7132 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::model::StationId;

9use crate::unwrap_option_or_throw;

10use crate::unwrap_result_or_throw;

11use crate::Response;

12use crate::ToSql;

13

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

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

16}

17

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

19 let account =

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

21 Response::with(account)

22}

23

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

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

26 let account =

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

28 let sql = format!(

29 r#"

30 SELECT

31 station.*,

32 station_status.is_restricted,

33 station_status.is_broken,

34 station_status.is_no_track_info,

35 station_status.is_hidden,

36 CASE

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

38 THEN false

39 ELSE true

40 END AS is_favorite

41 FROM station

42 LEFT JOIN favorite

43 ON station.id = favorite.station_id

44 LEFT JOIN station_status

45 ON station.id = station_status.station_id

46 {conditions}

47 AND station_status.is_hidden IS NOT true

48 OFFSET {offset}

49 LIMIT 10

50 "#,

51 account_id = account.id,

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

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

54 );

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

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

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

58 .await?;

59 Response::with(result)

60}

61

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

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

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

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

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

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

68 };

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

70 Ok(interval) => interval * 2,

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

72 };

73 let mut total = 0;

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

75 let mut buf = [0; 10000];

76 let mut title = None;

77 loop {

78 let len =

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

80 bytes.extend_from_slice(&buf);

81 if total + len > interval {

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

83 if let Some(cap) =

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

85 .captures_iter(&metadata)

86 .next()

87 {

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

89 }

90 break;

91 }

92 if total > interval * 2 {

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

94 break;

95 }

96 total += len;

97 }

98 Response::with(title)

99}

100

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

102 let account =

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

104 let sql = format!(

105 r#"

106 SELECT

107 station.*,

108 station_status.is_restricted,

109 station_status.is_broken,

110 station_status.is_no_track_info,

111 station_status.is_hidden,

112 true as is_favorite

113 FROM station

114 LEFT JOIN favorite

115 ON station.id = favorite.station_id

116 LEFT JOIN station_status

117 ON station.id = station_status.station_id

118 WHERE favorite.account_id = {account_id}

119 AND station_status.is_hidden IS NOT true

120 "#,

121 account_id = account.id,

122 );

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

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

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

126 .await?;

127 Response::with(result)

128}

129

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

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

132 let account =

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

134 let sql = format!(

135 r#"

136 INSERT INTO

137 favorite

138 (account_id, station_id)

139 VALUES

140 ({account_id}, {station_id})

141 "#,

142 account_id = account.id,

143 station_id = station_id,

144 );

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

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

147 Response::with(())

148}

149

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

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

152 let account =

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

154 let sql = format!(

155 r#"

156 DELETE FROM

157 favorite

158 WHERE account_id = {account_id}

159 AND station_id = {station_id}

160 "#,

161 account_id = account.id,

162 station_id = station_id,

163 );

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

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

166 Response::with(())

167}

168

169pub async fn get_station(req: tide::Request<()>) -> tide::Result {

170 let station_id = req.query::<StationId>()?;

171 let account =

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

173 let sql = format!(

174 r#"

175 SELECT

176 station.*,

177 station_status.is_restricted,

178 station_status.is_broken,

179 station_status.is_no_track_info,

180 station_status.is_hidden,

181 CASE

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

183 THEN false

184 ELSE true

185 END AS is_favorite

186 FROM station

187 LEFT JOIN favorite

188 ON station.id = favorite.station_id

189 LEFT JOIN station_status

190 ON station.id = station_status.station_id

191 WHERE station.id = {station_id}

192 AND station_status.is_hidden IS NOT true

193 "#,

194 account_id = account.id,

195 station_id = station_id.id,

196 );

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

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

199 .fetch_optional(conn.acquire().await?)

200 .await?;

201 Response::with(result)

202}