检索访问信息Google gdata api C#
我正在尝试检索我的用户最近登录任何谷歌应用程序服务(如Gmail)的日期(或通过移动设备/imap/pop等为他们登录的日期)。我是谷歌教育应用程序领域的管理员,使用C#gdata api 我想回收学生用户名,如果他们已经离开超过一年没有登录到他们的gmail应用程序,并要求最后访问日期来完成这一点 如果可能的话,请告诉我检索访问信息Google gdata api C#,c#,rest,gdata-api,C#,Rest,Gdata Api,我正在尝试检索我的用户最近登录任何谷歌应用程序服务(如Gmail)的日期(或通过移动设备/imap/pop等为他们登录的日期)。我是谷歌教育应用程序领域的管理员,使用C#gdata api 我想回收学生用户名,如果他们已经离开超过一年没有登录到他们的gmail应用程序,并要求最后访问日期来完成这一点 如果可能的话,请告诉我 谢谢。我使用了gmail报告API。我忘了这是从哪里弄来的,但我是从什么地方偷来的。如果你知道在哪里,请放一个评论链接 /// <summary> //
谢谢。我使用了gmail报告API。我忘了这是从哪里弄来的,但我是从什么地方偷来的。如果你知道在哪里,请放一个评论链接
/// <summary>
/// This contains the logic for constructing and submitting a report
/// request to the Google Apps reporting service and reading the response.
///
/// The description of the web service protocol can be found at:
///
/// http://code.google.com/apis/apps/reporting/google_apps_reporting_api.html
///
/// Example usage:
/// Get the latest accounts report to standard output.
/// client.getReport("accounts", null, null);
/// Get the accounts report for May 15, 2007 and save it to out.txt.
/// client.getReport("accounts", "2007-05-15", "out.txt");
/// </summary>
public class ReportsManager
{
/// <summary>
/// URL to POST to obtain an authentication token
/// </summary>
private const string CLIENT_LOGIN_URL =
"https://www.google.com/accounts/ClientLogin";
/// <summary>
/// URL to POST to retrive resports from the API
/// </summary>
private const string REPORTING_URL =
"https://www.google.com/hosted/services/v1.0/reports/ReportingData";
/// <summary>
/// Date format of the API
/// </summary>
private const string DATE_FORMAT = "yyyy-MM-dd";
/// <summary>
/// Hour of the day when the API data gets published
/// </summary>
private const int PUBLISH_HOUR_OF_DAY = 13; // Publish hour + 1 hour;
/// <summary>
/// Time diference to UTC
/// </summary>
private const int PUBLISH_TIME_DIFERENCE_TO_UTC = -8;
/// <summary>
/// Email command-line argument
/// </summary>
private const string EMAIL_ARG = "email";
/// <summary>
/// Password command-line argument
/// </summary>
private const string PASSWORD_ARG = "password";
/// <summary>
/// Domain command-line argument
/// </summary>
private const string DOMAIN_ARG = "domain";
/// <summary>
/// Report command-line argument
/// </summary>
private const string REPORT_ARG = "report";
/// <summary>
/// Date command-line argument
/// </summary>
private const string DATE_ARG = "date";
/// <summary>
/// Output File command-line argument
/// </summary>
private const string OUT_FILE_ARG = "out";
/// <summary>
/// Message for command-line usage
/// </summary>
private const string USAGE = "Usage: " +
"ReportingAPI --" + EMAIL_ARG + " <email> --" +
PASSWORD_ARG + " <password> [ --" +
DOMAIN_ARG + " <domain> ] --" +
REPORT_ARG + " <report name> [ --" +
DATE_ARG + " <YYYY-MM-DD> ] [ --" +
OUT_FILE_ARG + " <file name> ]";
/// <summary>
/// List of command-line arguments
/// </summary>
private static string[] PROPERTY_NAMES = new String[] {EMAIL_ARG,
PASSWORD_ARG, DOMAIN_ARG, REPORT_ARG, DATE_ARG, OUT_FILE_ARG};
/// <summary>
/// List of required command-line arguments
/// </summary>
private static string[] REQUIRED_PROPERTY_NAMES = new String[] {
EMAIL_ARG, PASSWORD_ARG, REPORT_ARG};
/// <summary>
/// Google Apps Domain
/// </summary>
public string domain = null;
/// <summary>
/// Email address of an Administrator account
/// </summary>
public string email = null;
/// <summary>
/// Password of the Administrator account
/// </summary>
public string password = null;
/// <summary>
/// Identifies the type of account
/// </summary>
private string accountType = "HOSTED";
/// <summary>
/// Identifies the Google service
/// </summary>
private string service = "apps";
/// <summary>
/// Contains a token value that Google uses to authorize
/// access to the requested report data
/// </summary>
private string token = null;
/// <summary>
/// Default constructor
/// </summary>
public ReportsManager(string username, string password, string domain)
{
this.email = username + "@" + domain;
this.password = password;
this.domain = domain;
}
/// <summary>
/// Retrieves the Authentication Token
/// </summary>
/// <returns>Returns the authentication token.</returns>
public string GetToken()
{
return this.token;
}
/// <summary>
/// Logs in the user and initializes the Token
/// </summary>
public void ClientLogin()
{
string token = null;
UTF8Encoding encoding = new UTF8Encoding();
string postData = "Email=" + System.Web.HttpUtility.UrlEncode(this.email) +
"&Passwd=" + System.Web.HttpUtility.UrlEncode(this.password) +
"&accountType=" + System.Web.HttpUtility.UrlEncode(this.accountType) +
"&service=" + System.Web.HttpUtility.UrlEncode(this.service);
byte[] data = encoding.GetBytes(postData);
HttpWebRequest request =
(HttpWebRequest)WebRequest.Create(CLIENT_LOGIN_URL);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = data.Length;
Stream inputStream = request.GetRequestStream();
inputStream.Write(data, 0, data.Length);
inputStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
string responseStr = (new StreamReader(
response.GetResponseStream())).ReadToEnd();
char[] tokenizer = { '\r', '\n' };
string[] parts = responseStr.Split(tokenizer);
foreach (string part in parts)
{
if (part.StartsWith("SID="))
{
token = part.Substring(4);
break;
}
}
this.token = token;
}
/// <summary>
/// Creates a XML request for the Report
/// </summary>
/// <param name="reportName">The name of the Report: activity,
/// disk_space, email_clients, quota_limit_accounts,
/// summary, suspended_account</param>
/// <param name="date">Date of the Report</param>
/// <returns>Thx XML request as a string</returns>
public string createRequestXML(string reportName, string date)
{
if (this.domain == null)
{
this.domain = getAdminEmailDomain();
}
string xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
xml += "<rest xmlns=\"google:accounts:rest:protocol\"";
xml += " xmlns:xsi=\"";
xml += "http://www.w3.org/2001/XMLSchema-instance\">";
xml += "<type>Report</type>";
xml += "<token>" + this.GetToken() + "</token>";
xml += "<domain>" + this.domain + "</domain>";
xml += "<date>" + date + "</date>";
xml += "<reportType>daily</reportType>";
xml += "<reportName>" + reportName + "</reportName>";
xml += "</rest>";
return xml;
}
/// <summary>
/// Get the domain of the admin's email address.
/// </summary>
/// <returns>the domain, otherwise returns null</returns>
public string getAdminEmailDomain()
{
if (this.email != null)
{
int atIndex = this.email.IndexOf('@');
if (atIndex > 0 && atIndex + 1 < this.email.Length)
{
return this.email.Substring(atIndex + 1);
}
}
else
{
throw new ArgumentNullException("Invalid Email");
}
return null;
}
public enum ReportType
{
accounts,
activity,
disk_space,
email_clients,
quota_limit_accounts,
summary,
suspended_account
}
/// <summary>
/// Get the reports by reportName for a Date, and writes the report
/// at filename /// or to the console if filename is null.
/// </summary>
/// <param name="reportName">The name of the Report: activity,
/// disk_space, email_clients, quota_limit_accounts,summary,
/// suspended_account</param>
/// <param name="date">Date of the Report,
/// null date gets latest date available</param>
private Dictionary<string, ArrayList> getReport(string reportName, string date)
{
if (date == null)
{
date = getLatestReportDate().ToString(DATE_FORMAT);
}
else
{
try
{
date = System.Convert.ToDateTime(date).ToString
(DATE_FORMAT);
}
catch
{
throw new ArgumentException("Invalid Date");
}
}
string xml = createRequestXML(reportName, date);
HttpWebRequest request =
(HttpWebRequest)WebRequest.Create(REPORTING_URL);
request.Method = "POST";
UTF8Encoding encoding = new UTF8Encoding();
byte[] postBuffer = encoding.GetBytes(xml);
request.ContentLength = postBuffer.Length;
request.ContentType = "application/x-www-form-urlencoded";
Stream requestStream = request.GetRequestStream();
requestStream.Write(postBuffer, 0, postBuffer.Length);
requestStream.Close();
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
StreamReader reader = new StreamReader(
response.GetResponseStream());
String firstLine = null;
String lineBuffer = String.Empty;
if (reader.Peek() >= 0)
{
firstLine = reader.ReadLine();
checkError(firstLine, reader);
}
Dictionary<string, ArrayList> csv = new Dictionary<string, ArrayList>();
string[] headers = null;
if (firstLine != null)
{
headers = firstLine.Split(',');
foreach (string header in headers)
{
csv.Add(header, new ArrayList());
}
}
if (headers != null)
{
while ((lineBuffer = reader.ReadLine()) != null)
{
string[] dataLine = lineBuffer.Split(',');
for (int i = 0; i < csv.Keys.Count; i++)
{
csv[headers[i]].Add(dataLine[i]);
}
}
}
reader.Close();
return csv;
}
/// <summary>
/// Get the reports by reportName for a Date, and writes the report
/// at filename or to the console if filename is null.
/// </summary>
/// <param name="reportName">The name of the Report: activity,
/// disk_space, email_clients, quota_limit_accounts,summary,
/// suspended_account</param>
/// <param name="date">
/// Date of the Report, null date gets latest date available</param>
public Dictionary<string, ArrayList> getReport(ReportType reportType, DateTime date)
{
string reportName = Enum.GetName(typeof(ReportType), reportType);
return this.getReport(reportName, date.ToString(DATE_FORMAT));
}
/// <summary>
/// Checks for errors on the Http Response, errors are on XML format.
/// When the response is xml throws an Exception with the xml text.
/// </summary>
/// <param name="firstLine">
/// First line of the StreamReader from the Http Response</param>
/// <param name="reader">StreamReader from the Http Response</param>
private void checkError(string firstLine, StreamReader reader)
{
if (firstLine.Trim().StartsWith("<?xml"))
{
String xmlText = firstLine;
while (reader.Peek() >= 0)
{
xmlText += reader.ReadLine();
}
throw new Exception(xmlText);
}
}
/// <summary>
/// Get latest available report date,
/// based on report service time zone.
/// Reports for the current date are available after 12:00 PST8PDT
/// the following day.
/// </summary>
/// <returns>Lastest date available</returns>
public DateTime getLatestReportDate()
{
if (DateTime.UtcNow.AddHours(PUBLISH_TIME_DIFERENCE_TO_UTC).Hour
< PUBLISH_HOUR_OF_DAY)
{
return DateTime.Now.AddDays(-2);
}
else
{
return DateTime.Now.AddDays(-1);
}
}
/// <summary>
/// Gets the properties from the command-line arguments.
/// </summary>
/// <param name="args">command-line arguments</param>
/// <returns>Properties Hashtable</returns>
private static Hashtable getProperties(string[] args)
{
Hashtable properties = new Hashtable();
for (int i = 0; i < args.Length; i++)
{
bool found = false;
for (int j = 0; j < PROPERTY_NAMES.Length; j++)
{
if (args[i].Equals("--" + PROPERTY_NAMES[j]))
{
found = true;
if (i + 1 < args.Length)
{
properties.Add(PROPERTY_NAMES[j], args[i + 1]);
i++;
break;
}
else
{
throw new ArgumentException("Missing value for " +
"command-line parameter " + args[i]);
}
}
}
if (!found)
{
throw new ArgumentException(
"Unrecognized parameter " + args[i]);
}
}
for (int i = 0; i < REQUIRED_PROPERTY_NAMES.Length; i++)
{
if (properties[REQUIRED_PROPERTY_NAMES[i]] == null)
{
throw new ArgumentException("Missing value for " +
"command-line parameter " + REQUIRED_PROPERTY_NAMES[i]);
}
}
return properties;
}
}
//
///这包含构建和提交报告的逻辑
///请求谷歌应用程序报告服务并读取响应。
///
///有关web服务协议的说明,请访问:
///
/// http://code.google.com/apis/apps/reporting/google_apps_reporting_api.html
///
///用法示例:
///获取标准输出的最新帐户报告。
///client.getReport(“accounts”,null,null);
///获取2007年5月15日的帐户报告,并将其保存到out.txt。
///client.getReport(“accounts”,“2007-05-15”,“out.txt”);
///
公共类报表管理器
{
///
///发布以获取身份验证令牌的URL
///
私有常量字符串客户端\u登录\u URL=
"https://www.google.com/accounts/ClientLogin";
///
///从API发布以检索响应的URL
///
私有常量字符串报告\u URL=
"https://www.google.com/hosted/services/v1.0/reports/ReportingData";
///
///API的日期格式
///
私有常量字符串日期\u格式=“yyyy-MM-dd”;
///
///API数据发布的时间
///
private const int PUBLISH_HOUR_OF_DAY=13;//PUBLISH HOUR+1小时;
///
///与UTC的时间差
///
专用常数int PUBLISH_TIME_DIFERENCE_TO_UTC=-8;
///
///电子邮件命令行参数
///
private const string EMAIL_ARG=“EMAIL”;
///
///密码命令行参数
///
私有常量字符串密码\u ARG=“PASSWORD”;
///
///域命令行参数
///
private const string DOMAIN_ARG=“DOMAIN”;
///
///报告命令行参数
///
private const string REPORT_ARG=“REPORT”;
///
///日期命令行参数
///
private const string DATE_ARG=“DATE”;
///
///输出文件命令行参数
///
private const string OUT\u FILE\u ARG=“OUT”;
///
///用于命令行使用的消息
///
private const string用法=“用法:”+
“ReportingAPI--“+电子邮件参数+”--”+
密码_ARG+“[--”+
域_ARG+“]--”+
报告_ARG+“[--”+
日期\u ARG+“][--”+
OUT_FILE_ARG+“]”;
///
///命令行参数列表
///
私有静态字符串[]属性\u名称=新字符串[]{EMAIL\u ARG,
密码参数、域参数、报告参数、日期参数、输出文件参数};
///
///所需命令行参数的列表
///
私有静态字符串[]必需\u属性\u名称=新字符串[]{
电子邮件、密码、报告;
///
///谷歌应用程序域
///
公共字符串域=null;
///
///管理员帐户的电子邮件地址
///
公共字符串email=null;
///
///管理员帐户的密码
///
公共字符串密码=null;
///
///标识帐户的类型
///
私有字符串accountType=“HOSTED”;
///
///标识Google服务
///
私有字符串服务=“应用程序”;
///
///包含Google用于授权的令牌值
///访问请求的报告数据
///
私有字符串标记=null;
///
///默认构造函数
///
公共报表管理器(字符串用户名、字符串密码、字符串域)
{
this.email=用户名+“@”+域;
this.password=密码;
this.domain=域;
}
///
///检索身份验证令牌
///
///返回身份验证令牌。
公共字符串GetToken()
{
返回此.token;
}
///
///登录用户并初始化令牌
///
public void ClientLogin()
{
字符串标记=null;
UTF8Encoding=新的UTF8Encoding();
string postData=“Email=”+System.Web.HttpUtility.UrlEncode(this.Email)+
“&Passwd=“+System.Web.HttpUtility.UrlEncode(this.password)+
“&accountType=“+System.Web.HttpUtility.UrlEncode(this.accountType)+
“&service=“+System.Web.HttpUtility.UrlEncode(this.service);
byte[]data=encoding.GetBytes(postData);
HttpWebRequest请求=
(HttpWebRequest)WebRequest.Create(客户端登录地址);
request.Method=“POST”;
request.ContentType=“application/x-www-form-urlencoded”;
request.ContentLength=data.Length;
Stream inputStream=request.GetRequestStream();
inputStream.Write(数据,0,数据长度);
inputStream.Close();
HttpWebResponse=(HttpWebResponse)request.GetResponse();
字符串responsest=(新的StreamReader)(
ReportsManager reports = new ReportsManager("*", "*", "*");
reports.ClientLogin();
Dictionary<string, ArrayList> accountReport = reports.getReport(ReportsManager.ReportType.accounts, DateTime.Today);
int count = accountReport["account_name"].Count;
Hashtable usersLastLoggedIn = new Hashtable();
for (int i = 0; i < count; i++)
{
DateTime lastLogged = DateTime.Parse(accountReport["last_login_time"][i].ToString());
DateTime lastWebMail = DateTime.Parse(accountReport["last_web_mail_time"][i].ToString());
DateTime lastPop = DateTime.Parse(accountReport["last_pop_time"][i].ToString());
if (lastWebMail > lastLogged) { lastLogged = lastWebMail; }
if (lastPop > lastLogged) { lastLogged = lastPop; }
usersLastLoggedIn.Add(accountReport["account_name"][i].ToString().Replace('@' + ConfigurationManager.AppSettings["domain"], string.Empty), lastLogged);
}