so://phie

verbal

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

blob: 3ae1d95c17f61e2badb88aa2da238a14f972e2a6 (14265 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 add_account(mut req: tide::Request<()>) -> tide::Result {

24 if req.ext::<model::Account>().is_some() {

25 return Response::throw("already logged in with another account!");

26 }

27 let add_account = req.body_json::<model::AddAccount>().await?;

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

29 let sql = format!(

30 r#"

31 INSERT INTO

32 account

33 (name, language)

34 VALUES

35 ('{name}', '{language}')

36 RETURNING account.*

37 "#,

38 name = add_account.name,

39 language = add_account.language,

40 );

41 let account = sqlx::query_as::<_, model::Account>(&sql)

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

43 .await?;

44 let sql = format!(

45 r#"

46 INSERT INTO

47 device

48 (uid, account_id)

49 VALUES

50 (uuid_generate_v4(), {account_id})

51 RETURNING device.*

52 "#,

53 account_id = account.id,

54 );

55 let device = sqlx::query_as::<_, model::Device>(&sql)

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

57 .await?;

58 Response::with(device)

59}

60

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

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

63 let account =

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

65 let sql = format!(

66 r#"

67 SELECT

68 station.*,

69 station_status.is_restricted,

70 station_status.is_broken,

71 station_status.is_no_track_info,

72 station_status.is_hidden,

73 station_status.is_icon,

74 station_stats.playtime,

75 CASE

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

77 THEN false

78 ELSE true

79 END AS is_favorite

80 FROM station

81 LEFT JOIN favorite

82 ON station.id = favorite.station_id

83 LEFT JOIN station_status

84 ON station.id = station_status.station_id

85 LEFT JOIN station_stats

86 ON station.id = station_stats.station_id

87 AND station_stats.account_id = {account_id}

88 {conditions}

89 AND station_status.is_hidden IS NOT true

90 OFFSET {offset}

91 LIMIT 10

92 "#,

93 account_id = account.id,

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

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

96 );

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

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

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

100 .await?;

101 Response::with(result)

102}

103

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

105 let account =

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

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

108 let sql = format!(

109 r#"

110 INSERT INTO

111 station_stats

112 (account_id, station_id, playtime)

113 VALUES

114 ({account_id}, {station_id}, 1)

115 ON CONFLICT (account_id, station_id)

116 DO UPDATE

117 SET playtime = station_stats.playtime + EXCLUDED.playtime,

118 latest_at = now();

119 "#,

120 account_id = account.id,

121 station_id = station.id,

122 );

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

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

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

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

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

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

129 };

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

131 Ok(interval) => interval * 2,

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

133 };

134 let mut total = 0;

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

136 let mut buf = [0; 10000];

137 let mut title = None;

138 loop {

139 let len =

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

141 bytes.extend_from_slice(&buf);

142 if total + len > interval {

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

144 if let Some(cap) =

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

146 .captures_iter(&metadata)

147 .next()

148 {

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

150 }

151 break;

152 }

153 if total > interval * 2 {

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

155 break;

156 }

157 total += len;

158 }

159 Response::with(title)

160}

161

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

163 let account =

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

165 let sql = format!(

166 r#"

167 SELECT

168 station.*,

169 station_status.is_restricted,

170 station_status.is_broken,

171 station_status.is_no_track_info,

172 station_status.is_hidden,

173 station_status.is_icon,

174 station_stats.playtime,

175 true as is_favorite

176 FROM station

177 LEFT JOIN favorite

178 ON station.id = favorite.station_id

179 LEFT JOIN station_status

180 ON station.id = station_status.station_id

181 LEFT JOIN station_stats

182 ON station.id = station_stats.station_id

183 AND station_stats.account_id = {account_id}

184 WHERE favorite.account_id = {account_id}

185 AND station_status.is_hidden IS NOT true

186 "#,

187 account_id = account.id,

188 );

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

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

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

192 .await?;

193 Response::with(result)

194}

195

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

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

198 let account =

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

200 let sql = format!(

201 r#"

202 INSERT INTO

203 favorite

204 (account_id, station_id)

205 VALUES

206 ({account_id}, {station_id})

207 "#,

208 account_id = account.id,

209 station_id = station_id,

210 );

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

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

213 Response::with(())

214}

215

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

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

218 let account =

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

220 let sql = format!(

221 r#"

222 DELETE FROM

223 favorite

224 WHERE account_id = {account_id}

225 AND station_id = {station_id}

226 "#,

227 account_id = account.id,

228 station_id = station_id,

229 );

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

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

232 Response::with(())

233}

234

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

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

237 let account =

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

239 let sql = format!(

240 r#"

241 SELECT

242 station.*,

243 station_status.is_restricted,

244 station_status.is_broken,

245 station_status.is_no_track_info,

246 station_status.is_hidden,

247 station_status.is_icon,

248 station_stats.playtime,

249 CASE

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

251 THEN false

252 ELSE true

253 END AS is_favorite

254 FROM station

255 LEFT JOIN favorite

256 ON station.id = favorite.station_id

257 LEFT JOIN station_status

258 ON station.id = station_status.station_id

259 LEFT JOIN station_stats

260 ON station.id = station_stats.station_id

261 AND station_stats.account_id = {account_id}

262 WHERE station.id = {station_id}

263 AND station_status.is_hidden IS NOT true

264 "#,

265 account_id = account.id,

266 station_id = station_id,

267 );

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

269 let result = sqlx::query_as::<_, model::StationDetail>(&sql)

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

271 .await?;

272 Response::with(result)

273}

274

275pub async fn get_group(req: tide::Request<()>) -> tide::Result {

276 let group_id = unwrap_result_or_throw!(req.param("id"), "no group id found!");

277 let account =

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

279 let sql = format!(

280 r#"

281 SELECT

282 station.*,

283 station_status.is_restricted,

284 station_status.is_broken,

285 station_status.is_no_track_info,

286 station_status.is_hidden,

287 station_status.is_icon,

288 station_stats.playtime,

289 CASE

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

291 THEN false

292 ELSE true

293 END AS is_favorite

294 FROM station

295 LEFT JOIN favorite

296 ON station.id = favorite.station_id

297 LEFT JOIN station_status

298 ON station.id = station_status.station_id

299 LEFT JOIN station_stats

300 ON station.id = station_stats.station_id

301 AND station_stats.account_id = {account_id}

302 WHERE station.group_id = {group_id}

303 AND station_status.is_hidden IS NOT true

304 "#,

305 account_id = account.id,

306 group_id = group_id,

307 );

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

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

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

311 .await?;

312 Response::with(result)

313}

314

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

316 let sql = r#"

317 SELECT

318 country

319 FROM station

320 WHERE country != ''

321 GROUP BY country

322 ORDER BY COUNT(*) DESC;

323 "#

324 .to_string();

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

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

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

328 .await?;

329 Response::with(result)

330}

331

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

333 let sql = r#"

334 SELECT

335 UNNEST(languages) AS language

336 FROM station

337 GROUP BY UNNEST(languages)

338 ORDER BY COUNT(*) DESC;

339 "#

340 .to_string();

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

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

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

344 .await?;

345 Response::with(result)

346}

347

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

349 let sql = r#"

350 SELECT

351 UNNEST(tags) AS tag

352 FROM station

353 GROUP BY UNNEST(tags)

354 ORDER BY COUNT(*) DESC

355 LIMIT 100;

356 "#

357 .to_string();

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

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

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

361 .await?;

362 Response::with(result)

363}

364

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

366 let account =

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

368 let sql = format!(

369 r#"

370 SELECT

371 device.*

372 FROM device

373 WHERE device.account_id = {account_id}

374 "#,

375 account_id = account.id,

376 );

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

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

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

380 .await?;

381 Response::with(result)

382}

383

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

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

386 let account =

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

388 let sql = format!(

389 r#"

390 UPDATE

391 account

392 SET

393 name = '{name}',

394 language = '{language}'

395 WHERE account.id = {account_id}

396 RETURNING *

397 "#,

398 account_id = account.id,

399 name = updated_account.name.unwrap_or_default(),

400 language = updated_account.language,

401 );

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

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

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

405 .await?;

406 Response::with(result)

407}