aboutsummaryrefslogtreecommitdiffstats
path: root/src/slskd/Application.cs
blob: 70d726abb8c2041ca66da3cd86da6151b72a787a (plain) (blame)
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
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
// <copyright file="Application.cs" company="slskd Team">
//     Copyright (c) slskd Team. All rights reserved.
//
//     This program is free software: you can redistribute it and/or modify
//     it under the terms of the GNU Affero General Public License as published
//     by the Free Software Foundation, either version 3 of the License, or
//     (at your option) any later version.
//
//     This program is distributed in the hope that it will be useful,
//     but WITHOUT ANY WARRANTY; without even the implied warranty of
//     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//     GNU Affero General Public License for more details.
//
//     You should have received a copy of the GNU Affero General Public License
//     along with this program.  If not, see https://www.gnu.org/licenses/.
// </copyright>

using Microsoft.Extensions.Options;

namespace slskd
{
    using System;
    using System.Collections.Concurrent;
    using System.Collections.Generic;
    using System.Diagnostics;
    using System.IO;
    using System.Linq;
    using System.Net;
    using System.Net.Sockets;
    using System.Reflection;
    using System.Runtime;
    using System.Runtime.InteropServices;
    using System.Text.RegularExpressions;
    using System.Threading;
    using System.Threading.Tasks;
    using Microsoft.AspNetCore.SignalR;
    using Microsoft.Extensions.Caching.Memory;
    using Microsoft.Extensions.Hosting;
    using Serilog;
    using Serilog.Events;
    using slskd.Configuration;
    using slskd.Core.API;
    using slskd.Integrations.Pushbullet;
    using slskd.Messaging;
    using slskd.Relay;
    using slskd.Search;
    using slskd.Shares;
    using slskd.Transfers;
    using slskd.Transfers.API;
    using slskd.Users;
    using Soulseek;
    using Soulseek.Diagnostics;

    public interface IApplication : IHostedService
    {
        public Task CheckVersionAsync();
        public void CollectGarbage();
    }

    public sealed class Application : IApplication
    {
        /// <summary>
        ///     The name of the default user group.
        /// </summary>
        public const string DefaultGroup = "default";

        /// <summary>
        ///     The name of the privileged user group.
        /// </summary>
        public const string PrivilegedGroup = "privileged";

        /// <summary>
        ///     The name of the leecher user group.
        /// </summary>
        public const string LeecherGroup = "leechers";

        /// <summary>
        ///     The name of the blacklisted user group.
        /// </summary>
        public const string BlacklistedGroup = "blacklisted";

        private static readonly string ApplicationShutdownTransferExceptionMessage = "Application shut down";

        public Application(
            OptionsAtStartup optionsAtStartup,
            IOptionsMonitor<Options> optionsMonitor,
            IManagedState<State> state,
            ISoulseekClient soulseekClient,
            IConnectionWatchdog connectionWatchdog,
            ITransferService transferService,
            IBrowseTracker browseTracker,
            IRoomTracker roomTracker,
            IRoomService roomService,
            IUserService userService,
            IMessagingService messagingService,
            IShareService shareService,
            IPushbulletService pushbulletService,
            IRelayService relayService,
            IHubContext<ApplicationHub> applicationHub,
            IHubContext<LogsHub> logHub)
        {
            Console.CancelKeyPress += (_, args) =>
            {
                ShuttingDown = true;
                Program.MasterCancellationTokenSource.Cancel();
                Log.Warning("Received SIGINT");
            };

            foreach (var signal in new[] { PosixSignal.SIGINT, PosixSignal.SIGQUIT, PosixSignal.SIGTERM })
            {
                PosixSignalRegistration.Create(signal, context =>
                {
                    ShuttingDown = true;
                    Program.MasterCancellationTokenSource.Cancel();
                    Log.Fatal("Received {Signal}", signal);
                    Environment.Exit(1);
                });
            }

            OptionsAtStartup = optionsAtStartup;

            OptionsMonitor = optionsMonitor;
            OptionsMonitor.OnChange(async options => await OptionsMonitor_OnChange(options));

            PreviousOptions = OptionsMonitor.CurrentValue;

            Flags = Program.Flags;

            var regexOptions = RegexOptions.Compiled;

            if (!Flags.CaseSensitiveRegEx)
            {
                regexOptions |= RegexOptions.IgnoreCase;
            }

            CompiledSearchResponseFilters = OptionsAtStartup.Filters.Search.Request.Select(f => new Regex(f, regexOptions));

            State = state;
            State.OnChange(state => State_OnChange(state));

            Shares = shareService;
            Shares.StateMonitor.OnChange(state => ShareState_OnChange(state));

            Transfers = transferService;
            BrowseTracker = browseTracker;
            Pushbullet = pushbulletService;

            RoomService = roomService;
            Users = userService;
            Messaging = messagingService;
            ApplicationHub = applicationHub;

            Relay = relayService;
            Relay.StateMonitor.OnChange(relayState => State.SetValue(state => state with { Relay = relayState.Current }));

            LogHub = logHub;
            Program.LogEmitted += (_, log) => LogHub.EmitLogAsync(log);

            Client = soulseekClient;

            Client.DiagnosticGenerated += Client_DiagnosticGenerated;

            Client.TransferStateChanged += Client_TransferStateChanged;
            Client.TransferProgressUpdated += Client_TransferProgressUpdated;

            Client.BrowseProgressUpdated += Client_BrowseProgressUpdated;
            Client.UserStatusChanged += Client_UserStatusChanged;
            Client.PrivateMessageReceived += Client_PrivateMessageRecieved;

            Client.PrivateRoomMembershipAdded += (e, room) => Log.Information("Added to private room {Room}", room);
            Client.PrivateRoomMembershipRemoved += (e, room) => Log.Information("Removed from private room {Room}", room);
            Client.PrivateRoomModerationAdded += (e, room) => Log.Information("Promoted to moderator in private room {Room}", room);
            Client.PrivateRoomModerationRemoved += (e, room) => Log.Information("Demoted from moderator in private room {Room}", room);

            Client.PublicChatMessageReceived += Client_PublicChatMessageReceived;
            Client.RoomMessageReceived += Client_RoomMessageReceived;
            Client.Disconnected += Client_Disconnected;
            Client.Connected += Client_Connected;
            Client.LoggedIn += Client_LoggedIn;
            Client.StateChanged += Client_StateChanged;
            Client.DistributedNetworkStateChanged += Client_DistributedNetworkStateChanged;
            Client.DownloadDenied += (e, args) => Log.Information("Download of {Filename} from {Username} was denied: {Message}", args.Filename, args.Username, args.Message);
            Client.DownloadFailed += (e, args) => Log.Information("Download of {Filename} from {Username} failed", args.Filename, args.Username);

            ConnectionWatchdog = connectionWatchdog;

            Clock.EveryMinute += Clock_EveryMinute;
            Clock.EveryFiveMinutes += Clock_EveryFiveMinutes;
            Clock.EveryThirtyMinutes += Clock_EveryThirtyMinutes;
            Clock.EveryHour += Clock_EveryHour;
        }

        /// <summary>
        ///     Gets a value indicating whether the application is in the process of shutting down.
        /// </summary>
        public static bool IsShuttingDown => Environment.HasShutdownStarted || ShuttingDown;

        private static bool ShuttingDown { get; set; } = false;

        private ISoulseekClient Client { get; set; }
        private IRoomService RoomService { get; set; }
        private IBrowseTracker BrowseTracker { get; set; }
        private IConnectionWatchdog ConnectionWatchdog { get; }
        private IMessagingService Messaging { get; set; }
        private ILogger Log { get; set; } = Serilog.Log.ForContext<Application>();
        private ConcurrentDictionary<string, ILogger> Loggers { get; } = new ConcurrentDictionary<string, ILogger>();
        private Options Options => OptionsMonitor.CurrentValue;
        private OptionsAtStartup OptionsAtStartup { get; set; }
        private IOptionsMonitor<Options> OptionsMonitor { get; set; }
        private SemaphoreSlim OptionsSyncRoot { get; } = new SemaphoreSlim(1, 1);
        private Options PreviousOptions { get; set; }
        private IPushbulletService Pushbullet { get; }
        private DateTime SharesRefreshStarted { get; set; }
        private IManagedState<State> State { get; }
        private ITransferService Transfers { get; init; }
        private IHubContext<ApplicationHub> ApplicationHub { get; set; }
        private IHubContext<LogsHub> LogHub { get; set; }
        private IUserService Users { get; set; }
        private IShareService Shares { get; set; }
        private IRelayService Relay { get; set; }
        private IMemoryCache Cache { get; set; } = new MemoryCache(new MemoryCacheOptions());
        private IEnumerable<Regex> CompiledSearchResponseFilters { get; set; }
        private IEnumerable<Guid> ActiveDownloadIdsAtPreviousShutdown { get; set; } = Enumerable.Empty<Guid>();
        private Options.FlagsOptions Flags { get; set; }

        public void CollectGarbage()
        {
            var sw = new Stopwatch();

            Log.Debug("Collecting garbage");

            sw.Start();

            GCSettings.LargeObjectHeapCompactionMode = GCLargeObjectHeapCompactionMode.CompactOnce;
#pragma warning disable S1215 // "GC.Collect" should not be called
            GC.Collect(2, GCCollectionMode.Forced, blocking: true, compacting: true);
#pragma warning restore S1215 // "GC.Collect" should not be called

            sw.Stop();

            Log.Debug("Garbage collection completed in {Duration}ms", sw.ElapsedMilliseconds);
        }

        /// <summary>
        ///     Gets the version of the latest application release.
        /// </summary>
        /// <returns>The operation context.</returns>
        public async Task CheckVersionAsync()
        {
            if (Program.IsDevelopment)
            {
                Log.Information("Skipping version check for Development build");
                return;
            }

            if (Program.IsCanary)
            {
                // todo: use the docker hub API to find the latest canary tag
                Log.Information("Skipping version check for Canary build; check for updates manually.");
                return;
            }

            Log.Information("Checking GitHub Releases for latest version");

            try
            {
                var latestVersion = await GitHub.GetLatestReleaseVersion(
                    organization: Program.AppName,
                    repository: Program.AppName,
                    userAgent: $"{Program.AppName} v{Program.FullVersion}");

                if (latestVersion > Version.Parse(Program.SemanticVersion))
                {
                    State.SetValue(state => state with { Version = state.Version with { Latest = latestVersion.ToString(), IsUpdateAvailable = true } });
                    Log.Information("A new version is available! {CurrentVersion} -> {LatestVersion}", Program.SemanticVersion, latestVersion);
                }
                else
                {
                    State.SetValue(state => state with { Version = state.Version with { Latest = Program.SemanticVersion, IsUpdateAvailable = false } });
                    Log.Information("Version {CurrentVersion} is up to date.", Program.SemanticVersion);
                }
            }
            catch (Exception ex)
            {
                Log.Warning("Failed to check version: {Message}", ex.Message);
                throw;
            }
        }

        async Task IHostedService.StartAsync(CancellationToken cancellationToken)
        {
            Log.Information("Application started");

            // if the application shut down "uncleanly", transfers may need to be cleaned up. we deliberately don't allow these
            // records to be updated if the application has started to shut down so that we can do this cleanup and properly
            // disposition them as having failed due to an application shutdown, instead of some random exception thrown while
            // things are being disposed.
            var activeUploads = Transfers.Uploads.List(t => !t.State.HasFlag(TransferStates.Completed), includeRemoved: false)
                .Where(t => !t.State.HasFlag(TransferStates.Completed)) // https://github.com/dotnet/efcore/issues/10434
                .ToList();

            foreach (var upload in activeUploads)
            {
                Log.Debug("Cleaning up dangling upload {Filename} to {Username}", upload.Filename, upload.Username);
                upload.State = TransferStates.Completed | TransferStates.Errored;
                upload.Exception = ApplicationShutdownTransferExceptionMessage;
                Transfers.Uploads.Update(upload);
            }

            var activeDownloads = Transfers.Downloads.List(t => !t.State.HasFlag(TransferStates.Completed) && !t.Removed)
                .Where(t => !t.State.HasFlag(TransferStates.Completed)) // https://github.com/dotnet/efcore/issues/10434
                .ToList();

            foreach (var download in activeDownloads)
            {
                Log.Debug("Cleaning up dangling download {Filename} from {Username}", download.Filename, download.Username);
                download.State = TransferStates.Completed | TransferStates.Errored;
                download.Exception = ApplicationShutdownTransferExceptionMessage;
                Transfers.Downloads.Update(download);
            }

            // save the ids of any downloads that were active, so we can re-enqueue them after we've connected and logged in.
            // we need to check the database before we re-request to make sure the user didn't remove them from the UI while
            // the application was running, but before it was logged in. so just save the ids.
            ActiveDownloadIdsAtPreviousShutdown = activeDownloads.Select(d => d.Id);
            Log.Debug("Downloads to resume upon connection: {Ids}", ActiveDownloadIdsAtPreviousShutdown.ToJson());

            Log.Debug("Configuring client");

            ProxyOptions proxyOptions = default;

            if (OptionsAtStartup.Soulseek.Connection.Proxy.Enabled)
            {
                proxyOptions = new ProxyOptions(
                    address: OptionsAtStartup.Soulseek.Connection.Proxy.Address,
                    port: OptionsAtStartup.Soulseek.Connection.Proxy.Port.Value,
                    username: OptionsAtStartup.Soulseek.Connection.Proxy.Username,
                    password: OptionsAtStartup.Soulseek.Connection.Proxy.Password);
            }

            var connectionOptions = new ConnectionOptions(
                readBufferSize: OptionsAtStartup.Soulseek.Connection.Buffer.Read,
                writeBufferSize: OptionsAtStartup.Soulseek.Connection.Buffer.Write,
                writeQueueSize: OptionsAtStartup.Soulseek.Connection.Buffer.WriteQueue,
                connectTimeout: OptionsAtStartup.Soulseek.Connection.Timeout.Connect,
                inactivityTimeout: OptionsAtStartup.Soulseek.Connection.Timeout.Inactivity,
                proxyOptions: proxyOptions);

            var configureKeepAlive = new Action<Socket>(socket =>
            {
                socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
                socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, OptionsAtStartup.Soulseek.Connection.Timeout.Inactivity / 1000);
                socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval, OptionsAtStartup.Soulseek.Connection.Timeout.Inactivity / 1000);
                socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveRetryCount, 3);
            });

            var serverOptions = connectionOptions.With(configureSocketAction: configureKeepAlive);
            var distributedOptions = connectionOptions.With(configureSocketAction: configureKeepAlive);

            var transferOptions = connectionOptions.With(
                readBufferSize: OptionsAtStartup.Soulseek.Connection.Buffer.Transfer,
                writeBufferSize: OptionsAtStartup.Soulseek.Connection.Buffer.Transfer);

            var patch = new SoulseekClientOptionsPatch(
                listenIPAddress: IPAddress.Parse(OptionsAtStartup.Soulseek.ListenIpAddress),
                listenPort: OptionsAtStartup.Soulseek.ListenPort,
                enableListener: true,
                userEndPointCache: new UserEndPointCache(),
                distributedChildLimit: OptionsAtStartup.Soulseek.DistributedNetwork.ChildLimit,
                enableDistributedNetwork: !OptionsAtStartup.Soulseek.DistributedNetwork.Disabled,
                acceptDistributedChildren: !OptionsAtStartup.Soulseek.DistributedNetwork.DisableChildren,
                maximumUploadSpeed: OptionsAtStartup.Global.Upload.SpeedLimit,
                maximumDownloadSpeed: OptionsAtStartup.Global.Download.SpeedLimit,
                autoAcknowledgePrivateMessages: false,
                acceptPrivateRoomInvitations: true,
                serverConnectionOptions: serverOptions,
                peerConnectionOptions: connectionOptions,
                transferConnectionOptions: transferOptions,
                distributedConnectionOptions: distributedOptions,
                userInfoResolver: UserInfoResolver,
                browseResponseResolver: BrowseResponseResolver,
                directoryContentsResolver: DirectoryContentsResponseResolver,
                enqueueDownload: EnqueueDownload,
                searchResponseCache: new SearchResponseCache(),
                searchResponseResolver: SearchResponseResolver,
                placeInQueueResolver: PlaceInQueueResolver);

            await Client.ReconfigureOptionsAsync(patch);

            Log.Debug("Client configured");
            Log.Information("Listening for incoming connections on {IP}:{Port}", OptionsAtStartup.Soulseek.ListenIpAddress, OptionsAtStartup.Soulseek.ListenPort);

            if (OptionsAtStartup.Soulseek.Connection.Proxy.Enabled)
            {
                Log.Information($"Using Proxy {OptionsAtStartup.Soulseek.Connection.Proxy.Address}:{OptionsAtStartup.Soulseek.Connection.Proxy.Port}");
            }

            if (!OptionsAtStartup.Flags.NoVersionCheck)
            {
                _ = CheckVersionAsync();
            }

            if (!OptionsAtStartup.Flags.NoShareScan)
            {
                try
                {
                    await Shares.InitializeAsync(forceRescan: OptionsAtStartup.Flags.ForceShareScan);
                }
                catch (Exception)
                {
                    Log.Error("Failed to initialize shares. Sharing is disabled");
                }
            }

            // the placement of this may be a bit contentious long term; when the clock starts, all of the
            // scheduled tasks will fire for the first time. the clock EventArgs contain a FirstRun flag
            // to help timed logic decide whether to run, but as a safeguard the start is delayed until
            // *just* before the application connects to the server/controller, meaning all configuration
            // and bootup tasks are complete. if this needs to be moved higher, a way to defer tasks from
            // the first run of the clock will need to be introduced, and those deferred tasks will need
            // to be executed around here somewhere.
            Log.Information("Starting system clock...");
            await Clock.StartAsync();
            Log.Information("System clock started");

            if (OptionsAtStartup.Relay.Enabled && OptionsAtStartup.Relay.Mode.ToEnum<RelayMode>() == RelayMode.Agent)
            {
                Log.Information("Running in Agent relay mode; not connecting to the Soulseek server.");
                await Relay.Client.StartAsync(cancellationToken);
            }
            else
            {
                if (OptionsAtStartup.Relay.Enabled)
                {
                    Log.Information("Running in Controller relay mode.  Listening for incoming Agent connections.");

                    if (OptionsAtStartup.Relay.Mode.ToEnum<RelayMode>() == RelayMode.Debug)
                    {
                        Log.Warning("Running in Debug relay mode; connecting to controller");
                        _ = Relay.Client.StartAsync(cancellationToken);
                    }
                }

                if (OptionsAtStartup.Flags.NoConnect)
                {
                    Log.Warning("Not connecting to the Soulseek server; 'no-connect' option is enabled");
                }
                else if (string.IsNullOrEmpty(OptionsAtStartup.Soulseek.Username) || string.IsNullOrEmpty(OptionsAtStartup.Soulseek.Password))
                {
                    Log.Warning($"Not connecting to the Soulseek server; username and/or password invalid.  Specify valid credentials and manually connect, or update config and restart.");
                }
                else
                {
                    var opt = OptionsAtStartup.Soulseek;

                    await Client.ConnectAsync(
                        address: opt.Address,
                        port: opt.Port,
                        username: opt.Username,
                        password: opt.Password).ConfigureAwait(false);
                }
            }
        }

        Task IHostedService.StopAsync(CancellationToken cancellationToken)
        {
            ShuttingDown = true;
            Log.Warning("Application is shutting down");

            Clock.Stop();

            Client.Disconnect("Shutting down", new ApplicationShutdownException("Shutting down"));
            Client.Dispose();
            Log.Information("Client stopped");
            return Task.CompletedTask;
        }

        private async Task EnqueueDownload(string username, IPEndPoint endpoint, string filename)
        {
            if (Users.IsBlacklisted(username, endpoint.Address))
            {
                Log.Information("Rejected enqueue request for blacklisted user {Username} ({IP})", username, endpoint.Address);
                throw new DownloadEnqueueException("File not shared.");
            }

            // in order to properly determine if the requested file would exceed any limits, we need to know the size of the file
            // it helps, too, that this will tell us whether the file is even shared.
            (string Host, string Filename, long Size) resolved;

            try
            {
                resolved = await Shares.ResolveFileAsync(filename);
            }
            catch (NotFoundException)
            {
                throw new DownloadEnqueueException("File not shared.");
            }

            // get the user's group. this will be the name of the user's group, if they have been added to a
            // user defined group, or one of the built-ins; 'default', 'privileged', 'leecher', or 'blacklisted'
            var group = await Users.GetOrFetchGroupAsync(username);

            // privileged users aren't subject to limits (for now)
            // i'm putting this off because 1) limits are unique to slskd, so all other clients are "unlimited"
            // and 2) i can't figure out what the limits would be, if not unlimited. users should get some level
            // of control, but i'd need to figure out a lower bound
            if (string.Equals(group, PrivilegedGroup))
            {
                Log.Debug("Limits bypassed for {Username} and {File}; user is privileged", username, filename);
                await Transfers.Uploads.EnqueueAsync(username, filename);
                return;
            }

            // resolve the limits for this user's group.  there's no 'fallthrough' here, if limits for a group
            // are unset, then that group is unlimited.
            Options.GroupsOptions.LimitsOptions limits;

            if (Options.Groups.UserDefined.TryGetValue(group, out var userDefinedOptions))
            {
                limits = userDefinedOptions.Limits;
            }
            else
            {
                limits = group switch
                {
                    DefaultGroup => Options.Groups.Default.Limits,
                    LeecherGroup => Options.Groups.Leechers.Limits,
                    _ => Options.Groups.Default.Limits,
                };
            }

            bool IsNull(Options.GroupsOptions.LimitsExtendedOptions l) => l is null || (l?.Files is null && l?.Megabytes is null);

            // if no limits are set, we're good to go; just enqueue the file.
            if (limits is null || (IsNull(limits.Daily) && IsNull(limits.Weekly) && IsNull(limits.Queued)))
            {
                Log.Debug("Limits bypassed for {Username} and {File}; no limits are set", username, filename);
                await Transfers.Uploads.EnqueueAsync(username, filename);
                return;
            }

            var sw = new Stopwatch();
            sw.Start();

            /*
             * we have limits set, so now we have to fetch the data and compare to see if any would be hit if we allow this transfer to be enqueued.
             * the strategy here is to summarize all uploads:
             * 1) belonging to this user
             * 2) that were started within the time period
             * 3) that did not end due to an error (state includes errored, exception column is set)
            */
            (bool Files, bool Megabytes) OverLimits((int Files, long Bytes) stats, Options.GroupsOptions.LimitsExtendedOptions options, long size)
            {
                var files = false;
                var megabytes = false;
                var byteLimit = (options?.Megabytes ?? 0) * 1000 * 1000;

                if (options?.Megabytes is not null && (stats.Bytes + size) > byteLimit)
                {
                    Log.Debug("Projected bytes {Bytes} exceeds limit {Limit}", stats.Bytes + size, byteLimit);
                    megabytes = true;
                }

                if (options?.Files is not null && (stats.Files + 1) > options.Files)
                {
                    Log.Debug("Projected file count {Files} exceeds limit {Limit}", stats.Files + 1, options.Files);
                    files = true;
                }

                return (files, megabytes);
            }

            // start with the queue, since that should contain the fewest files and should be the least expensive to check
            // "queued" includes both queued and in progress; records with a null EndedAt property, which is guaranteed to be set
            // for terminal transfers.
            if (!IsNull(limits.Queued))
            {
                var queued = Transfers.Uploads.Summarize(
                    expression: t => t.Username == username && t.EndedAt == null);

                Log.Debug("Fetched queue stats: files: {Files}, bytes: {Bytes} ({Time}ms)", queued.Files, queued.Bytes, sw.ElapsedMilliseconds);

                var over = OverLimits(queued, limits!.Queued, resolved.Size);

                if (over.Files || over.Megabytes)
                {
                    Log.Information("Rejected enqueue request for user {Username}: Queued limits exceeded", username);
                    throw new DownloadEnqueueException($"Too many {(over.Files ? "files" : "megabytes")} queued");
                }
            }

            // start with weekly, as this is the most likely limit to be hit and we want to keep the work to a minimum
            // transfers that 'count' for the weekly limit are uploads that:
            // * started within the last week
            // * which have or have not ended (assuming queued files will complete)
            // * that were not errored
            if (!IsNull(limits.Weekly))
            {
                var erroredState = TransferStates.Completed | TransferStates.Errored;
                var cutoffDateTime = DateTime.UtcNow.AddDays(-7);
                var weekly = Transfers.Uploads.Summarize(
                    expression: t =>
                        t.Username == username
                        && t.StartedAt >= cutoffDateTime
                        && !t.State.HasFlag(erroredState)
                        && t.Exception == null);

                Log.Debug("Fetched weekly stats: files: {Files}, bytes: {Bytes} ({Time}ms)", weekly.Files, weekly.Bytes, sw.ElapsedMilliseconds);

                var over = OverLimits(weekly, limits!.Weekly, resolved.Size);

                if (over.Files || over.Megabytes)
                {
                    Log.Information("Rejected enqueue request for user {Username}: Weekly limits exceeded", username);
                    throw new DownloadEnqueueException($"Too many {(over.Files ? "files" : "megabytes")} this week");
                }
            }

            // lastly, check daily limits. the criteria for this is the same as weekly, just looking over the previous day instead
            // of the previous 7.
            if (!IsNull(limits.Daily))
            {
                var erroredState = TransferStates.Completed | TransferStates.Errored;
                var cutoffDateTime = DateTime.UtcNow.AddDays(-1);
                var daily = Transfers.Uploads.Summarize(
                    expression: t =>
                        t.Username == username
                        && t.StartedAt >= cutoffDateTime
                        && !t.State.HasFlag(erroredState)
                        && t.Exception == null);

                Log.Debug("Fetched daily stats: files: {Files}, bytes: {Bytes} ({Time}ms)", daily.Files, daily.Bytes, sw.ElapsedMilliseconds);

                var over = OverLimits(daily, limits!.Daily, resolved.Size);

                if (over.Files || over.Megabytes)
                {
                    Log.Information("Rejected enqueue request for user {Username}: Daily limits exceeded", username);
                    throw new DownloadEnqueueException($"Too many {(over.Files ? "files" : "megabytes")} today");
                }
            }

            sw.Stop();
            Log.Debug("Enqueue decision made in {Duration}ms", sw.ElapsedMilliseconds);

            await Transfers.Uploads.EnqueueAsync(username, filename);
        }

        /// <summary>
        ///     Creates and returns an instances of <see cref="BrowseResponse"/> in response to a remote request.
        /// </summary>
        /// <param name="username">The username of the requesting user.</param>
        /// <param name="endpoint">The IP endpoint of the requesting user.</param>
        /// <returns>A Task resolving an IEnumerable of Soulseek.Directory.</returns>
        private async Task<BrowseResponse> BrowseResponseResolver(string username, IPEndPoint endpoint)
        {
            Metrics.Browse.RequestsReceived.Inc(1);

            if (Users.IsBlacklisted(username, endpoint.Address))
            {
                Log.Information("Returned empty browse listing for blacklisted user {Username} ({IP})", username, endpoint.Address);
                return new BrowseResponse();
            }

            try
            {
                var sw = new Stopwatch();
                sw.Start();

                BrowseResponse response = default;

                var cacheFilename = Path.Combine(Program.DataDirectory, "browse.cache");
                var cacheFileInfo = new FileInfo(cacheFilename);

                if (!cacheFileInfo.Exists)
                {
                    Log.Warning("Browse response not cached. Rebuilding...");
                    response = await CacheBrowseResponse();
                }
                else
                {
                    var stream = new FileStream(cacheFilename, FileMode.Open, FileAccess.Read);
                    response = new RawBrowseResponse(cacheFileInfo.Length, stream);
                }

                Log.Information("Sent browse response to {User}", username);

                sw.Stop();

                Metrics.Browse.ResponseLatency.Observe(sw.ElapsedMilliseconds);
                Metrics.Browse.CurrentResponseLatency.Update(sw.ElapsedMilliseconds);
                Metrics.Browse.ResponsesSent.Inc(1);

                return response;
            }
            catch (Exception ex)
            {
                Log.Warning(ex, "Failed to resolve browse response: {Message}", ex.Message);
                throw;
            }
        }

        private void Client_BrowseProgressUpdated(object sender, BrowseProgressUpdatedEventArgs args)
        {
            BrowseTracker.AddOrUpdate(args.Username, args);
        }

        private void Client_Connected(object sender, EventArgs e)
        {
            ConnectionWatchdog.Stop();
            Log.Information("Connected to the Soulseek server");
        }

        private void Client_DiagnosticGenerated(object sender, DiagnosticEventArgs args)
        {
            static LogEventLevel TranslateLogLevel(DiagnosticLevel diagnosticLevel) => diagnosticLevel switch
            {
                DiagnosticLevel.Debug => LogEventLevel.Debug,
                DiagnosticLevel.Info => LogEventLevel.Debug,
                DiagnosticLevel.Warning => LogEventLevel.Warning,
                DiagnosticLevel.None => default,
                _ => default,
            };

            var source = sender.GetType().FullName;

            if (source.EndsWith("DistributedConnectionManager") && !Options.Soulseek.DistributedNetwork.Logging)
            {
                return;
            }

            var logger = Loggers.GetOrAdd(source, Log.ForContext("Context", "Soulseek").ForContext("SubContext", source));

            logger.Write(TranslateLogLevel(args.Level), "{@Message}", args.Message);
        }

        private void Client_Disconnected(object sender, SoulseekClientDisconnectedEventArgs args)
        {
            if (State.CurrentValue.PendingReconnect)
            {
                State.SetValue(state => state with { PendingReconnect = false });
            }

            if (args.Exception is ObjectDisposedException || args.Exception is ApplicationShutdownException)
            {
                Log.Information("Disconnected from the Soulseek server: the client is shutting down");
            }
            else if (args.Exception is IntentionalDisconnectException)
            {
                Log.Information("Disconnected from the Soulseek server: disconnected by the user");
            }
            else if (args.Exception is LoginRejectedException)
            {
                Log.Error("Disconnected from the Soulseek server: invalid username or password");
            }
            else if (args.Exception is KickedFromServerException)
            {
                Log.Error("Disconnected from the Soulseek server: another client logged in using the same username");
            }
            else
            {
                Log.Error("Disconnected from the Soulseek server: {Message}", args.Exception?.Message ?? args.Message);
                ConnectionWatchdog.Start();
            }
        }

        private async Task RefreshUserStatistics(bool force = false)
        {
            if (force || !Cache.TryGetValue(CacheKeys.UserStatisticsToken, out _))
            {
                var stats = await Client.GetUserStatisticsAsync(Client.Username);
                var privileges = await Client.GetPrivilegesAsync();

                State.SetValue(state => state with
                {
                    User = state.User with
                    {
                        Statistics = stats.ToUserStatisticsState(),
                        Privileges = new UserPrivilegeState()
                        {
                            IsPrivileged = privileges > 0,
                            PrivilegesRemaining = privileges,
                        },
                    },
                });

                Cache.Set(CacheKeys.UserStatisticsToken, true, TimeSpan.FromHours(4));
            }
        }

        private async void Client_LoggedIn(object sender, EventArgs e)
        {
            Log.Information("Logged in to the Soulseek server as {Username}", Client.Username);

            try
            {
                // send whatever counts we have currently. we'll probably connect before the cache is primed, so these will be zero
                // initially, but we'll update them when the cache is filled.
                await Client.SetSharedCountsAsync(State.CurrentValue.Shares.Directories, State.CurrentValue.Shares.Files);

                // fetch our average upload speed from the server, so we can provide it along with search results
                await RefreshUserStatistics(force: true);

                // we previously saved a list of all of the download ids that were active at the previous shutdown; fetch the latest
                // record for those transfers from the db and ensure they haven't been removed from the UI while the application was offline
                // the user doesn't want those transfers anymore and we don't want to add them back.
                var resumeableDownloads = Transfers.Downloads.List(t => !t.Removed && ActiveDownloadIdsAtPreviousShutdown.Contains(t.Id));

                if (resumeableDownloads.Any())
                {
                    Log.Information("Attempting to re-enqueue previously active downloads...");

                    var groups = resumeableDownloads.GroupBy(d => d.Username);

                    // re-request downloads. we use a try/catch here because there's a very good chance that the other user is offline.
                    foreach (var group in groups)
                    {
                        var username = group.Key;
                        var files = group.Select(f => (f.Filename, f.Size));

                        try
                        {
                            await Transfers.Downloads.EnqueueAsync(username, files);
                        }
                        catch (Exception ex)
                        {
                            Log.Warning("Failed to re-enqueue {Count} file(s) from {Username}: {Message}", files.Count(), username, ex.Message);
                        }
                    }
                }

                // clear the ids we saved at startup; we don't want to re-request these again if the connection is cycled
                ActiveDownloadIdsAtPreviousShutdown = Enumerable.Empty<Guid>();
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Failed to execute post-login actions");
            }
        }

        private void Client_PrivateMessageRecieved(object sender, PrivateMessageReceivedEventArgs args)
        {
            Messaging.Conversations.HandleMessageAsync(args.Username, PrivateMessage.FromEventArgs(args));

            if (Options.Integration.Pushbullet.Enabled && !args.Replayed)
            {
                _ = Pushbullet.PushAsync($"Private Message from {args.Username}", args.Username, args.Message);
            }
        }

        private void Client_PublicChatMessageReceived(object sender, PublicChatMessageReceivedEventArgs args)
        {
            Log.Information("[Public Chat/{Room}] [{Username}]: {Message}", args.RoomName, args.Username, args.Message);

            if (Options.Integration.Pushbullet.Enabled && args.Message.Contains(Client.Username))
            {
                _ = Pushbullet.PushAsync($"Room Mention by {args.Username} in {args.RoomName}", args.RoomName, args.Message);
            }
        }

        private void Client_RoomMessageReceived(object sender, RoomMessageReceivedEventArgs args)
        {
            var message = RoomMessage.FromEventArgs(args, DateTime.UtcNow);

            if (Options.Integration.Pushbullet.Enabled && message.Message.Contains(Client.Username))
            {
                _ = Pushbullet.PushAsync($"Room Mention by {message.Username} in {message.RoomName}", message.RoomName, message.Message);
            }
        }

        private void Client_StateChanged(object sender, SoulseekClientStateChangedEventArgs e)
        {
            State.SetValue(state => state with
            {
                Server = state.Server with
                {
                    Address = Client.Address,
                    IPEndPoint = Client.IPEndPoint,
                    State = Client.State,
                },
                User = state.User with
                {
                    Username = Client.Username,
                },
            });
        }

        private void Client_DistributedNetworkStateChanged(object sender, DistributedNetworkInfo e)
        {
            State.SetValue(state => state with
            {
                DistributedNetwork = new DistributedNetworkState()
                {
                    BranchLevel = e.BranchLevel,
                    BranchRoot = e.BranchRoot,
                    CanAcceptChildren = e.CanAcceptChildren,
                    ChildLimit = e.ChildLimit,
                    Children = e.Children.Select(c => c.Username).ToList().AsReadOnly(),
                    HasParent = e.HasParent,
                    IsBranchRoot = e.IsBranchRoot,
                    Parent = e.Parent.Username,
                },
            });

            Metrics.DistributedNetwork.HasParent.Set(e.HasParent ? 1 : 0);
            Metrics.DistributedNetwork.BranchLevel.Set(e.BranchLevel);
            Metrics.DistributedNetwork.ChildLimit.Set(e.ChildLimit);
            Metrics.DistributedNetwork.Children.Set(e.Children.Count);
        }

        private void Clock_EveryMinute(object sender, ClockEventArgs e)
        {
            Metrics.DistributedNetwork.BroadcastLatency.Observe(Client.DistributedNetwork.AverageBroadcastLatency ?? 0);
            Metrics.DistributedNetwork.CurrentBroadcastLatency.Set(Client.DistributedNetwork.AverageBroadcastLatency ?? 0);
        }

        private void Clock_EveryFiveMinutes(object sender, ClockEventArgs e)
        {
            _ = Task.Run(() => PruneTransfers());
        }

        private void Clock_EveryThirtyMinutes(object sender, ClockEventArgs e)
        {
            _ = Task.Run(() => PruneFiles());
        }

        private void Clock_EveryHour(object sender, ClockEventArgs e)
        {
            _ = Task.Run(() => MaybeRescanShares());
        }

        private async Task MaybeRescanShares()
        {
            // ignore this if we're already scanning. there are multiple safeguards using
            // SemaphoreSlim later in the call chain if we manage to slip by somehow, though
            if (Shares.StateMonitor.CurrentValue.Scanning)
            {
                return;
            }

            var ttl = Options.Shares.Cache.Retention;

            // no configured TTL; never re-scan automatically
            if (!ttl.HasValue)
            {
                return;
            }

            // "x minutes ago"
            var cutoffTimestamp = DateTimeOffset.UtcNow
                .AddMinutes(-ttl.Value)
                .ToUnixTimeMilliseconds();

            // get a list of all scans that 1) started after our cutoff timestamp
            var scansInRange = await Shares.ListScansAsync(startedAtOrAfter: cutoffTimestamp);

            // 2) that succeeded (have a valid EndedAt)
            // and 3) have not been marked suspect
            // if there's no scan that meets all 3 criteria, try to re-scan
            if (!scansInRange.Any(s => s.EndedAt is not null && !s.Suspect))
            {
                Log.Information("Beginning scheduled re-scan of shares (previous scan is older than {Minutes} minutes)", ttl);

                // fire and forget. if something slips through the underlying logic will log.
                _ = Task.Run(() => Shares.ScanAsync());
            }
        }

        private void PruneFiles()
        {
            void PruneDirectory(int? age, string directory)
            {
                try
                {
                    if (!age.HasValue)
                    {
                        return;
                    }

                    Log.Debug("Pruning files older than {Age} minutes from {Directory}", age, directory);

                    var options = new EnumerationOptions
                    {
                        IgnoreInaccessible = true,
                        AttributesToSkip = FileAttributes.Hidden | FileAttributes.System,
                        RecurseSubdirectories = true,
                    };

                    var files = System.IO.Directory.GetFiles(directory, "*", options)
                        .Select(filename => new FileInfo(filename))
                        .Where(file => file.LastAccessTimeUtc <= DateTime.UtcNow.AddMinutes(-age.Value));

                    Log.Debug("Found {Count} files of need of pruning", files.Count());

                    int errors = 0;

                    foreach (var file in files)
                    {
                        try
                        {
                            file.Delete();
                        }
                        catch (Exception ex)
                        {
                            errors++;
                            Log.Warning(ex, "Failed to prune file {File}: {Message}", file, ex.Message);
                        }
                    }

                    Log.Debug("Pruning complete. Deleted: {Deleted}, Errors: {Errors}", files.Count() - errors, errors);
                }
                catch (Exception ex)
                {
                    Log.Error("Failed to prune files in directory {Directory}: {Message}", directory, ex.Message);
                }
            }

            PruneDirectory(age: Options.Retention.Files.Incomplete, directory: Options.Directories.Incomplete);
            PruneDirectory(age: Options.Retention.Files.Complete, directory: Options.Directories.Downloads);
        }

        private void PruneTransfers()
        {
            var options = OptionsMonitor.CurrentValue.Retention;

            void PruneUpload(int? age, TransferStates state)
            {
                if (age.HasValue)
                {
                    Transfers.Uploads.Prune(age.Value, TransferStates.Completed | state);
                }
            }

            void PruneDownload(int? age, TransferStates state)
            {
                if (age.HasValue)
                {
                    Transfers.Downloads.Prune(age.Value, TransferStates.Completed | state);
                }
            }

            try
            {
                PruneUpload(options.Transfers.Upload.Succeeded, TransferStates.Succeeded);
                PruneUpload(options.Transfers.Upload.Cancelled, TransferStates.Cancelled);
                PruneUpload(options.Transfers.Upload.Errored, TransferStates.Errored);

                PruneDownload(options.Transfers.Download.Succeeded, TransferStates.Succeeded);
                PruneDownload(options.Transfers.Download.Cancelled, TransferStates.Cancelled);
                PruneDownload(options.Transfers.Download.Errored, TransferStates.Errored);
            }
            catch
            {
                Log.Error("Encountered one or more errors while pruning transfers");
            }
        }

        private void Client_TransferProgressUpdated(object sender, TransferProgressUpdatedEventArgs args)
        {
            // no-op. this is really verbose, use for troubleshooting.
        }

        private void Client_TransferStateChanged(object sender, TransferStateChangedEventArgs args)
        {
            var xfer = args.Transfer;
            var direction = xfer.Direction.ToString().ToUpper();
            var user = xfer.Username;
            var file = Path.GetFileName(xfer.Filename);
            var oldState = args.PreviousState;
            var state = xfer.State;

            var completed = xfer.State.HasFlag(TransferStates.Completed);

            Log.Information($"[{direction}] [{user}/{file}] {oldState} => {state}{(completed ? $" ({xfer.BytesTransferred}/{xfer.Size} = {xfer.PercentComplete}%) @ {xfer.AverageSpeed.SizeSuffix()}/s" : string.Empty)}");

            if (xfer.Direction == TransferDirection.Upload && xfer.State.HasFlag(TransferStates.Completed | TransferStates.Succeeded) && args.Transfer.AverageSpeed > 0)
            {
                try
                {
                    _ = Client.SendUploadSpeedAsync(Convert.ToInt32(Math.Ceiling(args.Transfer.AverageSpeed)));
                }
                catch (Exception ex)
                {
                    Log.Error(ex, "Failed to report upload speed");
                }
            }
        }

        private void Client_UserStatusChanged(object sender, UserStatus args)
        {
            // todo: react to watched user status changes
        }

        private Task<int?> PlaceInQueueResolver(string username, IPEndPoint endpoint, string filename)
        {
            try
            {
                var place = Transfers.Uploads.Queue.EstimatePosition(username, filename);
                return Task.FromResult((int?)place);
            }
            catch (NotFoundException)
            {
                return Task.FromResult<int?>(null);
            }
            catch (Exception ex)
            {
                Log.Warning(ex, "Failed to estimate place in queue for {Filename} requested by {Username}", filename, username);
                throw;
            }
        }

        /// <summary>
        ///     Creates and returns a <see cref="Soulseek.Directory"/> in response to a remote request.
        /// </summary>
        /// <param name="username">The username of the requesting user.</param>
        /// <param name="endpoint">The IP endpoint of the requesting user.</param>
        /// <param name="token">The unique token for the request, supplied by the requesting user.</param>
        /// <param name="directory">The requested directory.</param>
        /// <returns>A Task resolving an instance of Soulseek.Directory containing the contents of the requested directory.</returns>
        private async Task<Soulseek.Directory> DirectoryContentsResponseResolver(string username, IPEndPoint endpoint, int token, string directory)
        {
            if (Users.IsBlacklisted(username, endpoint.Address))
            {
                Log.Information("Returned empty directory listing for blacklisted user {Username} ({IP})", username, endpoint.Address);
                return new Soulseek.Directory(directory);
            }

            try
            {
                var dir = await Shares.ListDirectoryAsync(directory);
                return dir;
            }
            catch (Exception ex)
            {
                Log.Warning(ex, "Failed to resolve directory contents: {Message}", ex.Message);
                throw;
            }
        }

        private async Task OptionsMonitor_OnChange(Options newOptions)
        {
            // this code is known to fire more than once per update. i'm not sure whether these might be executed concurrently.
            // lock to be safe, because we need to accurately track the last value of Options for diffing purposes. threading
            // shenanigans here could lead to missed updates.
            await OptionsSyncRoot.WaitAsync();

            try
            {
                var pendingRestart = false;
                var pendingReconnect = false;
                var soulseekRequiresReconnect = false;

                var diff = PreviousOptions.DiffWith(newOptions);

                // don't react to duplicate/no-change events https://github.com/slskd/slskd/issues/126
                if (!diff.Any())
                {
                    return;
                }

                foreach (var (property, fqn, left, right) in diff)
                {
                    static bool HasAttribute<T>(PropertyInfo property) => property.CustomAttributes.Any(a => a.AttributeType == typeof(T));

                    var requiresRestart = HasAttribute<RequiresRestartAttribute>(property);
                    var requiresReconnect = HasAttribute<RequiresReconnectAttribute>(property);

                    Log.Debug($"{fqn} changed from '{left.ToJson() ?? "<null>"}' to '{right.ToJson() ?? "<null>"}'{(requiresRestart ? ". Restart required to take effect." : string.Empty)}{(requiresReconnect ? "; Reconnect required to take effect." : string.Empty)}");

                    pendingRestart |= requiresRestart;
                    pendingReconnect |= requiresReconnect;
                }

                if (PreviousOptions.Shares.Directories.Except(newOptions.Shares.Directories).Any()
                    || newOptions.Shares.Directories.Except(PreviousOptions.Shares.Directories).Any())
                {
                    State.SetValue(state => state with { Shares = state.Shares with { ScanPending = true } });
                    Log.Information("Shared directory configuration changed.  Shares must be re-scanned for changes to take effect.");
                }

                if (PreviousOptions.Shares.Filters.Except(newOptions.Shares.Filters).Any()
                    || newOptions.Shares.Filters.Except(PreviousOptions.Shares.Filters).Any())
                {
                    State.SetValue(state => state with { Shares = state.Shares with { ScanPending = true } });
                    Log.Information("File filter configuration changed.  Shares must be re-scanned for changes to take effect.");
                }

                if (PreviousOptions.Filters.Search.Request.Except(newOptions.Filters.Search.Request).Any()
                    || newOptions.Filters.Search.Request.Except(PreviousOptions.Filters.Search.Request).Any())
                {
                    CompiledSearchResponseFilters = newOptions.Filters.Search.Request.Select(f => new Regex(f, RegexOptions.Compiled));
                    Log.Information("Updated and re-compiled search response filters");
                }

                if (PreviousOptions.Rooms.Except(newOptions.Rooms).Any()
                    || newOptions.Rooms.Except(PreviousOptions.Rooms).Any())
                {
                    Log.Information("Room configuration changed.  Joining any newly added rooms.");
                    _ = RoomService.TryJoinAsync(newOptions.Rooms);
                }

                // determine whether any Soulseek options changed. if so, we need to construct a patch and invoke ReconfigureOptionsAsync().
                var slskDiff = PreviousOptions.Soulseek.DiffWith(newOptions.Soulseek);
                var globalDiff = PreviousOptions.Global.DiffWith(newOptions.Global);

                if (slskDiff.Any() || globalDiff.Any())
                {
                    var old = PreviousOptions.Soulseek;
                    var update = newOptions.Soulseek;

                    Log.Debug("Soulseek options changed from {Previous} to {Current}", old.ToJson(), update.ToJson());

                    // determine whether any Connection options changed. if so, replace the whole object. Soulseek.NET doesn't
                    // offer a way to patch parts of connection options. the updates only affect new connections, so a partial
                    // patch doesn't make a lot of sense anyway.
                    var connectionDiff = old.Connection.DiffWith(update.Connection);

                    ConnectionOptions connectionPatch = null;
                    ConnectionOptions serverPatch = null;
                    ConnectionOptions distributedPatch = null;
                    ConnectionOptions transferPatch = null;

                    if (connectionDiff.Any())
                    {
                        var connection = update.Connection;

                        ProxyOptions proxyPatch = null;

                        if (connection.Proxy.Enabled)
                        {
                            proxyPatch = new ProxyOptions(
                                address: connection.Proxy.Address,
                                port: connection.Proxy.Port.Value,
                                username: connection.Proxy.Username,
                                password: connection.Proxy.Password);
                        }

                        connectionPatch = new ConnectionOptions(
                            readBufferSize: connection.Buffer.Read,
                            writeBufferSize: connection.Buffer.Write,
                            writeQueueSize: connection.Buffer.WriteQueue,
                            connectTimeout: connection.Timeout.Connect,
                            inactivityTimeout: connection.Timeout.Inactivity,
                            proxyOptions: proxyPatch);

                        var configureKeepAlive = new Action<Socket>(socket =>
                        {
                            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);
                            socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveTime, connection.Timeout.Inactivity / 1000);
                            socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveInterval, connection.Timeout.Inactivity / 1000);
                            socket.SetSocketOption(SocketOptionLevel.Tcp, SocketOptionName.TcpKeepAliveRetryCount, 3);
                        });

                        serverPatch = connectionPatch.With(configureSocketAction: configureKeepAlive);
                        distributedPatch = connectionPatch.With(configureSocketAction: configureKeepAlive);

                        transferPatch = connectionPatch.With(
                            readBufferSize: OptionsAtStartup.Soulseek.Connection.Buffer.Transfer,
                            writeBufferSize: OptionsAtStartup.Soulseek.Connection.Buffer.Transfer);
                    }

                    var patch = new SoulseekClientOptionsPatch(
                        listenIPAddress: old.ListenIpAddress == update.ListenIpAddress ? null : IPAddress.Parse(update.ListenIpAddress),
                        listenPort: old.ListenPort == update.ListenPort ? null : update.ListenPort,
                        enableDistributedNetwork: old.DistributedNetwork.Disabled == update.DistributedNetwork.Disabled ? null : !update.DistributedNetwork.Disabled,
                        distributedChildLimit: old.DistributedNetwork.ChildLimit == update.DistributedNetwork.ChildLimit ? null : update.DistributedNetwork.ChildLimit,
                        acceptDistributedChildren: old.DistributedNetwork.DisableChildren == update.DistributedNetwork.DisableChildren ? null : !update.DistributedNetwork.DisableChildren,
                        maximumUploadSpeed: newOptions.Global.Upload.SpeedLimit,
                        maximumDownloadSpeed: newOptions.Global.Download.SpeedLimit,
                        serverConnectionOptions: serverPatch,
                        peerConnectionOptions: connectionPatch,
                        transferConnectionOptions: transferPatch,
                        incomingConnectionOptions: connectionPatch,
                        distributedConnectionOptions: distributedPatch);

                    soulseekRequiresReconnect = await Client.ReconfigureOptionsAsync(patch);
                }

                // require a reconnect if the client is connected and any options marked [RequiresReconnect] changed, OR if the
                // call to reconfigure the client requires a reconnect
                if ((Client.State.HasFlag(SoulseekClientStates.Connected) && pendingReconnect) || soulseekRequiresReconnect)
                {
                    State.SetValue(state => state with { PendingReconnect = true });
                    Log.Information("One or more updated Soulseek options requires the client to be disconnected, then reconnected to the network to take effect.");
                }

                if (pendingRestart)
                {
                    State.SetValue(state => state with { PendingRestart = true });
                    Log.Information("One or more updated options requires an application restart to take effect.");
                }

                PreviousOptions = newOptions;
                _ = ApplicationHub.BroadcastOptionsAsync(newOptions);

                Log.Information("Options updated successfully.");
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Failed to apply option update: {Message}", ex.Message);
            }
            finally
            {
                OptionsSyncRoot.Release();
            }
        }

        /// <summary>
        ///     Creates and returns a <see cref="Response"/> in response to the given <paramref name="query"/>.
        /// </summary>
        /// <param name="username">The username of the requesting user.</param>
        /// <param name="token">The search token.</param>
        /// <param name="query">The search query.</param>
        /// <returns>A Task resolving a SearchResponse, or null.</returns>
        private async Task<SearchResponse> SearchResponseResolver(string username, int token, SearchQuery query)
        {
            Metrics.Search.RequestsReceived.Inc(1);

            if (Users.IsBlacklisted(username))
            {
                Log.Information("Returned empty search response for blacklisted user {Username}", username);
                return new SearchResponse(username, token, hasFreeUploadSlot: false, uploadSpeed: 0, queueLength: int.MaxValue, fileList: Enumerable.Empty<Soulseek.File>());
            }

            if (CompiledSearchResponseFilters.Any(filter => filter.IsMatch(query.SearchText)))
            {
                return null;
            }

            // sometimes clients send search queries consisting only of exclusions; drop them.
            // no other clients send search results for these, even though it is technically possible.
            if (!query.Terms.Any())
            {
                return null;
            }

            try
            {
                var sw = new Stopwatch();
                sw.Start();

                var results = await Shares.SearchAsync(query);

                sw.Stop();

                Metrics.Search.ResponseLatency.Observe(sw.ElapsedMilliseconds);
                Metrics.Search.CurrentResponseLatency.Update(sw.ElapsedMilliseconds);

                if (results.Any())
                {
                    // make sure our average speed (as reported by the server) is reasonably up to date
                    await RefreshUserStatistics();

                    // note: the following uses cached user data to determine group, so if the user's data
                    // isn't cached they may get a forecast based on the wrong group.  this is a hot path though,
                    // and we don't want to incur the massive penalties that would caching data for each request.
                    var forecastedPosition = Transfers.Uploads.Queue.ForecastPosition(username);

                    Log.Information("[{Context}]: Sending {Count} records to {Username} for query '{Query}'", "SEARCH RESULT SENT", results.Count(), username, query.SearchText);

                    Metrics.Search.ResponsesSent.Inc(1);

                    return new SearchResponse(
                        Client.Username,
                        token,
                        uploadSpeed: State.CurrentValue.User.Statistics.AverageSpeed,
                        hasFreeUploadSlot: forecastedPosition == 0,
                        queueLength: forecastedPosition,
                        fileList: results);
                }

                // if no results, either return null or an instance of SearchResponse with a fileList of length 0 in either case, no
                // response will be sent to the requestor.
                return null;
            }
            catch (Exception ex)
            {
                Log.Warning(ex, "Failed to resolve search response: {Message}", ex.Message);
                throw;
            }
        }

        private void ShareState_OnChange((ShareState Previous, ShareState Current) state)
        {
            var (previous, current) = state;
            bool rebuildBrowseCache = false;

            if (!previous.Scanning && current.Scanning)
            {
                // the scan is starting. update the application state without manipulation
                SharesRefreshStarted = DateTime.UtcNow;

                State.SetValue(s => s with { Shares = current });

                Log.Information("Share scan started");
            }
            else if (previous.Scanning && !current.Scanning)
            {
                // the scan is finishing. update the application state without manipulation...
                State.SetValue(s => s with { Shares = current });

                if (current.Faulted)
                {
                    Log.Error("Failed to scan shares.");
                }
                else
                {
                    // ...but if it completed successfully, immediately update again to lower the pending flag
                    State.SetValue(state => state with { Shares = state.Shares with { ScanPending = false } });
                    Log.Information("Shares scanned successfully. Found {Directories} directories and {Files} files in {Duration}ms", current.Directories, current.Files, (DateTime.UtcNow - SharesRefreshStarted).TotalMilliseconds);

                    SharesRefreshStarted = default;

                    if (Client.State.HasFlag(SoulseekClientStates.Connected | SoulseekClientStates.LoggedIn))
                    {
                        _ = Task.Run(async () =>
                        {
                            await Client.SetSharedCountsAsync(State.CurrentValue.Shares.Directories, State.CurrentValue.Shares.Files);
                            await RefreshUserStatistics(force: true);
                        });
                    }
                }
            }
            else if (!previous.Ready && current.Ready)
            {
                // the share transitioned into ready without completing a scan; it was loaded from disk
                // this will (or should) also be true when the scan completes, which is why the code is using an else if here,
                // but only if it happens without a corresponding lowering of the scanning flag do we want to execute this.
                State.SetValue(state => state with { Shares = current with { ScanPending = false } });
                Log.Information("Share cache loaded from disk successfully. Sharing {Directories} directories and {Files} files", current.Directories, current.Files);
                rebuildBrowseCache = true;
            }
            else
            {
                // the scan is neither starting nor finishing; this is a status update of some sort,
                // not a state change. we want to clamp the frequency of these during a scan to avoid overwhelming clients,
                // only update if the progress has changed by at least 1%.
                var lastProgress = Math.Round(previous.ScanProgress * 100);
                var currentProgress = Math.Round(current.ScanProgress * 100);

                if (lastProgress != currentProgress && Math.Round(currentProgress, 0) % 1d == 0)
                {
                    State.SetValue(s => s with { Shares = current });
                    Log.Information("Scanned {Percent}% of shared directories. Found {Files} files so far.", currentProgress, current.Files);
                }
            }

            // if the host configuration changed, update *just* the hosts to avoid stepping on anything that might
            // have also happened above. a change in hosts will invalidate the cache, so do that too.
            if (previous.Hosts.ToJson() != current.Hosts.ToJson())
            {
                State.SetValue(state => state with
                {
                    Shares = state.Shares with
                    {
                        Hosts = current.Hosts,
                        Directories = current.Directories,
                        Files = current.Files,
                    },
                });

                rebuildBrowseCache = true;
            }

            // if a scan just completed successfully (but not failed!), shares were loaded from disk, or
            // host configuration changed, rebuild caches and upload shares to the network controller (if connected)
            if (rebuildBrowseCache)
            {
                _ = CacheBrowseResponse();
                _ = Relay.Client.SynchronizeAsync();
            }
        }

        private async Task<BrowseResponse> CacheBrowseResponse()
        {
            try
            {
                var sw = new Stopwatch();
                sw.Start();

                var directories = await Shares.BrowseAsync();
                var response = new BrowseResponse(directories);
                var temp = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
                var destination = Path.Combine(Program.DataDirectory, "browse.cache");

                Log.Information("Warming browse response cache...");
                await System.IO.File.WriteAllBytesAsync(temp, response.ToByteArray());

                Log.Debug("Saved cache to temp file {File}", temp);

                System.IO.File.Move(temp, destination, overwrite: true);

                sw.Stop();
                Log.Information("Browse response cached successfully in {Duration}ms", sw.ElapsedMilliseconds);
                return response;
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Error caching browse response: {Message}", ex.Message);
                throw;
            }
        }

        private void State_OnChange((State Previous, State Current) state)
        {
            _ = ApplicationHub.BroadcastStateAsync(state.Current);
        }

        /// <summary>
        ///     Creates and returns a <see cref="UserInfo"/> object in response to a remote request.
        /// </summary>
        /// <param name="username">The username of the requesting user.</param>
        /// <param name="endpoint">The IP endpoint of the requesting user.</param>
        /// <returns>A Task resolving the UserInfo instance.</returns>
        private async Task<UserInfo> UserInfoResolver(string username, IPEndPoint endpoint)
        {
            if (Users.IsBlacklisted(username, endpoint.Address))
            {
                return new UserInfo(
                    description: Options.Soulseek.Description,
                    uploadSlots: 0,
                    queueLength: int.MaxValue,
                    hasFreeUploadSlot: false);
            }

            try
            {
                // note: users must first be watched or cached for leech and privilege detection to work.
                // we are deliberately skipping it here; if the username is watched
                // leech detection works and they get accurate info, if not, they won't
                var groupName = await Users.GetOrFetchGroupAsync(username);
                var group = Transfers.Uploads.Queue.GetGroupInfo(groupName);

                // forecast the position at which this user would enter the queue if they were to request
                // a file at this moment. this will be zero if a slot is available and the transfer would
                // begin immediately
                var forecastedPosition = Transfers.Uploads.Queue.ForecastPosition(username);

                // if i get a user's info to determine whether i want to download files from them,
                // i want to know how many slots they have, which gives me an idea of how fast their
                // queue moves, and the length of the queue *ahead of me*, meaning how long i'd have to
                // wait until my first download starts.
                var info = new UserInfo(
                    description: Options.Soulseek.Description,
                    uploadSlots: group.Slots,
                    queueLength: forecastedPosition,
                    hasFreeUploadSlot: forecastedPosition == 0);

                return info;
            }
            catch (Exception ex)
            {
                Log.Warning(ex, "Failed to resolve user info: {Message}", ex.Message);
                throw;
            }
        }
    }
}