so://phie

verbal

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

blob: 6377a4b0132f6a532f088860d877664c9b988ba9 (15269 bytes)[doc][blame][raw]

1#[macro_use]

2extern crate diesel;

3

4use diesel::prelude::*;

5use tide_diesel::DieselMiddleware;

6use tide_diesel::DieselRequestExt;

7use tide_compress::CompressMiddleware;

8

9mod utils;

10mod error;

11mod config;

12mod schema;

13mod models;

14mod adapter;

15mod response;

16mod middleware;

17

18use config::Config;

19use models::*;

20use schema::account::dsl::account;

21use response::Response;

22use middleware::CorsMiddleware;

23

24#[async_std::main]

25async fn main() -> tide::Result<()> {

26

27 let config = Config::from_file("./config.ron")

28 .expect("Unable to parse config!");

29

30 let mut app = tide::new();

31

32 /* bind database middleware */

33 app.with(DieselMiddleware::new(&config.database.to_string()).unwrap());

34

35 /* bind cors middleware */

36 app.with(CorsMiddleware::new(&config.options.origin));

37

38 /* bind compression middleware */

39 app.with(CompressMiddleware::new());

40

41 /* handle prefetch */

42 app.at("*").options(|_: tide::Request<()>| async move {

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

44 });

45

46 /* provide index */

47 app.at("/").serve_file("www/index.html")?;

48

49 /* provide assets */

50 app.at("/asset").serve_dir("www/asset/")?;

51

52 /* provide app */

53 app.at("/app").serve_dir("app/")?;

54

55 app.at("/api").get(|req: tide::Request<()>| async move {

56 let conn = req.pg_conn().await?;

57 let results = account.load::<Account>(&conn)?;

58 Response::with(results)

59 });

60

61 app.listen(&config.server.to_string()).await?;

62

63 Ok(())

64

65}

66

67 // /* get account */

68 // app.at("/api/account").get(|req: tide::Request<State>| async move {

69 // let account = match identify(&req).await {

70 // Ok(model) => model,

71 // Err(err) => return Response::throw(err),

72 // };

73 // Response::with(&account.inner)

74 // });

75

76 // /* create account */

77 // app.at("/api/account").post(|req: tide::Request<State>| async move {

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

79 // let account = Model::new(Account::default());

80 // match sqlx::query(&account.into_insert("account"))

81 // .execute(conn.acquire().await.unwrap())

82 // .await

83 // {

84 // Ok(_) => Response::success(),

85 // Err(err) => Response::throw(Error::new(ErrorKind::Query, &err.to_string())),

86 // }

87 // });

88

89 // /* update account */

90 // app.at("/api/account").put(|mut req: tide::Request<State>| async move {

91 // let mut account = match identify(&req).await {

92 // Ok(model) => model,

93 // Err(err) => return Response::throw(err),

94 // };

95 // let inner = match req.body_json::<Account>().await {

96 // Ok(inner) => inner,

97 // Err(err) => return Response::throw(Error::new(ErrorKind::Arguments, &err.to_string())),

98 // };

99 // account.inner = inner;

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

101 // match sqlx::query(&account.into_update("account"))

102 // .execute(conn.acquire().await.unwrap())

103 // .await

104 // {

105 // Ok(_) => Response::success(),

106 // Err(err) => Response::throw(Error::new(ErrorKind::Query, &err.to_string())),

107 // }

108 // });

109

110 // /* get favorite */

111 // app.at("/api/favorite").get(|req: tide::Request<State>| async move {

112 // let state = req.state();

113 // let account = match identify(&req).await {

114 // Ok(model) => model,

115 // Err(err) => return Response::throw(err),

116 // };

117 // let query = format!(

118 // "

119 // SELECT station_id FROM favorite

120 // WHERE account_id = {}

121 // ORDER BY created_at DESC

122 // ",

123 // &account.id,

124 // );

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

126 // let station_ids = match sqlx::query(&query)

127 // .fetch_all(conn.acquire().await.unwrap())

128 // .await

129 // {

130 // Ok(rows) => rows.iter().map(|row| row.get("station_id")).collect::<Vec<String>>(),

131 // Err(err) => return Response::throw(Error::new(ErrorKind::Query, &err.to_string())),

132 // };

133 // let url = format!(

134 // "{}/json/stations/byuuid?uuids={}",

135 // &state.config.options.api_url,

136 // &station_ids.join(","),

137 // );

138 // let mut response = match surf::get(&url).await {

139 // Ok(response) => response,

140 // Err(err) => return Response::throw(Error::new(ErrorKind::Fetch, &err.to_string())),

141 // };

142 // let adapters = match response.body_json::<Vec<StationAdapter>>().await {

143 // Ok(adapters) => adapters,

144 // Err(err) => return Response::throw(Error::new(ErrorKind::Parse, &err.to_string())),

145 // };

146 // let mut stations = vec![];

147 // for station_id in station_ids {

148 // for adapter in &adapters {

149 // if adapter.stationuuid == station_id {

150 // let mut station = Station::default();

151 // station.is_favorite = true;

152 // stations.push(adapter.clone().populate(station));

153 // }

154 // }

155 // }

156 // Response::with(&stations)

157 // });

158

159 // /* create favorite */

160 // app.at("/api/favorite").post(|mut req: tide::Request<State>| async move {

161 // let account = match identify(&req).await {

162 // Ok(model) => model,

163 // Err(err) => return Response::throw(err),

164 // };

165 // let id = match req.body_json::<String>().await {

166 // Ok(inner) => inner,

167 // Err(err) => return Response::throw(Error::new(ErrorKind::Arguments, &err.to_string())),

168 // };

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

170 // let favorite = Model::new(Favorite::new(&id, account.id));

171 // match sqlx::query(&favorite.into_insert("favorite"))

172 // .execute(conn.acquire().await.unwrap())

173 // .await

174 // {

175 // Ok(_) => Response::success(),

176 // Err(err) => Response::throw(Error::new(ErrorKind::Query, &err.to_string())),

177 // }

178 // });

179

180 // /* delete favorite */

181 // app.at("/api/favorite").delete(|mut req: tide::Request<State>| async move {

182 // let account = match identify(&req).await {

183 // Ok(model) => model,

184 // Err(err) => return Response::throw(err),

185 // };

186 // let id = match req.body_json::<String>().await {

187 // Ok(inner) => inner,

188 // Err(err) => return Response::throw(Error::new(ErrorKind::Arguments, &err.to_string())),

189 // };

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

191 // match sqlx::query(&format!(

192 // "

193 // DELETE FROM favorite

194 // WHERE account_id = {}

195 // AND station_id = '{}'

196 // ",

197 // &account.id,

198 // &id,

199 // ))

200 // .execute(conn.acquire().await.unwrap())

201 // .await

202 // {

203 // Ok(_) => Response::success(),

204 // Err(err) => Response::throw(Error::new(ErrorKind::Query, &err.to_string())),

205 // }

206 // });

207

208 // /* search */

209 // app.at("/api/search").get(|req: tide::Request<State>| async move {

210 // let account = match identify(&req).await {

211 // Ok(model) => model,

212 // Err(err) => return Response::throw(err),

213 // };

214 // let inner = match req.query::<Search>() {

215 // Ok(inner) => inner,

216 // Err(err) => return Response::throw(Error::new(ErrorKind::Arguments, &err.to_string())),

217 // };

218 // let state = req.state();

219 // let url = format!(

220 // "{}/json/stations/search?{}",

221 // &state.config.options.api_url,

222 // &inner.into_query(),

223 // );

224 // let mut response = match surf::get(&url).await {

225 // Ok(response) => response,

226 // Err(err) => return Response::throw(Error::new(ErrorKind::Fetch, &err.to_string())),

227 // };

228 // let adapters = match response.body_json::<Vec<StationAdapter>>().await {

229 // Ok(adapters) => adapters,

230 // Err(err) => return Response::throw(Error::new(ErrorKind::Parse, &err.to_string())),

231 // };

232 // let query = format!(

233 // "

234 // SELECT station_id

235 // FROM favorite

236 // WHERE account_id = {}

237 // ",

238 // &account.id,

239 // );

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

241 // let station_ids = match sqlx::query(&query)

242 // .fetch_all(conn.acquire().await.unwrap())

243 // .await

244 // {

245 // Ok(rows) => rows.iter().map(|row| row.get("station_id")).collect::<Vec<String>>(),

246 // Err(err) => return Response::throw(Error::new(ErrorKind::Query, &err.to_string())),

247 // };

248 // let mut stations = vec![];

249 // for adapter in &adapters {

250 // let mut station = Station::default();

251 // station.is_favorite = station_ids.contains(&adapter.stationuuid);

252 // stations.push(adapter.clone().populate(station));

253 // }

254 // Response::with(&stations)

255 // });

256

257 // /* song */

258 // app.at("/api/song").get(|mut req: tide::Request<State>| async move {

259 // let _ = match identify(&req).await {

260 // Ok(model) => model,

261 // Err(err) => return Response::throw(err),

262 // };

263 // let inner = match req.body_json::<String>().await {

264 // Ok(inner) => inner,

265 // Err(err) => return Response::throw(Error::new(ErrorKind::Arguments, &err.to_string())),

266 // };

267 // let mut response = match surf::get(&inner)

268 // .header("icy-metadata", "1")

269 // .await {

270 // Ok(response) => response,

271 // Err(err) => return Response::throw(Error::new(ErrorKind::Fetch, &err.to_string())),

272 // };

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

274 // Some(header) => header.as_str(),

275 // None => return Response::throw(Error::new(ErrorKind::Arguments, "No request header 'icy-metaint' found!")),

276 // };

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

278 // Ok(value) => value * 2,

279 // Err(err) => return Response::throw(Error::new(ErrorKind::Parse, &err.to_string())),

280 // };

281 // let mut count = 0;

282 // let mut bytes = vec![];

283 // let mut buf = [0; 10000];

284 // let mut title = None;

285 // loop {

286 // let len = response.read(&mut buf).await.unwrap();

287 // bytes.extend_from_slice(&buf);

288 // if count + len > interval {

289 // let metadata = String::from_utf8_lossy(&bytes);

290 // for cap in Regex::new("StreamTitle='([^;]*)';").unwrap()

291 // .captures_iter(&metadata)

292 // {

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

294 // break;

295 // }

296 // break;

297 // }

298 // count += len;

299 // }

300 // Response::with_option(title)

301 // });

302

303 // /* get code */

304 // app.at("/api/code").get(|req: tide::Request<State>| async move {

305 // let account = match identify(&req).await {

306 // Ok(model) => model,

307 // Err(err) => return Response::throw(err),

308 // };

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

310 // match sqlx::query_as::<_, Code>(

311 // &format!(

312 // "

313 // SELECT *, timestamp <= CURRENT_TIMESTAMP AT TIME ZONE 'UTC' - INTERVAL '1 minutes' as expired

314 // FROM code

315 // WHERE account_id = {}

316 // ",

317 // &account.id,

318 // )

319 // )

320 // .fetch_one(conn.acquire().await.unwrap())

321 // .await

322 // {

323 // Ok(code) => Response::with(code),

324 // Err(err) => Response::throw(Error::new(ErrorKind::Query, &err.to_string())),

325 // }

326 // });

327

328 // /* create code */

329 // app.at("/api/code").post(|req: tide::Request<State>| async move {

330 // let account = match identify(&req).await {

331 // Ok(model) => model,

332 // Err(err) => return Response::throw(err),

333 // };

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

335 // let code = Code::new();

336 // match sqlx::query(

337 // &format!(

338 // "

339 // INSERT INTO code

340 // (code, account_id, timestamp, used)

341 // VALUES

342 // ('{}', '{}', CURRENT_TIMESTAMP, false)

343 // ON CONFLICT

344 // (account_id)

345 // DO UPDATE

346 // SET

347 // code = excluded.code,

348 // timestamp = excluded.timestamp,

349 // used = excluded.used

350 // ",

351 // &code.code,

352 // &account.id,

353 // )

354 // )

355 // .execute(conn.acquire().await.unwrap())

356 // .await

357 // {

358 // Ok(_) => Response::with(code),

359 // Err(err) => Response::throw(Error::new(ErrorKind::Query, &err.to_string())),

360 // }

361 // });

362

363 // /* update code */

364 // app.at("/api/code").put(|req: tide::Request<State>| async move {

365 // let _ = match identify(&req).await {

366 // Ok(model) => model,

367 // Err(err) => return Response::throw(err),

368 // };

369 // Response::success()

370 // });

371

372// async fn identify(req: &tide::Request<State>) -> Result<Model<Account>, Error> {

373// let token = match req.header("verbal-token") {

374// Some(header) => header.as_str(),

375// None => return Err(Error::new(ErrorKind::Identity, "No request header 'verbal-token' provided!")),

376// };

377// let query = format!(

378// "

379// SELECT account.* FROM account

380// INNER JOIN device

381// ON device.account_id = account.id

382// WHERE device.token = '{}'

383// ",

384// &token,

385// );

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

387// let id = match sqlx::query(&query)

388// .fetch_one(conn.acquire().await.unwrap())

389// .await

390// {

391// Ok(row) => row.get("id"),

392// Err(_) => return Err(Error::new(ErrorKind::Identity, "No account found for provided header 'verbal-token'!")),

393// };

394// let inner = match sqlx::query_as::<_, Account>(&query)

395// .fetch_one(conn.acquire().await.unwrap())

396// .await

397// {

398// Ok(inner) => inner,

399// Err(_) => return Err(Error::new(ErrorKind::Identity, "No account found for provided header 'verbal-token'!")),

400// };

401// Ok(Model::from(id, inner))

402// }