so://phie

verbal

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

blob: 1ca755c815c66a1f8327a20dda9dbf87e0e77ca2 (12739 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 info!("{:#?}", add_account);

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

30 let sql = format!(

31 r#"

32 INSERT INTO

33 account

34 (name, language)

35 VALUES

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

37 RETURNING account.*

38 "#,

39 name = add_account.name,

40 language = add_account.language,

41 );

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

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

44 .await?;

45 info!("{:#?}", account);

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 info!("{:#?}", device);

61 Response::with(device)

62}

63

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

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

66 let account =

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

68 let sql = format!(

69 r#"

70 SELECT

71 station.*,

72 station_status.is_restricted,

73 station_status.is_broken,

74 station_status.is_no_track_info,

75 station_status.is_hidden,

76 station_status.is_icon,

77 station_stats.playtime,

78 CASE

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

80 THEN false

81 ELSE true

82 END AS is_favorite

83 FROM station

84 LEFT JOIN favorite

85 ON station.id = favorite.station_id

86 LEFT JOIN station_status

87 ON station.id = station_status.station_id

88 LEFT JOIN station_stats

89 ON station.id = station_stats.station_id

90 AND station_stats.account_id = {account_id}

91 {conditions}

92 AND station_status.is_hidden IS NOT true

93 OFFSET {offset}

94 LIMIT 10

95 "#,

96 account_id = account.id,

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

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

99 );

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

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

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

103 .await?;

104 Response::with(result)

105}

106

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

108 let account =

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

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

111 let sql = format!(

112 r#"

113 INSERT INTO

114 station_stats

115 (account_id, station_id, playtime)

116 VALUES

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

118 ON CONFLICT (account_id, station_id)

119 DO UPDATE

120 SET playtime = station_stats.playtime + EXCLUDED.playtime;

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_countries(req: tide::Request<()>) -> tide::Result {

278 let sql = r#"

279 SELECT

280 country

281 FROM station

282 WHERE country != ''

283 GROUP BY country

284 ORDER BY COUNT(*) DESC;

285 "#

286 .to_string();

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

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

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

290 .await?;

291 Response::with(result)

292}

293

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

295 let sql = r#"

296 SELECT

297 UNNEST(languages) AS language

298 FROM station

299 GROUP BY UNNEST(languages)

300 ORDER BY COUNT(*) DESC;

301 "#

302 .to_string();

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

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

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

306 .await?;

307 Response::with(result)

308}

309

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

311 let sql = r#"

312 SELECT

313 UNNEST(tags) AS tag

314 FROM station

315 GROUP BY UNNEST(tags)

316 ORDER BY COUNT(*) DESC

317 LIMIT 100;

318 "#

319 .to_string();

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

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

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

323 .await?;

324 Response::with(result)

325}

326

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

328 let account =

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

330 let sql = format!(

331 r#"

332 SELECT

333 device.*

334 FROM device

335 WHERE device.account_id = {account_id}

336 "#,

337 account_id = account.id,

338 );

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

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

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

342 .await?;

343 Response::with(result)

344}

345

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

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

348 let account =

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

350 let sql = format!(

351 r#"

352 UPDATE

353 account

354 SET

355 name = '{name}',

356 language = '{language}'

357 WHERE account.id = {account_id}

358 RETURNING *

359 "#,

360 account_id = account.id,

361 name = updated_account.name.unwrap_or_default(),

362 language = updated_account.language,

363 );

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

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

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

367 .await?;

368 Response::with(result)

369}