so://phie

verbal

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

blob: bc330f0a0c03dff300359435a21cf212cf66076a (10872 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 CASE

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

38 THEN false

39 ELSE true

40 END AS is_favorite

41 FROM station

42 LEFT JOIN favorite

43 ON station.id = favorite.station_id

44 LEFT JOIN station_status

45 ON station.id = station_status.station_id

46 {conditions}

47 AND station_status.is_hidden IS NOT true

48 OFFSET {offset}

49 LIMIT 10

50 "#,

51 account_id = account.id,

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

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

54 );

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

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

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

58 .await?;

59 Response::with(result)

60}

61

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

63 let account =

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

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

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

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

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

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

70 };

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

72 Ok(interval) => interval * 2,

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

74 };

75 let mut total = 0;

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

77 let mut buf = [0; 10000];

78 let mut title = None;

79 loop {

80 let len =

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

82 bytes.extend_from_slice(&buf);

83 if total + len > interval {

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

85 if let Some(cap) =

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

87 .captures_iter(&metadata)

88 .next()

89 {

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

91 }

92 break;

93 }

94 if total > interval * 2 {

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

96 break;

97 }

98 total += len;

99 }

100 let sql = format!(

101 r#"

102 INSERT INTO

103 station_stats

104 (account_id, station_id, playtime)

105 VALUES

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

107 ON CONFLICT (account_id, station_id)

108 DO UPDATE

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

110 "#,

111 account_id = account.id,

112 station_id = station.id,

113 );

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

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

116 Response::with(title)

117}

118

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

120 let account =

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

122 let sql = format!(

123 r#"

124 SELECT

125 station.*,

126 station_status.is_restricted,

127 station_status.is_broken,

128 station_status.is_no_track_info,

129 station_status.is_hidden,

130 station_status.is_icon,

131 true as is_favorite

132 FROM station

133 LEFT JOIN favorite

134 ON station.id = favorite.station_id

135 LEFT JOIN station_status

136 ON station.id = station_status.station_id

137 WHERE favorite.account_id = {account_id}

138 AND station_status.is_hidden IS NOT true

139 "#,

140 account_id = account.id,

141 );

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

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

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

145 .await?;

146 Response::with(result)

147}

148

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

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

151 let account =

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

153 let sql = format!(

154 r#"

155 INSERT INTO

156 favorite

157 (account_id, station_id)

158 VALUES

159 ({account_id}, {station_id})

160 "#,

161 account_id = account.id,

162 station_id = station_id,

163 );

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

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

166 Response::with(())

167}

168

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

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

171 let account =

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

173 let sql = format!(

174 r#"

175 DELETE FROM

176 favorite

177 WHERE account_id = {account_id}

178 AND station_id = {station_id}

179 "#,

180 account_id = account.id,

181 station_id = station_id,

182 );

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

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

185 Response::with(())

186}

187

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

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

190 let account =

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

192 let sql = format!(

193 r#"

194 SELECT

195 station.*,

196 station_status.is_restricted,

197 station_status.is_broken,

198 station_status.is_no_track_info,

199 station_status.is_hidden,

200 station_status.is_icon,

201 CASE

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

203 THEN false

204 ELSE true

205 END AS is_favorite

206 FROM station

207 LEFT JOIN favorite

208 ON station.id = favorite.station_id

209 LEFT JOIN station_status

210 ON station.id = station_status.station_id

211 WHERE station.id = {station_id}

212 AND station_status.is_hidden IS NOT true

213 "#,

214 account_id = account.id,

215 station_id = station_id,

216 );

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

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

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

220 .await?;

221 Response::with(result)

222}

223

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

225 let sql = r#"

226 SELECT

227 country

228 FROM station

229 WHERE country != ''

230 GROUP BY country

231 ORDER BY COUNT(*) DESC;

232 "#

233 .to_string();

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

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

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

237 .await?;

238 Response::with(result)

239}

240

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

242 let sql = r#"

243 SELECT

244 UNNEST(languages) AS language

245 FROM station

246 GROUP BY UNNEST(languages)

247 ORDER BY COUNT(*) DESC;

248 "#

249 .to_string();

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

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

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

253 .await?;

254 Response::with(result)

255}

256

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

258 let sql = r#"

259 SELECT

260 UNNEST(tags) AS tag

261 FROM station

262 GROUP BY UNNEST(tags)

263 ORDER BY COUNT(*) DESC

264 LIMIT 100;

265 "#

266 .to_string();

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

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

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

270 .await?;

271 Response::with(result)

272}

273

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

275 let account =

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

277 let sql = format!(

278 r#"

279 SELECT

280 device.*

281 FROM device

282 WHERE device.account_id = {account_id}

283 "#,

284 account_id = account.id,

285 );

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

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

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

289 .await?;

290 Response::with(result)

291}

292

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

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

295 let account =

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

297 let sql = format!(

298 r#"

299 UPDATE

300 account

301 SET

302 name = '{name}',

303 language = '{language}'

304 WHERE account.id = {account_id}

305 RETURNING *

306 "#,

307 account_id = account.id,

308 name = updated_account.name.unwrap_or_default(),

309 language = updated_account.language,

310 );

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

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

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

314 .await?;

315 Response::with(result)

316}