chat.rkt 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. #lang racket
  2. (provide (all-defined-out))
  3. (require net/url
  4. net/rfc6455 ;; web sockets
  5. json
  6. "api.rkt")
  7. (ws-idle-timeout +inf.0)
  8. ;; Creates a new connection and spaws threads for handling incoming events
  9. ;; and for sending pings.
  10. ;; Returns an object that can be used with e.g. send-message
  11. (define (make-connection server-addr user-name
  12. #:on-chat on-chat ;;; called with (on-chat from message)
  13. #:on-response on-response ;;; called with (on-response message)
  14. #:on-users on-users ;;; called with (on-users users)
  15. #:on-notify on-notify ;;; called with (on-notify msg)
  16. #:on-join on-join ;;; called with (on-join user)
  17. #:on-leave on-leave ;;; called with (on-leave user)
  18. #:on-name-change on-name-change
  19. ;;; called with (on-name-change old-name new-name)
  20. )
  21. (define c (ws-connect (string->url server-addr)))
  22. (define user-color "#00FFAA")
  23. (define evt (ws-recv-evt c))
  24. (define (handle-evt)
  25. (let ([v (sync evt)])
  26. (cond
  27. [(eof-object? v)
  28. (printf "RIP socket\n")
  29. (ws-close! c)]
  30. [(string? v)
  31. (let ([js (string->jsexpr v)])
  32. (cond
  33. [(is-chat-message? js)
  34. (define msg (get-chat-message js))
  35. (match msg
  36. [(chat-message message from color type)
  37. (match type
  38. ['chat (on-chat from message)]
  39. ['response (on-response message)]
  40. [_
  41. (log-warning
  42. (format "chat.rkt/handl-evt: cannot handle message type in ~s" msg))])])]
  43. [(is-users-reply? js)
  44. (on-users (get-users-reply js))]
  45. [(is-notify? js)
  46. (log-info (format "MovieNight notification: ~a" js))
  47. (on-notify (get-notify js))]
  48. [(is-event? js)
  49. (define ed (get-event-data js))
  50. (match ed
  51. [(event-data type data)
  52. (match type
  53. ['join (on-join data)]
  54. ['leave (on-leave data)]
  55. [(or 'name-changed
  56. 'name-change-forced)
  57. (match (string-split data ":")
  58. [(list old-nick new-nick)
  59. (on-name-change old-nick new-nick)]
  60. [_ #f])]
  61. [_
  62. (log-warning
  63. (format "chat.rkt/handl-evt: cannot handle event type in ~s" ed))])])]
  64. [else
  65. (log-warning
  66. (format "chat.rkt/handle-evt: don't know how to handle ~a" (jsexpr->string js)))]))
  67. (handle-evt)]
  68. [else
  69. (printf "Unknown msg: ~a" v)
  70. (handle-evt)])))
  71. (define (do-ping)
  72. (sleep 10)
  73. (send-ping c)
  74. (do-ping))
  75. (void (thread handle-evt))
  76. (void (thread do-ping))
  77. c)
  78. (define (nickname-check nick)
  79. (and (>= (string-length nick) 3)
  80. (<= (string-length nick) 10)
  81. ;; TODO other checks
  82. ))