Browse Source

Mastodon-API refactor

pull/86/head
Toromino 5 months ago
parent
commit
163ea3f8a1

+ 12
- 14
src/activitypub/controller.rs View File

@@ -300,22 +300,20 @@ fn handle_object(object: serde_json::Value) {
300 300
     let serialized_object: Object = serde_json::from_value(object.clone()).unwrap();
301 301
 
302 302
     if !serialized_object.inReplyTo.is_none() {
303
-        let object_id = serialized_object.id;
304
-        let reply_id = serialized_object.inReplyTo.unwrap().clone();
305
-        thread::spawn(move || {
306
-            if !object_exists(&object_id) {
307
-                fetch_object_by_id(reply_id);
308
-            }
309
-        });
303
+        if !object_exists(&serialized_object.inReplyTo.clone().unwrap()) {
304
+            fetch_object_by_id(serialized_object.inReplyTo.unwrap().to_string());
305
+        }
310 306
     }
311 307
 
312
-    // Wrapping new object in an activity, as raw objects don't get stored
313
-    let activity = create(
314
-        &serialized_object.attributedTo,
315
-        object,
316
-        serialized_object.to,
317
-        serialized_object.cc,
318
-    );
308
+    if !object_exists(&serialized_object.id) {
309
+        // Wrapping new object in an activity, as raw objects don't get stored
310
+        let _activity = create(
311
+            &serialized_object.attributedTo,
312
+            object,
313
+            serialized_object.to,
314
+            serialized_object.cc,
315
+        );
316
+    }
319 317
 }
320 318
 
321 319
 /// Handles a newly fetched actor

+ 20
- 13
src/activitypub/routes.rs View File

@@ -4,35 +4,42 @@ use activitypub::controller;
4 4
 use activitypub::ActivitypubMediatype;
5 5
 use activitypub::ActivitystreamsResponse;
6 6
 use activitypub::Signature;
7
+use rocket::http::Status;
7 8
 use serde_json;
8 9
 
9 10
 #[get("/activities/<id>")]
10
-pub fn activity(media_type: ActivitypubMediatype, id: String) -> ActivitystreamsResponse {
11
+pub fn activity(_media_type: ActivitypubMediatype, id: String) -> ActivitystreamsResponse {
11 12
     ActivitystreamsResponse(ap_activity::get_activity_json_by_id(&id).to_string())
12 13
 }
13 14
 
14 15
 #[get("/actors/<handle>")]
15
-pub fn actor(media_type: ActivitypubMediatype, handle: String) -> ActivitystreamsResponse {
16
+pub fn actor(_media_type: ActivitypubMediatype, handle: String) -> ActivitystreamsResponse {
16 17
     ActivitystreamsResponse(ap_actor::get_json_by_preferred_username(&handle).to_string())
17 18
 }
18 19
 
19 20
 #[post("/actors/<id>/inbox", data = "<activity>")]
20
-pub fn actor_inbox(id: String, activity: String, _signature: Signature) {
21
-    controller::prepare_incoming(
22
-        serde_json::from_str(&activity).unwrap_or_else(|_| serde_json::json!({})),
23
-        _signature,
24
-    );
21
+pub fn actor_inbox(id: String, activity: String, _signature: Signature) -> Status {
22
+    match serde_json::from_str(&activity) {
23
+        Ok(serialized_activity) => {
24
+            controller::prepare_incoming(serialized_activity, _signature);
25
+            return rocket::http::Status::Ok;
26
+        }
27
+        Err(_) => return rocket::http::Status::BadRequest,
28
+    }
25 29
 }
26 30
 
27 31
 #[post("/inbox", data = "<activity>")]
28
-pub fn inbox(activity: String, _signature: Signature) {
29
-    controller::prepare_incoming(
30
-        serde_json::from_str(&activity).unwrap_or_else(|_| serde_json::json!({})),
31
-        _signature,
32
-    );
32
+pub fn inbox(activity: String, _signature: Signature) -> Status {
33
+    match serde_json::from_str(&activity) {
34
+        Ok(serialized_activity) => {
35
+            controller::prepare_incoming(serialized_activity, _signature);
36
+            return rocket::http::Status::Ok;
37
+        }
38
+        Err(_) => return rocket::http::Status::BadRequest,
39
+    }
33 40
 }
34 41
 
35 42
 #[get("/objects/<id>")]
36
-pub fn object(media_type: ActivitypubMediatype, id: String) -> ActivitystreamsResponse {
43
+pub fn object(_media_type: ActivitypubMediatype, id: String) -> ActivitystreamsResponse {
37 44
     ActivitystreamsResponse(ap_activity::get_object_json_by_id(&id).to_string())
38 45
 }

+ 1
- 1
src/kibou_api/mod.rs View File

@@ -12,7 +12,7 @@ use activity::{
12 12
 use activitypub::activity::{serialize_from_internal_activity, Tag};
13 13
 use activitypub::actor::{add_follow, remove_follow};
14 14
 use activitypub::controller as ap_controller;
15
-use activitypub::routes::object;
15
+
16 16
 use actor::{get_actor_by_acct, get_actor_by_id, get_actor_by_uri, is_actor_followed_by, Actor};
17 17
 use database;
18 18
 use diesel::PgConnection;

+ 174
- 122
src/mastodon_api/controller.rs View File

@@ -4,13 +4,15 @@ use activitypub;
4 4
 use actor;
5 5
 use actor::get_actor_by_id;
6 6
 use actor::get_actor_by_uri;
7
+use cached::TimedCache;
8
+use chrono;
7 9
 use chrono::Utc;
8 10
 use database;
9 11
 use diesel::PgConnection;
10 12
 use env;
11 13
 use kibou_api;
12 14
 use mastodon_api::{
13
-    Account, Attachment, HomeTimeline, Notification, PublicTimeline, RegistrationForm,
15
+    Account, Attachment, HomeTimeline, Instance, Notification, PublicTimeline, RegistrationForm,
14 16
     Relationship, Source, Status, StatusForm,
15 17
 };
16 18
 use notification::notifications_for_actor;
@@ -23,7 +25,7 @@ use rocket_contrib::json::JsonValue;
23 25
 use timeline;
24 26
 use timeline::{home_timeline as get_home_timeline, public_timeline as get_public_timeline};
25 27
 
26
-pub fn account_json_by_id(id: i64) -> JsonValue {
28
+pub fn account(id: i64) -> JsonValue {
27 29
     let database = database::establish_connection();
28 30
 
29 31
     match actor::get_actor_by_id(&database, &id) {
@@ -94,7 +96,7 @@ pub fn account_create(form: &RegistrationForm) -> Option<Token> {
94 96
         actor::create_actor(&database, &mut new_actor);
95 97
 
96 98
         match actor::get_local_actor_by_preferred_username(&database, &form.username) {
97
-            Ok(actor) => Some(oauth::token::create(&form.username)),
99
+            Ok(_actor) => Some(oauth::token::create(&form.username)),
98 100
             Err(_) => None,
99 101
         }
100 102
     } else {
@@ -115,14 +117,12 @@ pub fn account_statuses_json_by_id(
115 117
         Ok(actor) => {
116 118
             match timeline::user_timeline(&database, actor, max_id, since_id, min_id, limit) {
117 119
                 Ok(statuses) => {
118
-                    let mut serialized_statuses: Vec<Status> = vec![];
119
-
120
-                    for status in statuses {
121
-                        if let Ok(valid_status) = status_cached_by_id(status) {
122
-                            serialized_statuses.push(valid_status)
123
-                        }
124
-                    }
125
-                    json!(serialized_statuses)
120
+                    let status_vec: Vec<Status> = statuses
121
+                        .iter()
122
+                        .filter(|&id| status_cached_by_id(*id).is_ok())
123
+                        .map(|id| status_cached_by_id(*id).unwrap())
124
+                        .collect();
125
+                    return json!(status_vec);
126 126
                 }
127 127
                 Err(_) => json!({"error": "Error generating user timeline."}),
128 128
             }
@@ -148,8 +148,40 @@ pub fn context_json_for_id(id: i64) -> JsonValue {
148 148
     let database = database::establish_connection();
149 149
 
150 150
     match activity::get_activity_by_id(&database, id) {
151
-        Ok(activity) => {
152
-            json!({"ancestors": status_parents_for_id(&database, id, true), "descendants": status_children_for_id(&database, id, true)})
151
+        Ok(_activity) => {
152
+            let mut ancestors = status_parents_for_id(&database, id, true);
153
+            let mut descendants = status_children_for_id(&database, id, true);
154
+            ancestors.sort_by(|status_a, status_b| {
155
+                chrono::DateTime::parse_from_rfc3339(&status_a.created_at)
156
+                    .unwrap_or_else(|_| {
157
+                        chrono::DateTime::parse_from_rfc3339(&Utc::now().to_rfc3339()).unwrap()
158
+                    })
159
+                    .timestamp()
160
+                    .cmp(
161
+                        &chrono::DateTime::parse_from_rfc3339(&status_b.created_at)
162
+                            .unwrap_or_else(|_| {
163
+                                chrono::DateTime::parse_from_rfc3339(&Utc::now().to_rfc3339())
164
+                                    .unwrap()
165
+                            })
166
+                            .timestamp(),
167
+                    )
168
+            });
169
+            descendants.sort_by(|status_a, status_b| {
170
+                chrono::DateTime::parse_from_rfc3339(&status_a.created_at)
171
+                    .unwrap_or_else(|_| {
172
+                        chrono::DateTime::parse_from_rfc3339(&Utc::now().to_rfc3339()).unwrap()
173
+                    })
174
+                    .timestamp()
175
+                    .cmp(
176
+                        &chrono::DateTime::parse_from_rfc3339(&status_b.created_at)
177
+                            .unwrap_or_else(|_| {
178
+                                chrono::DateTime::parse_from_rfc3339(&Utc::now().to_rfc3339())
179
+                                    .unwrap()
180
+                            })
181
+                            .timestamp(),
182
+                    )
183
+            });
184
+            json!({"ancestors": ancestors, "descendants": descendants})
153 185
         }
154 186
         Err(_) => json!({"error": "Status not found"}),
155 187
     }
@@ -199,13 +231,62 @@ pub fn follow(token: String, id: i64) -> JsonValue {
199 231
     }
200 232
 }
201 233
 
202
-pub fn home_timeline_json(parameters: HomeTimeline, token: String) -> JsonValue {
203
-    match home_timeline(parameters, token) {
204
-        Ok(statuses) => json!(statuses),
205
-        Err(_) => json!({"error": "An error occured while generating timeline."}),
234
+pub fn home_timeline(parameters: HomeTimeline, token: String) -> JsonValue {
235
+    let database = database::establish_connection();
236
+
237
+    match verify_token(&database, token) {
238
+        Ok(token) => match actor::get_local_actor_by_preferred_username(&database, &token.actor) {
239
+            Ok(actor) => {
240
+                match get_home_timeline(
241
+                    &database,
242
+                    actor,
243
+                    parameters.max_id,
244
+                    parameters.since_id,
245
+                    parameters.min_id,
246
+                    parameters.limit,
247
+                ) {
248
+                    Ok(statuses) => {
249
+                        let status_vec: Vec<Status> = statuses
250
+                            .iter()
251
+                            .filter(|&id| status_cached_by_id(*id).is_ok())
252
+                            .map(|id| status_cached_by_id(*id).unwrap())
253
+                            .collect();
254
+                        return json!(status_vec);
255
+                    }
256
+                    Err(_e) => json!({"error": "An error occured while generating home timeline"}),
257
+                }
258
+            }
259
+            Err(_e) => json!({"error": "User associated to token not found"}),
260
+        },
261
+        Err(_e) => json!({"error": "Invalid oauth token"}),
206 262
     }
207 263
 }
208 264
 
265
+pub fn instance_info() -> JsonValue {
266
+    let database = database::establish_connection();
267
+    json!(Instance {
268
+        uri: format!(
269
+            "{base_scheme}://{base_domain}",
270
+            base_scheme = env::get_value(String::from("endpoint.base_scheme")),
271
+            base_domain = env::get_value(String::from("endpoint.base_domain"))
272
+        ),
273
+        title: env::get_value(String::from("node.name")),
274
+        description: env::get_value(String::from("node.description")),
275
+        email: env::get_value(String::from("node.contact_email")),
276
+        version: String::from("2.3.0 (compatible; Kibou 0.1)"),
277
+        thumbnail: None,
278
+        // Kibou does not support Streaming_API yet, but this value is not nullable according to
279
+        // Mastodon-API's specifications, so that is why it is showing an empty value instead
280
+        urls: serde_json::json!({"streaming_api": ""}),
281
+        // `domain_count` always stays 0 as Kibou does not keep data about remote nodes
282
+        stats: serde_json::json!({"user_count": actor::count_local_actors(&database).unwrap_or_else(|_| 0),
283
+        "status_count": activity::count_local_ap_notes(&database).unwrap_or_else(|_| 0),
284
+        "domain_count": 0}),
285
+        languages: vec![],
286
+        contact_account: None
287
+    })
288
+}
289
+
209 290
 pub fn notifications(token: String, limit: Option<i64>) -> JsonValue {
210 291
     let database = database::establish_connection();
211 292
 
@@ -236,43 +317,31 @@ pub fn notifications(token: String, limit: Option<i64>) -> JsonValue {
236 317
     }
237 318
 }
238 319
 
239
-pub fn public_timeline_json(parameters: PublicTimeline) -> JsonValue {
240
-    match public_timeline(parameters) {
241
-        Ok(statuses) => json!(statuses),
242
-        Err(_) => json!({"error": "An error occured while generating timeline."}),
243
-    }
244
-}
245
-
246
-pub fn relationships_json_by_token(token: &str, ids: Vec<i64>) -> JsonValue {
247
-    match relationships_by_token(token, ids) {
248
-        Ok(relationships) => json!(relationships),
249
-        Err(e) => json!({ "error": e }),
250
-    }
251
-}
252
-
253
-pub fn reblog(token: String, id: i64) -> JsonValue {
320
+pub fn public_timeline(parameters: PublicTimeline) -> JsonValue {
254 321
     let database = database::establish_connection();
255 322
 
256
-    match activity::get_activity_by_id(&database, id) {
257
-        Ok(activity) => match account_by_oauth_token(token) {
258
-            Ok(account) => {
259
-                kibou_api::react(
260
-                    &account.id.parse::<i64>().unwrap(),
261
-                    "Announce",
262
-                    activity.data["object"]["id"].as_str().unwrap(),
263
-                );
264
-                json!(status_cached_by_id(id))
265
-            }
266
-            Err(_) => json!({"error": "Token invalid!"}),
267
-        },
268
-        Err(_) => json!({"error": "Status not found"}),
323
+    match get_public_timeline(
324
+        &database,
325
+        parameters.local.unwrap_or_else(|| false),
326
+        parameters.only_media.unwrap_or_else(|| false),
327
+        parameters.max_id,
328
+        parameters.since_id,
329
+        parameters.min_id,
330
+        parameters.limit,
331
+    ) {
332
+        Ok(statuses) => {
333
+            let status_vec: Vec<Status> = statuses
334
+                .iter()
335
+                .filter(|&id| status_cached_by_id(*id).is_ok())
336
+                .map(|id| status_cached_by_id(*id).unwrap())
337
+                .collect();
338
+            return json!(status_vec);
339
+        }
340
+        Err(_e) => json!({"error": "An error occured while generating timeline."}),
269 341
     }
270 342
 }
271 343
 
272
-pub fn relationships_by_token(
273
-    token: &str,
274
-    ids: Vec<i64>,
275
-) -> Result<Vec<Relationship>, &'static str> {
344
+pub fn relationships(token: &str, ids: Vec<i64>) -> JsonValue {
276 345
     let database = database::establish_connection();
277 346
 
278 347
     match verify_token(&database, token.to_string()) {
@@ -342,11 +411,30 @@ pub fn relationships_by_token(
342 411
                         None => (),
343 412
                     }
344 413
                 }
345
-                return Ok(relationships);
414
+                return json!(relationships);
346 415
             }
347
-            Err(_) => Err("User not found."),
416
+            Err(_) => json!({"error": "User not found."}),
348 417
         },
349
-        Err(_) => Err("Acces token invalid!"),
418
+        Err(_) => json!({"error": "Access token invalid!"}),
419
+    }
420
+}
421
+
422
+pub fn reblog(token: String, id: i64) -> JsonValue {
423
+    let database = database::establish_connection();
424
+
425
+    match activity::get_activity_by_id(&database, id) {
426
+        Ok(activity) => match account_by_oauth_token(token) {
427
+            Ok(account) => {
428
+                kibou_api::react(
429
+                    &account.id.parse::<i64>().unwrap(),
430
+                    "Announce",
431
+                    activity.data["object"]["id"].as_str().unwrap(),
432
+                );
433
+                json!(status_cached_by_id(id))
434
+            }
435
+            Err(_) => json!({"error": "Token invalid!"}),
436
+        },
437
+        Err(_) => json!({"error": "Status not found"}),
350 438
     }
351 439
 }
352 440
 
@@ -418,8 +506,6 @@ pub fn status_cached_by_id(id: i64) -> Result<Status, String> {
418 506
 }
419 507
 
420 508
 pub fn status_json_by_id(id: i64) -> JsonValue {
421
-    let database = database::establish_connection();
422
-
423 509
     match status_cached_by_id(id) {
424 510
         Ok(status) => json!(status),
425 511
         Err(_) => json!({"error": "Status not found."}),
@@ -479,7 +565,7 @@ pub fn unsupported_endpoint() -> JsonValue {
479 565
 }
480 566
 
481 567
 cached! {
482
-    MASTODON_API_ACCOUNT_CACHE;
568
+    MASTODON_API_ACCOUNT_CACHE: TimedCache<(&'static str), Result<serde_json::Value, String>> = TimedCache::with_lifespan(300);
483 569
 fn account_by_uri(uri: &'static str) -> Result<serde_json::Value, String> = {
484 570
     let database = database::establish_connection();
485 571
     match actor::get_actor_by_uri(&database, uri) {
@@ -545,74 +631,10 @@ fn count_statuses(db_connection: &PgConnection, account_uri: &str) -> i64 {
545 631
     }
546 632
 }
547 633
 
548
-fn home_timeline(
549
-    parameters: HomeTimeline,
550
-    token: String,
551
-) -> Result<Vec<Status>, diesel::result::Error> {
552
-    let database = database::establish_connection();
553
-
554
-    match verify_token(&database, token) {
555
-        Ok(token) => match actor::get_local_actor_by_preferred_username(&database, &token.actor) {
556
-            Ok(actor) => {
557
-                match get_home_timeline(
558
-                    &database,
559
-                    actor,
560
-                    parameters.max_id,
561
-                    parameters.since_id,
562
-                    parameters.min_id,
563
-                    parameters.limit,
564
-                ) {
565
-                    Ok(statuses) => {
566
-                        let mut serialized_statuses: Vec<Status> = vec![];
567
-
568
-                        for status in statuses {
569
-                            if let Ok(valid_status) = status_cached_by_id(status) {
570
-                                serialized_statuses.push(valid_status)
571
-                            }
572
-                        }
573
-
574
-                        Ok(serialized_statuses)
575
-                    }
576
-                    Err(e) => Err(e),
577
-                }
578
-            }
579
-            Err(e) => Err(e),
580
-        },
581
-        Err(e) => Err(e),
582
-    }
583
-}
584
-
585
-fn public_timeline(parameters: PublicTimeline) -> Result<Vec<Status>, diesel::result::Error> {
586
-    let database = database::establish_connection();
587
-
588
-    match get_public_timeline(
589
-        &database,
590
-        parameters.local.unwrap_or_else(|| false),
591
-        parameters.only_media.unwrap_or_else(|| false),
592
-        parameters.max_id,
593
-        parameters.since_id,
594
-        parameters.min_id,
595
-        parameters.limit,
596
-    ) {
597
-        Ok(statuses) => {
598
-            let mut serialized_statuses: Vec<Status> = vec![];
599
-
600
-            for status in statuses {
601
-                if let Ok(valid_status) = status_cached_by_id(status) {
602
-                    serialized_statuses.push(valid_status)
603
-                }
604
-            }
605
-
606
-            Ok(serialized_statuses)
607
-        }
608
-        Err(e) => Err(e),
609
-    }
610
-}
611
-
612 634
 fn serialize_attachments_from_activitystreams(activity: &activity::Activity) -> Vec<Attachment> {
613 635
     let mut media_attachments: Vec<Attachment> = Vec::new();
614 636
     match activity.data["object"].get("attachment") {
615
-        Some(attachmenets) => {
637
+        Some(_attachments) => {
616 638
             let serialized_attachments: Vec<activitypub::Attachment> =
617 639
                 serde_json::from_value(activity.data["object"]["attachment"].to_owned()).unwrap();
618 640
 
@@ -660,6 +682,36 @@ fn serialize_notification_from_activitystreams(
660 682
                 .unwrap(),
661 683
             status: Some(status_cached_by_id(activity.id).unwrap()),
662 684
         }),
685
+        "Announce" => Ok(Notification {
686
+            id: activity.id.to_string(),
687
+            _type: String::from("reblog"),
688
+            created_at: serialized_activity.published,
689
+            account: account_cached_by_uri(Box::leak(activity.actor.to_owned().into_boxed_str()))
690
+                .unwrap(),
691
+            status: Some(
692
+                status_cached_by_id(
693
+                    get_ap_object_by_id(&database, serialized_activity.object.as_str().unwrap())
694
+                        .unwrap()
695
+                        .id,
696
+                )
697
+                .unwrap(),
698
+            ),
699
+        }),
700
+        "Like" => Ok(Notification {
701
+            id: activity.id.to_string(),
702
+            _type: String::from("favourite"),
703
+            created_at: serialized_activity.published,
704
+            account: account_cached_by_uri(Box::leak(activity.actor.to_owned().into_boxed_str()))
705
+                .unwrap(),
706
+            status: Some(
707
+                status_cached_by_id(
708
+                    get_ap_object_by_id(&database, serialized_activity.object.as_str().unwrap())
709
+                        .unwrap()
710
+                        .id,
711
+                )
712
+                .unwrap(),
713
+            ),
714
+        }),
663 715
         _ => Err(()),
664 716
     }
665 717
 }
@@ -781,7 +833,7 @@ fn serialize_status_from_activitystreams(activity: activity::Activity) -> Result
781 833
                         pinned: None,
782 834
                     })
783 835
                 }
784
-                Err(e) => Err(()),
836
+                Err(_e) => Err(()),
785 837
             }
786 838
         }
787 839
         _ => Err(()),
@@ -789,7 +841,7 @@ fn serialize_status_from_activitystreams(activity: activity::Activity) -> Result
789 841
 }
790 842
 
791 843
 cached! {
792
-    MASTODON_API_STATUS_CACHE;
844
+    MASTODON_API_STATUS_CACHE: TimedCache<(i64), Result<serde_json::Value, String>> = TimedCache::with_lifespan(300);
793 845
 fn status_by_id(id: i64) -> Result<serde_json::Value, String> = {
794 846
     let database = database::establish_connection();
795 847
     match activity::get_activity_by_id(&database, id) {

+ 0
- 32
src/mastodon_api/mod.rs View File

@@ -1,16 +1,9 @@
1 1
 pub mod controller;
2 2
 pub mod routes;
3
-
4
-use activity;
5
-use actor;
6
-use database;
7
-use env;
8 3
 use rocket::request;
9 4
 use rocket::request::FromRequest;
10 5
 use rocket::request::Request;
11 6
 use rocket::Outcome;
12
-use rocket_contrib::json;
13
-use rocket_contrib::json::JsonValue;
14 7
 use serde::{Deserialize, Serialize};
15 8
 use serde_json;
16 9
 
@@ -226,31 +219,6 @@ impl<'a, 'r> FromRequest<'a, 'r> for AuthorizationHeader {
226 219
     }
227 220
 }
228 221
 
229
-pub fn get_instance_info() -> JsonValue {
230
-    let database = database::establish_connection();
231
-    json!(Instance {
232
-        uri: format!(
233
-            "{base_scheme}://{base_domain}",
234
-            base_scheme = env::get_value(String::from("endpoint.base_scheme")),
235
-            base_domain = env::get_value(String::from("endpoint.base_domain"))
236
-        ),
237
-        title: env::get_value(String::from("node.name")),
238
-        description: env::get_value(String::from("node.description")),
239
-        email: env::get_value(String::from("node.contact_email")),
240
-        version: String::from("2.3.0 (compatible; Kibou 0.1)"),
241
-        thumbnail: None,
242
-        // Kibou does not support Streaming_API yet, but this value is not nullable according to
243
-        // Mastodon-API's specifications, so that is why it is showing an empty value instead
244
-        urls: serde_json::json!({"streaming_api": ""}),
245
-        // `domain_count` always stays 0 as Kibou does not keep data about remote nodes
246
-        stats: serde_json::json!({"user_count": actor::count_local_actors(&database).unwrap_or_else(|_| 0),
247
-        "status_count": activity::count_local_ap_notes(&database).unwrap_or_else(|_| 0),
248
-        "domain_count": 0}),
249
-        languages: vec![],
250
-        contact_account: None
251
-    })
252
-}
253
-
254 222
 pub fn parse_authorization_header(header: &str) -> String {
255 223
     let header_vec: Vec<&str> = header.split(" ").collect();
256 224
 

+ 31
- 29
src/mastodon_api/routes.rs View File

@@ -1,7 +1,7 @@
1 1
 use mastodon_api::controller;
2 2
 use mastodon_api::{
3
-    get_instance_info, parse_authorization_header, ApplicationForm, AuthorizationHeader,
4
-    HomeTimeline, PublicTimeline, StatusForm,
3
+    parse_authorization_header, ApplicationForm, AuthorizationHeader, HomeTimeline, PublicTimeline,
4
+    StatusForm,
5 5
 };
6 6
 use oauth::application::Application;
7 7
 use rocket::request::LenientForm;
@@ -9,17 +9,17 @@ use rocket_contrib::json::JsonValue;
9 9
 
10 10
 #[get("/api/v1/accounts/<id>")]
11 11
 pub fn account(id: i64) -> JsonValue {
12
-    controller::account_json_by_id(id)
12
+    return controller::account(id);
13 13
 }
14 14
 
15 15
 #[options("/api/v1/accounts/<id>")]
16 16
 pub fn options_account(id: i64) -> JsonValue {
17
-    account(id)
17
+    return account(id);
18 18
 }
19 19
 
20 20
 #[post("/api/v1/accounts/<id>/follow")]
21 21
 pub fn account_follow(_token: AuthorizationHeader, id: i64) -> JsonValue {
22
-    controller::follow(parse_authorization_header(&_token.to_string()), id)
22
+    return controller::follow(parse_authorization_header(&_token.to_string()), id);
23 23
 }
24 24
 
25 25
 #[get("/api/v1/accounts/<id>/statuses?<only_media>&<pinned>&<exclude_replies>&<max_id>&<since_id>&<min_id>&<limit>&<exclude_reblogs>")]
@@ -34,7 +34,7 @@ pub fn account_statuses(
34 34
     limit: Option<i64>,
35 35
     exclude_reblogs: Option<bool>,
36 36
 ) -> JsonValue {
37
-    controller::account_statuses_json_by_id(id, max_id, since_id, min_id, limit)
37
+    return controller::account_statuses_json_by_id(id, max_id, since_id, min_id, limit);
38 38
 }
39 39
 
40 40
 #[options("/api/v1/accounts/<id>/statuses?<only_media>&<pinned>&<exclude_replies>&<max_id>&<since_id>&<min_id>&<limit>&<exclude_reblogs>")]
@@ -49,7 +49,7 @@ pub fn options_account_statuses(
49 49
     limit: Option<i64>,
50 50
     exclude_reblogs: Option<bool>,
51 51
 ) -> JsonValue {
52
-    account_statuses(
52
+    return account_statuses(
53 53
         id,
54 54
         only_media,
55 55
         pinned,
@@ -59,28 +59,30 @@ pub fn options_account_statuses(
59 59
         min_id,
60 60
         limit,
61 61
         exclude_reblogs,
62
-    )
62
+    );
63 63
 }
64 64
 
65 65
 #[post("/api/v1/accounts/<id>/unfollow")]
66 66
 pub fn account_unfollow(_token: AuthorizationHeader, id: i64) -> JsonValue {
67
-    controller::unfollow(parse_authorization_header(&_token.to_string()), id)
67
+    return controller::unfollow(parse_authorization_header(&_token.to_string()), id);
68 68
 }
69 69
 
70 70
 #[get("/api/v1/accounts/verify_credentials")]
71 71
 pub fn account_verify_credentials(_token: AuthorizationHeader) -> JsonValue {
72
-    controller::account_json_by_oauth_token(parse_authorization_header(&_token.to_string()))
72
+    return controller::account_json_by_oauth_token(parse_authorization_header(
73
+        &_token.to_string(),
74
+    ));
73 75
 }
74 76
 
75 77
 #[options("/api/v1/accounts/verify_credentials")]
76 78
 pub fn options_account_verify_credentials(_token: AuthorizationHeader) -> JsonValue {
77
-    account_verify_credentials(_token)
79
+    return account_verify_credentials(_token);
78 80
 }
79 81
 
80 82
 #[post("/api/v1/apps", data = "<form>")]
81 83
 pub fn application(form: LenientForm<ApplicationForm>) -> JsonValue {
82 84
     let form_data: ApplicationForm = form.into_inner();
83
-    controller::application_create(Application {
85
+    return controller::application_create(Application {
84 86
         id: 0,
85 87
         client_name: Some(form_data.client_name),
86 88
         client_id: String::new(),
@@ -88,7 +90,7 @@ pub fn application(form: LenientForm<ApplicationForm>) -> JsonValue {
88 90
         redirect_uris: form_data.redirect_uris,
89 91
         scopes: form_data.scopes,
90 92
         website: form_data.website,
91
-    })
93
+    });
92 94
 }
93 95
 
94 96
 #[get("/api/v1/custom_emojis")]
@@ -103,12 +105,12 @@ pub fn filters() -> JsonValue {
103 105
 
104 106
 #[options("/api/v1/apps", data = "<form>")]
105 107
 pub fn options_application(form: LenientForm<ApplicationForm>) -> JsonValue {
106
-    application(form)
108
+    return application(form);
107 109
 }
108 110
 
109 111
 #[get("/api/v1/instance")]
110 112
 pub fn instance() -> JsonValue {
111
-    get_instance_info()
113
+    return controller::instance_info();
112 114
 }
113 115
 
114 116
 #[get("/api/v1/notifications?<limit>")]
@@ -118,40 +120,40 @@ pub fn notifications(_token: AuthorizationHeader, limit: Option<i64>) -> JsonVal
118 120
 
119 121
 #[options("/api/v1/instance")]
120 122
 pub fn options_instance() -> JsonValue {
121
-    instance()
123
+    return controller::instance_info();
122 124
 }
123 125
 
124 126
 #[get("/api/v1/statuses/<id>")]
125 127
 pub fn status(id: i64) -> JsonValue {
126
-    controller::status_json_by_id(id)
128
+    return controller::status_json_by_id(id);
127 129
 }
128 130
 
129 131
 #[options("/api/v1/statuses/<id>")]
130 132
 pub fn options_status(id: i64) -> JsonValue {
131
-    status(id)
133
+    return status(id);
132 134
 }
133 135
 
134 136
 #[get("/api/v1/statuses/<id>/context")]
135 137
 pub fn status_context(id: i64) -> JsonValue {
136
-    controller::context_json_for_id(id)
138
+    return controller::context_json_for_id(id);
137 139
 }
138 140
 
139 141
 #[post("/api/v1/statuses/<id>/favourite")]
140 142
 pub fn status_favourite(_token: AuthorizationHeader, id: i64) -> JsonValue {
141
-    controller::favourite(parse_authorization_header(&_token.to_string()), id)
143
+    return controller::favourite(parse_authorization_header(&_token.to_string()), id);
142 144
 }
143 145
 
144 146
 #[post("/api/v1/statuses", data = "<form>")]
145 147
 pub fn status_post(form: LenientForm<StatusForm>, _token: AuthorizationHeader) -> JsonValue {
146
-    controller::status_post(
148
+    return controller::status_post(
147 149
         form.into_inner(),
148 150
         parse_authorization_header(&_token.to_string()),
149
-    )
151
+    );
150 152
 }
151 153
 
152 154
 #[post("/api/v1/statuses/<id>/reblog")]
153 155
 pub fn status_reblog(_token: AuthorizationHeader, id: i64) -> JsonValue {
154
-    controller::reblog(parse_authorization_header(&_token.to_string()), id)
156
+    return controller::reblog(parse_authorization_header(&_token.to_string()), id);
155 157
 }
156 158
 
157 159
 #[get("/api/v1/timelines/home?<max_id>&<since_id>&<min_id>&<limit>")]
@@ -162,7 +164,7 @@ pub fn home_timeline(
162 164
     limit: Option<i64>,
163 165
     _token: AuthorizationHeader,
164 166
 ) -> JsonValue {
165
-    controller::home_timeline_json(
167
+    return controller::home_timeline(
166 168
         HomeTimeline {
167 169
             max_id,
168 170
             since_id,
@@ -170,7 +172,7 @@ pub fn home_timeline(
170 172
             limit,
171 173
         },
172 174
         parse_authorization_header(&_token.to_string()),
173
-    )
175
+    );
174 176
 }
175 177
 
176 178
 #[options("/api/v1/timelines/home?<max_id>&<since_id>&<min_id>&<limit>")]
@@ -181,7 +183,7 @@ pub fn options_home_timeline(
181 183
     limit: Option<i64>,
182 184
     _token: AuthorizationHeader,
183 185
 ) -> JsonValue {
184
-    home_timeline(max_id, since_id, min_id, limit, _token)
186
+    return home_timeline(max_id, since_id, min_id, limit, _token);
185 187
 }
186 188
 
187 189
 #[get("/api/v1/timelines/public?<local>&<only_media>&<max_id>&<since_id>&<min_id>&<limit>")]
@@ -193,14 +195,14 @@ pub fn public_timeline(
193 195
     min_id: Option<i64>,
194 196
     limit: Option<i64>,
195 197
 ) -> JsonValue {
196
-    controller::public_timeline_json(PublicTimeline {
198
+    return controller::public_timeline(PublicTimeline {
197 199
         local,
198 200
         only_media,
199 201
         max_id,
200 202
         since_id,
201 203
         min_id,
202 204
         limit,
203
-    })
205
+    });
204 206
 }
205 207
 
206 208
 #[options("/api/v1/timelines/public?<local>&<only_media>&<max_id>&<since_id>&<min_id>&<limit>")]
@@ -212,5 +214,5 @@ pub fn options_public_timeline(
212 214
     min_id: Option<i64>,
213 215
     limit: Option<i64>,
214 216
 ) -> JsonValue {
215
-    public_timeline(local, only_media, max_id, since_id, min_id, limit)
217
+    return public_timeline(local, only_media, max_id, since_id, min_id, limit);
216 218
 }

+ 2
- 2
src/oauth/application.rs View File

@@ -32,8 +32,8 @@ pub fn verify_credentials(
32 32
         .limit(1)
33 33
         .first::<QueryOAuthApplication>(db_connection)
34 34
     {
35
-        Ok(application) => true,
36
-        Err(e) => false,
35
+        Ok(_application) => true,
36
+        Err(_e) => false,
37 37
     }
38 38
 }
39 39
 

+ 2
- 2
src/oauth/authorization.rs View File

@@ -56,7 +56,7 @@ pub fn get_authorization_by_code(
56 56
 pub fn handle_user_authorization(
57 57
     user_form: UserForm,
58 58
     client_id: Option<String>,
59
-    response_type: Option<String>,
59
+    _response_type: Option<String>,
60 60
     redirect_uri: Option<String>,
61 61
     state: Option<String>,
62 62
     styling: Option<bool>,
@@ -74,7 +74,7 @@ pub fn handle_user_authorization(
74 74
                         Some(value) => format!("&state={}", value),
75 75
                         None => String::from(""),
76 76
                     };
77
-                    let mut symbol = if redirect_uri.contains("?") {
77
+                    let symbol = if redirect_uri.contains("?") {
78 78
                         "&".to_string()
79 79
                     } else {
80 80
                         "?".to_string()

+ 5
- 8
src/oauth/routes.rs View File

@@ -1,18 +1,15 @@
1
-use std::collections::HashMap;
2
-
1
+use oauth::authorization::{handle_user_authorization, UserForm};
2
+use oauth::token::{get_token, TokenForm};
3 3
 use rocket::request::LenientForm;
4 4
 use rocket::response::Redirect;
5
-use rocket_contrib::templates::Template;
6
-
7
-use oauth::authorization::handle_user_authorization;
8
-use oauth::authorization::UserForm;
9
-use oauth::token::{get_token, TokenForm};
10 5
 use rocket_contrib::json::JsonValue;
6
+use rocket_contrib::templates::Template;
7
+use std::collections::HashMap;
11 8
 
12 9
 #[get("/oauth/authorize?<styling>")]
13 10
 pub fn authorize(styling: Option<bool>) -> Template {
14 11
     let mut parameters = HashMap::<String, String>::new();
15
-    parameters.insert(String::from("error_context"), String::from(""));
12
+    parameters.insert(String::from("error_context"), String::new());
16 13
     parameters.insert(
17 14
         String::from("styling"),
18 15
         styling.unwrap_or_else(|| true).to_string(),

+ 1
- 1
src/raito_fe/api_controller.rs View File

@@ -220,7 +220,7 @@ pub fn register(form: LenientForm<RegistrationForm>) -> Option<String> {
220 220
 
221 221
 pub fn relationships_by_token(token: &str, ids: Vec<i64>) -> Option<Vec<Relationship>> {
222 222
     if unsafe { BYPASS_API } == &true {
223
-        match controller::relationships_by_token(token, ids) {
223
+        match serde_json::from_value(controller::relationships(token, ids).into()) {
224 224
             Ok(relationships) => Some(relationships),
225 225
             Err(_) => None,
226 226
         }

+ 1
- 1
src/raito_fe/mod.rs View File

@@ -56,7 +56,7 @@ impl<'a, 'r> FromRequest<'a, 'r> for Authentication {
56 56
 impl<'a, 'r> FromRequest<'a, 'r> for LocalConfiguration {
57 57
     type Error = ();
58 58
 
59
-    fn from_request(request: &'a Request<'r>) -> request::Outcome<LocalConfiguration, ()> {
59
+    fn from_request(_request: &'a Request<'r>) -> request::Outcome<LocalConfiguration, ()> {
60 60
         let mut new_config = HashMap::<String, String>::new();
61 61
         new_config.insert("javascript_enabled".to_string(), "false".to_string());
62 62
         new_config.insert("mastodon_api_base_uri".to_string(), unsafe {

+ 2
- 2
src/raito_fe/renderer.rs View File

@@ -140,7 +140,7 @@ pub fn account_follow(
140 140
     id: i64,
141 141
     unfollow: bool,
142 142
 ) -> Template {
143
-    let database = database::establish_connection();
143
+    let _database = database::establish_connection();
144 144
 
145 145
     let mut context = HashMap::<String, String>::new();
146 146
     context.extend(configuration.clone());
@@ -380,7 +380,7 @@ pub fn index(configuration: LocalConfiguration, authentication: Authentication)
380 380
     let mut context = HashMap::<String, String>::new();
381 381
 
382 382
     match &authentication.account {
383
-        Some(account) => return home_timeline(configuration, authentication),
383
+        Some(_account) => return home_timeline(configuration, authentication),
384 384
         None => {
385 385
             context.extend(configuration);
386 386
             context.extend(prepare_authentication_context(&authentication));

+ 1
- 1
src/tests/utils.rs View File

@@ -28,7 +28,7 @@ pub fn create_local_test_actor(username: &str) -> actor::Actor {
28 28
     test_actor
29 29
 }
30 30
 
31
-pub fn delete_test_actor(mut actor: actor::Actor) {
31
+pub fn delete_test_actor(actor: actor::Actor) {
32 32
     let database = database::establish_connection();
33 33
     actor::delete(&database, actor);
34 34
 }

+ 1
- 1
src/timeline.rs View File

@@ -70,7 +70,7 @@ pub fn public_activities(db_connection: &PgConnection) -> Result<Vec<i64>, diese
70 70
 pub fn public_timeline(
71 71
     db_connection: &PgConnection,
72 72
     local: bool,
73
-    only_media: bool,
73
+    _only_media: bool,
74 74
     max_id: Option<i64>,
75 75
     since_id: Option<i64>,
76 76
     min_id: Option<i64>,

+ 1
- 1
src/web/federator.rs View File

@@ -17,7 +17,7 @@ pub fn enqueue(mut actor: Actor, activity: serde_json::Value, inboxes: Vec<Strin
17 17
 
18 18
         println!("Federating activity to inbox: {}", inbox);
19 19
 
20
-        let request = client
20
+        let _request = client
21 21
             .post(&inbox)
22 22
             .header(DATE, chrono::Utc::now().to_rfc2822().to_string())
23 23
             .header(HOST, host)

+ 0
- 1
src/web/http_signatures.rs View File

@@ -3,7 +3,6 @@ use openssl::hash::MessageDigest;
3 3
 use openssl::pkey::PKey;
4 4
 use openssl::rsa::Rsa;
5 5
 use openssl::sign::Verifier;
6
-use std::collections::HashMap;
7 6
 
8 7
 #[derive(Debug)]
9 8
 pub struct Signature {

+ 1
- 1
src/well_known/webfinger.rs View File

@@ -8,7 +8,7 @@ use rocket_contrib::json::JsonValue;
8 8
 pub fn webfinger(resource: &RawStr) -> JsonValue {
9 9
     let database = database::establish_connection();
10 10
 
11
-    let mut parsed_resource: &str = &resource.as_str().replace("%3A", ":").replace("%40", "@");
11
+    let parsed_resource: &str = &resource.as_str().replace("%3A", ":").replace("%40", "@");
12 12
 
13 13
     match get_actor_by_acct(&database, &str::replace(parsed_resource, "acct:", "")) {
14 14
         Ok(actor) => {

Loading…
Cancel
Save