This repository has been archived by the owner on Jul 30, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
MultiAccountManager.cs
460 lines (401 loc) · 19.7 KB
/
MultiAccountManager.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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
using Microsoft.EntityFrameworkCore.ChangeTracking;
using PoGo.NecroBot.Logic.Exceptions;
using PoGo.NecroBot.Logic.Forms;
using PoGo.NecroBot.Logic.Logging;
using PoGo.NecroBot.Logic.Model;
using PoGo.NecroBot.Logic.Model.Settings;
using PoGo.NecroBot.Logic.State;
using PoGo.NecroBot.Logic.Tasks;
using PoGo.NecroBot.Logic.Utils;
using PokemonGo.RocketAPI;
using PokemonGo.RocketAPI.Enums;
using PokemonGo.RocketAPI.Extensions;
using PokemonGo.RocketAPI.Util;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using TinyIoC;
namespace PoGo.NecroBot.Logic
{
public class MultiAccountManager
{
private AccountConfigContext _context = new AccountConfigContext();
private const string ACCOUNT_DB_NAME = "accounts.db";
public object Settings { get; private set; }
private GlobalSettings _globalSettings { get; set; }
Client Client { get; set; }
Account account { get; set; }
public MultiAccountManager(GlobalSettings globalSettings, List<AuthConfig> accounts)
{
_globalSettings = globalSettings;
MigrateDatabase();
SyncDatabase(accounts);
}
public MultiAccountManager()
{
}
private LocalView<Account> _localAccounts;
public LocalView<Account> Accounts
{
get
{
if (_localAccounts != null)
return _localAccounts;
if (_context.Account.Count() > 0)
{
foreach (var item in _context.Account.OrderBy(p => p.Id))
{
item.IsRunning = 0;
item.LastRuntimeUpdatedAt = null;
}
_context.SaveChanges();
}
_localAccounts = _context.Account.Local;
return _localAccounts;
}
}
public AccountConfigContext GetDbContext()
{
return _context;
}
public List<Account> AccountsReadOnly
{
get
{
return _context.Account.ToList();
}
}
public Account GetCurrentAccount()
{
var session = TinyIoCContainer.Current.Resolve<ISession>();
return _context.Account.FirstOrDefault(a => session.Settings.Username == a.Username && session.Settings.AuthType == a.AuthType);
}
public void SwitchAccounts(Account newAccount)
{
if (newAccount == null)
return;
var runningAccount = GetCurrentAccount();
if (runningAccount != null)
{
runningAccount.IsRunning = 0;
if (runningAccount.LastRuntimeUpdatedAt.HasValue)
{
runningAccount.RuntimeTotal = (int)runningAccount.RuntimeTotal; //+= (now - TimeUtil.GetDateTimeFromMilliseconds(runningAccount.LastRuntimeUpdatedAt.Value)).TotalMinutes;
runningAccount.LastRuntimeUpdatedAt = DateTime.Now.ToUnixTime();
}
UpdateLocalAccount(runningAccount);
}
newAccount.IsRunning = 1;
newAccount.LoggedTime = DateTime.Now.ToUnixTime();
newAccount.LastRuntimeUpdatedAt = newAccount.LoggedTime;
UpdateLocalAccount(newAccount);
// Update current auth config with new account.
_globalSettings.Auth.CurrentAuthConfig.AuthType = (AuthType)newAccount.AuthType;
_globalSettings.Auth.CurrentAuthConfig.Username = newAccount.Username;
_globalSettings.Auth.CurrentAuthConfig.Password = newAccount.Password;
_globalSettings.Auth.CurrentAuthConfig.AutoExitBotIfAccountFlagged = newAccount.AutoExitBotIfAccountFlagged;
_globalSettings.Auth.CurrentAuthConfig.AccountLatitude = newAccount.AccountLatitude;
_globalSettings.Auth.CurrentAuthConfig.AccountLongitude = newAccount.AccountLongitude;
_globalSettings.Auth.CurrentAuthConfig.AccountActive = newAccount.AccountActive;
_globalSettings.Auth.CurrentAuthConfig.RunStart = newAccount.RunStart;
_globalSettings.Auth.CurrentAuthConfig.RunEnd = newAccount.RunEnd;
string body = "";
foreach (var item in Accounts)
{
body = body + $"{item.Username} - {item.GetRuntime()}\r\n";
}
}
public void BlockCurrentBot(int expired = 60)
{
var currentAccount = GetCurrentAccount();
if (currentAccount != null)
{
currentAccount.ReleaseBlockTime = DateTime.Now.AddMinutes(expired).ToUnixTime();
UpdateLocalAccount(currentAccount);
}
}
private void LoadDataFromDB()
{
if (_context.Account.Count() > 0)
{
foreach (var item in _context.Account.OrderBy(p => p.Id))
{
item.IsRunning = 0;
UpdateLocalAccount(item);
}
_context.SaveChanges();
}
}
private void MigrateDatabase()
{
if (AuthSettings.SchemaVersionBeforeMigration == UpdateConfig.CURRENT_SCHEMA_VERSION)
return;
int schemaVersion = AuthSettings.SchemaVersionBeforeMigration;
// Add future schema migrations below.
int version;
for (version = schemaVersion; version < UpdateConfig.CURRENT_SCHEMA_VERSION; version++)
{
Logging.Logger.Write($"Migrating {ACCOUNT_DB_NAME} from schema version {version} to {version + 1}", LogLevel.Info);
switch (version)
{
case 19:
// Just delete the accounts.db so it gets regenerated from scratch.
File.Delete(ACCOUNT_DB_NAME);
break;
case 25:
File.Delete(ACCOUNT_DB_NAME);
break;
}
}
}
private void SyncDatabase(List<AuthConfig> authConfigs)
{
if (authConfigs.Count() == 0)
return;
// Add new accounts and update existing accounts.
foreach (var authConfig in authConfigs)
{
if (string.IsNullOrEmpty(authConfig.Username) || string.IsNullOrEmpty(authConfig.Password))
continue;
var existing = _context.Account.FirstOrDefault(x => x.Username == authConfig.Username && x.AuthType == authConfig.AuthType);
if (existing == null)
{
try
{
Account newAcc = new Account(authConfig);
_context.Account.Add(newAcc);
_context.SaveChanges();
}
catch (Exception)
{
Logic.Logging.Logger.Write($"Error while saving data into {ACCOUNT_DB_NAME}, please delete {ACCOUNT_DB_NAME} and restart bot to have it fully work in order");
}
}
else
{
// Update credentials in database using values from json.
existing.Username = authConfig.Username;
existing.Password = authConfig.Password;
existing.AutoExitBotIfAccountFlagged = authConfig.AutoExitBotIfAccountFlagged;
existing.AccountLatitude = authConfig.AccountLatitude;
existing.AccountLongitude = authConfig.AccountLongitude;
existing.AccountActive = authConfig.AccountActive;
existing.RunStart = authConfig.RunStart;
existing.RunEnd = authConfig.RunEnd;
_context.SaveChanges();
}
}
// Remove accounts that are not in the auth.json but in the database.
List<Account> accountsToRemove = new List<Account>();
foreach (var item in _context.Account)
{
var existing = authConfigs.FirstOrDefault(x => x.Username == item.Username && x.AuthType == item.AuthType);
if (existing == null)
{
accountsToRemove.Add(item);
}
}
foreach (var item in accountsToRemove)
{
_context.Account.Remove(item);
}
_context.SaveChanges();
}
internal Account GetMinRuntime(bool ignoreBlockCheck = false)
{
if (_context.Account.Count() == 0)
return null;
if (ignoreBlockCheck)
return _context.Account.OrderByDescending(x => x.RuntimeTotal).ThenByDescending(x => x.Level).ThenByDescending(x => x.CurrentXp).Where(a => a.AccountActive == true && a.LastLogin != "Failure" && DateTime.Now.TimeOfDay.TotalSeconds >= a.RunStart && DateTime.Now.TimeOfDay.TotalSeconds <= a.RunEnd).Last();
else
return _context.Account.OrderByDescending(x => x.Level).ThenByDescending(x => x.CurrentXp).ThenBy(x => x.RuntimeTotal).Where(x => x != null && x.ReleaseBlockTime.HasValue && x.ReleaseBlockTime < DateTime.Now.ToUnixTime()).Last();
}
public bool AllowMultipleBot()
{
return _context.Account.Count() > 1;
}
public Account GetStartUpAccount()
{
ISession session = TinyIoCContainer.Current.Resolve<ISession>();
Account startupAccount = null;
if (!AllowMultipleBot())
{
startupAccount = _context.Account.Last();
}
else
{
startupAccount = GetMinRuntime(true);
}
if (AllowMultipleBot()
&& session.LogicSettings.MultipleBotConfig.SelectAccountOnStartUp)
{
SelectAccountForm f = new SelectAccountForm();
f.ShowDialog();
startupAccount = f.SelectedAccount;
}
return startupAccount;
}
private DateTime disableSwitchTime = DateTime.MinValue;
internal void DisableSwitchAccountUntil(DateTime untilTime)
{
if (disableSwitchTime < untilTime) disableSwitchTime = untilTime;
}
public bool AllowSwitch()
{
return disableSwitchTime < DateTime.Now;
}
public Account GetSwitchableAccount(Account bot = null, bool pauseIfNoSwitchableAccount = true)
{
ISession session = TinyIoCContainer.Current.Resolve<ISession>();
var currentAccount = GetCurrentAccount();
// If the bot to switch to is the same as the current bot then just return.
if (bot == currentAccount)
return bot;
if (bot != null)
return bot;
if (_context.Account.Count() > 0)
{
var runnableAccount = _context.Account.OrderByDescending(p => p.RuntimeTotal).ThenByDescending(p => p.Level).ThenByDescending(p => p.CurrentXp).Where(a => a != currentAccount && a.AccountActive == true && a.LastLogin != "Failure" && DateTime.Now.TimeOfDay.TotalSeconds >= a.RunStart && DateTime.Now.TimeOfDay.TotalSeconds <= a.RunEnd).LastOrDefault();
if (runnableAccount != null)
return runnableAccount;
}
if (!pauseIfNoSwitchableAccount)
return null;
// If we got here all accounts blocked so pause and retry.
var pauseTime = session.LogicSettings.MultipleBotConfig.OnLimitPauseTimes;
Logic.Logging.Logger.Write($"All accounts are blocked. None of your accounts are available to switch to, so bot will sleep for {pauseTime} minutes until next account is available to run.");
if (session.LogicSettings.NotificationConfig.EnablePushBulletNotification)
PushNotificationClient.SendNotification(session, "All accounts are blocked.", $"None of your accounts are available to switch to, so bot will sleep for {pauseTime} minutes until next account is available to run.", true).ConfigureAwait(false);
Task.Delay(pauseTime * 60 * 1000).Wait();
return GetSwitchableAccount();
}
private bool switchAccountRequest = false;
public void SwitchAccountTo(Account account)
{
requestedAccount = account;
switchAccountRequest = true;
}
public void ThrowIfSwitchAccountRequested()
{
if (switchAccountRequest && requestedAccount != null && (!requestedAccount.IsRunning.HasValue || requestedAccount.IsRunning.Value == 0))
{
switchAccountRequest = false;
throw new ActiveSwitchAccountManualException(requestedAccount);
}
}
private Account requestedAccount = null;
public void UpdateLocalAccount(Account current, bool save = true)
{
var localAccount = Accounts.Where(a => a.Id == current.Id).FirstOrDefault();
if (localAccount != null)
{
localAccount.Nickname = current.Nickname;
localAccount.RaisePropertyChanged("Nickname");
localAccount.RuntimeTotal = current.RuntimeTotal;
localAccount.RaisePropertyChanged("RuntimeTotal");
localAccount.IsRunning = current.IsRunning;
localAccount.RaisePropertyChanged("IsRunning");
localAccount.Level = current.Level;
localAccount.RaisePropertyChanged("Level");
localAccount.LastLogin = current.LastLogin;
localAccount.RaisePropertyChanged("LastLogin");
localAccount.LastLoginTimestamp = current.LastLoginTimestamp;
localAccount.RaisePropertyChanged("LastLoginTimestamp");
localAccount.Level = current.Level;
localAccount.RaisePropertyChanged("Level");
localAccount.Stardust = current.Stardust;
localAccount.RaisePropertyChanged("Stardust");
localAccount.CurrentXp = current.CurrentXp;
localAccount.RaisePropertyChanged("CurrentXp");
localAccount.NextLevelXp = current.NextLevelXp;
localAccount.RaisePropertyChanged("NextLevelXp");
localAccount.PrevLevelXp = current.PrevLevelXp;
localAccount.RaisePropertyChanged("PrevLevelXp");
localAccount.RaisePropertyChanged("ExperienceInfo");
localAccount.AccountLatitude = string.IsNullOrEmpty(current.AccountLatitude.ToString()) ? Client.CurrentLatitude : current.AccountLatitude;
localAccount.AccountLongitude = string.IsNullOrEmpty(current.AccountLongitude.ToString()) ? Client.CurrentLongitude : current.AccountLongitude;
localAccount.AccountActive = current.AccountActive;
if (save)
_context.SaveChanges();
}
}
public void DumpAccountList()
{
var userL = 0;
var maxL = 0;
var user = "";
foreach (var item in Accounts)
{
user = string.IsNullOrEmpty(item.Nickname) ? item.Username : item.Nickname;
userL = user.Length;
if (userL > maxL)
{
maxL = userL;
}
}
int acnt = 0;
foreach (var item in Accounts.OrderByDescending(p => p.AccountActive).ThenByDescending(p => p.Level).ThenByDescending(p => p.CurrentXp))
{
user = string.IsNullOrEmpty(item.Nickname) ? item.Username : item.Nickname;
acnt = acnt + 1;
if (item.RuntimeTotal == null) { item.RuntimeTotal = 0.0; }
int M = (int)item.RuntimeTotal;
int H = 0;
if (M >= 60) { H = (int)(M / 60); M = M - H * 60; }
string RT = " : ";
if (item.RuntimeTotal > 0) { RT = $"{H.ToString("00")}:{ M.ToString("00")}"; }
if (item.LastLogin == "Failure") { item.AccountActive = false; }
//if (((DateTime.Now.TimeOfDay.TotalMilliseconds - item.LastLoginTimestamp.Value) / 86400) >= 14) { item.AccountActive = false; }
if (item.Level > 0)
{
if (item.AccountActive && DateTime.Now.TimeOfDay.TotalSeconds >= item.RunStart && DateTime.Now.TimeOfDay.TotalSeconds <= item.RunEnd)
Logger.Write($"{acnt,2}) {user.PadRight(maxL)} | Lvl: {item.Level,2:#0} | XP: {item.CurrentXp,8:0} ({(int)((double)item.CurrentXp.Value / item.NextLevelXp.Value * 100),2:#0}%) | SD: {item.Stardust,8:0} | Runtime: {RT} | Last Login: {TimeUtil.GetDateTimeFromMilliseconds(item.LastLoginTimestamp.Value).ToLocalTime().ToString("MMM dd-HH:mm")}", LogLevel.BotStats);
else
Logger.Write($"{acnt,2})-{user.PadRight(maxL)} | Lvl: {item.Level,2:#0} | XP: {item.CurrentXp,8:0} ({(int)((double)item.CurrentXp.Value / item.NextLevelXp.Value * 100),2:#0}%) | SD: {item.Stardust,8:0} | Runtime: {RT} | Last Login: {TimeUtil.GetDateTimeFromMilliseconds(item.LastLoginTimestamp.Value).ToLocalTime().ToString("MMM dd-HH:mm")}", LogLevel.BotStats, ConsoleColor.Red);
}
else
{
if (item.AccountActive && DateTime.Now.TimeOfDay.TotalSeconds >= item.RunStart && DateTime.Now.TimeOfDay.TotalSeconds <= item.RunEnd)
Logger.Write($"{acnt,2}) {user.PadRight(maxL)} | Lvl: ?? | XP: 0 ( 0%) | SD: 0 | Runtime: : | Last Login: N/A", LogLevel.BotStats, ConsoleColor.Yellow);
else
Logger.Write($"{acnt,2})-{user.PadRight(maxL)} | Lvl: ?? | XP: 0 ( 0%) | SD: 0 | Runtime: : | Last Login: N/A", LogLevel.BotStats, ConsoleColor.Red);
}
}
}
public Account FindAvailableAccountForPokemonSwitch(string encounterId)
{
ISession session = TinyIoCContainer.Current.Resolve<ISession>();
//set current
Account switchableAccount = GetSwitchableAccount(null, false); // Don't pause if no switchable account is available.
if (switchableAccount != null)
{
if (session.Cache.GetCacheItem(CatchPokemonTask.GetUsernameEncounterCacheKey(switchableAccount.Username, encounterId)) == null)
{
// Don't edit the running account until we actually switch. Just return the pending account.
return switchableAccount;
}
}
return null;
}
internal void DirtyEventHandle(Statistics stat)
{
var account = GetCurrentAccount();
if (account == null)
return;
account.Level = stat.StatsExport.Level;
account.Stardust = stat.TotalStardust;
account.CurrentXp = stat.StatsExport.CurrentXp - stat.StatsExport.LevelXp;
account.NextLevelXp = stat.StatsExport.LevelupXp - stat.StatsExport.LevelXp;
account.PrevLevelXp = stat.StatsExport.PreviousXp - stat.StatsExport.LevelXp;
var now = DateTime.Now;
if (account.LastRuntimeUpdatedAt.HasValue)
{
account.RuntimeTotal += (now - TimeUtil.GetDateTimeFromMilliseconds(account.LastRuntimeUpdatedAt.Value)).TotalMinutes;
account.LastRuntimeUpdatedAt = now.ToUnixTime();
}
UpdateLocalAccount(account);
}
}
}