1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
#![deny(missing_docs)]
extern crate chrono;
#[macro_use]
extern crate failure_derive;
extern crate failure;
extern crate serde;
extern crate serde_json as json;
extern crate open;
extern crate tiny_http;
extern crate url;
extern crate rand;
extern crate hyper;
extern crate tokio_core;
extern crate futures;
extern crate hyper_tls;
#[macro_use]
extern crate log;
use std::collections::{HashMap, VecDeque};
use json::Value;
use hyper::{Request, Method};
#[cfg(test)]
mod test;
pub mod net;
pub mod data;
pub mod errors;
use errors::RedditError;
use failure::Error;
use url::Url;
use net::{Connection, body_from_map, uri_params_from_map};
use net::auth::OAuth;
use data::{Comment, Comments, Listing, Sort, Thing};
pub struct App {
conn: net::Connection,
}
impl App {
pub fn new(appname: &str, appversion: &str, appauthor: &str) -> Result<App, Error> {
Ok(App {
conn: Connection::new(appname, appversion, appauthor)?,
})
}
pub fn authorize(&mut self, oauth: &net::auth::OauthApp) -> Result<(), Error> {
self.conn.auth = Some(OAuth::new(&self.conn, oauth)?);
Ok(())
}
pub fn get_posts(&self, sub: &str, sort: Sort) -> Result<Value, Error> {
let req = Request::new(
Method::Get,
Url::parse_with_params(
&format!(
"https://www.reddit.com/r/{}/.\
json",
sub
),
sort.param(),
)?
.into_string()
.parse()?,
);
self.conn.run_request(req)
}
pub fn submit_self(&self, sub: &str, title: &str, text: &str, sendreplies: bool) -> Result<Value, Error> {
let mut params: HashMap<&str, &str> = HashMap::new();
params.insert("sr", sub);
params.insert("kind", "self");
params.insert("title", title);
params.insert("text", text);
params.insert("sendreplies", if sendreplies { "true" } else { "false" });
let mut req = Request::new(
Method::Post,
"https://oauth.reddit.com/api/submit/.json".parse()?,
);
req.set_body(body_from_map(¶ms));
self.conn.run_auth_request(req)
}
pub fn get_self(&self) -> Result<Value, Error> {
let req = Request::new(
Method::Get,
"https://oauth.reddit.com/api/v1/me/.json".parse()?,
);
self.conn.run_auth_request(req)
}
pub fn get_user(&self, name: &str) -> Result<Value, Error> {
let req = Request::new(
Method::Get,
format!("https://www.reddit.com/user/{}/about/.json", name)
.parse()?,
);
self.conn.run_request(req)
}
pub fn create_comment_stream(&self, sub: &str) -> Comments {
Comments::new(self, sub)
}
pub fn get_recent_comments(&self, sub: &str, limit: Option<i32>, before: Option<String>) -> Result<Listing<Comment>, Error> {
let limit_str;
let before_str;
let mut params: HashMap<&str, &str> = HashMap::new();
if let Some(limit) = limit {
limit_str = limit.to_string();
params.insert("limit", &limit_str);
}
if let Some(before) = before {
before_str = before;
params.insert("before", &before_str);
}
let req = Request::new(Method::Get, uri_params_from_map(&format!("https://www.reddit.com/r/{}/comments.json", sub), ¶ms)?);
let resp = self.conn.run_request(req)?;
let comments = Listing::from_value(&resp["data"]["children"], "", self)?;
Ok(comments)
}
pub fn get_comment_tree(&self, post: &str) -> Result<Listing<Comment>, Error> {
let mut req = Request::new(
Method::Get,
format!("https://www.reddit.com/comments/{}/.json", post)
.parse()?,
);
let mut params: HashMap<&str, &str> = HashMap::new();
params.insert("limit", "2147483648");
params.insert("depth", "2147483648");
req.set_body(body_from_map(¶ms));
let data = self.conn.run_request(req)?;
let data = data[1]["data"]["children"].clone();
Listing::from_value(&data, post, &self)
}
pub fn more_children(&self, link_id: &str, morechildren_id: &str, comments: &[&str]) -> Result<Listing<Comment>, Error> {
let mut string = String::from("t3_");
let link_id = if !link_id.starts_with("t3_") {
string.push_str(link_id);
&string
} else {
link_id
};
let limit = 5;
let mut chunks: Vec<String> = Vec::new();
let mut chunk_buf = String::new();
for (i, id) in comments.iter().enumerate() {
if i != 0 && i % limit == 0 {
chunk_buf.pop();
chunks.push(chunk_buf);
chunk_buf = String::new();
}
chunk_buf.push_str(&format!("{},", id));
}
chunk_buf.pop();
chunks.push(chunk_buf);
trace!("Chunks are {:?}", chunks);
let mut lists = Vec::new();
for chunk in chunks {
let mut params: HashMap<&str, &str> = HashMap::new();
params.insert("children", &chunk);
params.insert("link_id", link_id);
params.insert("id", morechildren_id);
params.insert("api_type", "json");
trace!("Getting more children {} from {}", chunk, link_id);
let mut req = Request::new(
Method::Post,
"https://www.reddit.com/api/morechildren/.json".parse()?,
);
req.set_body(body_from_map(¶ms));
let data = self.conn.run_request(req)?;
trace!("Scanning {}", data);
let list: Listing<Comment> = Listing::from_value(&data["json"]["data"]["things"], link_id, self)?;
lists.push(list);
}
let mut final_list = VecDeque::new();
for list in &mut lists {
final_list.append(&mut list.children);
}
let mut listing: Listing<Comment> = Listing::new();
for comment in final_list {
listing.insert_comment(comment);
}
Ok(listing)
}
pub fn comment(&self, text: &str, thing: &str) -> Result<(), Error> {
let mut params: HashMap<&str, &str> = HashMap::new();
params.insert("text", text);
params.insert("thing_id", thing);
let mut req = Request::new(
Method::Post,
"https://oauth.reddit.com/api/comment".parse()?,
);
req.set_body(body_from_map(¶ms));
self.conn.run_auth_request(req)?;
Ok(())
}
#[allow(unused_must_use)]
pub fn set_sticky(&self, sticky: bool, slot: Option<i32>, id: &str) -> Result<(), Error> {
let numstr;
let mut params: HashMap<&str, &str> = HashMap::new();
params.insert("state", if sticky { "1" } else { "0" });
if let Some(num) = slot {
if num != 1 && num != 2 {
return Err(Error::from(RedditError::BadRequest {
request: format!("Sticky's are limited to slots 1 and 2"),
response: "not sent".to_string(),
}));
}
numstr = num.to_string();
params.insert("num", &numstr);
}
params.insert("id", id);
let mut req = Request::new(
Method::Post,
"https://oauth.reddit.com/api/set_subreddit_sticky/.json"
.parse()?,
);
req.set_body(body_from_map(¶ms));
self.conn.run_auth_request(req);
Ok(())
}
pub fn load_thing<T>(&self, fullname: &str) -> Result<T, Error>
where
T: Thing,
{
let mut params: HashMap<&str, &str> = HashMap::new();
params.insert("names", fullname);
let req = Request::new(
Method::Get,
format!("https://www.reddit.com/by_id/{}/.json", fullname)
.parse()?,
);
let response = self.conn.run_request(req)?;
T::from_value(&response, self)
}
pub fn message(&self, to: &str, subject: &str, body: &str) -> Result<(), Error> {
let mut params: HashMap<&str, &str> = HashMap::new();
params.insert("to", to);
params.insert("subject", subject);
params.insert("text", body);
let mut req = Request::new(
Method::Post,
"https://oauth.reddit.com/api/compose/.json".parse()?,
);
req.set_body(body_from_map(¶ms));
match self.conn.run_auth_request(req) {
Ok(_) => Ok(()),
Err(e) => Err(e),
}
}
}