so://phie

verbal

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

blob: e0b2d671867565ff98653d702c6780c3deff394d (12649 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 "#,

119 account_id = account.id,

120 station_id = station.id,

121 );

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

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

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

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

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

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

128 };

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

130 Ok(interval) => interval * 2,

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

132 };

133 let mut total = 0;

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

135 let mut buf = [0; 10000];

136 let mut title = None;

137 loop {

138 let len =

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

140 bytes.extend_from_slice(&buf);

141 if total + len > interval {

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

143 if let Some(cap) =

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

145 .captures_iter(&metadata)

146 .next()

147 {

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

149 }

150 break;

151 }

152 if total > interval * 2 {

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

154 break;

155 }

156 total += len;

157 }

158 Response::with(title)

159}

160

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

162 let account =

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

164 let sql = format!(

165 r#"

166 SELECT

167 station.*,

168 station_status.is_restricted,

169 station_status.is_broken,

170 station_status.is_no_track_info,

171 station_status.is_hidden,

172 station_status.is_icon,

173 station_stats.playtime,

174 true as is_favorite

175 FROM station

176 LEFT JOIN favorite

177 ON station.id = favorite.station_id

178 LEFT JOIN station_status

179 ON station.id = station_status.station_id

180 LEFT JOIN station_stats

181 ON station.id = station_stats.station_id

182 AND station_stats.account_id = {account_id}

183 WHERE favorite.account_id = {account_id}

184 AND station_status.is_hidden IS NOT true

185 "#,

186 account_id = account.id,

187 );

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

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

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

191 .await?;

192 Response::with(result)

193}

194

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

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

197 let account =

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

199 let sql = format!(

200 r#"

201 INSERT INTO

202 favorite

203 (account_id, station_id)

204 VALUES

205 ({account_id}, {station_id})

206 "#,

207 account_id = account.id,

208 station_id = station_id,

209 );

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

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

212 Response::with(())

213}

214

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

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

217 let account =

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

219 let sql = format!(

220 r#"

221 DELETE FROM

222 favorite

223 WHERE account_id = {account_id}

224 AND station_id = {station_id}

225 "#,

226 account_id = account.id,

227 station_id = station_id,

228 );

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

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

231 Response::with(())

232}

233

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

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

236 let account =

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

238 let sql = format!(

239 r#"

240 SELECT

241 station.*,

242 station_status.is_restricted,

243 station_status.is_broken,

244 station_status.is_no_track_info,

245 station_status.is_hidden,

246 station_status.is_icon,

247 station_stats.playtime,

248 CASE

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

250 THEN false

251 ELSE true

252 END AS is_favorite

253 FROM station

254 LEFT JOIN favorite

255 ON station.id = favorite.station_id

256 LEFT JOIN station_status

257 ON station.id = station_status.station_id

258 LEFT JOIN station_stats

259 ON station.id = station_stats.station_id

260 AND station_stats.account_id = {account_id}

261 WHERE station.id = {station_id}

262 AND station_status.is_hidden IS NOT true

263 "#,

264 account_id = account.id,

265 station_id = station_id,

266 );

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

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

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

270 .await?;

271 Response::with(result)

272}

273

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

275 let sql = r#"

276 SELECT

277 country

278 FROM station

279 WHERE country != ''

280 GROUP BY country

281 ORDER BY COUNT(*) DESC;

282 "#

283 .to_string();

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

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

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

287 .await?;

288 Response::with(result)

289}

290

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

292 let sql = r#"

293 SELECT

294 UNNEST(languages) AS language

295 FROM station

296 GROUP BY UNNEST(languages)

297 ORDER BY COUNT(*) DESC;

298 "#

299 .to_string();

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

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

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

303 .await?;

304 Response::with(result)

305}

306

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

308 let sql = r#"

309 SELECT

310 UNNEST(tags) AS tag

311 FROM station

312 GROUP BY UNNEST(tags)

313 ORDER BY COUNT(*) DESC

314 LIMIT 100;

315 "#

316 .to_string();

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

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

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

320 .await?;

321 Response::with(result)

322}

323

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

325 let account =

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

327 let sql = format!(

328 r#"

329 SELECT

330 device.*

331 FROM device

332 WHERE device.account_id = {account_id}

333 "#,

334 account_id = account.id,

335 );

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

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

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

339 .await?;

340 Response::with(result)

341}

342

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

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

345 let account =

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

347 let sql = format!(

348 r#"

349 UPDATE

350 account

351 SET

352 name = '{name}',

353 language = '{language}'

354 WHERE account.id = {account_id}

355 RETURNING *

356 "#,

357 account_id = account.id,

358 name = updated_account.name.unwrap_or_default(),

359 language = updated_account.language,

360 );

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

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

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

364 .await?;

365 Response::with(result)

366}