summaryrefslogtreecommitdiff
path: root/vndbApi.ml
blob: 7200ef6fb43de7091aa77db550b94d1597164e09 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
(* Copyright (c) 2010-2011 Yoran Heling
 *
 * Permission is hereby granted, free of charge, to any person obtaining
 * a copy of this software and associated documentation files (the
 * "Software"), to deal in the Software without restriction, including
 * without limitation the rights to use, copy, modify, merge, publish,
 * distribute, sublicense, and/or sell copies of the Software, and to
 * permit persons to whom the Software is furnished to do so, subject to
 * the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
 *)

open Unix


type reply =
    RInvalid of string (* unable to parse reply for some reason (string=raw reply) *)
  | ROK
  | RResults of (int * bool * Json.json list) (* num, more, items *)
  | RError of (string * string * Json.json)   (* id, msg, json obj *)


type user =
    Anonymous
  | User of (string * string)


class connection
    (pollfunc : file_descr -> bool -> (unit -> unit) -> unit)
    (waitfunc : int -> (unit -> unit) -> unit)
  = object (self)
  val mutable s_sock = (None : file_descr option) (* None when disconnected *)
  val mutable s_host = "beta.vndb.org"
  val mutable s_port = 19534
  val mutable s_addr = (None : inet_addr option)
  val mutable linefunc = (None : (bool -> string -> unit) option)
  val mutable disconnectfunc = (None : (unit -> unit) option)
  val cmd_queue = (Queue.create () : (string * (reply -> unit)) Queue.t)
  val mutable cmd_running = false


  method get_host = s_host
  method set_host h = s_host <- h; s_addr <- None
  method get_port = s_port
  method set_port p = s_port <- p
  method get_addr = s_addr
  method set_linefunc f = linefunc <- f
  method set_disconnectfunc f = disconnectfunc <- f
  method connected = match s_sock with None -> false | Some _ -> true


  method private parsereply str =
    try
      (* space and newline are always ignored with scanf, so no need to check
       * for that. (this parser is rather lazy, and may accept incorrect input) *)
      let name, value =
        Scanf.sscanf str "%[\r\t] %[a-z] %[\r\t] %[^\004]" (fun _ a _ b -> (a,b)) in
      match name with
      | "ok" -> ROK
      | "error" -> 
        let obj = Json.json_of_string value in
        RError (
          Json.get_string (Json.get_value obj "id"),
          Json.get_string (Json.get_value obj "msg"),
          obj
        )
      | "results" ->
        let obj = Json.json_of_string value in
        RResults (
          int_of_string  (Json.get_int (Json.get_value obj "num")),
          Json.get_bool  (Json.get_value obj "more"),
          Json.get_array (Json.get_value obj "items")
        )
      | _ -> raise (Failure "Incorrect reply code")
    with _ -> RInvalid str
    (* the above try .. throws away any info on why it was invalid. but oh well,
     * it's not like the server will send invalid data anytime soon anyway *)


  method private docmd () =
    if (not cmd_running && not (Queue.is_empty cmd_queue) && s_sock <> None) then (
      cmd_running <- true;
      let cmd, recvcb = Queue.peek cmd_queue in
      let s = match s_sock with None -> assert false | Some x -> x in
      let reply = ref "" in
      let buf = String.create 8192 in
      let finish () =
        reply := String.sub !reply 0 (String.rindex !reply '\004');
        (match linefunc with None -> () | Some f -> f false !reply);
        let preply = self#parsereply !reply in
        match preply with
        (* Oops! throttled error, let's wait a few seconds and try again *)
        | RError ("throttled", _, obj) -> (
          let wait = match Json.get_value obj "minwait" with
          | Json.Int i -> int_of_string i
          | Json.Number n -> int_of_float (ceil (float_of_string n))
          | _ -> assert false in
          waitfunc wait (fun () ->
            cmd_running <- false;
            self#docmd ()
          ))
        (* Not throttled, so consider this command as finished *)
        | _ -> 
          ignore (Queue.pop cmd_queue);
          cmd_running <- false;
          self#docmd ();
          recvcb preply
      in
      let rec dorecv () =
        let cnt = recv s buf 0 (String.length buf) [] in
        if cnt == 0 then self#disconnect else (
          reply := !reply ^ (String.sub buf 0 cnt);
          match String.contains !reply '\004' with
          | true  -> finish ()
          | false -> pollfunc s true dorecv
        )
      in
      let dosend () = 
        (* assumes the command can be sent with a single call *)
        let cnt = send s
          (cmd ^ (String.make 1 (char_of_int 4)))
          0 (String.length cmd + 1) [] in
        if cnt == 0 then self#disconnect else (
          match linefunc with None -> () | Some f -> f true cmd;
          pollfunc s true dorecv
        )
      in
      pollfunc s false dosend
    )


  method addcmd cmd recvcb =
    Queue.push (cmd, recvcb) cmd_queue;
    self#docmd ()


  (* TODO: keep monitoring connection after successful connect *)
  method connect cf ff =
    (* get IP (blocks!) *)
    let ip = match s_addr with
    | Some x -> x
    | None -> (gethostbyname s_host).h_addr_list.(0) in
    (* create socket *)
    let s = socket PF_INET SOCK_STREAM 0 in
    (* and connect *)
    let success () =
      clear_nonblock s;
      s_sock <- Some s;
      s_addr <- Some ip;
      cf ip s_port in
    let failure a b c =
      close s;
      ff a b c in
    set_nonblock s;
    try
      ignore (connect s (ADDR_INET (ip, s_port)));
      (* no error? assume this was a successfull blocking connect *)
      success ()
    (* non-blocking connect, poll for the result *)
    with Unix_error (EINPROGRESS, _, _) ->
      pollfunc s false (fun () -> 
        clear_nonblock s;
        match getsockopt_error s with
        | None -> success ()
        | Some e -> failure e "connect" (error_message e)
      )
    (* blocking connect, but failed *)
    | Unix_error (a, b, c) -> failure a b c


  method disconnect =
    (* we'll have to clear the comamnd queue when disconnected, since we need to
     * be able to issue the login command the first thing after a reconnect...
     * It might be an idea to either special-case the login command or call all
     * registered callback functions with an error.
     * Behaviour is currently undefined when disconnect is called while a
     * command is being handled. *)
    Queue.clear cmd_queue;
    cmd_running <- false;
    match s_sock with None -> () | Some s -> close s; s_sock <- None;
    match disconnectfunc with None -> () | Some f -> f ()


  method login user recvcb =
    let cr = match user with
    | Anonymous   -> []
    | User (n, p) -> [
      ("username",  Json.String n);
      ("password",  Json.String p)
    ] in
    let o = Json.Object (cr @ [
      ("protocol",  Json.Int    "1");
      ("client",    Json.String "Serika");
      ("clientver", Json.Number "0.1")
    ]) in
    self#addcmd ("login " ^ (Json.string_of_json o)) recvcb

end