main.go 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308
  1. package main
  2. import (
  3. "context"
  4. "flag"
  5. "fmt"
  6. "log"
  7. "math/rand"
  8. "net"
  9. "net/http"
  10. "google.golang.org/grpc"
  11. "google.golang.org/grpc/grpclog"
  12. "google.golang.org/grpc/credentials"
  13. "google.golang.org/grpc/examples/data"
  14. // "github.com/improbable-eng/grpc-web/go/grpcweb"
  15. _ "net/http/pprof"
  16. pb "git.capella.pro/thepaint/protos"
  17. "encoding/base64"
  18. "encoding/json"
  19. "github.com/improbable-eng/grpc-web/go/grpcweb"
  20. "github.com/pion/webrtc/v3"
  21. "github.com/sirupsen/logrus"
  22. )
  23. var (
  24. tls = flag.Bool("tls", false, "Connection uses TLS if true, else plain TCP")
  25. certFile = flag.String("cert_file", "", "The TLS cert file")
  26. keyFile = flag.String("key_file", "", "The TLS key file")
  27. jsonDBFile = flag.String("json_db_file", "", "A json file containing a list of features")
  28. port = flag.Int("port", 8080, "The server port")
  29. )
  30. type server struct {
  31. pb.UnimplementedPaintClientServer
  32. // savedFeatures []*pb.Feature // read-only after initialized
  33. //
  34. // mu sync.Mutex // protects routeNotes
  35. // routeNotes map[string][]*pb.RouteNote
  36. }
  37. func main() {
  38. grpclog.V(10)
  39. flag.Parse()
  40. lis, err := net.Listen("tcp", fmt.Sprintf("localhost:%d", *port))
  41. if err != nil {
  42. log.Fatalf("failed to listen: %v", err)
  43. }
  44. var opts []grpc.ServerOption
  45. if *tls {
  46. if *certFile == "" {
  47. *certFile = data.Path("x509/server_cert.pem")
  48. }
  49. if *keyFile == "" {
  50. *keyFile = data.Path("x509/server_key.pem")
  51. }
  52. creds, err := credentials.NewServerTLSFromFile(*certFile, *keyFile)
  53. if err != nil {
  54. log.Fatalf("Failed to generate credentials %v", err)
  55. }
  56. opts = []grpc.ServerOption{grpc.Creds(creds)}
  57. }
  58. grpcServer := grpc.NewServer(opts...)
  59. s := newServer()
  60. pb.RegisterPaintClientServer(grpcServer, s)
  61. logrus.Printf("starting %d", *port)
  62. wrappedServer := grpcweb.WrapServer(grpcServer,
  63. grpcweb.WithOriginFunc(func(origin string) bool { return true }),
  64. grpcweb.WithWebsocketsMessageReadLimit(100000))
  65. handler := func(resp http.ResponseWriter, req *http.Request) {
  66. logrus.Info(req)
  67. if req.ProtoMajor != 2 {
  68. wrappedServer.ServeHTTP(resp, req)
  69. } else {
  70. grpcServer.ServeHTTP(resp, req)
  71. }
  72. }
  73. httpServer := http.Server{
  74. Addr: fmt.Sprintf(":%d", port),
  75. // Handler: CompressHandler(http.HandlerFunc(handler)),
  76. Handler: http.HandlerFunc(handler),
  77. }
  78. go func() {
  79. http.ListenAndServe(":8081", nil)
  80. }()
  81. if err := httpServer.Serve(lis); err != nil {
  82. grpclog.Fatalf("failed starting http server: %v", err)
  83. }
  84. }
  85. func (s *server) Paint(ctx context.Context, request *pb.PaintRequest) (*pb.PaintReply, error) {
  86. panic("implement me")
  87. }
  88. func (s *server) Monitor(sub *pb.MonitorSub, monitorServer pb.PaintClient_MonitorServer) error {
  89. // for k := 0; k < 4; k++ {
  90. // points := []*pb.MonitorPoint{}
  91. // for i := 64*k; i < 64*(k+1); i++ {
  92. // for j := 0; j < 256; j++ {
  93. // points = append(points, &pb.MonitorPoint{
  94. // Point: &pb.BPoint{
  95. // X: int32(i),
  96. // Y: int32(j),
  97. // },
  98. // Color: &pb.BColor{
  99. // Rgba: uint32(rand.Intn(256)) | uint32(rand.Intn(256))<<8 | uint32(rand.Intn(256))<<16 | 255<<24,
  100. // },
  101. // })
  102. // }
  103. // }
  104. //
  105. // monitorServer.Send(&pb.MonitorReply{
  106. // Points: points,
  107. // // BytesPoints: b.Bytes(),
  108. // })
  109. // }
  110. points := []*pb.MonitorPoint{}
  111. for i := 0; i < 256; i++ {
  112. for j := 0; j < 256; j++ {
  113. points = append(points, &pb.MonitorPoint{
  114. Point: &pb.BPoint{
  115. X: int32(i),
  116. Y: int32(j),
  117. },
  118. Color: &pb.BColor{
  119. Rgba: uint32(rand.Intn(256)) | uint32(rand.Intn(256))<<8 | uint32(rand.Intn(256))<<16 | 255<<24,
  120. },
  121. })
  122. }
  123. }
  124. monitorServer.Send(&pb.MonitorReply{
  125. Points: points,
  126. // BytesPoints: b.Bytes(),
  127. })
  128. return nil
  129. }
  130. // func (s *server) RequestRTC(req pb.PaintClient_RequestRTCServer) error {
  131. // offer(req)
  132. // return nil
  133. // }
  134. func newServer() *server {
  135. s := &server{}
  136. return s
  137. }
  138. func handleError(err error) {
  139. logrus.Error(err)
  140. }
  141. func (s *server) RequestRTC(stream pb.PaintClient_RequestRTCServer) error {
  142. logrus.Info("NEW GRPC")
  143. // Configure and create a new PeerConnection.
  144. config := webrtc.Configuration{
  145. ICEServers: []webrtc.ICEServer{
  146. {
  147. URLs: []string{"stun:melvans.com:3478"},
  148. Username: "b84e4232f84505e3c3967184df374f2cdaa954f1",
  149. Credential: "afc39ae0591c132292f73a87f6f3725311fbafa0",
  150. // URLs: []string{"stun:stun.l.google.com:19302"},
  151. },
  152. },
  153. }
  154. pc, err := webrtc.NewPeerConnection(config)
  155. if err != nil {
  156. handleError(err)
  157. }
  158. // Create DataChannel.
  159. sendChannel, err := pc.CreateDataChannel("data", nil)
  160. if err != nil {
  161. handleError(err)
  162. }
  163. sendChannel.OnClose(func() {
  164. logrus.Println("sendChannel has closed")
  165. })
  166. sendChannel.OnOpen(func() {
  167. logrus.Println("sendChannel has opened")
  168. })
  169. sendChannel.OnMessage(func(msg webrtc.DataChannelMessage) {
  170. logrus.Println(string(msg.Data))
  171. })
  172. // Create offer
  173. offer, err := pc.CreateOffer(nil)
  174. if err != nil {
  175. handleError(err)
  176. }
  177. if err := pc.SetLocalDescription(offer); err != nil {
  178. handleError(err)
  179. }
  180. // Add handlers for setting up the connection.
  181. pc.OnICEConnectionStateChange(func(state webrtc.ICEConnectionState) {
  182. logrus.Println(state)
  183. })
  184. // connectionString := make(chan bool)
  185. // Trickle ICE. Emit server candidate to client
  186. pc.OnICECandidate(func(i *webrtc.ICECandidate) {
  187. if i == nil {
  188. return
  189. }
  190. // candidateString, err := json.Marshal(i.ToJSON())
  191. // if err != nil {
  192. // logrus.Error(err)
  193. // return
  194. // }
  195. logrus.Println(i)
  196. err = stream.Send(&pb.RTCData{
  197. Event: string(pc.LocalDescription().Type.String()),
  198. Data: string(pc.LocalDescription().SDP),
  199. })
  200. // connectionString <- true
  201. if err != nil {
  202. logrus.Error(err)
  203. return
  204. }
  205. })
  206. for {
  207. msg, err := stream.Recv()
  208. if err != nil {
  209. logrus.Error(err)
  210. return err
  211. }
  212. answer := webrtc.SessionDescription{
  213. SDP: msg.Data,
  214. Type: webrtc.NewSDPType(msg.Event),
  215. }
  216. err = pc.SetRemoteDescription(answer)
  217. if err != nil {
  218. logrus.Error(err)
  219. return err
  220. }
  221. }
  222. // // If PeerConnection is closed remove it from global list
  223. // pc.OnConnectionStateChange(func(p webrtc.PeerConnectionState) {
  224. // switch p {
  225. // case webrtc.PeerConnectionStateFailed:
  226. // if err := pc.Close(); err != nil {
  227. // log.Print(err)
  228. // }
  229. // case webrtc.PeerConnectionStateClosed:
  230. // log.Print("closed")
  231. // }
  232. // })
  233. // offer, err := pc.CreateOffer(nil)
  234. // if err != nil {
  235. // logrus.Error(err)
  236. // }
  237. // if err = pc.SetLocalDescription(offer); err != nil {
  238. // logrus.Error(err)
  239. // }
  240. // logrus.Println(offer)
  241. // <-connectionString
  242. // answer := webrtc.SessionDescription{
  243. // SDP: sub.Data,
  244. // Type: webrtc.SDPTypeAnswer,
  245. // }
  246. // err = pc.SetRemoteDescription(answer)
  247. // if err != nil {
  248. // logrus.Error(err)
  249. // }
  250. // return nil
  251. }
  252. func Encode(obj interface{}) string {
  253. b, err := json.Marshal(obj)
  254. if err != nil {
  255. panic(err)
  256. }
  257. return base64.StdEncoding.EncodeToString(b)
  258. }
  259. func websocketHandler(w http.ResponseWriter, r *http.Request) {
  260. }