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.

51 lines
1.2 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. "encoding/json"
  15. "fmt"
  16. "time"
  17. )
  18. var getId = func() uint64 {
  19. return uint64(time.Now().UnixNano() / 1000)
  20. }
  21. func Marshal(p *Packet) ([]byte, error) {
  22. if p == nil {
  23. return nil, fmt.Errorf("no packet")
  24. }
  25. if p.Type == "" {
  26. return nil, fmt.Errorf("packet type not set")
  27. }
  28. body, err := json.Marshal(p.auxBody)
  29. if err != nil {
  30. return nil, fmt.Errorf("failed to encode body: %v", err)
  31. }
  32. id := p.Id
  33. if id == 0 {
  34. id = getId()
  35. }
  36. data, err := json.Marshal(Packet{
  37. Id: id,
  38. Type: p.Type,
  39. Body: body,
  40. })
  41. if err != nil {
  42. return nil, err
  43. }
  44. return append(data, '\n'), nil
  45. }