Esempio n. 1
0
        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);

                Global.Logger.Debug("GoogleDriveApp: download exportLink - " + downloadUrl);
                try
                {
                    using (var response = request.GetResponse())
                    using (var fileStream = new ResponseStream(response))
                    {
                        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");
        }
Esempio n. 2
0
        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);
                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));
                bytes = Encoding.UTF8.GetBytes(mediaPartStart);
                tmpStream.Write(bytes, 0, bytes.Length);

                content.CopyTo(tmpStream);

                var mediaPartEnd = string.Format("\r\n--{0}--\r\n", boundary);
                bytes = Encoding.UTF8.GetBytes(mediaPartEnd);
                tmpStream.Write(bytes, 0, bytes.Length);

                request.Method = "POST";
                request.Headers.Add("Authorization", "Bearer " + token);
                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;
        }
Esempio n. 3
0
        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);

            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;
        }
Esempio n. 4
0
 private static string GetDriveFile(string googleFileId, Token token)
 {
     if (token == null)
     {
         Global.Logger.Error("GoogleDriveApp: token is null");
         throw new SecurityException("Access token is null");
     }
     try
     {
         var resultResponse = RequestHelper.PerformRequest(GoogleUrlFile.Replace("{fileId}", googleFileId),
                                                           headers: new Dictionary<string, string> {{"Authorization", "Bearer " + token}});
         Global.Logger.Debug("GoogleDriveApp: file response - " + resultResponse);
         return resultResponse;
     }
     catch (Exception ex)
     {
         Global.Logger.Error("GoogleDriveApp: file request", ex);
     }
     return null;
 }
Esempio n. 5
0
        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);
            }
        }
Esempio n. 6
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"),
                    Timestamp = DateTime.UtcNow,
                };

            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;
        }
Esempio n. 7
0
        private static UserInfo GetUserInfo(Token token, out bool isNew)
        {
            isNew = false;
            if (token == null)
            {
                Global.Logger.Error("GoogleDriveApp: token is null");
                throw new SecurityException("Access token is null");
            }

            var resultResponse = string.Empty;
            try
            {
                resultResponse = RequestHelper.PerformRequest(GoogleUrlUserInfo.Replace("{access_token}", HttpUtility.UrlEncode(token.ToString())));
                Global.Logger.Debug("GoogleDriveApp: userinfo response - " + resultResponse);
            }
            catch (Exception ex)
            {
                Global.Logger.Error("GoogleDriveApp: userinfo request", ex);
            }

            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))
            {
                userInfo = new UserInfo
                    {
                        FirstName = googleUserInfo.Value<string>("given_name"),
                        LastName = googleUserInfo.Value<string>("family_name"),
                        Email = email,
                    };

                var gender = googleUserInfo.Value<string>("gender");
                if (!string.IsNullOrEmpty(gender))
                {
                    userInfo.Sex = gender == "male";
                }

                var cultureName = googleUserInfo.Value<string>("locale");
                if(string.IsNullOrEmpty(cultureName))
                    cultureName = Thread.CurrentThread.CurrentUICulture.Name;

                var cultureInfo = SetupInfo.EnabledCultures.Find(c => String.Equals(c.Name, cultureName, StringComparison.InvariantCultureIgnoreCase));
                if (cultureInfo != null)
                {
                    userInfo.CultureName = cultureInfo.Name;
                }
                else
                {
                    Global.Logger.DebugFormat("From google app new personal user '{0}' without culture {1}", userInfo.Email, cultureName);
                }

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

                var pwd = UserManagerWrapper.GeneratePassword();

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

                isNew = true;

                Global.Logger.Debug("GoogleDriveApp: new user " + userInfo.ID);
            }

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

                db.ExecuteNonQuery(queryInsert);
            }
        }
Esempio n. 10
0
        private static UserInfo GetUserInfo(Token token, out bool isNew)
        {
            isNew = false;
            if (token == null)
            {
                Global.Logger.Error("GoogleDriveApp: token is null");
                throw new SecurityException("Access token is null");
            }

            var resultResponse = RequestHelper.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))
            {
                userInfo = new UserInfo
                    {
                        Status = EmployeeStatus.Active,
                        FirstName = googleUserInfo.Value<string>("given_name"),
                        LastName = googleUserInfo.Value<string>("family_name"),
                        Email = email,
                        WorkFromDate = TenantUtil.DateTimeNow(),
                    };

                var gender = googleUserInfo.Value<string>("gender");
                if (!string.IsNullOrEmpty(gender))
                {
                    userInfo.Sex = gender == "male";
                }

                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();

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

                isNew = true;

                Global.Logger.Debug("GoogleDriveApp: new user " + userInfo.ID);
            }

            return userInfo;
        }
Esempio n. 11
0
        private static string GetBoxFile(string boxFileId, Token token)
        {
            if (token == null)
            {
                Global.Logger.Error("BoxApp: token is null");
                throw new SecurityException("Access token is null");
            }

            var resultResponse = RequestHelper.PerformRequest(BoxUrlFile.Replace("{fileId}", boxFileId),
                                                              headers: new Dictionary<string, string> { { "Authorization", "Bearer " + token.AccessToken } });
            Global.Logger.Debug("BoxApp: file response - " + resultResponse);
            return resultResponse;
        }
Esempio n. 12
0
        private static UserInfo GetUserInfo(Token token, out bool isNew)
        {
            isNew = false;
            if (token == null)
            {
                Global.Logger.Error("BoxApp: token is null");
                throw new SecurityException("Access token is null");
            }

            var resultResponse = RequestHelper.PerformRequest(BoxUrlUserInfo,
                                                              headers: new Dictionary<string, string> { { "Authorization", "Bearer " + token.AccessToken } });
            Global.Logger.Debug("BoxApp: userinfo response - " + resultResponse);

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

            var email = boxUserInfo.Value<string>("login");
            var userInfo = CoreContext.UserManager.GetUserByEmail(email);
            if (Equals(userInfo, Constants.LostUser))
            {
                userInfo = new UserInfo
                    {
                        Status = EmployeeStatus.Active,
                        FirstName = boxUserInfo.Value<string>("name"),
                        Email = email,
                        MobilePhone = boxUserInfo.Value<string>("phone"),
                        WorkFromDate = TenantUtil.DateTimeNow(),
                    };

                var cultureName = boxUserInfo.Value<string>("language") ?? 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();

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

                isNew = true;

                Global.Logger.Debug("BoxApp: new user " + userInfo.ID);
            }

            return userInfo;
        }