//
        // GET: /about

        public JsonResult about()
        {
            DriveService service = Session["service"] as DriveService;

            if (service == null)
            {
                // redirect user to authentication
            }

            Google.Apis.Drive.v2.Data.About about = service.About.Get().Fetch();

            JsonResult result = Json(new { quotaBytesTotal = about.QuotaBytesTotal, quotaBytesUsed = about.QuotaBytesUsed });

            result.JsonRequestBehavior = JsonRequestBehavior.AllowGet;

            return(result);
        }
Example #2
0
        /// <summary>
        /// Method that process the Uri.
        /// </summary>
        /// <param name="request">Information sent by the browser about the request</param>
        /// <param name="response">Information that is being sent back to the client.</param>
        /// <param name="session">Session used to </param>
        /// <exception cref="InternalServerException">Failed to find file extension</exception>
        /// <exception cref="ForbiddenException">File type is forbidden.</exception>
        public override bool Process(IHttpRequest request, IHttpResponse response, IHttpSession session)
        {
            string state = request.QueryString["state"].Value;
            string code  = request.QueryString["code"].Value;

            if (code != null && code.Length > 9 && request.Uri.LocalPath == "/")
            {
                response.Redirect("/drive?code=" + code);
                return(false);
            }

            try
            {
                switch (request.Uri.LocalPath)
                {
                case "/drive_callback":
                    if (true)
                    {
                        byte[] body = Encoding.UTF8.GetBytes(code);
                        response.Body.Write(body, 0, body.Length);
                        response.Send();
                    }
                    break;

                case "/drive":
                    #region

                    if (true)
                    {
                        string url  = "";
                        string json = "{}";
                        if (state == null)
                        {
                            state = "thinhtu";
                        }
                        if (code == null)
                        {
                            code = "thinhtu";
                        }

                        try
                        {
                            IAuthenticator authenticator = Utils.GetCredentials(code, state);
                            // Store the authenticator and the authorized service in session
                            session["authenticator"] = authenticator;
                            DriveService sv = Utils.BuildService(authenticator);
                            session["service"] = sv;
                        }
                        catch (CodeExchangeException)
                        {
                            if (session["service"] == null || session["authenticator"] == null)
                            {
                                url = Utils.GetAuthorizationUrl("", state);
                                response.Redirect(url);
                                return(false);
                            }
                        }
                        catch (NoRefreshTokenException e)
                        {
                            url = e.AuthorizationUrl;
                            response.Redirect(url);
                            return(false);
                        }

                        response.Redirect("/user");
                        return(false);

                        //////DriveState driveState = new DriveState();

                        //////if (!string.IsNullOrEmpty(state))
                        //////{
                        //////    driveState = Newtonsoft.Json.JsonConvert.DeserializeObject<DriveState>(state);
                        //////}

                        //////if (driveState.action == "open")
                        //////{
                        //////    //return OpenWith(driveState);
                        //////    json = Newtonsoft.Json.JsonConvert.SerializeObject(new { FileIds = driveState.ids });
                        //////}
                        //////else
                        //////{
                        //////    //return CreateNew(driveState);
                        //////    json = Newtonsoft.Json.JsonConvert.SerializeObject(new { FileIds = new string[] { "" } });
                        //////}

                        //////response.ContentType = "application/json; charset=UTF-8";
                        //////byte[] body = Encoding.UTF8.GetBytes(json);
                        //////response.Body.Write(body, 0, body.Length);
                        //////response.Send();
                    }

                    #endregion
                    break;

                case "/user":
                    #region
                    if (true)
                    {
                        IAuthenticator authenticator = session["authenticator"] as IAuthenticator;
                        Userinfo       userInfo      = Utils.GetUserInfo(authenticator);
                        string         json          = Newtonsoft.Json.JsonConvert.SerializeObject(new { email = userInfo.Email, link = userInfo.Link, picture = userInfo.Picture });

                        response.ContentType = "application/json; charset=UTF-8";
                        byte[] body = Encoding.UTF8.GetBytes(json);
                        response.Body.Write(body, 0, body.Length);
                        response.Send();
                    }
                    #endregion
                    break;

                case "/about":
                    #region
                    if (true)
                    {
                        DriveService service = session["service"] as DriveService;
                        if (service == null)
                        {
                            // redirect user to authentication
                            byte[] body = Encoding.UTF8.GetBytes("Redirect user to authentication");
                            response.Body.Write(body, 0, body.Length);
                            response.Send();
                        }
                        else
                        {
                            Google.Apis.Drive.v2.Data.About about = service.About.Get().Fetch();
                            string json = Newtonsoft.Json.JsonConvert.SerializeObject(new { quotaBytesTotal = about.QuotaBytesTotal, quotaBytesUsed = about.QuotaBytesUsed });

                            response.ContentType = "application/json; charset=UTF-8";
                            byte[] body = Encoding.UTF8.GetBytes(json);
                            response.Body.Write(body, 0, body.Length);
                            response.Send();
                        }
                    }
                    #endregion
                    break;

                case "/favicon.ico":
                    byte[] body1 = Encoding.UTF8.GetBytes(string.Empty);
                    response.Body.Write(body1, 0, body1.Length);
                    response.Send();
                    break;

                default:
                    #region

                    if (request.Uri.LocalPath.EndsWith("/"))
                    {
                        string   pathLocal = GetPath(request.Uri);
                        string[] folders   = Directory.GetDirectories(pathLocal);

                        string subPath = pathLocal.Replace(this._basePath, string.Empty).Trim();
                        if (subPath.Length > 0)
                        {
                            subPath = subPath.Replace("\\", "/");
                        }


                        string file_index = string.Format("{0}{1}{2}", this._basePath, subPath, "index.html").Replace("/", "\\");
                        if (File.Exists(file_index) && !request.Uri.ToString().Contains("?file"))
                        {
                            string htm  = File.ReadAllText(file_index);
                            byte[] body = Encoding.UTF8.GetBytes(htm);
                            response.Body.Write(body, 0, body.Length);
                            response.Send();
                        }
                        else
                        {
                            StringBuilder biHome = new StringBuilder();
                            string[]      files  = Directory.GetFiles(pathLocal)
                                                   //.Where(x =>
                                                   //    x.ToLower().EndsWith(".txt") ||
                                                   //    x.ToLower().EndsWith(".md") ||
                                                   //    x.ToLower().EndsWith(".json") ||
                                                   //    x.ToLower().EndsWith(".html") ||
                                                   //    x.ToLower().EndsWith(".htm")
                                                   //)
                                                   .ToArray();
                            foreach (string pi in folders)
                            {
                                biHome.Append(string.Format("<a href=/{0}{1}/>{1}</a><br>", subPath, Path.GetFileName(pi)));
                            }
                            biHome.Append("<br>");
                            foreach (string pi in files)
                            {
                                biHome.Append(string.Format("<a href=/{0}{1}>{1}</a><br>", subPath, Path.GetFileName(pi)));
                            }

                            byte[] body = Encoding.UTF8.GetBytes(string.Format("<h1>{0}</h1>{1}<br><hr>{2}", request.Uri.LocalPath, biHome.ToString(), DateTime.Now.ToString()));
                            response.Body.Write(body, 0, body.Length);
                            response.Send();
                        }

                        return(true);
                    }

                    if (!CanHandle(request.Uri))
                    {
                        return(false);
                    }

                    string path      = GetPath(request.Uri);
                    string extension = GetFileExtension(path);
                    if (extension == null)
                    {
                        throw new InternalServerException("Failed to find file extension");
                    }

                    if (MimeTypes.ContainsKey(extension))
                    {
                        response.ContentType = MimeTypes[extension];
                    }
                    else
                    {
                        throw new ForbiddenException("Forbidden file type: " + extension);
                    }

                    using (FileStream stream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
                    {
                        if (!string.IsNullOrEmpty(request.Headers["if-Modified-Since"]))
                        {
                            DateTime since    = DateTime.Parse(request.Headers["if-Modified-Since"]).ToUniversalTime();
                            DateTime modified = File.GetLastWriteTime(path).ToUniversalTime();

                            // Truncate the subsecond portion of the time stamp (if present)
                            modified = new DateTime(modified.Year, modified.Month, modified.Day, modified.Hour,
                                                    modified.Minute, modified.Second, DateTimeKind.Utc);

                            if (modified > since)
                            {
                                response.Status = HttpStatusCode.NotModified;
                            }
                        }

                        // Fixed by Albert, Team MediaPortal: ToUniversalTime
                        if (_useLastModifiedHeader)
                        {
                            response.AddHeader("Last-modified", File.GetLastWriteTime(path).ToUniversalTime().ToString("r"));
                        }
                        response.ContentLength = stream.Length;
                        response.SendHeaders();

                        if (request.Method != "Headers" && response.Status != HttpStatusCode.NotModified)
                        {
                            byte[] buffer    = new byte[8192];
                            int    bytesRead = stream.Read(buffer, 0, 8192);
                            while (bytesRead > 0)
                            {
                                response.SendBody(buffer, 0, bytesRead);
                                bytesRead = stream.Read(buffer, 0, 8192);
                            }
                        }
                    }

                    #endregion
                    break;
                }
            }
            catch (FileNotFoundException err)
            {
                throw new InternalServerException("Failed to process file.", err);
            }

            return(true);
        }
Example #3
0
 public GoogleMimeTypeManager(Google.Apis.Drive.v2.Data.About aboutInfo)
 {
     _aboutInfo      = aboutInfo;
     _exportComparer = new PriorityStringComparer(DefaultMimeTypes.Keys.ToArray(), StringComparer.CurrentCulture);
 }