aboutsummaryrefslogtreecommitdiffstats
path: root/test/AfbAngular.js
blob: 3db1ad591eb602ea6880a503d36fba614b6c8869 (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
(function (){'use strict';

  // some default values
  // note that how default values are defined/used may change
  var defaults = {
      token: '123456789',
      api: '/api'
    };

  var CALL = 2;
  var RETOK = 3;
  var RETERR = 4;
  var EVENT = 5;

  var PROTO1 = "x-afb-ws-json1";

  // Definition of the Angular module
  var AfbClientModule = angular.module('AfbClient', []);

  // The instanciation of the module
  AfbClientModule.factory('AfbClient', [ '$location', function ($location) {
    var refid = $location.host();
    var params = $location.search();
    return clients[refid] || (client[refid] = new AfbContext(refid, params));
  }]);

  // prototype for handling context by uuid and token
  function AfbContext(refid, params) {
    this.refid = refid;
    this.api = params.api || defaults.api;
    this.uhttp = params.uhttp || this.api+'/';
    this.uws = params.uws || this.api;
    this.token = params.token || defaults.token;
    this.uuid = params.uuid;
    this.ws = null;
  }

  AfbContext.prototype = {
    call: function(method, query) { return getws(this).call(method, query); },
    get: function(method, query) { return $http.get(this.uhttp+method, mixtu(this, query)); },
    post: function(method, query) { return $http.post(this.uhttp+method, mixtu(this, query)); },
  };

  function getws(ctxt) {
    return ctxt.ws || (ctxt.ws = new AfbWebSocket(ctxt));
  }

  function mixtu(ctxt, query) {
    return ("token" in query) ? query : angular.extend({token:ctxt.token},query);
  }

  // prototype for websocket
  function AfbWebSocket(ctxt) {
    var protos = [ PROTO1 ];
    this.context = ctxt;
    var url = "ws:" + ctxt.refid + ctxt.uws;
    var q = ctxt.uuid ? ("?x-afb-uuid=" + ctxt.uuid) : "";
    if (ctxt.token)
      q = (q ? (q + "&") : "?") + ("x-afb-token=" + ctxt.token);
    this.pendings = {};
    this.awaitens = {};
    this.counter = 0;
    this.ws = new WebSocket(url + q, protos);
    this.ws.onopen = onopen.bind(this);
    this.ws.onerror = onerror.bind(this);
    this.ws.onclose = onclose.bind(this);
    this.ws.onmessage = onmessage.bind(this);
    this.onopen = onopen;
    this.onabort = onabort;
  }

  AfbWebSocket.prototype = {
    call: function(method, query) {
        return new Promise((function(resolve, reject){
          var id = String(this.counter = 4095 & (this.counter + 1));
          while (id in this.pendings) id = String(this.counter = 4095 & (this.counter + 1));
          this.pendings[id] = [ resolve, reject ];
          var arr = [CALL, id, method, request ];
          var tok = this.context.token; if (tok) arr.push(tok);
          this.ws.send(angular.toJson(arr, 0));
        }).bind(this));
      },
    addEvent: function (name, handler) {
        (this.awaitens[name] || (this.awaitens[name] = [])).push(handler);
      },
    removeEvent: function (name, handler) {
        var a = this.awaitens[name];
        if (a) {
          var i = a.indexOf(handler);
          if (i >= 0) a.splice(i, 1);
        }
      }

  };

  function onmessage(ev) {
    var obj = angular.fromJson(ev.data);
    var id = obj[1];
    var ans = obj[2];
    if (obj[3])
      this.context.token = obj[3];
    switch (obj[0]) {
    case RETOK:  reply(this.pendings, id, ans, 0); break; 
    case RETERR: reply(this.pendings, id, ans, 1); break; 
    case EVENT:   fire(this.awaitens, id, ans);    break; 

    }
  }

  function fire(awaitens, name, data) {
    var a = awaitens[name];
    if (a) a.forEach(function(handler){handler(data);});
    var i = name.indexOf("/");
    if (i >= 0) {
      a = awaitens[name.substring(0,i)];
      if (a) a.forEach(function(handler){handler(data);});
    }
    a = awaitens["*"];
    if (a) a.forEach(function(handler){handler(data);});
  }

  function reply(pendings, id, ans, offset) {
    if (id in pendings) {
      var p = pendings[id];
      delete pendings[id];
      var f = p[offset];
      if (f) f(ans);
    }
  }










	AFB_websocket = function(onopen, onabort) {
	}

	function onerror(event) {
		var f = this.onabort;
		if (f) {
			delete this.onopen;
			delete this.onabort;
			f && f(this);
		}
		this.onerror && this.onerror(this);
	}

	function onopen(event) {
		var f = this.onopen;
		delete this.onopen;
		delete this.onabort;
		f && f(this);
	}

	function onclose(event) {
		for (var id in this.pendings) {
			var ferr = this.pendings[id].onerror;
			ferr && ferr(null, this);
		}
		this.pendings = {};
		this.onclose && this.onclose();
	}

	function close() {
		this.ws.close();
	}

	function call(method, request) {
	}

/*
  // Factory is a singleton and share its context within all instances.
  AfbClientModule.factory('AppCall', function ($http, AppConfig, $log) {
    var myCalls = {
      get : function(plugin, action, query, callback) {
        if (!query.token) query.token = AppConfig.session.token; // add token to provided query
        $http.get('/api/' + plugin + '/' + action , {params: query}).then (callback, callback);
      }
    };
    return myCalls;
  });
*/





})();
"o">% 9; return index; } /* * Scores the position described by 'b' * for the player of color 'c' using an analysis of 'depth'. * Returns 1 if player 'c' will win. * Returns -1 if opponent of player 'c' will win. * returns 0 otherwise. */ static int score_position(char b[9], char c, int depth) { int i, t, r; /* check if winner */ if (winner(b) == c) return 1; /* when depth of analysis is reached return unknown case */ if (--depth == 0) return 0; /* switch to the opponent */ c = (char)('O' + 'X' - c); /* inspect opponent moves */ r = 1; for (i = 0 ; i < 9 ; i++) { if (b[i] == ' ') { b[i] = c; t = score_position(b, c, depth); b[i] = ' '; if (t > 0) return -1; /* opponent will win */ if (t == 0) r = 0; /* something not clear */ } } return r; } /* get one move: return the computed index of the move */ static int get_move(struct board *board) { int index, depth, t, f; char c; char b[9]; /* compute the depth */ depth = board->level - 1; if (board->moves + depth > 9) depth = 9 - board->moves; /* case of null depth */ if (depth == 0) return get_random_move(board->board); /* depth and more */ memcpy(b, board->board, 9); c = color(board->moves); f = 0; for (index = 0 ; index < 9 ; index++) { if (board->board[index] == ' ') { board->board[index] = c; t = score_position(board->board, c, depth); board->board[index] = ' '; if (t > 0) return index; if (t < 0) b[index] = '+'; else f = 1; } } return get_random_move(f ? b : board->board); } /* * get the board description */ static struct json_object *describe(struct board *board) { int i; char w; struct json_object *resu, *arr; resu = json_object_new_object(); json_object_object_add(resu, "boardid", json_object_new_int(board->id)); json_object_object_add(resu, "level", json_object_new_int(board->level)); arr = json_object_new_array(); json_object_object_add(resu, "board", arr); for (i = 0 ; i < 9 ; i++) json_object_array_add(arr, json_object_new_string_len(&board->board[i], 1)); arr = json_object_new_array(); json_object_object_add(resu, "history", arr); for (i = 0 ; i < board->moves ; i++) json_object_array_add(arr, json_object_new_int(board->history[i])); w = winner(board->board); if (w) json_object_object_add(resu, "winner", json_object_new_string_len(&w, 1)); else if (board->moves == 9) json_object_object_add(resu, "winner", json_object_new_string("none")); return resu; } /* * signals a change of the board */ static void changed(struct board *board, const char *reason) { struct waiter *waiter, *next; struct json_object *description; /* get the description */ description = describe(board); waiter = board->waiters; board->waiters = NULL; while (waiter != NULL) { next = waiter->next; afb_req_success(waiter->req, json_object_get(description), reason); afb_req_unref(waiter->req); free(waiter); waiter = next; } afb_daemon_broadcast_event(afbitf->daemon, reason, description); } /* * retrieves the board of the request */ static inline struct board *board_of_req(struct afb_req req) { return afb_req_context(req, (void*)get_new_board, (void*)release_board); } /* * start a new game */ static void new(struct afb_req req) { struct board *board; /* retrieves the context for the session */ board = board_of_req(req); INFO(afbitf, "method 'new' called for boardid %d", board->id); /* reset the game */ memset(board->board, ' ', sizeof board->board); board->moves = 0; /* replies */ afb_req_success(req, NULL, NULL); /* signal change */ changed(board, "new"); } /* * get the board */ static void board(struct afb_req req) { struct board *board; struct json_object *description; /* retrieves the context for the session */ board = board_of_req(req); INFO(afbitf, "method 'board' called for boardid %d", board->id); /* describe the board */ description = describe(board); /* send the board's description */ afb_req_success(req, description, NULL); } /* * move a piece */ static void move(struct afb_req req) { struct board *board; int i; const char *index; /* retrieves the context for the session */ board = board_of_req(req); INFO(afbitf, "method 'move' called for boardid %d", board->id); /* retrieves the arguments of the move */ index = afb_req_value(req, "index"); i = index == NULL ? -1 : atoi(index); /* checks validity of arguments */ if (i < 0 || i > 8) { WARNING(afbitf, "can't move to %s: %s", index?:"?", index?"wrong value":"not set"); afb_req_fail(req, "error", "bad request"); return; } /* checks validity of the state */ if (winner(board->board) != 0) { WARNING(afbitf, "can't move to %s: game is terminated", index); afb_req_fail(req, "error", "game terminated"); return; } /* checks validity of the move */ if (board->board[i] != ' ') { WARNING(afbitf, "can't move to %s: room occupied", index); afb_req_fail(req, "error", "occupied"); return; } /* applies the move */ INFO(afbitf, "method 'move' for boardid %d, index=%s", board->id, index); add_move(board, i); /* replies */ afb_req_success(req, NULL, NULL); /* signals change */ changed(board, "move"); } /* * set the level */ static void level(struct afb_req req) { struct board *board; int l; const char *level; /* retrieves the context for the session */ board = board_of_req(req); INFO(afbitf, "method 'level' called for boardid %d", board->id); /* retrieves the arguments */ level = afb_req_value(req, "level"); l = level == NULL ? -1 : atoi(level); /* check validity of arguments */ if (l < 1 || l > 10) { WARNING(afbitf, "can't set level to %s: %s", level?:"?", level?"wrong value":"not set"); afb_req_fail(req, "error", "bad request"); return; } /* set the level */ INFO(afbitf, "method 'level' for boardid %d, level=%d", board->id, l); board->level = l; /* replies */ afb_req_success(req, NULL, NULL); /* signals change */ changed(board, "level"); } /* * Join a board */ static void join(struct afb_req req) { struct board *board, *new_board; const char *id; /* retrieves the context for the session */ board = board_of_req(req); INFO(afbitf, "method 'join' called for boardid %d", board->id); /* retrieves the arguments */ id = afb_req_value(req, "boardid"); if (id == NULL) goto bad_request; /* none is a special id for joining a new session */ if (strcmp(id, "none") == 0) { new_board = get_new_board(); goto success; } /* searchs the board to join */ new_board = search_board(atoi(id)); if (new_board == NULL) goto bad_request; /* * joining its board is stupid but possible * however when called with the same stored pointer * afb_req_context_set will not call the release * function 'release_board'. So the use_count MUST not * be incremented. */ if (new_board != board) new_board->use_count++; success: /* set the new board (and leaves the previous one) */ afb_req_context_set(req, new_board, (void*)release_board); /* replies */ afb_req_success(req, NULL, NULL); return; bad_request: WARNING(afbitf, "can't join boardid %s: %s", id ? : "?", !id ? "no boardid" : atoi(id) ? "not found" : "bad boardid"); afb_req_fail(req, "error", "bad request"); return; } /* * Undo the last move */ static void undo(struct afb_req req) { struct board *board; int i; /* retrieves the context for the session */ board = board_of_req(req); INFO(afbitf, "method 'undo' called for boardid %d", board->id); /* checks the state */ if (board->moves == 0) { WARNING(afbitf, "can't undo"); afb_req_fail(req, "error", "bad request"); return; } /* undo the last move */ i = board->history[--board->moves]; board->board[i] = ' '; /* replies */ afb_req_success(req, NULL, NULL); /* signals change */ changed(board, "undo"); } /* * computer plays */ static void play(struct afb_req req) { struct board *board; int index; /* retrieves the context for the session */ board = board_of_req(req); INFO(afbitf, "method 'play' called for boardid %d", board->id); /* checks validity of the state */ if (winner(board->board) != 0 || board->moves == 9) { WARNING(afbitf, "can't play: game terminated (%s)", winner(board->board) ? "has winner" : "no room left"); afb_req_fail(req, "error", "game terminated"); return; } /* gets the move and plays it */ index = get_move(board); add_move(board, index); /* replies */ afb_req_success(req, describe(board), NULL); /* signals change */ changed(board, "play"); } static void wait(struct afb_req req) { struct board *board; struct waiter *waiter; /* retrieves the context for the session */ board = board_of_req(req); INFO(afbitf, "method 'wait' called for boardid %d", board->id); /* creates the waiter and enqueues it */ waiter = calloc(1, sizeof *waiter); waiter->req = req; waiter->next = board->waiters; afb_req_addref(req); board->waiters = waiter; } /* * array of the verbs exported to afb-daemon */ static const struct afb_verb_desc_v1 binding_verbs[] = { /* VERB'S NAME SESSION MANAGEMENT FUNCTION TO CALL SHORT DESCRIPTION */ { .name= "new", .session= AFB_SESSION_NONE, .callback= new, .info= "Starts a new game" }, { .name= "play", .session= AFB_SESSION_NONE, .callback= play, .info= "Asks the server to play" }, { .name= "move", .session= AFB_SESSION_NONE, .callback= move, .info= "Tells the client move" }, { .name= "board", .session= AFB_SESSION_NONE, .callback= board, .info= "Get the current board" }, { .name= "level", .session= AFB_SESSION_NONE, .callback= level, .info= "Set the server level" }, { .name= "join", .session= AFB_SESSION_CHECK,.callback= join, .info= "Join a board" }, { .name= "undo", .session= AFB_SESSION_NONE, .callback= undo, .info= "Undo the last move" }, { .name= "wait", .session= AFB_SESSION_NONE, .callback= wait, .info= "Wait for a change" }, { .name= NULL } /* marker for end of the array */ }; /* * description of the binding for afb-daemon */ static const struct afb_binding binding_description = { /* description conforms to VERSION 1 */ .type= AFB_BINDING_VERSION_1, .v1= { /* fills the v1 field of the union when AFB_BINDING_VERSION_1 */ .prefix= "tictactoe", /* the API name (or binding name or prefix) */ .info= "Sample tac-tac-toe game", /* short description of of the binding */ .verbs = binding_verbs /* the array describing the verbs of the API */ } }; /* * activation function for registering the binding called by afb-daemon */ const struct afb_binding *afbBindingV1Register(const struct afb_binding_interface *itf) { afbitf = itf; // records the interface for accessing afb-daemon return &binding_description; // returns the description of the binding }