raventhemer 1.4.4

A theme manager and switcher for desktop linux
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
pub mod ravens {
    use std::fs;
    use std::io;
    use std::fs::{File, OpenOptions};
    use std::io::Read;
    use std::env;
    use serde_json;
    use std::io::Write;
    use tar::{Archive, Builder};
    use reqwest;
    use ravenlib::rlib;
    fn get_home() -> String {
        return String::from(env::home_dir().unwrap().to_str().unwrap());
    }
    #[derive(Serialize, Deserialize, Debug)]
    pub struct UserInfo {
        name: String,
        token: String,
    }
    #[derive(Serialize, Deserialize, Debug)]
    pub struct MetaRes {
        screen: String,
        description: String,
    }
    pub fn load_info() -> Result<UserInfo, String> {
        if fs::metadata(get_home() + "/.config/raven/ravenserver.json").is_ok() {
            let mut info = String::new();
            File::open(get_home() + "/.config/raven/ravenserver.json")
                .expect("Couldn't read user info")
                .read_to_string(&mut info)
                .unwrap();
            let un = serde_json::from_str(&info);
            if un.is_ok() {
                Ok(un.unwrap())
            } else {
                Err("User info file in incorrect state".to_string())
            }
        } else {
            Err("Not logged in".to_string())
        }
    }
    pub fn export(theme_name: &str) {
        if fs::metadata(get_home() + "/.config/raven/themes/" + theme_name).is_ok() {
            let tb = File::create(theme_name.to_string() + ".tar").unwrap();
            let mut b = Builder::new(tb);
            b.append_dir_all(
                theme_name.to_string(),
                get_home() + "/.config/raven/themes/" + theme_name,
            ).expect("Couldn't add theme to archive");
            b.into_inner().expect("Couldn't write tar archive");
            println!("Wrote theme to {}.tar", theme_name)
        } else {
            println!("Theme does not exist");
        }
    }
    pub fn import(file_name: &str) {
        if fs::metadata(file_name).is_ok() {
            let mut arch = Archive::new(File::open(file_name).unwrap());
            arch.unpack(get_home() + "/.config/raven/themes/").expect(
                "Couldn't unpack theme archive",
            );
            println!("Imported theme.");
        }
    }
    fn up_info(inf: UserInfo) {
        let winfpath = get_home() + "/.config/raven/~ravenserver.json";
        let infpath = get_home() + "/.config/raven/ravenserver.json";
        OpenOptions::new()
            .create(true)
            .write(true)
            .open(&winfpath)
            .expect("Couldn't open user info file")
            .write_all(serde_json::to_string(&inf).unwrap().as_bytes())
            .expect("Couldn't write to user info file");
        fs::copy(&winfpath, &infpath).unwrap();
        fs::remove_file(&winfpath).unwrap();
    }
    pub fn logout() {
        fs::remove_file(get_home() + "/.config/raven/ravenserver.json")
            .expect("Couldn't delete user info file");
        println!("Successfully logged you out");
    }
    pub fn get_host() -> String {
        let conf = rlib::get_config();
        conf.host
    }
    pub fn delete_user(pass: String) {
        let info = load_info().unwrap();
        let client = reqwest::Client::new();
        let res = client
            .post(
                &(get_host() + "/themes/users/delete/" + &info.name + "?token=" + &info.token +
                      "&pass=" + &pass),
            )
            .send();
        if res.is_ok() {
            let res = res.unwrap();
            if res.status().is_success() {
                println!("Successfully deleted user and all owned themes. Logging out");
                logout();
            } else {
                if res.status() == reqwest::StatusCode::FORBIDDEN {
                    println!("You are trying to delete a user you are not. Bad!");
                } else if res.status() == reqwest::StatusCode::UNAUTHORIZED {
                    println!(
                        "You're trying to delete a user w/o providing authentication credentials"
                    );
                } else if res.status() == reqwest::StatusCode::NOT_FOUND {
                    println!("You're trying to delete a user that doesn't exist");
                } else {
                    println!("Server error. Code {:?}", res.status());
                }
            }
        } else {
            println!("Something went wrong with deleting your user. Error message:");
            println!("{:?}", res);

        }
    }
    pub fn create_user(name: String, pass: String, pass2: String) {
        if pass == pass2 {
            let client = reqwest::Client::new();
            let res = client
                .post(
                    &(get_host() + "/themes/user/create?name=" + &name + "&pass=" + &pass),
                )
                .send();
            if res.is_ok() {
                let res = res.unwrap();
                if res.status().is_success() {
                    println!(
                        "Successfully created user. Sign in with `raven login [name] [password]`"
                    );
                } else {
                    if res.status() == reqwest::StatusCode::FORBIDDEN {
                        println!("User already created. Pick a different name!");
                    } else if res.status() == reqwest::StatusCode::PAYLOAD_TOO_LARGE {
                        println!(
                            "Either your username or password was too long. The limit is 20 characters for username, and 100 for password."
                        );
                    } else {
                        println!("Server error. Code {:?}", res.status());
                    }
                }
            } else {
                println!("Something went wrong with creating a user. Error message:");
                println!("{:?}", res);
            }
        } else {
            println!("Passwords need to match");
        }
    }
    pub fn upload_theme(name: String) {
        let info = load_info().unwrap();
        if fs::metadata(get_home() + "/.config/raven/themes/" + &name).is_ok() {
            export(&name);
            if fs::metadata(name.clone() + ".tar").is_ok() {
                let form = reqwest::multipart::Form::new()
                    .file("fileupload", name.clone() + ".tar")
                    .unwrap();
                let res = reqwest::Client::new()
                    .post(
                        &(get_host() + "/themes/upload?name=" + &name + "&token=" + &info.token),
                    )
                    .multipart(form)
                    .send();

                if res.is_ok() {
                    let res = res.unwrap();
                    if res.status().is_success() {
                        if res.status() == reqwest::StatusCode::CREATED {
                            println!("Theme successfully uploaded.");
                        } else {
                            println!("Theme successfully updated.");
                        }
                        let theme_st = rlib::load_store(name.clone());
                        if theme_st.screenshot != rlib::default_screen() {
                            pub_metadata(name.clone(), String::from("screen"), theme_st.screenshot);
                        }
                        pub_metadata(
                            name.clone(),
                            String::from("description"),
                            theme_st.description,
                        );
                        fs::remove_file(name + ".tar").unwrap();
                    } else {
                        if res.status() == reqwest::StatusCode::FORBIDDEN {
                            println!("That theme already exists, and you are not its owner.");
                        } else {
                            println!("Server error. Code {:?}", res.status());
                        }

                    }
                } else {
                    println!("Something went wrong with uploading the theme. Error message:");
                    println!("{:?}", res);

                }
            } else {
                println!(
                    "Something has gone wrong. Check if the theme file was written to current directory."
                );
            }
        } else {
            println!("That theme does not exist");
        }
    }
    pub fn get_metadata(name: String) -> Result<MetaRes, String> {
        let client = reqwest::Client::new();
        let res = client.get(&(get_host() + "/themes/meta/" + &name)).send();
        if res.is_ok() {
            let mut res = res.unwrap();
            if res.status().is_success() {
                let meta: MetaRes = res.json().expect("Couldn't deserialize metadata responnse");
                Ok(meta)
            } else {
                if res.status() == reqwest::StatusCode::NOT_FOUND {
                    Err("Theme not found".to_string())
                } else {
                    Err("Internal Server Error".to_string())
                }
            }
        } else {
            Err("Could not fetch metadata".to_string())
        }
    }
    pub fn pub_metadata(name: String, typem: String, value: String) {
        let info = load_info().unwrap();
        let client = reqwest::Client::new();
        let res = client
            .post(
                &(get_host() + "/themes/meta/" + &name + "?typem=" + &typem + "&value=" + &value +
                      "&token=" + &info.token),
            )
            .send();
        if res.is_ok() {
            let res = res.unwrap();
            if res.status().is_success() {
                println!("Successfully updated theme metadata");
            } else {
                if res.status() == reqwest::StatusCode::NOT_FOUND {
                    println!("That theme hasn't been published");
                } else if res.status() == reqwest::StatusCode::FORBIDDEN {
                    println!("Can't edit the metadata of a theme that isn't yours");
                } else if res.status() == reqwest::StatusCode::PRECONDITION_FAILED {
                    println!("That isn't a valid metadata type");
                } else if res.status() == reqwest::StatusCode::PAYLOAD_TOO_LARGE {
                    println!(
                        "Your description or screenshot url was more than 200 characters long. Please shorten itt."
                    );
                } else {
                    println!("Server error. Code {:?}", res.status());

                }
            }
        }
    }
    pub fn unpublish_theme(name: String) {
        let info = load_info().unwrap();
        let client = reqwest::Client::new();
        let res = client
            .post(
                &(get_host() + "/themes/delete/" + &name + "?token=" + &info.token),
            )
            .send();
        if res.is_ok() {
            let res = res.unwrap();
            if res.status().is_success() {
                println!("Successfully unpublished theme");
            } else {
                if res.status() == reqwest::StatusCode::NOT_FOUND {
                    println!("Can't unpublish a nonexistent theme");
                } else if res.status() == reqwest::StatusCode::FORBIDDEN {
                    println!("Can't unpublish a theme that isn't yours");
                } else if res.status() == reqwest::StatusCode::UNAUTHORIZED {
                    println!("Did not provide a valid login token");
                } else {
                    println!("Server error. Code {:?}", res.status());

                }
            }
        } else {
            println!("Something went wrong with unpublishing the theme. Error message: ");
            println!("{:?}", res);
        }
    }
    pub fn install_warning(esp: bool) {
        println!(
            "Warning: When you install themes from the online repo, there is some danger. Please evaluate the theme files before loading the theme, and if you find any malicious theme, please report it on the theme's page at {} and it will be removed.",
            get_host()
        );
        if esp {
            println!(
                "This theme should be scrutinized more carefully as it includes a bash script which will be run automatically."
            );
        }
        println!("Thank you for helping keep the repo clean!");
    }
    pub fn download_theme(name: String, force: bool) {
        let client = reqwest::Client::new();
        let res = client.get(&(get_host() + "/themes/repo/" + &name)).send();
        if res.is_ok() {
            let mut res = res.unwrap();
            if res.status().is_success() {
                let mut file = OpenOptions::new()
                    .create(true)
                    .write(true)
                    .open(name.clone() + ".tar")
                    .expect("Couldn't write theme file");
                res.copy_to(&mut file).expect("Couldn't pipe to archive");
                println!("Downloaded theme.");
                if res.status() == reqwest::StatusCode::ALREADY_REPORTED && !force {
                    print!(
                        "This theme has recently been reported, and has not been approved by an admin. It is not advisable to install this theme. Are you sure you would like to continue? (y/n)"
                    );
                    io::stdout().flush().unwrap();
                    let mut r = String::new();
                    io::stdin().read_line(&mut r).unwrap();
                    if r.trim() == "y" {
                        println!(
                            "Continuing. Please look carefully at the theme files in ~/.config/raven/themes/{} before loading this theme.",
                            name.clone()
                        );
                        import(&(name.clone() + ".tar"));
                        println!("Imported theme. Removing archive.");
                        fs::remove_file(name.clone() + ".tar").unwrap();
                        println!("Downloading metadata.");
                        let meta = get_metadata(name.clone()).unwrap();
                        let mut st = rlib::load_store(name.clone());
                        st.screenshot = meta.screen;
                        st.description = meta.description;
                        rlib::up_theme(st);
                        if fs::metadata(
                            get_home() + "/.config/raven/themes/" + &name + "/script",
                        ).is_ok() ||
                            fs::metadata(
                                get_home() + "/.config/raven/themes/" + &name + "/lemonbar",
                            ).is_ok()
                        {
                            if !force {
                                install_warning(true);
                            }
                        } else {
                            if !force {
                                install_warning(false);
                            }
                        }
                    } else {
                        println!("Removing downloaded archive.");
                        fs::remove_file(name.clone() + ".tar").unwrap();
                    }
                } else {
                    if res.status() == reqwest::StatusCode::ALREADY_REPORTED {
                        print!(
                            "This theme has recently been reported, and has not been approved by an admin. It is not advisable to install this theme. Continuing because of --force."
                        );
                    }
                    import(&(name.clone() + ".tar"));
                    println!("Imported theme. Removing archive.");
                    fs::remove_file(name.clone() + ".tar").unwrap();
                    println!("Downloading metadata.");
                    let meta = get_metadata(name.clone()).unwrap();
                    let mut st = rlib::load_store(name.clone());
                    st.screenshot = meta.screen;
                    st.description = meta.description;
                    rlib::up_theme(st);
                    if fs::metadata(get_home() + "/.config/raven/themes/" + &name + "/script")
                        .is_ok() ||
                        fs::metadata(get_home() + "/.config/raven/themes/" + &name + "/lemonbar")
                            .is_ok()
                    {
                        if !force {
                            install_warning(true);
                        }
                    } else {
                        if !force {
                            install_warning(false);
                        }
                    }

                }

            } else {
                if res.status() == reqwest::StatusCode::NOT_FOUND {
                    println!("Theme has not been uploaded");
                } else {
                    println!("Server error. Code {:?}", res.status());
                }
            }
        } else {
            println!("Something went wrong with downloading the theme. Error message:");
            println!("{:?}", res);
        }
    }
    pub fn login_user(name: String, pass: String) {
        let client = reqwest::Client::new();
        let res = client
            .get(
                &(get_host() + "/themes/user/login?name=" + &name + "&pass=" + &pass),
            )
            .send();
        if res.is_ok() {
            let mut res = res.unwrap();
            if res.status().is_success() {
                println!("Successfully signed in. Writing login info to disk.");
                let info = res.json().unwrap();
                up_info(info);
            } else {
                if res.status() == reqwest::StatusCode::FORBIDDEN {
                    println!("Wrong login info. Try again!");
                } else {
                    println!("Server error. Code {:?}", res.status());
                }
            }
        } else {
            println!("Something went wrong with logging in. Error message:");
            println!("{:?}", res);
        }
    }
}