so://phie

verbal

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

blob: 79fe49a6bd733eb468ed3825f18b7c54fde3aa1b (5792 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 CASE

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

37 THEN false

38 ELSE true

39 END AS is_favorite

40 FROM station

41 LEFT JOIN favorite

42 ON station.id = favorite.station_id

43 LEFT JOIN station_status

44 ON station.id = station_status.station_id

45 {conditions}

46 AND station_status.is_hidden IS NOT true

47 OFFSET {offset}

48 LIMIT 10

49 "#,

50 account_id = account.id,

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

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

53 );

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

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

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

57 .await?;

58 Response::with(result)

59}

60

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

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

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

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

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

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

67 };

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

69 Ok(interval) => interval * 2,

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

71 };

72 let mut total = 0;

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

74 let mut buf = [0; 10000];

75 let mut title = None;

76 loop {

77 let len =

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

79 bytes.extend_from_slice(&buf);

80 if total + len > interval {

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

82 if let Some(cap) =

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

84 .captures_iter(&metadata)

85 .next()

86 {

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

88 }

89 break;

90 }

91 if total > interval * 2 {

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

93 break;

94 }

95 total += len;

96 }

97 Response::with(title)

98}

99

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

101 let account =

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

103 let sql = format!(

104 r#"

105 SELECT

106 station.*,

107 station_status.is_restricted,

108 station_status.is_broken,

109 station_status.is_no_track_info,

110 station_status.is_hidden,

111 true as is_favorite

112 FROM station

113 LEFT JOIN favorite

114 ON station.id = favorite.station_id

115 LEFT JOIN station_status

116 ON station.id = station_status.station_id

117 WHERE favorite.account_id = {account_id}

118 AND station_status.is_hidden IS NOT true

119 "#,

120 account_id = account.id,

121 );

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

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

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

125 .await?;

126 Response::with(result)

127}

128

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

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

131 let account =

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

133 let sql = format!(

134 r#"

135 INSERT INTO

136 favorite

137 (account_id, station_id)

138 VALUES

139 ({account_id}, {station_id})

140 "#,

141 account_id = account.id,

142 station_id = station_id,

143 );

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

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

146 Response::with(())

147}

148

149pub async fn delete_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 DELETE FROM

156 favorite

157 WHERE account_id = {account_id}

158 AND station_id = {station_id}

159 "#,

160 account_id = account.id,

161 station_id = station_id,

162 );

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

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

165 Response::with(())

166}