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
//! High level connection client
//!
//! This module provides `ParamBuilder` as an high level XML formatter to create parameter strings and
//! `Client` which can seamlessly interface with any school's studentvue API

use crate::{
    request::WebHandle,
    enums::*,
    model::*,
    error::VueError,
};
use std::{
    borrow::Cow,
    fmt,
    fmt::Write,
};
use quick_xml::de;
use serde::Deserialize;

// POST request endpoint (ProcessWebServiceRequest is redundant for SOAP requests)
// In this case since we are solely making regular POST requests it is required
static ENDPOINT: &str = "/Service/PXPCommunication.asmx/ProcessWebServiceRequest";

/// Struct which connects to the StudentVUE service
#[derive(Debug, Clone, PartialEq)]
pub struct Client<'c> {
    pub uri: Cow<'c, str>,
    pub user: &'c str,
    pub pwd: &'c str,
}

/// StudentVUE parameter builder
#[derive(Debug, Clone)]
pub struct ParamBuilder {
    pub param_str: String,
}

impl<'c> Client<'c> {
    /// Instantiates a new `Client` with the username, password, and corresponding StudentVUE district url
    pub fn create(district_url: &'c str, username: &'c str, password: &'c str) -> Self {
        Client {
            uri: [district_url, ENDPOINT].concat().into(),
            user: username,
            pwd: password,
        }
    }

    /// Calls a method from a specified `WebServiceHandle` with the specified parameters
    ///
    /// # Example
    ///
    /// ```
    /// use studentvue::{
    ///     client::Client,
    ///     enums::{Method, WebServiceHandle},
    ///     client::ParamBuilder
    /// };
    /// use std::env;
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let (user, pwd) = (env::args().next().unwrap(), env::args().next().unwrap());
    ///
    ///     let client = Client::create("https://studentvue.phoenixunion.org", user.as_str(), pwd.as_str());
    ///     let xml = client.call_service(WebServiceHandle::PXPWebServices, Method::StudentSchoolInfo, ParamBuilder::create())
    ///         .await
    ///         .expect("Could not call service!");
    ///
    ///     println!("{}", xml);
    /// }
    /// ```
    pub async fn call_service(
        &self,
        web_service_handle: WebServiceHandle,
        method_name: Method,
        param_str: ParamBuilder,
    ) -> Result<String, VueError> {
        let body = [
            ("userID", self.user),
            ("password", self.pwd),
            ("skipLoginLog", "true"),
            ("parent", "false"),
            ("webServiceHandleName", web_service_handle.into()),
            ("methodName", method_name.into()),
            ("paramStr", &param_str.build_string())
        ];

        Ok(
            WebHandle::send(&self.uri, body)
                .await?
        )
    }

    /// Retrieves grades from a student; can be current or from a specified reporting period
    #[inline]
    pub async fn get_grades(&self, report_period: Option<u64>) -> Result<grade::GbData, VueError> {
        let parms = if report_period.is_none() {
            ParamBuilder::create()
        } else {
            ParamBuilder::create()
                .add_elements(&[ParamType::ReportPeriod(report_period.unwrap())])?
        };

        let xml_data = self.call_service(WebServiceHandle::PXPWebServices, Method::GradeBook, parms)
                .await?;

        Ok(de::from_str(xml_data.as_str())?)
    }

    /// Gets the absences from the student
    #[inline]
    pub async fn get_attendance(&self) -> Result<attendance::AttData, VueError> {
        let xml_data = self.call_service(WebServiceHandle::PXPWebServices, Method::Attendance, ParamBuilder::create())
            .await?;

        Ok(de::from_str(xml_data.as_str())?)
    }

    /// Retrieves student information such as their name, address, and grade
    #[inline]
    pub async fn get_student_info(&self) -> Result<student::Student, VueError> {
        let xml_data = self.call_service(WebServiceHandle::PXPWebServices, Method::StudentInfo, ParamBuilder::create())
            .await?;

        Ok(de::from_str(xml_data.as_str())?)
    }

    /// Retrieves the student's current school schedule
    #[inline]
    pub async fn get_schedule(&self) -> Result<schedule::StudentClassSchedule, VueError> {
        let xml_data = self.call_service(WebServiceHandle::PXPWebServices, Method::StudentClassList, ParamBuilder::create())
            .await?;

        Ok(de::from_str(xml_data.as_str())?)
    }

    /// Grabs information about the currently attended school
    #[inline]
    pub async fn get_school_info(&self) -> Result<school::StudentSchoolInfoListing, VueError> {
        let xml_data = self.call_service(WebServiceHandle::PXPWebServices, Method::StudentSchoolInfo, ParamBuilder::create())
            .await?;

        Ok(de::from_str(xml_data.as_str())?)
    }
}

impl ParamBuilder {
    /// Creates a new `ParamBuilder` instance
    pub fn create() -> Self {
        ParamBuilder {
            param_str: String::new()
        }
    }

    /// Adds several elements to the `Parms` node
    #[inline]
    pub fn add_elements(&mut self, params: &[ParamType]) -> Result<Self, std::fmt::Error> {
        for p in params.iter() {
            write!(&mut self.param_str, "{}\n", p.to_string())?;
        }

        Ok(self.clone())
    }

    /// Creates a xml string based on the attained attribute strings
    #[inline]
    pub fn build_string(&self) -> String {
        ["<Parms>\n", self.param_str.as_ref(), "</Parms>"].concat()
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn xml_building() {
        let mut params = ParamBuilder::create()
            .add_elements(&[ParamType::AssignmentID("e2qekn"),
                ParamType::ChildIntID(1),
                ParamType::LanguageCode(0),
                ParamType::RequestDate("1/23/19"),
                ParamType::HealthImmunizations(true)
            ]).unwrap();

        let res = "<Parms>\n<AssignmentID>e2qekn</AssignmentID>\n<ChildIntID>1</ChildIntID>\n<LanguageCode>0</LanguageCode>\n<RequestDate>1/23/19</RequestDate>\n<HealthImmunizations>true</HealthImmunizations>\n</Parms>";
        assert_eq!(&params.build_string(), res);
    }
}