feat: add GuestUpdatedSubscription
parent
0f906a09c4
commit
021bebc9fb
|
@ -44,7 +44,9 @@ MonoBehaviour:
|
|||
m_Script: {fileID: 11500000, guid: e4d60f91c79e44408084c96be88f2f1a, type: 3}
|
||||
m_Name:
|
||||
m_EditorClassIdentifier:
|
||||
_port: 3000
|
||||
_ip: 192.168.1.122
|
||||
_receivePort: 8000
|
||||
_sendPort: 8001
|
||||
_dataReceived:
|
||||
PassBy: 0
|
||||
OnVision: 0
|
||||
|
@ -53,3 +55,4 @@ MonoBehaviour:
|
|||
Gender: 0
|
||||
AgeMin: 0
|
||||
AgeMax: 0
|
||||
PosPoints: []
|
||||
|
|
|
@ -12,7 +12,7 @@ MonoBehaviour:
|
|||
m_Script: {fileID: 11500000, guid: 1ccf793b7ca1cc645b9cd36d753b8e3c, type: 3}
|
||||
m_Name: Api Reference
|
||||
m_EditorClassIdentifier:
|
||||
url: https://api.play4promo.online/graphql
|
||||
url: http://192.168.1.126:50050/graphql
|
||||
queries: []
|
||||
mutations:
|
||||
- name: LoginAsGameMachine
|
||||
|
@ -195,7 +195,7 @@ MonoBehaviour:
|
|||
isComplete: 1
|
||||
- name: JoinPromotion
|
||||
type: 1
|
||||
query: "mutation JoinPromotion{\n joinPromotion( input :{ promotionId :\"63d879e156403000\"}
|
||||
query: "mutation JoinPromotion{\n joinPromotion( input :{ promotionId :\"63c67c5434403000\"}
|
||||
){\n id\n totalScore\n }\n}"
|
||||
queryString: joinPromotion
|
||||
returnType: Participant
|
||||
|
@ -281,8 +281,8 @@ MonoBehaviour:
|
|||
- name: SubmitGameSession
|
||||
type: 1
|
||||
query: "mutation SubmitGameSession{\n submitGameSession( input :{ playerId
|
||||
:\"63e71a16b6401000\", promotionId :\"63d879e156403000\", startAt :\"2024-05-22T01:27:17.4750128+07:00\",
|
||||
endAt :\"2024-05-22T01:27:29.5938457+07:00\", score :1000} ){\n startAt\n
|
||||
:\"63e7cde8d9c01000\", promotionId :\"63c67c5434403000\", startAt :\"2024-05-22T14:29:49.1804663+07:00\",
|
||||
endAt :\"2024-05-22T14:29:53.1833723+07:00\", score :1000} ){\n startAt\n
|
||||
endAt\n score\n }\n}"
|
||||
queryString: submitGameSession
|
||||
returnType: GameSession
|
||||
|
@ -392,7 +392,7 @@ MonoBehaviour:
|
|||
- name: GuestUpdatedSubscription
|
||||
type: 2
|
||||
query: "subscription GuestUpdatedSubscription{\n guestUpdatedSubscription(
|
||||
input :{ guestId :\"63e71a16b6401000\"} ){\n firstName\n lastName\n
|
||||
guestId :\"63e7cde8d9c01000\" ){\n firstName\n lastName\n
|
||||
phone\n email\n }\n}"
|
||||
queryString: guestUpdatedSubscription
|
||||
returnType: Guest
|
||||
|
|
|
@ -38,7 +38,7 @@ RenderSettings:
|
|||
m_ReflectionIntensity: 1
|
||||
m_CustomReflection: {fileID: 0}
|
||||
m_Sun: {fileID: 0}
|
||||
m_IndirectSpecularColor: {r: 0.37311953, g: 0.38074014, b: 0.3587274, a: 1}
|
||||
m_IndirectSpecularColor: {r: 0.37311918, g: 0.3807398, b: 0.35872716, a: 1}
|
||||
m_UseRadianceAmbientProbe: 0
|
||||
--- !u!157 &3
|
||||
LightmapSettings:
|
||||
|
@ -152,9 +152,9 @@ MonoBehaviour:
|
|||
m_Script: {fileID: 11500000, guid: 0c915a4976334babb372a35c1c2e050c, type: 3}
|
||||
m_Name:
|
||||
m_EditorClassIdentifier:
|
||||
_p4pGraph: {fileID: 11400000, guid: c2740d22f4ae04448a082f5f49761822, type: 2}
|
||||
_graphApi: {fileID: 11400000, guid: c2740d22f4ae04448a082f5f49761822, type: 2}
|
||||
_machineMac: D85ED3741515
|
||||
_promotionId: 63d879e156403000
|
||||
_promotionId: 63c67c5434403000
|
||||
--- !u!4 &398718624
|
||||
Transform:
|
||||
m_ObjectHideFlags: 0
|
||||
|
@ -316,13 +316,41 @@ PrefabInstance:
|
|||
serializedVersion: 3
|
||||
m_TransformParent: {fileID: 0}
|
||||
m_Modifications:
|
||||
- target: {fileID: 843514899178966387, guid: 7a832c1c97ca15e40bad68fa0ddb5007, type: 3}
|
||||
propertyPath: _ip
|
||||
value: 192.168.1.122
|
||||
objectReference: {fileID: 0}
|
||||
- target: {fileID: 5011611157645887697, guid: 7a832c1c97ca15e40bad68fa0ddb5007, type: 3}
|
||||
propertyPath: m_Name
|
||||
value: Upb Socket
|
||||
value: Udp Socket
|
||||
objectReference: {fileID: 0}
|
||||
- target: {fileID: 5011611157645887697, guid: 7a832c1c97ca15e40bad68fa0ddb5007, type: 3}
|
||||
propertyPath: m_IsActive
|
||||
value: 1
|
||||
objectReference: {fileID: 0}
|
||||
- target: {fileID: 7936842462643178004, guid: 7a832c1c97ca15e40bad68fa0ddb5007, type: 3}
|
||||
propertyPath: m_LocalPosition.x
|
||||
value: 0
|
||||
objectReference: {fileID: 0}
|
||||
- target: {fileID: 7936842462643178004, guid: 7a832c1c97ca15e40bad68fa0ddb5007, type: 3}
|
||||
propertyPath: m_LocalPosition.y
|
||||
value: 0
|
||||
objectReference: {fileID: 0}
|
||||
- target: {fileID: 7936842462643178004, guid: 7a832c1c97ca15e40bad68fa0ddb5007, type: 3}
|
||||
propertyPath: m_LocalPosition.z
|
||||
value: 0
|
||||
objectReference: {fileID: 0}
|
||||
- target: {fileID: 7936842462643178004, guid: 7a832c1c97ca15e40bad68fa0ddb5007, type: 3}
|
||||
propertyPath: m_LocalRotation.w
|
||||
value: 1
|
||||
objectReference: {fileID: 0}
|
||||
- target: {fileID: 7936842462643178004, guid: 7a832c1c97ca15e40bad68fa0ddb5007, type: 3}
|
||||
propertyPath: m_LocalRotation.x
|
||||
value: 0
|
||||
objectReference: {fileID: 0}
|
||||
- target: {fileID: 7936842462643178004, guid: 7a832c1c97ca15e40bad68fa0ddb5007, type: 3}
|
||||
propertyPath: m_LocalRotation.y
|
||||
value: 0
|
||||
objectReference: {fileID: 0}
|
||||
- target: {fileID: 7936842462643178004, guid: 7a832c1c97ca15e40bad68fa0ddb5007, type: 3}
|
||||
propertyPath: m_LocalRotation.z
|
||||
value: 0
|
||||
objectReference: {fileID: 0}
|
||||
- target: {fileID: 7936842462643178004, guid: 7a832c1c97ca15e40bad68fa0ddb5007, type: 3}
|
||||
propertyPath: m_LocalEulerAnglesHint.x
|
||||
|
|
|
@ -0,0 +1,42 @@
|
|||
using System;
|
||||
|
||||
namespace GadGame.Network
|
||||
{
|
||||
struct User
|
||||
{
|
||||
public string id;
|
||||
}
|
||||
|
||||
struct LoginDetails
|
||||
{
|
||||
public string accessToken;
|
||||
public string refreshToken;
|
||||
public User user;
|
||||
}
|
||||
|
||||
struct Participant
|
||||
{
|
||||
public string id;
|
||||
public int totalScore;
|
||||
public User player;
|
||||
public int myRanke;
|
||||
}
|
||||
|
||||
struct GameSession
|
||||
{
|
||||
public string id;
|
||||
public DateTime startAt;
|
||||
public DateTime endAt;
|
||||
public int score;
|
||||
public Participant participant;
|
||||
}
|
||||
|
||||
struct Guest
|
||||
{
|
||||
public string id;
|
||||
public string firstName;
|
||||
public string lastName;
|
||||
public string phone;
|
||||
public string email;
|
||||
}
|
||||
}
|
|
@ -0,0 +1,11 @@
|
|||
fileFormatVersion: 2
|
||||
guid: 1e138a913b8d45a2bf28b55225965a34
|
||||
MonoImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
defaultReferences: []
|
||||
executionOrder: 0
|
||||
icon: {instanceID: 0}
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
|
@ -1,4 +1,5 @@
|
|||
using System;
|
||||
using System.Net.WebSockets;
|
||||
using System.Threading.Tasks;
|
||||
using Cysharp.Threading.Tasks;
|
||||
using GadGame.Singleton;
|
||||
|
@ -9,24 +10,28 @@ using Newtonsoft.Json.Linq;
|
|||
using Sirenix.OdinInspector;
|
||||
using UnityEngine;
|
||||
using UnityEngine.Networking;
|
||||
using ZXing;
|
||||
using ZXing.QrCode;
|
||||
|
||||
namespace GadGame.Network
|
||||
{
|
||||
|
||||
class DataReceive
|
||||
struct DataReceive
|
||||
{
|
||||
public JObject[] errors = null;
|
||||
public JObject data = null;
|
||||
public JObject[] errors;
|
||||
public JObject data;
|
||||
}
|
||||
|
||||
public class P4PGraphqlManager : PersistentSingleton<P4PGraphqlManager>
|
||||
{
|
||||
[SerializeField] private GraphApi _p4pGraph;
|
||||
[SerializeField] private GraphApi _graphApi;
|
||||
[SerializeField] private string _machineMac;
|
||||
[SerializeField] private string _promotionId;
|
||||
|
||||
private DateTime _startTime;
|
||||
[ShowInInspector, HideInEditorMode] private string _userId;
|
||||
private string _userId;
|
||||
private string _userAccessToken;
|
||||
private string _machineAccessToken;
|
||||
|
||||
public Action<OnSubscriptionDataReceived> OnGuestUpdatedSubscription;
|
||||
|
||||
|
@ -53,6 +58,7 @@ namespace GadGame.Network
|
|||
|
||||
private void OnGuestUpdated(OnSubscriptionDataReceived dataReceived)
|
||||
{
|
||||
Debug.Log(dataReceived.data);
|
||||
OnGuestUpdatedSubscription?.Invoke(dataReceived);
|
||||
}
|
||||
|
||||
|
@ -64,7 +70,7 @@ namespace GadGame.Network
|
|||
|
||||
private async Task<bool> LoginMachine()
|
||||
{
|
||||
var query = _p4pGraph.GetQueryByName("LoginAsGameMachine", GraphApi.Query.Type.Mutation);
|
||||
var query = _graphApi.GetQueryByName("LoginAsGameMachine", GraphApi.Query.Type.Mutation);
|
||||
query.SetArgs(new
|
||||
{
|
||||
input = new
|
||||
|
@ -73,13 +79,14 @@ namespace GadGame.Network
|
|||
password = "Abc@123"
|
||||
}
|
||||
});
|
||||
var request = await _p4pGraph.Post(query);
|
||||
Debug.Log("LoginAsGameMachine " + request.result);
|
||||
var request = await _graphApi.Post(query);
|
||||
if (request.result == UnityWebRequest.Result.Success)
|
||||
{
|
||||
var receive = GetData(request.downloadHandler.text);
|
||||
if (receive.errors != null)
|
||||
if (receive.data != null)
|
||||
{
|
||||
var loginDetail = receive.data["loginAsGameMachine"]!.ToObject<LoginDetails>();
|
||||
_machineAccessToken = loginDetail.accessToken;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
@ -89,7 +96,7 @@ namespace GadGame.Network
|
|||
|
||||
public async Task<bool> CreateGuest()
|
||||
{
|
||||
var query = _p4pGraph.GetQueryByName("CreateGuest", GraphApi.Query.Type.Mutation);
|
||||
var query = _graphApi.GetQueryByName("CreateGuest", GraphApi.Query.Type.Mutation);
|
||||
query.SetArgs(new
|
||||
{
|
||||
input = new
|
||||
|
@ -97,16 +104,15 @@ namespace GadGame.Network
|
|||
password = "Abc@123"
|
||||
}
|
||||
});
|
||||
var request = await _p4pGraph.Post(query);
|
||||
Debug.Log("CreateGuest " + request.result);
|
||||
var request = await _graphApi.Post(query);
|
||||
if (request.result == UnityWebRequest.Result.Success)
|
||||
{
|
||||
var receive = GetData(request.downloadHandler.text);
|
||||
if (receive.data != null)
|
||||
{
|
||||
var guest = receive.data["createGuest"];
|
||||
_p4pGraph.SetAuthToken(guest?["accessToken"]?.ToString());
|
||||
_userId = guest?["user"]?["id"]?.ToString();
|
||||
var loginDetails = receive.data["createGuest"]!.ToObject<LoginDetails>();
|
||||
_userId = loginDetails.user.id;
|
||||
_userAccessToken = loginDetails.accessToken;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
@ -116,7 +122,7 @@ namespace GadGame.Network
|
|||
|
||||
public async Task<bool> JoinPromotion()
|
||||
{
|
||||
var query = _p4pGraph.GetQueryByName("JoinPromotion", GraphApi.Query.Type.Mutation);
|
||||
var query = _graphApi.GetQueryByName("JoinPromotion", GraphApi.Query.Type.Mutation);
|
||||
query.SetArgs(new
|
||||
{
|
||||
input = new
|
||||
|
@ -124,8 +130,9 @@ namespace GadGame.Network
|
|||
promotionId = _promotionId
|
||||
}
|
||||
});
|
||||
var request = await _p4pGraph.Post(query);
|
||||
Debug.Log("JoinPromotion " + request.result);
|
||||
|
||||
_graphApi.SetAuthToken(_userAccessToken);
|
||||
var request = await _graphApi.Post(query);
|
||||
if (request.result == UnityWebRequest.Result.Success)
|
||||
{
|
||||
var receive = GetData(request.downloadHandler.text);
|
||||
|
@ -142,7 +149,7 @@ namespace GadGame.Network
|
|||
public async Task<bool> SubmitGameSession(int gameScore)
|
||||
{
|
||||
var endTime = DateTime.Now.AddSeconds(-1);
|
||||
var query = _p4pGraph.GetQueryByName("SubmitGameSession", GraphApi.Query.Type.Mutation);
|
||||
var query = _graphApi.GetQueryByName("SubmitGameSession", GraphApi.Query.Type.Mutation);
|
||||
query.SetArgs(new
|
||||
{
|
||||
input = new
|
||||
|
@ -154,8 +161,9 @@ namespace GadGame.Network
|
|||
score = gameScore,
|
||||
}
|
||||
});
|
||||
var request = await _p4pGraph.Post(query);
|
||||
Debug.Log("Submit Game Session " + request.result);
|
||||
|
||||
_graphApi.SetAuthToken(_userAccessToken);
|
||||
var request = await _graphApi.Post(query);
|
||||
if (request.result == UnityWebRequest.Result.Success)
|
||||
{
|
||||
var receive = GetData(request.downloadHandler.text);
|
||||
|
@ -173,17 +181,54 @@ namespace GadGame.Network
|
|||
await GuestUpdatedSubscription();
|
||||
}
|
||||
|
||||
private async Task GuestUpdatedSubscription()
|
||||
private async Task<Texture2D> GuestUpdatedSubscription()
|
||||
{
|
||||
var query = _p4pGraph.GetQueryByName("GuestUpdatedSubscription", GraphApi.Query.Type.Subscription);
|
||||
var query = _graphApi.GetQueryByName("GuestUpdatedSubscription", GraphApi.Query.Type.Subscription);
|
||||
query.SetArgs(new
|
||||
{
|
||||
input = new
|
||||
{
|
||||
guestId = _userId,
|
||||
}
|
||||
guestId = _userId,
|
||||
});
|
||||
await _p4pGraph.Subscribe(query);
|
||||
_graphApi.SetAuthToken(_machineAccessToken);
|
||||
var socket = await _graphApi.Subscribe(query);
|
||||
if (socket.State == WebSocketState.Open)
|
||||
{
|
||||
var link = $"https://play4promo.online/brands/{_promotionId}/scan-qr?token={_userAccessToken}";
|
||||
Debug.Log(link);
|
||||
return EncodeTextToQrCode(link);
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private Color32 [] Encode(string textForEncoding, int width, int height)
|
||||
{
|
||||
BarcodeWriter writer = new BarcodeWriter
|
||||
{
|
||||
Format = BarcodeFormat.QR_CODE,
|
||||
Options = new QrCodeEncodingOptions
|
||||
{
|
||||
Height = height,
|
||||
Width = width
|
||||
}
|
||||
};
|
||||
return writer.Write(textForEncoding);
|
||||
}
|
||||
|
||||
|
||||
private Texture2D EncodeTextToQrCode(string input, int width = 256, int height = 256)
|
||||
{
|
||||
if (String.IsNullOrWhiteSpace(input))
|
||||
{
|
||||
Debug.Log("You should write something");
|
||||
return null;
|
||||
}
|
||||
|
||||
var texture = new Texture2D(width, height);
|
||||
Color32 [] convertPixelToTexture = Encode(input, texture.width, texture.height);
|
||||
texture.SetPixels32(convertPixelToTexture);
|
||||
texture.Apply();
|
||||
|
||||
return texture;
|
||||
}
|
||||
}
|
||||
}
|
Binary file not shown.
|
@ -0,0 +1,33 @@
|
|||
fileFormatVersion: 2
|
||||
guid: c2434ceca8dfed74e9e676449d86a863
|
||||
PluginImporter:
|
||||
externalObjects: {}
|
||||
serializedVersion: 2
|
||||
iconMap: {}
|
||||
executionOrder: {}
|
||||
defineConstraints: []
|
||||
isPreloaded: 0
|
||||
isOverridable: 0
|
||||
isExplicitlyReferenced: 0
|
||||
validateReferences: 1
|
||||
platformData:
|
||||
- first:
|
||||
Any:
|
||||
second:
|
||||
enabled: 1
|
||||
settings: {}
|
||||
- first:
|
||||
Editor: Editor
|
||||
second:
|
||||
enabled: 0
|
||||
settings:
|
||||
DefaultValueInitialized: true
|
||||
- first:
|
||||
Windows Store Apps: WindowsStoreApps
|
||||
second:
|
||||
enabled: 0
|
||||
settings:
|
||||
CPU: AnyCPU
|
||||
userData:
|
||||
assetBundleName:
|
||||
assetBundleVariant:
|
|
@ -75,13 +75,13 @@ namespace GraphQlClient.Core
|
|||
return await Post(query);
|
||||
}
|
||||
|
||||
public async Task<ClientWebSocket> Subscribe(Query query, string socketId = "1", string protocol = "graphql-ws"){
|
||||
public async Task<ClientWebSocket> Subscribe(Query query, string socketId = "1", string protocol = "graphql-transport-ws"){
|
||||
if (String.IsNullOrEmpty(query.query))
|
||||
query.CompleteQuery();
|
||||
return await HttpHandler.WebsocketConnect(url, query.query, authToken, socketId, protocol);
|
||||
}
|
||||
|
||||
public async Task<ClientWebSocket> Subscribe(string queryName, Query.Type type, string socketId = "1", string protocol = "graphql-ws"){
|
||||
public async Task<ClientWebSocket> Subscribe(string queryName, Query.Type type, string socketId = "1", string protocol = "graphql-transport-ws"){
|
||||
Query query = GetQueryByName(queryName, type);
|
||||
return await Subscribe(query, socketId, protocol);
|
||||
}
|
||||
|
|
|
@ -14,14 +14,20 @@ namespace GraphQlClient.Core
|
|||
{
|
||||
public class HttpHandler
|
||||
{
|
||||
|
||||
|
||||
public static async Task<UnityWebRequest> PostAsync(string url, string details, string authToken = null){
|
||||
string jsonData = JsonConvert.SerializeObject(new{query = details});
|
||||
byte[] postData = Encoding.ASCII.GetBytes(jsonData);
|
||||
UnityWebRequest request = UnityWebRequest.PostWwwForm(url, UnityWebRequest.kHttpVerbPOST);
|
||||
request.uploadHandler = new UploadHandlerRaw(postData);
|
||||
byte[] postData = Encoding.UTF8.GetBytes(jsonData);
|
||||
var uri = new Uri(url);
|
||||
UnityWebRequest request = new UnityWebRequest(uri, "POST")
|
||||
{
|
||||
uploadHandler = new UploadHandlerRaw(postData),
|
||||
downloadHandler = new DownloadHandlerBuffer(),
|
||||
disposeCertificateHandlerOnDispose = true,
|
||||
disposeDownloadHandlerOnDispose = true,
|
||||
disposeUploadHandlerOnDispose = true
|
||||
};
|
||||
request.SetRequestHeader("Content-Type", "application/json");
|
||||
request.SetRequestHeader("Accept-Encoding", "gzip, deflate");
|
||||
if (!String.IsNullOrEmpty(authToken))
|
||||
request.SetRequestHeader("Authorization", "Bearer " + authToken);
|
||||
|
||||
|
@ -29,10 +35,14 @@ namespace GraphQlClient.Core
|
|||
requestBegin.FireEvent();
|
||||
|
||||
try{
|
||||
await request.SendWebRequest();
|
||||
request.SendWebRequest();
|
||||
while (!request.isDone)
|
||||
{
|
||||
await Task.Yield();
|
||||
}
|
||||
}
|
||||
catch(Exception e){
|
||||
Debug.Log("Testing exceptions");
|
||||
Debug.Log(e);
|
||||
OnRequestEnded requestFailed = new OnRequestEnded(e);
|
||||
requestFailed.FireEvent();
|
||||
}
|
||||
|
@ -43,30 +53,8 @@ namespace GraphQlClient.Core
|
|||
return request;
|
||||
}
|
||||
|
||||
public static async Task<UnityWebRequest> PostAsync(UnityWebRequest request, string details){
|
||||
string jsonData = JsonConvert.SerializeObject(new{query = details});
|
||||
byte[] postData = Encoding.ASCII.GetBytes(jsonData);
|
||||
request.uploadHandler = new UploadHandlerRaw(postData);
|
||||
OnRequestBegin requestBegin = new OnRequestBegin();
|
||||
requestBegin.FireEvent();
|
||||
|
||||
try{
|
||||
await request.SendWebRequest();
|
||||
}
|
||||
catch(Exception e){
|
||||
Debug.Log("Testing exceptions");
|
||||
OnRequestEnded requestFailed = new OnRequestEnded(e);
|
||||
requestFailed.FireEvent();
|
||||
}
|
||||
Debug.Log(request.downloadHandler.text);
|
||||
|
||||
OnRequestEnded requestSucceeded = new OnRequestEnded(request.downloadHandler.text);
|
||||
requestSucceeded.FireEvent();
|
||||
return request;
|
||||
}
|
||||
|
||||
|
||||
public static async Task<UnityWebRequest> GetAsync(string url, string authToken = null){
|
||||
public static async Task<UnityWebRequest> GetAsync(string url, string authToken = null){
|
||||
UnityWebRequest request = UnityWebRequest.Get(url);
|
||||
if (!String.IsNullOrEmpty(authToken))
|
||||
request.SetRequestHeader("Authorization", "Bearer " + authToken);
|
||||
|
@ -89,20 +77,17 @@ namespace GraphQlClient.Core
|
|||
#region Websocket
|
||||
|
||||
//Use this to subscribe to a graphql endpoint
|
||||
public static async Task<ClientWebSocket> WebsocketConnect(string subscriptionUrl, string details, string authToken = null, string socketId = "1", string protocol = "graphql-ws"){
|
||||
public static async Task<ClientWebSocket> WebsocketConnect(string subscriptionUrl, string details, string authToken = null, string socketId = "1", string protocol = "graphql-transport-ws"){
|
||||
string subUrl = subscriptionUrl.Replace("http", "ws");
|
||||
string id = socketId;
|
||||
ClientWebSocket cws = new ClientWebSocket();
|
||||
cws.Options.AddSubProtocol(protocol);
|
||||
if (!String.IsNullOrEmpty(authToken))
|
||||
cws.Options.SetRequestHeader("Authorization", "Bearer " + authToken);
|
||||
Uri u = new Uri(subUrl);
|
||||
Uri uri = new Uri(subUrl);
|
||||
try{
|
||||
await cws.ConnectAsync(u, CancellationToken.None);
|
||||
if (cws.State == WebSocketState.Open)
|
||||
Debug.Log("connected");
|
||||
await WebsocketInit(cws);
|
||||
await WebsocketSend(cws, id, details);
|
||||
Debug.Log("Websocket is connecting");
|
||||
await cws.ConnectAsync(uri, CancellationToken.None);
|
||||
await WebsocketInit(cws, id, authToken);
|
||||
await WebsocketSubscribe(cws, id, details);
|
||||
}
|
||||
catch (Exception e){
|
||||
Debug.Log("woe " + e.Message);
|
||||
|
@ -111,96 +96,119 @@ namespace GraphQlClient.Core
|
|||
return cws;
|
||||
}
|
||||
|
||||
public static async Task<ClientWebSocket> WebsocketConnect(ClientWebSocket cws, string subscriptionUrl, string details, string socketId = "1"){
|
||||
string subUrl = subscriptionUrl.Replace("http", "ws");
|
||||
string id = socketId;
|
||||
Uri u = new Uri(subUrl);
|
||||
try{
|
||||
await cws.ConnectAsync(u, CancellationToken.None);
|
||||
if (cws.State == WebSocketState.Open)
|
||||
Debug.Log("connected");
|
||||
await WebsocketInit(cws);
|
||||
await WebsocketSend(cws, id, details);
|
||||
}
|
||||
catch (Exception e){
|
||||
Debug.Log("woe " + e.Message);
|
||||
}
|
||||
|
||||
return cws;
|
||||
}
|
||||
static async Task WebsocketInit(ClientWebSocket cws, string id, string authToken){
|
||||
string jsonData = JsonConvert.SerializeObject(new
|
||||
{
|
||||
id,
|
||||
type = "connection_init",
|
||||
payload = new
|
||||
{
|
||||
authorization = "Bearer "+ authToken
|
||||
}
|
||||
|
||||
static async Task WebsocketInit(ClientWebSocket cws){
|
||||
string jsonData = "{\"type\":\"connection_init\"}";
|
||||
ArraySegment<byte> b = new ArraySegment<byte>(Encoding.ASCII.GetBytes(jsonData));
|
||||
}, Formatting.None);
|
||||
Debug.Log("Websocket is starting");
|
||||
ArraySegment<byte> b = new ArraySegment<byte>(Encoding.UTF8.GetBytes(jsonData));
|
||||
await cws.SendAsync(b, WebSocketMessageType.Text, true, CancellationToken.None);
|
||||
GetWsReturn(cws);
|
||||
Debug.Log("Websocket is updating");
|
||||
WebSocketUpdate(cws);
|
||||
}
|
||||
|
||||
static async Task WebsocketSend(ClientWebSocket cws, string id, string details){
|
||||
string jsonData = JsonConvert.SerializeObject(new {id = $"{id}", type = "start", payload = new{query = details}});
|
||||
ArraySegment<byte> b = new ArraySegment<byte>(Encoding.ASCII.GetBytes(jsonData));
|
||||
static async Task WebsocketSubscribe(ClientWebSocket cws, string id, string details){
|
||||
string jsonData = JsonConvert.SerializeObject(new
|
||||
{
|
||||
id,
|
||||
type = "subscribe",
|
||||
payload = new
|
||||
{
|
||||
query = details
|
||||
}
|
||||
}, Formatting.None);
|
||||
ArraySegment<byte> b = new ArraySegment<byte>(Encoding.UTF8.GetBytes(jsonData));
|
||||
await cws.SendAsync(b, WebSocketMessageType.Text, true, CancellationToken.None);
|
||||
}
|
||||
|
||||
//Call GetWsReturn to wait for a message from a websocket. GetWsReturn has to be called for each message
|
||||
static async void GetWsReturn(ClientWebSocket cws){
|
||||
ArraySegment<byte> buf = new ArraySegment<byte>(new byte[1024]);
|
||||
buf = WebSocket.CreateClientBuffer(1024, 1024);
|
||||
WebSocketReceiveResult r;
|
||||
string result = "";
|
||||
do{
|
||||
r = await cws.ReceiveAsync(buf, CancellationToken.None);
|
||||
result += Encoding.UTF8.GetString(buf.Array ?? throw new ApplicationException("Buf = null"), buf.Offset,
|
||||
r.Count);
|
||||
} while (!r.EndOfMessage);
|
||||
|
||||
if (String.IsNullOrEmpty(result))
|
||||
return;
|
||||
JObject obj = new JObject();
|
||||
try{
|
||||
obj = JObject.Parse(result);
|
||||
}
|
||||
catch (JsonReaderException e){
|
||||
throw new ApplicationException(e.Message);
|
||||
}
|
||||
|
||||
string subType = (string) obj["type"];
|
||||
switch (subType){
|
||||
case "connection_ack":
|
||||
static async void WebSocketUpdate(ClientWebSocket cws){
|
||||
while (true)
|
||||
{
|
||||
if (!(cws.State == WebSocketState.Connecting || cws.State == WebSocketState.Open))
|
||||
{
|
||||
Debug.Log("init_success, the handshake is complete");
|
||||
OnSubscriptionHandshakeComplete subscriptionHandshakeComplete =
|
||||
new OnSubscriptionHandshakeComplete();
|
||||
subscriptionHandshakeComplete.FireEvent();
|
||||
GetWsReturn(cws);
|
||||
Debug.Log("websocket was closed, stop the loop");
|
||||
break;
|
||||
}
|
||||
case "error":
|
||||
|
||||
ArraySegment<byte> buf = WebSocket.CreateClientBuffer(1024, 1024);
|
||||
if (buf.Array == null)
|
||||
{
|
||||
throw new ApplicationException("The handshake failed. Error: " + result);
|
||||
throw new WebSocketException("Buffer array is null!");
|
||||
}
|
||||
case "connection_error":
|
||||
{
|
||||
throw new ApplicationException("The handshake failed. Error: " + result);
|
||||
WebSocketReceiveResult r;
|
||||
var jsonBuild = new StringBuilder();
|
||||
do{
|
||||
r = await cws.ReceiveAsync(buf, CancellationToken.None);
|
||||
jsonBuild.Append(Encoding.UTF8.GetString(buf.Array, buf.Offset, r.Count));
|
||||
} while (!r.EndOfMessage);
|
||||
var jsonResult = jsonBuild.ToString();
|
||||
if (String.IsNullOrEmpty(jsonResult)) return;
|
||||
JObject jsonObj = new JObject();
|
||||
try{
|
||||
jsonObj = JObject.Parse(jsonResult);
|
||||
}
|
||||
case "data":
|
||||
{
|
||||
OnSubscriptionDataReceived subscriptionDataReceived = new OnSubscriptionDataReceived(result);
|
||||
subscriptionDataReceived.FireEvent();
|
||||
GetWsReturn(cws);
|
||||
break;
|
||||
}
|
||||
case "ka":
|
||||
{
|
||||
GetWsReturn(cws);
|
||||
break;
|
||||
}
|
||||
case "subscription_fail":
|
||||
{
|
||||
throw new ApplicationException("The subscription data failed");
|
||||
catch (JsonReaderException e){
|
||||
throw new ApplicationException(e.Message);
|
||||
}
|
||||
|
||||
string subType = (string) jsonObj["type"];
|
||||
switch (subType){
|
||||
case "connection_ack":
|
||||
{
|
||||
Debug.Log("init_success, the handshake is complete");
|
||||
OnSubscriptionHandshakeComplete subscriptionHandshakeComplete =
|
||||
new OnSubscriptionHandshakeComplete();
|
||||
subscriptionHandshakeComplete.FireEvent();
|
||||
continue;
|
||||
}
|
||||
case "error":
|
||||
{
|
||||
throw new ApplicationException("The handshake failed. Error: " + jsonResult);
|
||||
}
|
||||
case "connection_error":
|
||||
{
|
||||
throw new ApplicationException("The handshake failed. Error: " + jsonResult);
|
||||
}
|
||||
case "next":
|
||||
{
|
||||
OnSubscriptionDataReceived subscriptionDataReceived = new OnSubscriptionDataReceived(jsonResult);
|
||||
subscriptionDataReceived.FireEvent();
|
||||
continue;
|
||||
}
|
||||
case "ka":
|
||||
{
|
||||
continue;
|
||||
}
|
||||
case "subscription_fail":
|
||||
{
|
||||
throw new ApplicationException("The subscription data failed");
|
||||
}
|
||||
case "ping":
|
||||
{
|
||||
await cws.SendAsync(
|
||||
new ArraySegment<byte>(Encoding.UTF8.GetBytes($@"{{""type"":""pong""}}")),
|
||||
WebSocketMessageType.Text,
|
||||
true,
|
||||
CancellationToken.None
|
||||
);
|
||||
continue;
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
break;
|
||||
}
|
||||
|
||||
|
||||
}
|
||||
|
||||
public static async Task WebsocketDisconnect(ClientWebSocket cws, string socketId = "1"){
|
||||
|
|
|
@ -869,4 +869,4 @@ PlayerSettings:
|
|||
hmiLoadingImage: {fileID: 0}
|
||||
platformRequiresReadableAssets: 0
|
||||
virtualTexturingSupportEnabled: 0
|
||||
insecureHttpOption: 0
|
||||
insecureHttpOption: 2
|
||||
|
|
|
@ -0,0 +1,16 @@
|
|||
%YAML 1.1
|
||||
%TAG !u! tag:unity3d.com,2011:
|
||||
--- !u!114 &1
|
||||
MonoBehaviour:
|
||||
m_ObjectHideFlags: 53
|
||||
m_CorrespondingSourceObject: {fileID: 0}
|
||||
m_PrefabInstance: {fileID: 0}
|
||||
m_PrefabAsset: {fileID: 0}
|
||||
m_GameObject: {fileID: 0}
|
||||
m_Enabled: 1
|
||||
m_EditorHideFlags: 0
|
||||
m_Script: {fileID: 11500000, guid: a287be6c49135cd4f9b2b8666c39d999, type: 3}
|
||||
m_Name:
|
||||
m_EditorClassIdentifier:
|
||||
assetDefaultFramerate: 60
|
||||
m_DefaultFrameRate: 60
|
Loading…
Reference in New Issue