so://phie

verbal

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

blob: 3b787cfe3096c3fe50c7cad81ab12bfc29969052 (11493 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 station_status.is_icon,

36 station_stats.playtime,

37 CASE

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

39 THEN false

40 ELSE true

41 END AS is_favorite

42 FROM station

43 LEFT JOIN favorite

44 ON station.id = favorite.station_id

45 LEFT JOIN station_status

46 ON station.id = station_status.station_id

47 LEFT JOIN station_stats

48 ON station.id = station_stats.station_id

49 AND station_stats.account_id = {account_id}

50 {conditions}

51 AND station_status.is_hidden IS NOT true

52 OFFSET {offset}

53 LIMIT 10

54 "#,

55 account_id = account.id,

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

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

58 );

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

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

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

62 .await?;

63 Response::with(result)

64}

65

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

67 let account =

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

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

70 let sql = format!(

71 r#"

72 INSERT INTO

73 station_stats

74 (account_id, station_id, playtime)

75 VALUES

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

77 ON CONFLICT (account_id, station_id)

78 DO UPDATE

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

80 "#,

81 account_id = account.id,

82 station_id = station.id,

83 );

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

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

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

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

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

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

90 };

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

92 Ok(interval) => interval * 2,

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

94 };

95 let mut total = 0;

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

97 let mut buf = [0; 10000];

98 let mut title = None;

99 loop {

100 let len =

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

102 bytes.extend_from_slice(&buf);

103 if total + len > interval {

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

105 if let Some(cap) =

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

107 .captures_iter(&metadata)

108 .next()

109 {

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

111 }

112 break;

113 }

114 if total > interval * 2 {

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

116 break;

117 }

118 total += len;

119 }

120 Response::with(title)

121}

122

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

124 let account =

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

126 let sql = format!(

127 r#"

128 SELECT

129 station.*,

130 station_status.is_restricted,

131 station_status.is_broken,

132 station_status.is_no_track_info,

133 station_status.is_hidden,

134 station_status.is_icon,

135 station_stats.playtime,

136 true as is_favorite

137 FROM station

138 LEFT JOIN favorite

139 ON station.id = favorite.station_id

140 LEFT JOIN station_status

141 ON station.id = station_status.station_id

142 LEFT JOIN station_stats

143 ON station.id = station_stats.station_id

144 AND station_stats.account_id = {account_id}

145 WHERE favorite.account_id = {account_id}

146 AND station_status.is_hidden IS NOT true

147 "#,

148 account_id = account.id,

149 );

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

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

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

153 .await?;

154 Response::with(result)

155}

156

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

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

159 let account =

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

161 let sql = format!(

162 r#"

163 INSERT INTO

164 favorite

165 (account_id, station_id)

166 VALUES

167 ({account_id}, {station_id})

168 "#,

169 account_id = account.id,

170 station_id = station_id,

171 );

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

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

174 Response::with(())

175}

176

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

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

179 let account =

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

181 let sql = format!(

182 r#"

183 DELETE FROM

184 favorite

185 WHERE account_id = {account_id}

186 AND station_id = {station_id}

187 "#,

188 account_id = account.id,

189 station_id = station_id,

190 );

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

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

193 Response::with(())

194}

195

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

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

198 let account =

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

200 let sql = format!(

201 r#"

202 SELECT

203 station.*,

204 station_status.is_restricted,

205 station_status.is_broken,

206 station_status.is_no_track_info,

207 station_status.is_hidden,

208 station_status.is_icon,

209 station_stats.playtime,

210 CASE

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

212 THEN false

213 ELSE true

214 END AS is_favorite

215 FROM station

216 LEFT JOIN favorite

217 ON station.id = favorite.station_id

218 LEFT JOIN station_status

219 ON station.id = station_status.station_id

220 LEFT JOIN station_stats

221 ON station.id = station_stats.station_id

222 AND station_stats.account_id = {account_id}

223 WHERE station.id = {station_id}

224 AND station_status.is_hidden IS NOT true

225 "#,

226 account_id = account.id,

227 station_id = station_id,

228 );

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

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

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

232 .await?;

233 Response::with(result)

234}

235

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

237 let sql = r#"

238 SELECT

239 country

240 FROM station

241 WHERE country != ''

242 GROUP BY country

243 ORDER BY COUNT(*) DESC;

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

254 let sql = r#"

255 SELECT

256 UNNEST(languages) AS language

257 FROM station

258 GROUP BY UNNEST(languages)

259 ORDER BY COUNT(*) DESC;

260 "#

261 .to_string();

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

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

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

265 .await?;

266 Response::with(result)

267}

268

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

270 let sql = r#"

271 SELECT

272 UNNEST(tags) AS tag

273 FROM station

274 GROUP BY UNNEST(tags)

275 ORDER BY COUNT(*) DESC

276 LIMIT 100;

277 "#

278 .to_string();

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

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

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

282 .await?;

283 Response::with(result)

284}

285

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

287 let account =

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

289 let sql = format!(

290 r#"

291 SELECT

292 device.*

293 FROM device

294 WHERE device.account_id = {account_id}

295 "#,

296 account_id = account.id,

297 );

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

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

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

301 .await?;

302 Response::with(result)

303}

304

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

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

307 let account =

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

309 let sql = format!(

310 r#"

311 UPDATE

312 account

313 SET

314 name = '{name}',

315 language = '{language}'

316 WHERE account.id = {account_id}

317 RETURNING *

318 "#,

319 account_id = account.id,

320 name = updated_account.name.unwrap_or_default(),

321 language = updated_account.language,

322 );

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

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

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

326 .await?;

327 Response::with(result)

328}