mconnect - KDE Connect protocol implementation in Vala/C
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
1.6 KiB

  1. // Licensed under the Apache License, Version 2.0 (the "License");
  2. // you may not use this file except in compliance with the License.
  3. // You may obtain a copy of the License at
  4. //
  5. // http://www.apache.org/licenses/LICENSE-2.0
  6. //
  7. // Unless required by applicable law or agreed to in writing, software
  8. // distributed under the License is distributed on an "AS IS" BASIS,
  9. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  10. // See the License for the specific language governing permissions and
  11. // limitations under the License.
  12. package packet
  13. import (
  14. "bytes"
  15. "encoding/json"
  16. "io"
  17. "time"
  18. "github.com/pkg/errors"
  19. )
  20. var getId = func() uint64 {
  21. return uint64(time.Now().UnixNano() / 1000)
  22. }
  23. func Marshal(p *Packet) ([]byte, error) {
  24. b := &bytes.Buffer{}
  25. enc := NewEncoder(b)
  26. if err := enc.Encode(p); err != nil {
  27. return nil, err
  28. }
  29. return b.Bytes(), nil
  30. }
  31. type Encoder struct {
  32. w io.Writer
  33. j *json.Encoder
  34. }
  35. func NewEncoder(w io.Writer) *Encoder {
  36. return &Encoder{
  37. w: w,
  38. j: json.NewEncoder(w),
  39. }
  40. }
  41. type auxPacket struct {
  42. Packet
  43. Body interface{} `json:"body"`
  44. }
  45. func (e *Encoder) Encode(p *Packet) error {
  46. if p == nil {
  47. return errors.New("no packet")
  48. }
  49. if p.Type == "" {
  50. return errors.New("packet type not set")
  51. }
  52. id := p.Id
  53. if id == 0 {
  54. id = getId()
  55. }
  56. body := p.auxBody
  57. // encodes packet and appends a newline character
  58. err := e.j.Encode(auxPacket{
  59. Packet: Packet{
  60. Id: id,
  61. Type: p.Type,
  62. },
  63. Body: body,
  64. })
  65. if err != nil {
  66. return errors.Wrap(err, "failed to encode body")
  67. }
  68. return nil
  69. }