Пример #1
0
        public bool AuthorizeToEnterprise(int projectId)
        {
            if (UserInfo == null || string.IsNullOrEmpty(UserInfo.UserName))
            {
                return(false);
            }

            var enterpriseId = GetEnterpriseId();

            if (!enterpriseId.HasValue)
            {
                throw new ApplicationException("Get Enterprise info failed user name: [" + UserInfo.UserName + "]");
            }

            var projectAuthority = new ProjectAuthority();

            projectAuthority.EnterpriseId = enterpriseId.Value;
            projectAuthority.ProjectId    = projectId;

            var newId = m_db.Insert("ProjectAuthority", "project_authority_id", true, projectAuthority.GetTableObject());

            return((int)newId > 0);
        }
Пример #2
0
        /// <summary>
        /// Open remote project.
        /// </summary>
        /// <param name="address">The server address.</param>
        /// <param name="name">The project name.</param>
        /// <param name="username">Username that will be used to download the project.</param>
        /// <param name="accesstoken">Password that will be used to download the project.</param>
        /// <param name="directory">The directory when the project will be downloaded.</param>
        /// <returns>The project, null when something failed.</returns>
        public static Project OpenProject(string address, string name, string username, string accesstoken, string directory)
        {
            var authority = new ProjectAuthority
            {
                ProjectName = name,
                Username    = username,
                AccessToken = accesstoken
            };

            // send project authority request
            var    response = Request.Send(address + "authorize", authority.ToJson());
            string responseBody;

            using (var sr = new BinaryReader(response))
            {
                responseBody = sr.ReadString();
            }

            var authResult = JObject.Parse(responseBody);
            var authorized = authResult["auth"].ToObject <bool>();

            if (!authorized)
            {
                return(null);
            }

            // setup directory
            if (!directory.EndsWith("\\"))
            {
                directory += "\\";
            }

            if (!Directory.Exists(directory))
            {
                Directory.CreateDirectory(directory);
            }

            var dir = Directory.GetFiles(directory, "*.*");

            if (dir.Length > 0) // directory is not empty!
            {
                return(null);
            }

            // create local project
            var project = new Project
            {
                RootDir       = directory,
                ServerAddress = address,
                Authority     = authority
            };

            var mysyncDataDir = directory + ".mysync";
            var msDir         = Directory.CreateDirectory(mysyncDataDir);

            // hide the directory
            msDir.Attributes = FileAttributes.Directory | FileAttributes.Hidden;

            // build empty for 'last commit'.
            var emptyFilemap = Filemap.BuildEmpty();

            project._lastFilemap = emptyFilemap;

            // save
            File.WriteAllText(mysyncDataDir + "\\last_filemap.json", emptyFilemap.ToJson());

            // refresh the changes
            project.Refresh();

            // download all files
            project.Pull(x => { }); // TODO: progress

            return(project);
        }
Пример #3
0
        public static void Push(HttpListenerRequest request, HttpListenerResponse response)
        {
            var projectName = "";

            try
            {
                using (var reader = new BinaryReader(request.InputStream))
                {
                    using (var writer = new BinaryWriter(response.OutputStream))
                    {
                        try
                        {
                            var authority = ProjectAuthority.FromJson(Encoding.UTF8.GetString(
                                                                          reader.ReadBytes(reader.ReadInt32())
                                                                          ));

                            projectName = authority.ProjectName;

                            // validate project name, password and check permisions from clientData
                            if (!Authorization.HasAuthority(authority.AccessToken, projectName))
                            {
                                writer.Write("Failed - project not found!");
                                return;
                            }

                            // request project lock
                            if (ProjectLock.TryLock(projectName, ProjectLock.LockMode.Upload) !=
                                ProjectLock.LockMode.None)
                            {
                                writer.Write("Failed - project is locked!");
                                return;
                            }

                            // read commit
                            var commitData = reader.ReadBytes(reader.ReadInt32());
                            var commit     = Commit.FromJson(Encoding.UTF8.GetString(commitData));

                            var hasFile = reader.ReadBoolean();

                            if (hasFile)
                            {
                                Console.WriteLine("Receiving file...");
                                try
                                {
                                    // read data file
                                    using (var fs = File.Create("temp_recv.zip"))
                                    {
                                        try
                                        {
                                            int read;
                                            var buffer = new byte[64 * 1024];
                                            while ((read = reader.Read(buffer, 0, buffer.Length)) > 0)
                                            {
                                                fs.Write(buffer, 0, read);
                                            }
                                        }
                                        catch
                                        {
                                            // user lost connection or closed the client
                                            // before the whole data file arrived
                                            Console.WriteLine("User '" + authority.Username + "' canceled commit upload.");
                                            ProjectLock.Unlock(projectName);
                                            return;
                                        }
                                    }
                                }
                                catch
                                {
                                    // user lost connection or closed the client
                                    // before the whole data file arrived
                                    Console.WriteLine("User '" + authority.Username + "' commit upload failed.");
                                    ProjectLock.Unlock(projectName);
                                    return;
                                }
                            }

                            // --- from now - this part CAN'T fail, if so, the whole project may be incorrect after this!

                            var projectDir = "data/" + projectName;

                            // make commited files backup
                            commit.Backup(projectDir);

                            int commitId;
                            try
                            {
                                // downloaded
                                // now apply changes
                                commit.Apply(projectDir, "temp_recv.zip", hasFile);

                                // add commit to projects database
                                var projectCollection =
                                    ServerCore.Database.GetCollection <CommitModel>(projectName);
                                commitId = (int)projectCollection.Count(FilterDefinition <CommitModel> .Empty) + 1;

                                // build commit
                                var commitModel = new CommitModel
                                {
                                    CommitId          = commitId,
                                    CommitDescription = commit.Description,
                                    Files             = new CommitModel.FileDiff[commit.Files.Length]
                                };

                                for (var i = 0; i < commit.Files.Length; i++)
                                {
                                    var file = commit.Files[i];

                                    commitModel.Files[i] = new CommitModel.FileDiff
                                    {
                                        Name      = file.FileName,
                                        Version   = file.Version,
                                        Operation = (int)file.DiffType
                                    };
                                }

                                // insert
                                projectCollection.InsertOne(commitModel);

                                // delete zip file if exists
                                if (hasFile)
                                {
                                    File.Delete("temp_recv.zip");
                                }
                            }
                            catch (Exception ex)
                            {
                                Console.WriteLine("Failed to apply commit from user '" + authority.Username + "'");
                                writer.Write("#RESTORE Failed - error when updating project! Error: " + ex);

                                // restore backup
                                commit.RestoreBackup(projectDir);

                                // UNLOCK
                                ProjectLock.Unlock(projectName);
                                return;
                            }

                            // ok, we are out of the danger zone.

                            // return message
                            writer.Write("Done!");
                            writer.Write(commitId);

                            // clean backups
                            commit.CleanBackups(projectDir);

                            Console.WriteLine("User '" + authority.Username + "' pushed changes!");
                        }
                        catch (Exception ex)
                        {
                            writer.Write("Failed - invalid protocol/connection error! Error: " + ex);
                            Console.WriteLine("PUSH failed");
                            ProjectLock.Unlock(projectName);
                        }
                    }
                }
            }
            catch
            {
                // this shouldn't be possible,
                // but anyway handle exceptions here
                Console.WriteLine("PUSH failed");
                ProjectLock.Unlock(projectName);
            }

            Console.WriteLine("Push done");
            ProjectLock.Unlock(projectName);
        }