SFS2X Objective-C API  1.7.13
iOS / macOS / tvOS
SmartFox2XClient.h
1 //
2 // SmartFox2XClient.h
3 // SFS2X Client API
4 //
5 // Maintained and developed by A51 Integrated and GOTOANDPLAY snc
6 // Copyright 2022 GOTOANDPLAY snc | https://www.smartfoxserver.com All rights reserved.
7 //
8 
9 #import <Foundation/Foundation.h>
10 
11 //! Project version number for SFS2X_API_IOS_Catalyst.
12 FOUNDATION_EXPORT double SFS2X_API_IOS_CatalystVersionNumber;
13 
14 //! Project version string for SFS2X_API_IOS_Catalyst.
15 FOUNDATION_EXPORT const unsigned char SFS2X_API_IOS_CatalystVersionString[];
16 
17 #import "Room.h"
18 #import "SFSRoom.h"
19 #import "User.h"
20 #import "SFSUser.h"
21 #import "UserPrivileges.h"
22 #import "SFSBuddy.h"
23 #import "IBuddyManager.h"
24 #import "IUserManager.h"
25 #import "IRoomManager.h"
26 #import "IBitSwarmEvents.h"
27 #import "ISFSEvents.h"
28 #import "IConfigLoader.h"
29 #import "SFSEvent.h"
30 #import "SFSObject.h"
31 #import "SFSArray.h"
32 #import "RoomSettings.h"
33 #import "RoomProperties.h"
34 #import "UserProperties.h"
35 #import "IRequest.h"
36 #import "LoginRequest.h"
37 #import "LogoutRequest.h"
38 #import "JoinRoomRequest.h"
39 #import "LeaveRoomRequest.h"
40 #import "ChangeRoomNameRequest.h"
41 #import "ChangeRoomCapacityRequest.h"
42 #import "CreateRoomRequest.h"
43 #import "PlayerToSpectatorRequest.h"
44 #import "RoomPermissions.h"
45 #import "PublicMessageRequest.h"
46 #import "ChangeRoomPasswordStateRequest.h"
47 #import "AdminMessageRequest.h"
48 #import "BanMode.h"
49 #import "BanUserRequest.h"
50 #import "KickUserRequest.h"
51 #import "MessageRecipientMode.h"
52 #import "SpectatorToPlayerRequest.h"
53 #import "SubscribeRoomGroupRequest.h"
54 #import "UnsubscribeRoomGroupRequest.h"
55 #import "PrivateMessageRequest.h"
56 #import "SFSInvitation.h"
57 #import "ModeratorMessageRequest.h"
58 #import "InvitationReplyRequest.h"
59 #import "InviteUsersRequest.h"
60 #import "FindRoomsRequest.h"
61 #import "FindUsersRequest.h"
62 #import "SetRoomVariablesRequest.h"
63 #import "SFSRoomVariable.h"
64 #import "SetUserVariablesRequest.h"
65 #import "ObjectMessageRequest.h"
66 #import "SFSBuddyEvent.h"
67 #import "AddBuddyRequest.h"
68 #import "InitBuddyListRequest.h"
69 #import "RemoveBuddyRequest.h"
70 #import "BlockBuddyRequest.h"
71 #import "BuddyMessageRequest.h"
72 #import "GoOnlineRequest.h"
73 #import "SetBuddyVariablesRequest.h"
74 #import "SFSBuddyVariable.h"
75 #import "CreateSFSGameRequest.h"
76 #import "SFSGameSettings.h"
77 #import "QuickJoinGameRequest.h"
78 #import "MatchExpression.h"
79 #import "BoolMatch.h"
80 #import "StringMatch.h"
81 #import "LogicOperator.h"
82 #import "NumberMatch.h"
83 #import "ExtensionRequest.h"
84 #import "Logger.h"
85 #import "LogLevel.h"
86 #import "ConfigData.h"
87 #import "MMORoom.h"
88 #import "IMMOItemVariable.h"
89 #import "MMOItemVariable.h"
90 #import "IMMOItem.h"
91 #import "MMOItem.h"
92 #import "Vec3D.h"
93 #import "MMORoomSettings.h"
94 #import "SetUserPositionRequest.h"
95 #import "MapLimits.h"
96 #import "LagMonitor.h"
97 #import "JoinRoomInvitationRequest.h"
98 #import "QuickJoinOrCreateRoomRequest.h"
99 
100 @class BitSwarmClient;
101 @class Logger;
102 
103 extern NSString *const CLIENT_TYPE_SEPARATOR;
104 extern int const DEFAULT_HTTP_PORT;
105 
106 /** SmartFox2XClient is the main class in the SFS2X API.
107 
108  This class is responsible for connecting to the Server and dispatching all asynchronous events.
109  @warning *<b>Important:</b>* in the provided examples, <b>smartFox</b> always indicates a SmartFox2XClient instance.
110  */
111 
112 
113 @interface SmartFox2XClient : NSObject <IBitSwarmEvents, IConfigLoader>{
114 
115 
116 
117 @private
118  NSInteger _majVersion;
119  NSInteger _minVersion;
120  NSInteger _subVersion;
121 
122  NSMutableString *_clientDetails;
123 
124  // BlueBox default port
125  // int const DEFAULT_HTTP_PORT;
126 
127  BitSwarmClient *_bitSwarm;
128 
129  // If true the client is using Http Tunnelling
130  BOOL _useBlueBox;
131 
132  // last know ip address from ConfigData
133  NSString *_lastIpAddress;
134 
135  // If true the client is in the middle of a join transaction
136  BOOL _isJoining;
137 
138  // References the client's User object
139  id<User> _mySelf;
140 
141  // A unique session token, sent by the server during the handshake
142  NSString *_sessionToken;
143 
144  // Last joined room
145  id <Room> _lastJoinedRoom;
146 
147  // The logger
148  Logger *__weak _log;
149 
150  // API initialization flag
151  BOOL _inited;
152 
153  // Protocol debug flag
154  BOOL _debug;
155 
156  // Connection attempt flag
157  BOOL _isConnecting;
158 
159  // The global user manager
160  id <IUserManager> _userManager;
161 
162  // The global room manager
163  id <IRoomManager> _roomManager;
164 
165  // The global buddy manager
166  id <IBuddyManager> _buddyManager;
167 
168  ConfigData *_config;
169 
170  // The name of the currently joined Zone
171  NSString *_currentZone;
172 
173  // When true -> starts the connection right after successful config loading
174  BOOL _autoConnectOnConfig;
175 
176  id <ISFSEvents> __weak _delegate;
177 
178 
179 }
180 
181 
182 
183 /** Returns the Buddy Manager.
184 
185  @see SFSBuddyManager
186  */
187 @property (strong) id <IBuddyManager> buddyManager;
188 
189 /** Returns the current compression threshold.
190 
191  The value represent the maximum message size (in bytes) before the protocol compression is activated.
192  The value is determined by the server configuration.
193  */
194 @property (readonly) NSInteger compressionThreshold;
195 
196 /** Get the current client configuration.
197 
198  It can return null if the configuration was not loaded.
199 
200  @see loadConfig:connectOnSuccess:
201  */
202 @property (strong) ConfigData *config;
203 
204 /** The address where the client is connected (if the client is connected)
205 
206  @see connect:port:
207  @see loadConfig:connectOnSuccess:
208  */
209 @property (weak, readonly) NSString *currentIp;
210 
211 /** The TCP port of the server where the client is connected (if the client is connected)
212 
213  @see loadConfig:connectOnSuccess:
214  @see LoginRequest
215  */
216 @property (readonly) NSInteger currentPort;
217 
218 /** The current Zone in use, if user is logged in
219 
220  @see loadConfig:connectOnSuccess:
221  @see LoginRequest
222  */
223 @property (strong) NSString *currentZone;
224 
225 /** When set to true, provides detailed debugging data for all incoming/outgoing messages
226  */
227 @property (assign) BOOL debug;
228 
229 /** Returns true if the client connection is http tunnelled
230  */
231 @property (assign) BOOL useBlueBox;
232 
233 /** Returns true if the client connection is active
234  */
235 @property (readonly) BOOL isConnected;
236 
237 /** Returns the mode of the connection (Socket or HTTP)
238  */
239 @property (weak, readonly) NSString *connectionMode;
240 
241 @property (strong, readonly) LagMonitor *lagMonitor;
242 
243 /** Returns a list of Rooms currently joined by the client
244 
245  @see JoinRoomRequest
246  */
247 @property (weak, readonly) NSMutableArray *joinedRooms;
248 
249 /** Return the last joined Room, if any.
250 
251  Null is returned if there's no currently joined Room.
252 
253  @see JoinRoomRequest
254  */
255 @property (strong) id <Room> lastJoinedRoom;
256 
257 /** Get a reference to the logger
258 
259  @return the logger
260  */
261 @property (weak, readonly) Logger *logger;
262 
263 
264 /** This User object represents the User connected to SmartFoxServer 2X
265 
266  @see LoginRequest
267  */
268 @property (strong) id <User> mySelf;
269 
270 /** Returns the list of Rooms currently "watched" by the client.
271 
272  The list will contain all the Rooms that are currently joined and all the Rooms from the Room Groups that are subscribed.
273  At login time the User is automatically subscribed to all Room Groups specified in the Zone's *Default Groups* setting.
274 
275  @see SubscribeRoomGroupRequest
276  @see UnsubscribeRoomGroupRequest
277  */
278 @property (weak, readonly) NSArray *roomList;
279 
280 /** Returns the Room Manager.
281  @see SFSRoomManager
282  */
283 @property (strong) id <IRoomManager> roomManager;
284 
285 /** Returns the unique session token.
286 
287  The Session token is a String sent by the server to the client after the initial handshake.
288  */
289 @property (strong) NSString *sessionToken;
290 
291 /** Returns the User Manager.
292 
293  @see SFSUserManager
294  */
295 @property (strong) id <IUserManager> userManager;
296 
297 /** Return the API current version
298  */
299 @property (weak, readonly) NSString *version;
300 
301 @property (strong) BitSwarmClient *bitSwarm;
302 @property (readwrite) BOOL isJoining;
303 @property (weak, readonly) id <ISFSEvents> delegate;
304 
305 -(void)handleHandshake:(SFSEvent *)evt;
306 -(void)setReconnectionSeconds:(NSInteger)seconds;
307 -(NSInteger)getReconnectionSeconds;
308 -(void)handleClientDisconnection:(NSString *)reason;
309 -(void)handleReconnectionFailure;
310 -(void)handleLogout;
311 -(void)handleLogin:(SFSEvent *)evt;
312 -(BitSwarmClient *)getSocketEngine;
313 
314 
315 /** Initializes SmartFox Client
316 
317  @param debug (BOOL) determines debugging mode.
318  @param delegate (id <ISFSEvents>) delegate object that listens api events.
319 
320  @see smartFoxWithDebugMode:delegate:
321  */
322 -(id)initSmartFoxWithDebugMode:(BOOL)debug delegate:(id <ISFSEvents>)delegate;
323 
324 /** Initializes and returns SmartFox2XClient instance.
325 
326  @param debug (BOOL) determines debugging mode.
327  @param delegate (id <ISFSEvents>) delegate object that listens api events.
328 
329  @see initSmartFoxWithDebugMode:delegate:
330  */
331 +(id)smartFoxWithDebugMode:(BOOL)debug delegate:(id <ISFSEvents>)delegate;
332 
333 
334 /** Establish connection with SmartFoxServer 2X.
335 
336  Client will use the settings loaded via loadConfig
337 
338  @exception NSException if host/address or port in the config file is invalid.
339 
340  @see loadConfig:connectOnSuccess:
341  */
342 -(void)connect;
343 
344 /** Establish connection with SmartFoxServer 2X.
345 
346  Client will use the settings loaded via loadConfig if you pass nil value for host or -1 for port.
347 
348  @param host (NSString *) the address of the server to connect to
349  @param port (NSInteger) the TCP port (default port used by SFS2X is 9933)
350 
351  @exception NSException if an invalid host/address or port is passed
352 
353  @see connect
354  @see loadConfig:connectOnSuccess:
355  */
356 -(void)connect:(NSString *)host port:(int)port;
357 
358 /** Establish connection with SmartFoxServer 2X using a defined Configuration Object
359 
360  Client will use the settings loaded via loadConfig if you pass nil value for host or -1 for port.
361 
362  @param cfg (ConfigData *) configuration paramaters (host, port, etc)
363 
364  @exception NSException if an invalid host/address or port is passed
365 
366  <b>Example:</b><br/>
367  The following example shows how to pass a ConfigData object to connect directly with SFS 2X.
368 \code
369  smartFox = [[SmartFox2XClient alloc] initSmartFoxWithDebugMode:YES delegate:self];
370 
371  ConfigData *cfg = [[ConfigData alloc] init];
372  cfg.host = @"127.0.0.1";
373  cfg.port = 9933;
374  cfg.zone = @"BasicExamples";
375  cfg.useBlueBox = YES;
376 
377  // Start connection
378  [smartFox connectWithConfig:cfg];
379 
380  // Handle connection event
381  -(void) onConnection:(SFSEvent *)evt
382  {
383  NSNumber *success = [evt.params objectForKey:@"success"];
384 
385  if (success)
386  {
387  NSLog(@"Connection success");
388  }
389  else
390  {
391  NSLog(@"Connection failure");
392  }
393  }
394 
395 \endcode
396 
397  @see ConfigData
398  */
399 -(void)connectWithConfig:(ConfigData *)cfg;
400 
401 /** Disconnect from SmartFoxServer.
402  */
403 -(void)disconnect;
404 
405 /** Simulate an abrupt disconnection
406 
407  To be used for testing/simulations only.
408  */
409 -(void)killConnection;
410 
411 /** Enable the lag monitor.
412 
413  Toggles the automatic realtime monitoring of the lag between the client and the server (round robin).
414  When turned on, the <em>ISFSEvent.onPingPong</em> event is called every 4 seconds, providing the average of the last ten measured lag values.
415 
416  The Lag Monitor can be activated after the client has successfully logged in the Server.
417  The monitoring is automatically turned off when the user logs out of a Zone or gets disconnected.
418 
419  @param enabled (BOOL) toggles the state of the Lag Monitor
420  */
421 -(void) enableLagMonitor:(BOOL)enabled;
422 
423 /** Enable the lag monitor with custom settings
424 
425  Toggles the automatic realtime monitoring of the lag between the client and the server (round robin) with custom settings.
426 
427  The Lag Monitor can be activated after the client has successfully logged in the Server.
428  The monitoring is automatically turned off when the user logs out of a Zone or gets disconnected.
429 
430  @param enabled (BOOL) toggles the state of the Lag Monitor
431  @param interval (NSInteger) the number of seconds between each roundtrip calls (default = 4)
432  @param qSize (NSInteger) the number of measuerments kept in the local queue upon which the average is calculated (default = 10)
433  */
434 -(void) enableLagMonitorWithInterval:(BOOL)enabled interval:(NSInteger)interval queueSize:(NSInteger)qSize;
435 
436 /** Returns the HTTP URI that can be used to upload files to, using regular HTTP POST.
437  For more details on how to use this functionality see the <a href='http://docs2x.smartfoxserver.com/AdvancedTopics/file-uploads' target='_blank'>Upload File</a> tutorial
438 
439  NOTE: this property will return null if no API configuration has been set or the local User is not already logged in the server.
440  */
441 -(NSString*) httpUploadURI;
442 
443 /** Load a client configuration file.
444 
445  The SmartFox2XClient instance can be configured through an external xml configuration file loaded at run-time.
446  By default, the loadConfig method loads a file named sfs—config.xml, placed in the main bundle of the application.
447  If the connectOnSuccess parameter is set to <b>YES</b>, on loading completion the connect:port: method is automatically called by the API, otherwise the onConfigLoadSuccess event is dispatched.
448  In case of a loading error, the onConfigLoadFailure (ISFSEvents) event is fired.
449 
450  @param filePath (NSString *) external xml configuration file name (optional).
451  @param connectOnSuccess (BOOL) a boolean flag indicating if the connection to SmartFoxServer must be attempted upon configuration loading completion.
452 
453  <b>Usage Note:</b><br/>
454  The external xml configuration file has the following structure; ip, port and zone parameters are mandatory, all other parameters are optional.
455 \code
456  <SmartFoxConfig>
457  <ip>127.0.0.1</ip>
458  <port>9933</port>
459  <udpHost>127.0.0.1</udpHost>
460  <udpPort>9934</udpPort>
461  <zone>BasicExamples</zone>
462  <debug>true</debug>
463  <useBlueBox>true</useBlueBox>
464  <httpPort>8080</httpPort>
465  <blueBoxPollingRate>750</blueBoxPollingRate>
466  </SmartFoxConfig>
467 \endcode
468 
469  <b>Example:</b>
470 \code
471  The following example shows how to load an external configuration file.
472 
473  [smartfox loadConfig:@"sfs-config.xml" connectOnSuccess:NO];
474 
475  -(void)onConfigLoadSuccess:(SFSEvent *)evt
476  {
477  NSLog(@"Config file loaded, now connecting...");
478  [smartFox connect:smartFox.ipAddress, smartFox.port];
479  }
480 
481  -(void)onConfigLoadFailure:(SFSEvent *)evt
482  {
483  NSLog(@"Failed loading config file: %@", [evt.params objectForKey:@"message"]);
484  }
485 \endcode
486 
487  @see [ISFSEvents onConfigLoadSuccess:]
488  @see [ISFSEvents onConfigLoadFailure:]
489 
490  @warning *<b>Important:</b>* The SmartFox2XClient configuration file (client-side) should not be confused with the SmartFoxServer configuration file (server-side).
491  */
492 -(void)loadConfig:(NSString *)filePath connectOnSuccess:(BOOL)connectOnSuccess;
493 
494 -(void)loadConfig;
495 
496 /** Sends a request to the Server.
497 
498  All the available request objects are found in the documentation.
499 
500  @param request (id <IRequest>) a request object.
501 
502  Example:
503  \code
504  [smartFox send:[LoginRequest requestWithUserName:@"" password:@"" zoneName:smartFox.config.zone params:nil]];
505  \endcode
506 
507  */
508 -(void)send:(id <IRequest>)request;
509 
510 /** Finds a Room from its Id or returns nil if no Room with that Id exist in the room list
511 
512  @param roomId (NSInteger) the id of the room.
513 
514  @see roomList
515  @see SFSRoom
516  */
517 -(id <Room>)getRoomById:(NSInteger)roomId;
518 
519 /** Finds a Room from its name or returns nil if no Room with that name exist in the room list
520 
521  @param roomName (NSString *) the name of the room.
522 
523  @see roomList
524  @see SFSRoom
525  */
526 -(id <Room>)getRoomByName:(NSString *)roomName;
527 
528 /** Return the list of Rooms from a specific Room Group
529 
530  @param groupId (NSString *)the name of the Group
531  @return the list of rooms
532  @see SFSRoom
533  */
534 -(NSArray *)getRoomListFromGroup:(NSString *)groupId;
535 
536 /** Initialize the UDP Manager to create a UDP connection. If the host and port parameters are left nil and -1
537 
538  The UDP Manager will use the settings found in the config XML. UDP is only available through an ExtensionRequest.
539 
540  @param udpHost (NSString *) the host (IP) of the SFS Server
541  @param udpPort (NSInteger) the port of the SFS Server to handle UDP
542 
543  \code
544  -(void)onLogin:(SFSEvent *)evt
545  {
546  NSArray *keys = [evt.params allKeys];
547  for (NSString *key in keys)
548  {
549  // do somthing...
550  }
551  //initialize the UDP socket
552  [smartFox initUDP :nil :-1];
553  }
554  \endcode
555 
556  <b>Important:</b>
557  It is recommended to initialize the UDP connection after successful login to a zone.
558  */
559 -(void)initUDP:(NSString *)udpHost :(NSInteger)udpPort;
560 
561 
562 /** Allows to specify custom client details what will be used to gather statistics about the client platform via the Analytics Module. By default no details are sent.
563 
564  This method must be called before the connection is started.
565  The length of the two strings combined must be < 512 characters.
566 
567  @param platformId: (NSString *) The id of the runtime platform: for example "Unity WebPlayer" or "iOS".
568  @param version: (NSString *) An optional version of the runtime platform: for example "2.0.0".
569 
570  Example
571  \code
572  [smartFox setClientDetails:@"MyPlatform" :@"version 001"];
573  \endcode
574 
575 */
576 -(void)setClientDetails:(NSString *)platformId :(NSString *)version;
577 
578 /** Initializes the connection cryptography. Once this process is successfully completed all of the server's data will be encrypted using standard AES 128-bit algorithm, using a secure key served over HTTPS.
579 
580  <b>NOTE:</b> It is necessary to send this request right after a successful connection event, before login.
581 
582  <b>Example:</b><br/>
583  The code below allows to easily toggle the use of encryption for local vs production testing.
584 \code
585  BOOL useEncryption = YES;
586  smartFox = [[SmartFox2XClient alloc] initSmartFoxWithDebugMode:YES delegate:self];
587 
588  ConfigData *cfg = [[ConfigData alloc] init];
589  cfg.host = @"127.0.0.1";
590  cfg.port = 9933;
591  cfg.zone = @"BasicExamples";
592 
593  // Start connection
594  [smartFox connectWithConfig:cfg];
595 
596 
597  -(void) onConnection:(SFSEvent *)evt
598  {
599  NSNumber *success = [evt.params objectForKey:@"success"];
600 
601  if (success)
602  {
603  if (useEncryption)
604  [smartFox initCrypto];
605  else
606  [self sendLogin];
607  }
608  else
609  NSLog(@"Connection failed");
610  }
611 
612  - (void)onCryptoInit:(SFSEvent *)evt
613  {
614  NSNumber* success = [evt.params objectForKey:@"success"];
615 
616  if (success)
617  {
618  NSLog(@"Crypto Init Success!");
619  [self sendLogin];
620  }
621  else
622  NSLog(@"Crypto Init Failure!");
623  }
624 
625 
626  -(void) sendLogin
627  {
628  [smartFox send:[LoginRequest requestWithUserName:@"" password:@"" zoneName:smartFox.config.zone params:nil]];
629  }
630 
631  -(void) onLogin:(SFSEvent *)evt
632  {
633  NSLog("Logged in as: %@", smartFox.mySelf.name];
634  }
635  \endcode
636  */
637 -(void)initCrypto;
638 
639 /** Returns the current run loop mode.
640  Unless specified otherwise NSDefaultRunLoopMode is used by default.
641 
642  To learn more about run loop modes please refer to Apple's official documentation.
643  https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Multithreading/RunLoopManagement/RunLoopManagement.html
644 
645  */
646 -(NSRunLoopMode) getRunLoopMode;
647 
648 /** Allows to choose between two run loop modes
649 
650  The default mode is NSDefaultRunLoopMode. The alternative mode is NSRunLoopCommonModes.
651  The latter can be useful to use in conjunction with UI widgets such as UIViewTable that don't allow event dispatching while scrolling.
652 
653  <b>IMPORTANT<b>: make sure to change the run loop mode only before starting a connection.
654 
655  To learn more about run loop modes please refer to Apple's official documentation.
656  https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Multithreading/RunLoopManagement/RunLoopManagement.html
657 
658  @param mode (NSRunLoopMode) the run loop mode
659 
660  Example:
661  \code
662  _sfs = [[SmartFox2XClient alloc] initSmartFoxWithDebugMode:YES delegate:self];
663 
664  // Switch to different run loop mode
665  [[_sfs getSocketEngine] setRunLoopMode:NSRunLoopCommonModes];
666 
667  // Connection code...
668  \endcode
669 
670  */
671 -(void) setRunLoopMode:(NSRunLoopMode)mode;
672 
673 @end
ConfigData
Definition: ConfigData.h:15
ISFSEvents-p
Definition: ISFSEvents.h:21
SmartFox2XClient
Definition: SmartFox2XClient.h:113
SFSEvent
Definition: SFSEvent.h:65