so://phie

verbal

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

blob: 699756d03c707589fa17def3e0725afd424510b4 (16446 bytes)[doc][blame][raw]

1use async_std::io::ReadExt;

2use regex::Regex;

3use serde::Serialize;

4use sqlx::Acquire;

5use sqlx::Postgres;

6use tide_sqlx::SQLxRequestExt;

7

8use crate::model;

9use crate::unwrap_option_or_throw;

10use crate::unwrap_result_or_throw;

11use crate::Category;

12use crate::Response;

13use crate::ToSql;

14

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

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

17}

18

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

20 let account =

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

22 Response::with(account)

23}

24

25pub async fn add_account(mut req: tide::Request<()>) -> tide::Result {

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

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

28 }

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

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

31 let sql = format!(

32 r#"

33 INSERT INTO

34 account

35 (name, language)

36 VALUES

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

38 RETURNING account.*

39 "#,

40 name = add_account.name,

41 language = add_account.language,

42 );

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

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

45 .await?;

46 let sql = format!(

47 r#"

48 INSERT INTO

49 device

50 (uid, account_id)

51 VALUES

52 (uuid_generate_v4(), {account_id})

53 RETURNING device.*

54 "#,

55 account_id = account.id,

56 );

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

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

59 .await?;

60 Response::with(device)

61}

62

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

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

65 let account =

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

67 let sql = format!(

68 r#"

69 SELECT

70 station.*,

71 station_status.is_restricted,

72 station_status.is_broken,

73 station_status.is_no_track_info,

74 station_status.is_hidden,

75 station_status.is_icon,

76 station_stats.playtime,

77 CASE

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

79 THEN false

80 ELSE true

81 END AS is_favorite

82 FROM station

83 LEFT JOIN favorite

84 ON station.id = favorite.station_id

85 LEFT JOIN station_status

86 ON station.id = station_status.station_id

87 LEFT JOIN station_stats

88 ON station.id = station_stats.station_id

89 AND station_stats.account_id = {account_id}

90 {conditions}

91 AND station_status.is_hidden IS NOT true

92 OFFSET {offset}

93 LIMIT 10

94 "#,

95 account_id = account.id,

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

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

98 );

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

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

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

102 .await?;

103 Response::with(result)

104}

105

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

107 let account =

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

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

110 let sql = format!(

111 r#"

112 INSERT INTO

113 station_stats

114 (account_id, station_id, playtime)

115 VALUES

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

117 ON CONFLICT (account_id, station_id)

118 DO UPDATE

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

120 latest_at = now();

121 "#,

122 account_id = account.id,

123 station_id = station.id,

124 );

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

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

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

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

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

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

131 };

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

133 Ok(interval) => interval * 2,

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

135 };

136 let mut total = 0;

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

138 let mut buf = [0; 10000];

139 let mut title = None;

140 loop {

141 let len =

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

143 bytes.extend_from_slice(&buf);

144 if total + len > interval {

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

146 if let Some(cap) =

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

148 .captures_iter(&metadata)

149 .next()

150 {

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

152 }

153 break;

154 }

155 if total > interval * 2 {

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

157 break;

158 }

159 total += len;

160 }

161 Response::with(title)

162}

163

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

165 let account =

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

167 let sql = format!(

168 r#"

169 SELECT

170 station.*,

171 station_status.is_restricted,

172 station_status.is_broken,

173 station_status.is_no_track_info,

174 station_status.is_hidden,

175 station_status.is_icon,

176 station_stats.playtime,

177 true as is_favorite

178 FROM station

179 LEFT JOIN favorite

180 ON station.id = favorite.station_id

181 LEFT JOIN station_status

182 ON station.id = station_status.station_id

183 LEFT JOIN station_stats

184 ON station.id = station_stats.station_id

185 AND station_stats.account_id = {account_id}

186 WHERE favorite.account_id = {account_id}

187 AND station_status.is_hidden IS NOT true

188 "#,

189 account_id = account.id,

190 );

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

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

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

194 .await?;

195 Response::with(result)

196}

197

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

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

200 let account =

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

202 let sql = format!(

203 r#"

204 INSERT INTO

205 favorite

206 (account_id, station_id)

207 VALUES

208 ({account_id}, {station_id})

209 "#,

210 account_id = account.id,

211 station_id = station_id,

212 );

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

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

215 Response::with(())

216}

217

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

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

220 let account =

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

222 let sql = format!(

223 r#"

224 DELETE FROM

225 favorite

226 WHERE account_id = {account_id}

227 AND station_id = {station_id}

228 "#,

229 account_id = account.id,

230 station_id = station_id,

231 );

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

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

234 Response::with(())

235}

236

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

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

239 let account =

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

241 let sql = format!(

242 r#"

243 SELECT

244 station.*,

245 station_status.is_restricted,

246 station_status.is_broken,

247 station_status.is_no_track_info,

248 station_status.is_hidden,

249 station_status.is_icon,

250 station_stats.playtime,

251 CASE

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

253 THEN false

254 ELSE true

255 END AS is_favorite

256 FROM station

257 LEFT JOIN favorite

258 ON station.id = favorite.station_id

259 LEFT JOIN station_status

260 ON station.id = station_status.station_id

261 LEFT JOIN station_stats

262 ON station.id = station_stats.station_id

263 AND station_stats.account_id = {account_id}

264 WHERE station.id = {station_id}

265 AND station_status.is_hidden IS NOT true

266 "#,

267 account_id = account.id,

268 station_id = station_id,

269 );

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

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

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

273 .await?;

274 Response::with(result)

275}

276

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

278 let group_id = unwrap_result_or_throw!(req.param("id"), "no group id was provided!");

279 let account =

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

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

282 let sql = format!(

283 r#"

284 SELECT

285 station_group.*

286 FROM station_group

287 WHERE station_group.id = {group_id}

288 "#,

289 group_id = group_id,

290 );

291 let group = unwrap_option_or_throw!(

292 sqlx::query_as::<_, model::StationGroup>(&sql)

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

294 .await?,

295 "no group with id found!"

296 );

297 let sql = format!(

298 r#"

299 SELECT

300 station.*,

301 station_status.is_restricted,

302 station_status.is_broken,

303 station_status.is_no_track_info,

304 station_status.is_hidden,

305 station_status.is_icon,

306 station_stats.playtime,

307 CASE

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

309 THEN false

310 ELSE true

311 END AS is_favorite

312 FROM station

313 LEFT JOIN favorite

314 ON station.id = favorite.station_id

315 LEFT JOIN station_status

316 ON station.id = station_status.station_id

317 LEFT JOIN station_stats

318 ON station.id = station_stats.station_id

319 AND station_stats.account_id = {account_id}

320 WHERE station.group_id = {group_id}

321 AND station_status.is_hidden IS NOT true

322 "#,

323 account_id = account.id,

324 group_id = group_id,

325 );

326 let stations = sqlx::query_as::<_, model::Station>(&sql)

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

328 .await?;

329 #[derive(Serialize)]

330 struct Result {

331 group: model::StationGroup,

332 stations: Vec<model::Station>,

333 }

334 let result = Result { group, stations };

335 Response::with(result)

336}

337

338pub async fn get_category(req: tide::Request<()>) -> tide::Result {

339 let kind = unwrap_result_or_throw!(req.param("kind"), "no kind was provided!");

340 let account =

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

342 let category = unwrap_result_or_throw!(Category::from(kind), "invalid category provided!");

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

344 let sql = format!(

345 r#"

346 SELECT

347 station.*,

348 station_status.is_icon,

349 CASE

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

351 THEN false

352 ELSE true

353 END AS is_favorite

354 FROM station

355 LEFT JOIN favorite

356 ON station.id = favorite.station_id

357 LEFT JOIN station_status

358 ON station.id = station_status.station_id

359 LEFT JOIN station_stats

360 ON station.id = station_stats.station_id

361 AND station_stats.account_id = {account_id}

362 WHERE station_status.is_hidden IS NOT true

363 {category}

364 LIMIT 5

365 "#,

366 account_id = account.id,

367 category = unwrap_result_or_throw!(category.to_sql(), "cannot parse sql statement!"),

368 );

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

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

371 .await?;

372 Response::with(result)

373}

374

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

376 let sql = r#"

377 SELECT

378 country

379 FROM station

380 WHERE country != ''

381 GROUP BY country

382 ORDER BY COUNT(*) DESC;

383 "#

384 .to_string();

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

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

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

388 .await?;

389 Response::with(result)

390}

391

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

393 let sql = r#"

394 SELECT

395 UNNEST(languages) AS language

396 FROM station

397 GROUP BY UNNEST(languages)

398 ORDER BY COUNT(*) DESC;

399 "#

400 .to_string();

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

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

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

404 .await?;

405 Response::with(result)

406}

407

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

409 let sql = r#"

410 SELECT

411 UNNEST(tags) AS tag

412 FROM station

413 GROUP BY UNNEST(tags)

414 ORDER BY COUNT(*) DESC

415 LIMIT 100;

416 "#

417 .to_string();

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

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

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

421 .await?;

422 Response::with(result)

423}

424

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

426 let account =

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

428 let sql = format!(

429 r#"

430 SELECT

431 device.*

432 FROM device

433 WHERE device.account_id = {account_id}

434 "#,

435 account_id = account.id,

436 );

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

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

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

440 .await?;

441 Response::with(result)

442}

443

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

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

446 let account =

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

448 let sql = format!(

449 r#"

450 UPDATE

451 account

452 SET

453 name = '{name}',

454 language = '{language}'

455 WHERE account.id = {account_id}

456 RETURNING *

457 "#,

458 account_id = account.id,

459 name = updated_account.name.unwrap_or_default(),

460 language = updated_account.language,

461 );

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

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

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

465 .await?;

466 Response::with(result)

467}