public static void AcceptUploadPartFromA(CommandBody cmd)
        {
            FileTransmissionPartInfo upload = cmd.Data as FileTransmissionPartInfo;

            try
            {
                var fs = uploadStreams[upload.ID];

                fs.Position = upload.Position;
                fs.Write(upload.Content, 0, upload.Content.Length);


                Debug.WriteLine(fs.Position + "/" + fs.Length);
                if (upload.Position + upload.Content.Length == upload.Length)
                {
                    Debug.WriteLine("退出");
                    fs.Flush();
                    fs.Dispose();
                    uploadStreams.Remove(upload.ID);
                }

                Telnet.Instance.Send(new CommandBody(ApiCommand.File_CanSendNextUploadPart, cmd.AId, cmd.BId, upload.ID));
            }
            catch (Exception ex)
            {
                Telnet.Instance.Send(new CommandBody(ApiCommand.File_AskForCancelUpload, cmd.AId, cmd.BId, new FileFolderFeedback()
                {
                    ID = upload.ID, HasError = true, Message = ex.Message
                }));
            }
        }
        public static void SendDirectoryContent(CommandBody cmd)
        {
            string path = cmd.Data as string;
            FileFolderCollection files = new FileFolderCollection()
            {
                Path = path
            };

            if (!Directory.Exists(path))
            {
                files.Error = "不存在目录" + path;
            }
            else
            {
                try
                {
                    foreach (var p in Directory.EnumerateDirectories(path))
                    {
                        files.Add(new FileFolderInfo(new DirectoryInfo(p)));
                    }
                    foreach (var p in Directory.EnumerateFiles(path))
                    {
                        files.Add(new FileFolderInfo(new FileInfo(p)));
                    }
                }
                catch (Exception ex)
                {
                    files.Error = ex.Message;
                }
            }
            Telnet.Instance.Send(new CommandBody(ApiCommand.File_DirectoryContent, cmd.AId, cmd.BId, files));
        }
예제 #3
0
 public static void SendProperties(WMIClassInfo wmi, CommandBody cmd)
 {
     Task.Run(() =>
     {
         Telnet.Instance.Send(new CommandBody(Common.ApiCommand.WMI_Props, cmd.AId, Global.CurrentClient.ID, GetProperties(wmi)));
     });
 }
예제 #4
0
        public static void SendWMIClasses(string @namespace, CommandBody cmd)
        {
            Task.Run(() =>
            {
                var items   = GetWMIClasses(@namespace).classes;
                var classes = from x in items select new WMIClassInfo()
                {
                    Namespace = @namespace, Class = x
                };

                Telnet.Instance.Send(new CommandBody(Common.ApiCommand.WMI_Classes, cmd.AId, Global.CurrentClient.ID, classes.ToArray()));
            });
        }
        public static void CancelUploadFromA(CommandBody cmd)
        {
            var fs = uploadStreams[(Guid)cmd.Data];

            fs.Dispose();
            try
            {
                if (File.Exists(fs.Name))
                {
                    File.Delete(fs.Name);
                }
            }
            catch
            {
            }
        }
예제 #6
0
        static CommandBody Deserialize(MemoryStream ms)
        {
            CommandBody content = null;

            try
            {
                BinaryFormatter formatter = new BinaryFormatter();

                content = (CommandBody)formatter.Deserialize(ms);
            }
            catch (Exception e)
            {
                throw;
            }
            return(content);
        }
        public static void StartAcceptingUploading(CommandBody cmd)
        {
            var trans = cmd.Data as FileTransmissionInfo;

            string path = trans.File.Path;

            if (File.Exists(path))
            {
                Telnet.Instance.Send(new CommandBody(ApiCommand.File_PrepareUploadingFeedback, cmd.AId, cmd.BId, new FileFolderFeedback()
                {
                    ID = trans.ID, HasError = true, Message = "存在相同文件名的文件"
                }));
                return;
            }
            FileStream fs = null;

            try
            {
                fs = File.OpenWrite(path);
                fs.SetLength(trans.File.Length);
                uploadStreams.Add(trans.ID, fs);
            }
            catch (Exception ex)
            {
                try
                {
                    fs?.Dispose();
                    if (File.Exists(path))
                    {
                        File.Delete(path);
                    }
                }
                catch
                {
                }
                Telnet.Instance.Send(new CommandBody(ApiCommand.File_PrepareUploadingFeedback, cmd.AId, cmd.BId, new FileFolderFeedback()
                {
                    ID = trans.ID, HasError = true, Message = "创建文件失败:" + ex.Message
                }));
                return;
            }

            Telnet.Instance.Send(new CommandBody(ApiCommand.File_PrepareUploadingFeedback, cmd.AId, cmd.BId, new FileFolderFeedback()
            {
                ID = trans.ID, HasError = false, Message = "可以开始上传"
            }));
        }
예제 #8
0
        private byte[] Serialize(CommandBody obj)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                BinaryFormatter formatter = new BinaryFormatter();

                try
                {
                    formatter.Serialize(ms, obj);
                }
                catch (SerializationException e)
                {
                    throw;
                }

                return(ms.ToArray());
            }
        }
예제 #9
0
        public static void SendNamespaces(CommandBody cmd)
        {
            if (startGettingNamespaces)
            {
                Telnet.Instance.Send(new CommandBody(Common.ApiCommand.WMI_Namespace, cmd.AId, Global.CurrentClient.ID, namespaces));
                return;
            }
            startGettingNamespaces = true;
            // List<string> items = new List<string>();
            GetNamespaces("root");
            // return items.ToArray();

            Task GetNamespaces(string root)
            {
                return(Task.Run(async() =>
                {
                    // Enumerates all WMI instances of
                    // __namespace WMI class.
                    ManagementClass nsClass =
                        new ManagementClass(
                            new ManagementScope(root),
                            new ManagementPath("__namespace"),
                            null);
                    try
                    {
                        foreach (ManagementObject ns in nsClass.GetInstances())
                        {
                            // Add namespaces to the list.
                            string namespaceName = root + "\\" + ns["Name"].ToString();
                            // items.Add(namespaceName);
                            namespaces.Add(namespaceName);
                            Telnet.Instance.Send(new CommandBody(Common.ApiCommand.WMI_Namespace, cmd.AId, Global.CurrentClient.ID, new string[] { namespaceName }));

                            await GetNamespaces(namespaceName);
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                }));
            }
        }
예제 #10
0
        /// <summary>
        /// Post route "api/rover"
        /// </summary>
        /// <param name="body">The body.</param>
        /// <returns>
        /// the result of the commmand sent.
        /// </returns>
        public string Post([FromBody] CommandBody body)
        {
            switch (body.Type)
            {
            case CommandType.Move:
                if (ValidateMoveCommand(body.Command))
                {
                    return(Move(body.Command));
                }
                else
                {
                    return($"Malformed move command: {body.Command}");
                }

            case CommandType.SetupPlateau:
                if (ValidatePlateauCommand(body.Command, out int xPlateau, out int yPlateau))
                {
                    return(SetupPlateau(xPlateau, yPlateau));
                }
                else
                {
                    return($"Malformed Plateau command: {body.Command}");
                }
예제 #11
0
        /// <summary>
        /// Request to Document Server with command
        /// </summary>
        /// <param name="documentTrackerUrl">Url to the command service</param>
        /// <param name="method">Name of method</param>
        /// <param name="documentRevisionId">Key for caching on service, whose used in editor</param>
        /// <param name="callbackUrl">Url to the callback handler</param>
        /// <param name="users">users id for drop</param>
        /// <param name="meta">file meta data for update</param>
        /// <param name="signatureSecret">Secret key to generate the token</param>
        /// <param name="version">server version</param>
        /// <returns>Response</returns>
        public static CommandResultTypes CommandRequest(
            string documentTrackerUrl,
            CommandMethod method,
            string documentRevisionId,
            string callbackUrl,
            string[] users,
            MetaData meta,
            string signatureSecret,
            out string version)
        {
            var request = (HttpWebRequest)WebRequest.Create(documentTrackerUrl);

            request.Method      = "POST";
            request.ContentType = "application/json";
            request.Timeout     = Timeout;

            var body = new CommandBody
            {
                Command = method,
                Key     = documentRevisionId,
            };

            if (!string.IsNullOrEmpty(callbackUrl))
            {
                body.Callback = callbackUrl;
            }
            if (users != null && users.Length > 0)
            {
                body.Users = users;
            }
            if (meta != null)
            {
                body.Meta = meta;
            }

            if (!string.IsNullOrEmpty(signatureSecret))
            {
                var payload = new Dictionary <string, object>
                {
                    { "payload", body }
                };
                JsonWebToken.JsonSerializer = new JwtSerializer();
                var token = JsonWebToken.Encode(payload, signatureSecret, JwtHashAlgorithm.HS256);
                //todo: remove old scheme
                request.Headers.Add(FileUtility.SignatureHeader, "Bearer " + token);

                token      = JsonWebToken.Encode(body, signatureSecret, JwtHashAlgorithm.HS256);
                body.Token = token;
            }

            var bodyString = JsonConvert.SerializeObject(body);

            var bytes = Encoding.UTF8.GetBytes(bodyString ?? "");

            request.ContentLength = bytes.Length;
            using (var stream = request.GetRequestStream())
            {
                stream.Write(bytes, 0, bytes.Length);
            }

            // hack. http://ubuntuforums.org/showthread.php?t=1841740
            if (WorkContext.IsMono)
            {
                ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true;
            }

            string dataResponse;

            using (var response = request.GetResponse())
                using (var stream = response.GetResponseStream())
                {
                    if (stream == null)
                    {
                        throw new Exception("Response is null");
                    }

                    using (var reader = new StreamReader(stream))
                    {
                        dataResponse = reader.ReadToEnd();
                    }
                }

            var jResponse = JObject.Parse(dataResponse);

            try
            {
                version = jResponse.Value <string>("version");
            }
            catch (Exception)
            {
                version = "0";
            }

            return((CommandResultTypes)jResponse.Value <int>("error"));
        }
예제 #12
0
 public DataReceivedEventArgs(CommandBody datas)
 {
     //Command = command;
     Content = datas;
 }
예제 #13
0
 public DataSendedEventArgs(CommandBody datas)
 {
     //Command = command;
     Content = datas;
 }
        public static void FileFolderOperate(CommandBody cmd)
        {
            FileFolderOperationInfo operation = cmd.Data as FileFolderOperationInfo;
            FileFolderFeedback      feedback  = new FileFolderFeedback()
            {
                Path = operation.Source,
            };

            Task.Run(() =>
            {
                try
                {
                    if (File.Exists(operation.Source))
                    {
                        switch (operation.Operation)
                        {
                        case FileFolderOperation.Copy:
                            File.Copy(operation.Source, operation.Target, true);
                            feedback.Message = $"成功复制文件{operation.Source}到{operation.Target}";
                            break;

                        case FileFolderOperation.Move:
                            if (File.Exists(operation.Source))
                            {
                                feedback.HasError = false;
                                feedback.Message  = "目标文件已存在";
                                break;
                            }
                            File.Move(operation.Source, operation.Target);
                            feedback.Message = $"成功移动文件{operation.Source}到{operation.Target}";
                            break;

                        case FileFolderOperation.Delete:
                            File.Delete(operation.Source);
                            feedback.Message = $"成功删除文件{operation.Source}";
                            break;
                        }
                    }
                    else if (Directory.Exists(operation.Source))
                    {
                        switch (operation.Operation)
                        {
                        case FileFolderOperation.Copy:
                            FzLib.IO.FileSystem.CopyDirectory(operation.Source, operation.Target);
                            feedback.Message = $"成功复制文件夹{operation.Source}到{operation.Target}";
                            break;

                        case FileFolderOperation.Move:
                            if (File.Exists(operation.Source))
                            {
                                feedback.HasError = false;
                                feedback.Message  = "目标文件已存在";
                                break;
                            }
                            FzLib.IO.FileSystem.CopyDirectory(operation.Source, operation.Target);
                            feedback.Message = $"成功移动文件夹{operation.Source}到{operation.Target}";
                            Directory.Delete(operation.Source, true);
                            break;

                        case FileFolderOperation.Delete:
                            Directory.Delete(operation.Source, true);
                            feedback.Message = $"成功复制文件夹{operation.Source}";
                            break;
                        }
                    }
                    else
                    {
                        feedback.HasError = true;
                        feedback.Message  = "源文件不存在";
                    }
                }
                catch (Exception ex)
                {
                    feedback.HasError = true;
                    feedback.Message  = ex.Message;
                }
                Telnet.Instance.Send(new CommandBody(ApiCommand.File_OperationFeedback, cmd.AId, cmd.BId, feedback));
            });
        }
 public static void SendDiskDrives(CommandBody cmd)
 {
     Telnet.Instance.Send(new CommandBody(ApiCommand.File_RootDirectory, cmd.AId, cmd.BId, Directory.GetLogicalDrives()));
 }
예제 #16
0
        //public void Send(ApiCommand command)
        //{
        //    Send((byte)command, new byte[0]);
        //}
        //public void Send(byte command)
        //{
        //    Send(command, new byte[0]);
        //}
        //public void Send(byte command, object obj)
        //{
        //    Send(command, Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(obj)));
        //}
        //public void Send(ApiCommand command, object obj)
        //{
        //    Send((byte)command, Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(obj)));
        //}
        //public void Send(ApiCommand command, byte[] data)
        //{
        //    Send((byte)command, data);
        //}


        public void Send(CommandBody content)
        {
            Send(Serialize(content));

            DataSended?.Invoke(this, new DataReceivedEventArgs(content));
        }
예제 #17
0
        /// <summary>
        /// 接收消息线程方法
        /// </summary>
        /// <param name="clientSocket"></param>
        protected void Receive()
        {
            int bufferLength = 1024 * 1024 * 16;

            byte[] buffer = new byte[bufferLength];
            while (true)
            {
                int         length      = 0;
                int         totalLength = 0;
                byte[]      received    = null;
                CommandBody content     = null;
                using (MemoryStream stream = new MemoryStream())
                {
                    try
                    {
                        Stopwatch sw = Stopwatch.StartNew();
                        while (true)
                        {
                            try
                            {
                                length = ClientSocket.Receive(buffer);
                            }
                            catch (ObjectDisposedException)
                            {
                                return;
                            }
                            stream.Write(buffer, 0, length);
                            totalLength += length;
                            bool end = true;
                            if (length < SocketEnd.Length)
                            {
                                continue;
                            }
                            for (int i = length - SocketEnd.Length, j = 0; i < length; i++, j++)
                            {
                                if (buffer[i] != SocketEnd[j])
                                {
                                    end = false;
                                    break;
                                }
                            }
                            if (end)
                            {
                                break;
                            }
                        }
                    }
                    catch (SocketException ex)
                    {
                        if (ex.SocketErrorCode != SocketError.TimedOut)
                        {
                            SocketClosedByAccident?.Invoke(this, new SocketClosedByAccidentEventArgs(ex));
                            return;
                        }
                    }
                    stream.Flush();
                    //received = stream.ToArray();
                    //stream.Seek(0, SeekOrigin.Begin);
                    //received = new byte[totalLength - SocketEnd.Length];
                    //stream.Read(received, 0, totalLength - SocketEnd.Length);
                    stream.SetLength(totalLength - SocketEnd.Length);
                    stream.Seek(0, SeekOrigin.Begin);
                    content = Deserialize(stream);
                }
                tttt += totalLength;
                Debug.WriteLine("收到的长度:" + tttt);
                //byte command = received[0];
                //byte[] data = new byte[totalLength - 1 - SocketEnd.Length];
                //if (data.Length > 0)
                //{
                //    Array.Copy(received.ToArray(), 1, data, 0, totalLength - 1 - SocketEnd.Length);
                //}
                DataReceived?.Invoke(this, new DataReceivedEventArgs(content));
            }
        }
예제 #18
0
 public async Task Command(Endpoint endpoint, CommandBody data)
 {
     throw new NotImplementedException();
 }
예제 #19
0
        /// <summary>
        /// Request to Document Server with command
        /// </summary>
        /// <param name="documentTrackerUrl">Url to the command service</param>
        /// <param name="method">Name of method</param>
        /// <param name="documentRevisionId">Key for caching on service, whose used in editor</param>
        /// <param name="callbackUrl">Url to the callback handler</param>
        /// <param name="users">users id for drop</param>
        /// <param name="meta">file meta data for update</param>
        /// <param name="signatureSecret">Secret key to generate the token</param>
        /// <param name="version">server version</param>
        /// <returns>Response</returns>
        public static CommandResponse CommandRequest(FileUtility fileUtility,
                                                     string documentTrackerUrl,
                                                     CommandMethod method,
                                                     string documentRevisionId,
                                                     string callbackUrl,
                                                     string[] users,
                                                     MetaData meta,
                                                     string signatureSecret)
        {
            var request = (HttpWebRequest)WebRequest.Create(documentTrackerUrl);

            request.Method      = "POST";
            request.ContentType = "application/json";
            request.Timeout     = Timeout;

            var body = new CommandBody
            {
                Command = method,
                Key     = documentRevisionId,
            };

            if (!string.IsNullOrEmpty(callbackUrl))
            {
                body.Callback = callbackUrl;
            }
            if (users != null && users.Length > 0)
            {
                body.Users = users;
            }
            if (meta != null)
            {
                body.Meta = meta;
            }

            if (!string.IsNullOrEmpty(signatureSecret))
            {
                var payload = new Dictionary <string, object>
                {
                    { "payload", body }
                };

                var token = JsonWebToken.Encode(payload, signatureSecret);
                //todo: remove old scheme
                request.Headers.Add(fileUtility.SignatureHeader, "Bearer " + token);

                token      = JsonWebToken.Encode(body, signatureSecret);
                body.Token = token;
            }

            var bodyString = System.Text.Json.JsonSerializer.Serialize(body, new System.Text.Json.JsonSerializerOptions()
            {
                IgnoreNullValues = true,
                Encoder          = JavaScriptEncoder.UnsafeRelaxedJsonEscaping
            });

            var bytes = Encoding.UTF8.GetBytes(bodyString ?? "");

            request.ContentLength = bytes.Length;
            using (var stream = request.GetRequestStream())
            {
                stream.Write(bytes, 0, bytes.Length);
            }

            // hack. http://ubuntuforums.org/showthread.php?t=1841740
            if (WorkContext.IsMono)
            {
                ServicePointManager.ServerCertificateValidationCallback += (s, ce, ca, p) => true;
            }

            string dataResponse;

            using (var response = request.GetResponse())
                using (var stream = response.GetResponseStream())
                {
                    if (stream == null)
                    {
                        throw new Exception("Response is null");
                    }

                    using var reader = new StreamReader(stream);
                    dataResponse     = reader.ReadToEnd();
                }


            try
            {
                var commandResponse = JsonConvert.DeserializeObject <CommandResponse>(dataResponse);
                return(commandResponse);
            }
            catch (Exception ex)
            {
                return(new CommandResponse
                {
                    Error = CommandResponse.ErrorTypes.ParseError,
                    ErrorString = ex.Message
                });
            }
        }
        public static void StartDownloadingToA(CommandBody cmd)
        {
            Task.Run(() =>
            {
                FileTransmissionInfo download = cmd.Data as FileTransmissionInfo;
                var file = download.File;
                Debug.Assert(file.IsDirectory == false);
                try
                {
                    int bufferLength = 1024 * 1024;
                    byte[] buffer    = new byte[bufferLength];
                    using (FileStream fs = File.OpenRead(file.Path))
                    {
                        int length = 0;
                        while (true)
                        {
                            var cancel = Cancle.FirstOrDefault(p => p == download.ID);
                            if (cancel != default)
                            {
                                Cancle.TryTake(out cancel);
                                return;
                            }
                            long position = fs.Position;
                            int count     = bufferLength;
                            if (fs.Length - fs.Position < bufferLength)
                            {
                                count = (int)(fs.Length - fs.Position);
                            }
                            length = fs.Read(buffer, 0, count);
                            if (length == 0)
                            {
                                break;
                            }
                            if (length < bufferLength)
                            {
                                byte[] newBuffer = new byte[length];
                                Array.Copy(buffer, newBuffer, length);
                                buffer = newBuffer;
                            }

                            Telnet.Instance.Send(new CommandBody(ApiCommand.File_Download, cmd.AId, cmd.BId,
                                                                 new FileTransmissionPartInfo()
                            {
                                Content = buffer, Path = file.Path, Position = position, Length = fs.Length, ID = download.ID
                            }));
                            while (true)
                            {
                                var canNext = CanSendNextPart.FirstOrDefault(p => p == download.ID);
                                if (canNext != default)
                                {
                                    CanSendNextPart.TryTake(out canNext);
                                    break;
                                }
                                Thread.Sleep(30);
                            }
                        }
                    }
                }
                catch (Exception ex)
                {
                    Telnet.Instance.Send(new CommandBody(ApiCommand.File_ReadDownloadingFileError, cmd.AId, cmd.BId,
                                                         new FileFolderFeedback()
                    {
                        ID = download.ID, Path = file.Path, Message = ex.Message, HasError = true
                    }));
                }
            });
        }