/
ScreenTimeTracker.cs
239 lines (201 loc) · 8.15 KB
/
ScreenTimeTracker.cs
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
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
#if !DISABLE_PLAYFABENTITY_API && !DISABLE_PLAYFABCLIENT_API
using System;
using System.Collections.Generic;
using UnityEngine;
namespace PlayFab.Public
{
/// <summary>
/// Interface which can be used to implement class responsible for gathering and sending information about session.
/// </summary>
public interface IScreenTimeTracker
{
// Unity MonoBehaviour callbacks
void OnEnable();
void OnDisable();
void OnDestroy();
void OnApplicationQuit();
void OnApplicationFocus(bool isFocused);
// Class specific methods
void ClientSessionStart(string entityId, string entityType, string playFabUserId);
void Send();
}
/// <summary>
/// Class responsible for gathering and sending information about session, for example: focus duration, device info, etc.
/// </summary>
public class ScreenTimeTracker : IScreenTimeTracker
{
private Guid focusId;
private Guid gameSessionID;
private bool initialFocus = true;
private bool isSending = false;
private DateTime focusOffDateTime = DateTime.UtcNow;
private DateTime focusOnDateTime = DateTime.UtcNow;
private Queue<EventsModels.EventContents> eventsRequests = new Queue<EventsModels.EventContents>();
private EventsModels.EntityKey entityKey = new EventsModels.EntityKey();
private const String eventNamespace = "com.playfab.events.sessions";
private const int maxBatchSizeInEvents = 10;
/// <summary>
/// Start session, the function responsible for creating SessionID and gathering information about user and device
/// </summary>
/// <param name="playFabUserId">Result of the user's login, represent user ID</param>
public void ClientSessionStart(string entityId, string entityType, string playFabUserId)
{
gameSessionID = Guid.NewGuid();
entityKey.Id = entityId;
entityKey.Type = entityType;
EventsModels.EventContents eventInfo = new EventsModels.EventContents();
eventInfo.Name = "client_session_start";
eventInfo.EventNamespace = eventNamespace;
eventInfo.Entity = entityKey;
eventInfo.OriginalTimestamp = DateTime.UtcNow;
var payload = new Dictionary<string, object>
{
{ "UserID", playFabUserId},
{ "DeviceType", SystemInfo.deviceType},
{ "DeviceModel", SystemInfo.deviceModel},
{ "OS", SystemInfo.operatingSystem },
{ "ClientSessionID", gameSessionID },
};
eventInfo.Payload = payload;
eventsRequests.Enqueue(eventInfo);
// Fake a focus-on event at the time of the first login:
OnApplicationFocus(true);
}
/// <summary>
/// Gather information about user's focus. Calculates interaction durations.
/// Name mimics MonoBehaviour method, for ease of integration.
/// </summary>
/// <param name="isFocused">State of focus</param>
public void OnApplicationFocus(bool isFocused)
{
EventsModels.EventContents eventInfo = new EventsModels.EventContents();
DateTime currentUtcDateTime = DateTime.UtcNow;
eventInfo.Name = "client_focus_change";
eventInfo.EventNamespace = eventNamespace;
eventInfo.Entity = entityKey;
double focusStateDuration = 0.0;
if (initialFocus)
{
focusId = Guid.NewGuid();
}
if (isFocused)
{
// start counting focus-on time
focusOnDateTime = currentUtcDateTime;
// new id per focus
focusId = Guid.NewGuid();
if (!initialFocus)
{
focusStateDuration = (currentUtcDateTime - focusOffDateTime).TotalSeconds;
// this check safeguards from manual time changes while app is running
if (focusStateDuration < 0)
{
focusStateDuration = 0;
}
}
}
else
{
focusStateDuration = (currentUtcDateTime - focusOnDateTime).TotalSeconds;
// this check safeguards from manual time changes while app is running
if (focusStateDuration < 0)
{
focusStateDuration = 0;
}
// start counting focus-off time
focusOffDateTime = currentUtcDateTime;
}
var payload = new Dictionary<string, object> {
{ "FocusID", focusId },
{ "FocusState", isFocused },
{ "FocusStateDuration", focusStateDuration },
{ "EventTimestamp", currentUtcDateTime },
{ "ClientSessionID", gameSessionID },
};
eventInfo.OriginalTimestamp = currentUtcDateTime;
eventInfo.Payload = payload;
eventsRequests.Enqueue(eventInfo);
initialFocus = false;
if (!isFocused)
{
// Force the eventsRequests queue to empty.
// If we are losing focus we should make an attempt to push out a focus lost event ASAP
Send();
}
}
/// <summary>
/// Sends events to server.
/// </summary>
public void Send()
{
if ((PlayFabClientAPI.IsClientLoggedIn()) && (isSending == false))
{
isSending = true;
EventsModels.WriteEventsRequest request = new EventsModels.WriteEventsRequest();
request.Events = new List<EventsModels.EventContents>();
while ((eventsRequests.Count > 0) && (request.Events.Count < maxBatchSizeInEvents))
{
EventsModels.EventContents eventInfo = eventsRequests.Dequeue();
request.Events.Add(eventInfo);
}
if (request.Events.Count > 0)
{
PlayFabEventsAPI.WriteEvents(request, EventSentSuccessfulCallback, EventSentErrorCallback);
}
isSending = false;
}
}
/// <summary>
/// Callback to handle successful server interaction.
/// </summary>
/// <param name="response">Server response</param>
private void EventSentSuccessfulCallback(EventsModels.WriteEventsResponse response)
{
// add code to work with successful callback
}
/// <summary>
/// Callback to handle unsuccessful server interaction.
/// </summary>
/// <param name="response">Server response</param>
private void EventSentErrorCallback(PlayFabError response)
{
Debug.LogWarning("Failed to send session data. Error: " + response.GenerateErrorReport());
}
#region Unused MonoBehaviour compatibility methods
/// <summary>
/// Unused
/// Name mimics MonoBehaviour method, for ease of integration.
/// </summary>
public void OnEnable()
{
// add code sending events on enable
}
/// <summary>
/// Unused
/// Name mimics MonoBehaviour method, for ease of integration.
/// </summary>
public void OnDisable()
{
// add code sending events on disable
}
/// <summary>
/// Unused
/// Name mimics MonoBehaviour method, for ease of integration.
/// </summary>
public void OnDestroy()
{
// add code sending events on destroy
}
#endregion
/// <summary>
/// Trying to send event during game exit. Note: works only on certain platforms.
/// Name mimics MonoBehaviour method, for ease of integration.
/// </summary>
public void OnApplicationQuit()
{
// trying to send events during game exit
Send();
}
}
}
#endif