so://phie

verbal

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

blob: 860704b3ea3c266c82960daa5e5cd130ac5be50e (10087 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 station_status.is_hidden,

35 CASE

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

37 THEN false

38 ELSE true

39 END AS is_favorite

40 FROM station

41 LEFT JOIN favorite

42 ON station.id = favorite.station_id

43 LEFT JOIN station_status

44 ON station.id = station_status.station_id

45 {conditions}

46 AND station_status.is_hidden IS NOT true

47 OFFSET {offset}

48 LIMIT 10

49 "#,

50 account_id = account.id,

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

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

53 );

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

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

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

57 .await?;

58 Response::with(result)

59}

60

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

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

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

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

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

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

67 };

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

69 Ok(interval) => interval * 2,

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

71 };

72 let mut total = 0;

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

74 let mut buf = [0; 10000];

75 let mut title = None;

76 loop {

77 let len =

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

79 bytes.extend_from_slice(&buf);

80 if total + len > interval {

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

82 if let Some(cap) =

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

84 .captures_iter(&metadata)

85 .next()

86 {

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

88 }

89 break;

90 }

91 if total > interval * 2 {

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

93 break;

94 }

95 total += len;

96 }

97 Response::with(title)

98}

99

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

101 let account =

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

103 let sql = format!(

104 r#"

105 SELECT

106 station.*,

107 station_status.is_restricted,

108 station_status.is_broken,

109 station_status.is_no_track_info,

110 station_status.is_hidden,

111 true as is_favorite

112 FROM station

113 LEFT JOIN favorite

114 ON station.id = favorite.station_id

115 LEFT JOIN station_status

116 ON station.id = station_status.station_id

117 WHERE favorite.account_id = {account_id}

118 AND station_status.is_hidden IS NOT true

119 "#,

120 account_id = account.id,

121 );

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

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

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

125 .await?;

126 Response::with(result)

127}

128

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

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

131 let account =

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

133 let sql = format!(

134 r#"

135 INSERT INTO

136 favorite

137 (account_id, station_id)

138 VALUES

139 ({account_id}, {station_id})

140 "#,

141 account_id = account.id,

142 station_id = station_id,

143 );

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

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

146 Response::with(())

147}

148

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

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

151 let account =

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

153 let sql = format!(

154 r#"

155 DELETE FROM

156 favorite

157 WHERE account_id = {account_id}

158 AND station_id = {station_id}

159 "#,

160 account_id = account.id,

161 station_id = station_id,

162 );

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

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

165 Response::with(())

166}

167

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

169 let station_id = unwrap_result_or_throw!(req.param("id"), "no station id found!");

170 let account =

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

172 let sql = format!(

173 r#"

174 SELECT

175 station.*,

176 station_status.is_restricted,

177 station_status.is_broken,

178 station_status.is_no_track_info,

179 station_status.is_hidden,

180 CASE

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

182 THEN false

183 ELSE true

184 END AS is_favorite

185 FROM station

186 LEFT JOIN favorite

187 ON station.id = favorite.station_id

188 LEFT JOIN station_status

189 ON station.id = station_status.station_id

190 WHERE station.id = {station_id}

191 AND station_status.is_hidden IS NOT true

192 "#,

193 account_id = account.id,

194 station_id = station_id,

195 );

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

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

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

199 .await?;

200 Response::with(result)

201}

202

203pub async fn get_countries(req: tide::Request<()>) -> tide::Result {

204 let sql = r#"

205 SELECT

206 country

207 FROM station

208 WHERE country != ''

209 GROUP BY country

210 ORDER BY COUNT(*) DESC;

211 "#

212 .to_string();

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

214 let result = sqlx::query_as::<_, model::Value>(&sql)

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

216 .await?;

217 Response::with(result)

218}

219

220pub async fn get_languages(req: tide::Request<()>) -> tide::Result {

221 let sql = r#"

222 SELECT

223 UNNEST(languages) AS language

224 FROM station

225 GROUP BY UNNEST(languages)

226 ORDER BY COUNT(*) DESC;

227 "#

228 .to_string();

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

230 let result = sqlx::query_as::<_, model::Value>(&sql)

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

232 .await?;

233 Response::with(result)

234}

235

236pub async fn get_tags(req: tide::Request<()>) -> tide::Result {

237 let sql = r#"

238 SELECT

239 UNNEST(tags) AS tag

240 FROM station

241 GROUP BY UNNEST(tags)

242 ORDER BY COUNT(*) DESC

243 LIMIT 100;

244 "#

245 .to_string();

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

247 let result = sqlx::query_as::<_, model::Value>(&sql)

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

249 .await?;

250 Response::with(result)

251}

252

253pub async fn get_devices(req: tide::Request<()>) -> tide::Result {

254 let account =

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

256 let sql = format!(

257 r#"

258 SELECT

259 device.*

260 FROM device

261 WHERE device.account_id = {account_id}

262 "#,

263 account_id = account.id,

264 );

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

266 let result = sqlx::query_as::<_, model::Device>(&sql)

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

268 .await?;

269 Response::with(result)

270}

271

272pub async fn update_account(mut req: tide::Request<()>) -> tide::Result {

273 let updated_account = req.body_json::<model::Account>().await?;

274 let account =

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

276 let sql = format!(

277 r#"

278 UPDATE

279 account

280 SET

281 name = '{name}',

282 language = '{language}'

283 WHERE account.id = {account_id}

284 RETURNING *

285 "#,

286 account_id = account.id,

287 name = updated_account.name.unwrap_or_default(),

288 language = updated_account.language,

289 );

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

291 let result = sqlx::query_as::<_, model::Account>(&sql)

292 .fetch_one(conn.acquire().await?)

293 .await?;

294 Response::with(result)

295}