private static string ConvertFile(string downloadUrl, string fromExt, Token token)
        {
            Global.Logger.Debug("GoogleDriveApp: convert file");

            if (string.IsNullOrEmpty(downloadUrl))
            {
                Global.Logger.Error("GoogleDriveApp: downloadUrl is null");
                throw new Exception("downloadUrl is null");
            }

            var request = WebRequest.Create(downloadUrl);
            request.Method = "GET";
            request.Headers.Add("Authorization", "Bearer " + token.AccessToken);

            try
            {
                using (var response = request.GetResponse())
                using (var fileStream = new ResponseStream(response))
                {
                    Global.Logger.Debug("GoogleDriveApp: GetExternalUri - " + downloadUrl);

                    var key = DocumentServiceConnector.GenerateRevisionId(downloadUrl);
                    downloadUrl = DocumentServiceConnector.GetExternalUri(fileStream, response.ContentType, key);
                }
            }
            catch (WebException e)
            {
                Global.Logger.Error("GoogleDriveApp: Error GetExternalUri", e);
                request.Abort();
            }

            var toExt = FileUtility.GetInternalExtension(fromExt);
            try
            {
                Global.Logger.Debug("GoogleDriveApp: GetConvertedUri- " + downloadUrl);

                var key = DocumentServiceConnector.GenerateRevisionId(downloadUrl);
                DocumentServiceConnector.GetConvertedUri(downloadUrl, fromExt, toExt, key, false, out downloadUrl);
            }
            catch (Exception e)
            {
                Global.Logger.Error("GoogleDriveApp: Error GetConvertedUri", e);
            }

            return downloadUrl;
        }
        private static string CreateConvertedFile(string driveFile, Token token)
        {
            var jsonFile = JObject.Parse(driveFile);
            var fileName = GetCorrectTitle(jsonFile);
            fileName = FileUtility.ReplaceFileExtension(fileName, FileUtility.GetInternalExtension(fileName));

            var folderId = (string)jsonFile.SelectToken("parents[0].id");

            Global.Logger.Info("GoogleDriveApp: create copy - " + fileName);

            var mimeType = (jsonFile.Value<string>("mimeType") ?? "").ToLower();
            FileType fileType;
            if (GoogleMimeTypes.TryGetValue(mimeType, out fileType))
            {
                var links = jsonFile["exportLinks"];
                if (links == null)
                {
                    Global.Logger.Error("GoogleDriveApp: exportLinks is null");
                    throw new Exception("exportLinks is null");
                }

                var internalExt = FileUtility.InternalExtension[fileType];
                var requiredMimeType = MimeMapping.GetMimeMapping(internalExt);

                var exportLinks = links.ToObject<Dictionary<string, string>>();
                var downloadUrl = exportLinks[requiredMimeType] ?? "";

                if (string.IsNullOrEmpty(downloadUrl))
                {
                    Global.Logger.Error("GoogleDriveApp: exportLinks without requested mime - " + links);
                    throw new Exception("exportLinks without requested mime");
                }


                var request = WebRequest.Create(downloadUrl);
                request.Method = "GET";
                request.Headers.Add("Authorization", "Bearer " + token.AccessToken);

                try
                {
                    using (var response = request.GetResponse())
                    using (var fileStream = new ResponseStream(response))
                    {
                        Global.Logger.Debug("GoogleDriveApp: download exportLink - " + downloadUrl);

                        driveFile = CreateFile(fileStream, fileName, folderId, token);
                    }
                }
                catch (WebException e)
                {
                    Global.Logger.Error("GoogleDriveApp: Error download exportLink", e);
                    request.Abort();

                    var httpResponse = (HttpWebResponse)e.Response;
                    if (httpResponse.StatusCode == HttpStatusCode.Unauthorized && fileType == FileType.Spreadsheet)
                    {
                        throw new SecurityException(FilesCommonResource.AppDriveSpreadsheetException, e);
                    }
                }
            }
            else
            {
                var downloadUrl = jsonFile.Value<string>("downloadUrl");

                var ext = GetCorrectExt(jsonFile);
                var convertedUrl = ConvertFile(downloadUrl, ext, token);

                driveFile = CreateFile(convertedUrl, fileName, folderId, token);
            }

            jsonFile = JObject.Parse(driveFile);
            return jsonFile.Value<string>("id");
        }
        private static string CreateFile(string contentUrl, string fileName, string folderId, Token token)
        {
            if (string.IsNullOrEmpty(contentUrl))
            {
                Global.Logger.Error("GoogleDriveApp: downloadUrl is null");
                throw new Exception("downloadUrl is null");
            }
            Global.Logger.Debug("GoogleDriveApp: create from - " + contentUrl);

            var request = WebRequest.Create(contentUrl);

            using (var response = request.GetResponse())
            using (var content = new ResponseStream(response))
            {
                return CreateFile(content, fileName, folderId, token);
            }
        }
        private static string CreateFile(Stream content, string fileName, string folderId, Token token)
        {
            Global.Logger.Debug("GoogleDriveApp: create file");

            var request = (HttpWebRequest)WebRequest.Create(GoogleUrlUpload + "?uploadType=multipart");

            using (var tmpStream = new MemoryStream())
            {
                var boundary = DateTime.UtcNow.Ticks.ToString("x");

                var folderdata = string.IsNullOrEmpty(folderId) ? "" : string.Format(",\"parents\":[{{\"id\":\"{0}\"}}]", folderId);
                var metadata = string.Format("{{\"title\":\"{0}\"{1}}}", fileName, folderdata);
                var metadataPart = string.Format("\r\n--{0}\r\nContent-Type: application/json; charset=UTF-8\r\n\r\n{1}", boundary, metadata);
                Global.Logger.Debug("GoogleDriveApp: create file metadataPart - " + metadataPart);

                var bytes = Encoding.UTF8.GetBytes(metadataPart);
                tmpStream.Write(bytes, 0, bytes.Length);

                var mediaPartStart = string.Format("\r\n--{0}\r\nContent-Type: {1}\r\n\r\n", boundary, MimeMapping.GetMimeMapping(fileName));
                Global.Logger.Debug("GoogleDriveApp: create file mediaPartStart - " + mediaPartStart);

                bytes = Encoding.UTF8.GetBytes(mediaPartStart);
                tmpStream.Write(bytes, 0, bytes.Length);

                content.CopyTo(tmpStream);

                var mediaPartEnd = string.Format("\r\n--{0}--\r\n", boundary);
                Global.Logger.Debug("GoogleDriveApp: create file mediaPartEnd - " + mediaPartEnd);

                bytes = Encoding.UTF8.GetBytes(mediaPartEnd);
                tmpStream.Write(bytes, 0, bytes.Length);

                request.Method = "POST";
                request.Headers.Add("Authorization", "Bearer " + token.AccessToken);
                request.ContentType = "multipart/related; boundary=" + boundary;
                request.ContentLength = tmpStream.Length;
                Global.Logger.Debug("GoogleDriveApp: create file totalSize - " + tmpStream.Length);

                const int bufferSize = 2048;
                var buffer = new byte[bufferSize];
                int readed;
                tmpStream.Seek(0, SeekOrigin.Begin);
                while ((readed = tmpStream.Read(buffer, 0, bufferSize)) > 0)
                {
                    request.GetRequestStream().Write(buffer, 0, readed);
                }
            }

            try
            {
                using (var response = request.GetResponse())
                using (var stream = response.GetResponseStream())
                {
                    var result = stream != null ? new StreamReader(stream).ReadToEnd() : null;

                    Global.Logger.Debug("GoogleDriveApp: create file response - " + result);
                    return result;
                }
            }
            catch (WebException e)
            {
                Global.Logger.Error("GoogleDriveApp: Error create file", e);
                request.Abort();

                var httpResponse = (HttpWebResponse)e.Response;
                if (httpResponse.StatusCode == HttpStatusCode.Forbidden)
                {
                    throw new SecurityException(FilesCommonResource.ErrorMassage_SecurityException, e);
                }
            }
            return null;
        }
        private static string GetDriveFile(string googleFileId, Token token)
        {
            if (token == null)
            {
                Global.Logger.Info("GoogleDriveApp: token is null");
                throw new SecurityException("Access token is null");
            }

            var resultResponse = PerformRequest(GoogleUrlFile.Replace("{fileId}", googleFileId), headers: new Dictionary<string, string> { { "Authorization", "Bearer " + token.AccessToken } });
            Global.Logger.Debug("GoogleDriveApp: file response - " + resultResponse);
            return resultResponse;
        }
        private static UserInfo GetUserInfo(Token token)
        {
            if (token == null)
            {
                Global.Logger.Info("GoogleDriveApp: token is null");
                throw new SecurityException("Access token is null");
            }

            var resultResponse = PerformRequest(GoogleUrlUserInfo.Replace("{access_token}", token.AccessToken));
            Global.Logger.Debug("GoogleDriveApp: userinfo response - " + resultResponse);

            var googleUserInfo = JObject.Parse(resultResponse);
            if (googleUserInfo == null)
            {
                Global.Logger.Error("Error in userinfo request");
                return null;
            }

            var email = googleUserInfo.Value<string>("email");
            var userInfo = CoreContext.UserManager.GetUserByEmail(email);
            if (!Equals(userInfo, Constants.LostUser))
            {
                return userInfo;
            }


            userInfo = new UserInfo
                {
                    Status = EmployeeStatus.Active,
                    FirstName = googleUserInfo.Value<string>("given_name"),
                    LastName = googleUserInfo.Value<string>("family_name"),
                    Email = email,
                    Title = string.Empty,
                    Location = string.Empty,
                    WorkFromDate = TenantUtil.DateTimeNow(),
                };

            var cultureName = googleUserInfo.Value<string>("locale") ?? CultureInfo.CurrentUICulture.Name;
            var cultureInfo = SetupInfo.EnabledCultures.Find(c => String.Equals(c.TwoLetterISOLanguageName, cultureName, StringComparison.InvariantCultureIgnoreCase));
            if (cultureInfo != null)
            {
                userInfo.CultureName = cultureInfo.Name;
            }

            if (string.IsNullOrEmpty(userInfo.FirstName))
            {
                userInfo.FirstName = FilesCommonResource.UnknownFirstName;
            }
            if (string.IsNullOrEmpty(userInfo.LastName))
            {
                userInfo.LastName = FilesCommonResource.UnknownLastName;
            }

            var pwd = UserManagerWrapper.GeneratePassword();

            UserInfo newUserInfo;
            try
            {
                SecurityContext.AuthenticateMe(ASC.Core.Configuration.Constants.CoreSystem);
                newUserInfo = UserManagerWrapper.AddUser(userInfo, pwd);
            }
            finally
            {
                SecurityContext.Logout();
            }

            var linker = new AccountLinker("webstudio");
            linker.AddLink(newUserInfo.ID.ToString(), googleUserInfo.Value<string>("id") ?? "", ProviderConstants.OpenId);

            UserHelpTourHelper.IsNewUser = true;
            PersonalSettings.IsNewUser = true;

            Global.Logger.Debug("GoogleDriveApp: new user " + newUserInfo.ID);
            return newUserInfo;
        }
示例#7
0
        public static Token FromJson(String json)
        {
            if (string.IsNullOrEmpty(json)) return null;
            var parser = JObject.Parse(json);
            if (parser == null) return null;

            var accessToken = parser.Value<string>("access_token");

            if (String.IsNullOrEmpty(accessToken))
                return null;

            var token = new Token
                {
                    _accessToken = accessToken,
                    RefreshToken = parser.Value<string>("refresh_token"),
                };

            double expiresIn;
            if (double.TryParse(parser.Value<string>("expires_in"), out expiresIn))
                token.ExpiresIn = expiresIn;

            DateTime timestamp;
            if (DateTime.TryParse(parser.Value<string>("timestamp"), out timestamp))
                token.Timestamp = timestamp;

            return token;
        }
示例#8
0
 private static string EncryptToken(Token token)
 {
     var t = token.ToJson();
     return string.IsNullOrEmpty(t) ? string.Empty : InstanceCrypto.Encrypt(t);
 }
示例#9
0
        public static void SaveToken(Token token)
        {
            using (var db = new DbManager(FileConstant.DatabaseId))
            {
                var queryInsert = new SqlInsert(TableTitle, true)
                    .InColumnValue("user_id", SecurityContext.CurrentAccount.ID.ToString())
                    .InColumnValue("token", EncryptToken(token))
                    .InColumnValue("tenant_id", CoreContext.TenantManager.GetCurrentTenant().TenantId);

                db.ExecuteNonQuery(queryInsert);
            }
        }