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
use std::fs;
use std::fs::DirBuilder;
use chrono::Local;
use crypto::digest::Digest;
use crypto::sha1::Sha1;
use json::{array, JsonValue, object};

pub struct Body {}

impl Body {
    /// 内容信息处理
    pub fn def(header: JsonValue, body: Vec<u8>) -> JsonValue {
        let content_type = header["content-type"].as_str().unwrap();
        let content_length = header["content-length"].to_string().parse::<usize>().unwrap();
        let mut body_list = object! {
            get: object! {},
            post: object! {},
            files: object! {},
        };
        body_list["get"] = Body::query(header["uri"].clone().to_string());
        match content_type {
            "multipart/form-data" => {
                body_list = Body::multipart(header.clone(), body.clone(), body_list.clone());
            }
            "application/x-www-form-urlencoded" => {
                if content_length == 0 {
                    return body_list;
                }
                let text = String::from_utf8(body.clone()).unwrap();
                let text: Vec<&str> = text.split("&").collect();
                for item in text.iter() {
                    let row: Vec<&str> = item.split("=").collect();
                    body_list["post"][row[0].clone()] = row[1].clone().into();
                }
            }
            "application/json" => {
                if content_length == 0 {
                    return body_list;
                }
                let text = String::from_utf8(body.clone()).unwrap();
                body_list["post"] = json::parse(&*text.clone()).unwrap();
            }
            _ => {
                // println!(">>>>>>> >>>>>>");
                // println!("{}", data);
                // println!(">>>>>>> >>>>>>");
            }
        }
        body_list
    }

    /// 数据提取
    pub fn multipart(header: JsonValue, data: Vec<u8>, mut body_list: JsonValue) -> JsonValue {
        let boundary = header["boundary"].as_str().unwrap();
        let text = unsafe { String::from_utf8_unchecked(data.clone()) };
        let text = text.trim_start_matches("\r\n");
        let text = text.trim_end_matches(format!("\r\n--{}--\r\n", boundary.clone()).as_str()).to_string();

        let fg = format!("--{}\r\n", boundary.clone());
        let list: Vec<&str> = text.split(fg.as_str().clone()).collect();
        let mut index = 0;
        let mut body = data[2 + fg.len()..].to_vec();
        while index < list.len() {
            let item = list[index].to_string();
            let item = item.trim_start_matches(boundary.clone());
            let len = item.len();
            if len == 0 {
                index += 1;
                continue;
            }
            match item.contains("filename=") {
                false => {
                    let row: Vec<&str> = item.split("\r\n\r\n").collect();
                    let field: Vec<&str> = row[0].split("\"").collect();
                    let name = field[1];
                    let row: Vec<&str> = row[1].split("\r\n").collect();
                    let value: Vec<&str> = row[0].split("\"").collect();
                    body_list["post"][name] = value[0].clone().into();
                }
                true => {
                    let text: Vec<&str> = item.split("\r\n\r\n").collect();
                    let body = text[1];
                    let file = body.trim_start_matches("\u{0}");
                    let text: Vec<&str> = text[0].split("\r\n").collect();
                    let name: Vec<&str> = text[0].split("\"").collect();
                    let types: Vec<&str> = text[1].split(": ").collect();
                    let types = types[1];
                    let field = name[1];
                    let filename = name[3];
                    fn _content_type_mode(data: &str) -> String {
                        match data {
                            "image/png" => "png",
                            "image/jpeg" => "jpeg",
                            "image/jpg" => "jpg",
                            _ => "txt"
                        }.to_string().clone()
                    }
                    let mut file_data = object! {};
                    file_data["type"] = types.into();
                    file_data["name"] = filename.into();
                    file_data["size"] = file.len().into();


                    let mut hasher = Sha1::new();
                    hasher.input_str(file);

                    file_data["sha"] = hasher.result_str().into();
                    file_data["mode"] = JsonValue::String(_content_type_mode(types.clone()).clone());

                    let temp_file = format!("{}.{}", Local::now().timestamp_millis(), file_data["mode"]);

                    let public = header["public"].as_str().unwrap();
                    let temp= format!("{}/../temp", public);
                    let filename = format!("{}/../temp/{}", public, temp_file);
                    file_data["temp"] = filename.clone().into();
                    match DirBuilder::new().recursive(true).create(temp.clone()) {
                        Ok(_) => true,
                        Err(_) => false
                    };
                    match fs::write(filename.clone(), file.clone()) {
                        Ok(_) => {
                            if body_list["files"][field].is_empty() {
                                body_list["files"][field] = array![file_data];
                            } else {
                                body_list["files"][field].push(file_data).unwrap();
                            }
                            true
                        }
                        Err(_) => false
                    };
                }
            }
            index += 1;
            if index == list.len() {} else {
                body = body[len + fg.len()..].to_vec();
            }
        }
        body_list
    }
    pub fn query(data: String) -> JsonValue {
        let mut list = object! {};
        let query: Vec<&str> = data.split("?").collect();
        if query.len() == 1 {
            return list;
        }
        let query = query[1].clone();
        if query.is_empty() {
            return list;
        }
        let query: Vec<&str> = query.split("&").collect();

        for item in query.iter() {
            let row: Vec<&str> = item.split("=").collect();
            let key = row[0].clone();
            let value = row[1].clone();
            list[key] = value.into();
        }
        list
    }
}