Compare commits

..

108 Commits

Author SHA1 Message Date
JustArchi
91a96990aa Add !redeem^ 2016-09-22 19:27:16 +02:00
JustArchi
abff9bd28d Code review 2016-09-21 19:26:20 +02:00
JustArchi
e2a8c14a0d Code review 2016-09-21 18:22:27 +02:00
JustArchi
6489502be7 Misc 2016-09-21 16:10:28 +02:00
JustArchi
f6e7c06141 Code review 2016-09-21 15:56:35 +02:00
JustArchi
3548411cda Misc 2016-09-21 15:37:39 +02:00
JustArchi
43ce5eb257 Misc 2016-09-21 15:35:13 +02:00
JustArchi
2756a2ebc7 Shutdown double instances 2016-09-21 15:34:29 +02:00
JustArchi
d3470624bc Log processID too 2016-09-21 15:22:42 +02:00
JustArchi
0439656499 Misc 2016-09-20 16:29:13 +02:00
JustArchi
dc1ae32d37 Slightly improve key data updates 2016-09-20 16:05:04 +02:00
JustArchi
b3b07a465b Misc optimization 2016-09-20 15:37:40 +02:00
JustArchi
e6fff8c6bd Bump 2016-09-18 22:27:29 +02:00
JustArchi
b010009a2d AppVeyor: Skip build status changes 2016-09-18 22:15:06 +02:00
JustArchi
444eb97f49 Remove time left from !2fa
It doesn't make any sense if code works for ~2 minutes anyway
2016-09-18 22:10:11 +02:00
JustArchi
fbbe3c1d09 Partially revert < 5 seconds waits
It seems that Valve actually accepts not one but several tokens generated close to the point of request being sent, so our 2FA code will be always valid for 1-2 more minutes after supposed timeout...
2016-09-18 20:31:06 +02:00
JustArchi
69bf0022d5 Don't use MONO_DNS 2016-09-18 11:15:24 +02:00
JustArchi
ac6e9bc15a Bump 2016-09-17 05:45:07 +02:00
JustArchi
1df2c3b042 Implement my previous idea
Thanks to that, we can guarantee some room for networking, but also make users more happy as they'll never get 2FA tokens no human is capable of entering in time
2016-09-16 23:40:52 +02:00
JustArchi
160bfd612f Approach the problem in better way
The general problem is a mix of a few things: The fact that we don't have much time before steam network disconnects us, if we connect to it and not send log in request in acceptable time, the fact that Steam API might be unavailable and not provide us with server time, and the fact that we must know that time to generate valid tokens.
Previous solution would simply generate token immediately without asking Steam API, and schedule update in background for later, so even if we had incorrect time and failure of first try, second try would usually come with the right clock. If not, eventually we'd succeed anyway.
However, it's possible to slightly improve that - we can generate 2FA code BEFORE even connecting to steam network, this way we have time to ask Steam API, and in worst case of API timeout we'll simply try with our own clock anyway, and if it succeeds, timeframe before connecting and sending logon request should be small enough to fit - in worst case of being on the edge of 30 seconds, we'll simply try again later.
Perhaps it'd also make sense to modify slightly MobileAuthenticator to block and wait in case code is expiring in less than 5 seconds, that could be cool too!
2016-09-16 23:09:09 +02:00
JustArchi
feb80fbf49 Revert "Fix logging in when steam API is unavailable"
This reverts commit 5a267eb225.
2016-09-16 22:46:10 +02:00
JustArchi
5a267eb225 Fix logging in when steam API is unavailable
Or at least part of it...
2016-09-14 19:00:03 +02:00
JustArchi
ccfad31053 Misc 2016-09-14 18:43:34 +02:00
JustArchi
bd3dfa3664 Bump 2016-09-13 03:15:55 +02:00
JustArchi
18c6fd639a Misc 2016-09-13 03:12:58 +02:00
JustArchi
75e3ef9818 SteamClient.IsConnected hardening 2016-09-13 02:58:22 +02:00
JustArchi
44b401aabd Never override existing values 2016-09-12 21:01:09 +02:00
JustArchi
4d6f2811bb Unify mono params 2016-09-12 20:52:30 +02:00
JustArchi
11d4430bbc Rename Steam contextID to match ArchiBoT 2016-09-12 05:54:34 +02:00
JustArchi
0cea70ef6a Rename card checks methods to match ArchiBoT 2016-09-12 03:49:17 +02:00
JustArchi
e4df12fc5b Misc 2016-09-11 16:37:18 +02:00
JustArchi
19818f126f Bump 2016-09-09 02:53:33 +02:00
JustArchi
f2a2f93273 Allow an hour of time difference with offline messages 2016-09-09 02:50:13 +02:00
JustArchi
e6d4304ca1 Misc consistency 2016-09-05 20:21:50 +02:00
JustArchi
e020f54753 Optimize SteamTimeDifference
In very unlikely case of actually having exactly the same time difference, notice the difference between no value and value of 0
2016-09-05 18:46:00 +02:00
JustArchi
cada3fa920 Don't use bashisms in envsetup 2016-09-02 18:57:13 +02:00
JustArchi
2c99c4b433 Misc 2016-09-02 18:41:40 +02:00
JustArchi
a25a181cd9 Don't use bashisms in post-build scripts
They're always run with /bin/sh and that doesn't always equal to bash
2016-09-02 11:40:30 +02:00
Łukasz Domeradzki
5f3a6d4c10 Update CONTRIBUTING.md 2016-09-02 10:58:38 +02:00
JustArchi
3e82c9f11e Misc 2016-08-31 14:19:27 +02:00
JustArchi
bed87c4c80 Integrate DebugListener with Logger 2016-08-31 13:56:09 +02:00
JustArchi
37f5f82cf8 Bump 2016-08-31 09:27:33 +02:00
JustArchi
ff00b3049a Correct LoginID to use 0
It seems that some broken OSes actually can lead to result of obfuscation mask instead of real value, so ASF shouldn't use it
2016-08-30 17:42:01 +02:00
JustArchi
b316d3b03a Don't attempt to farm hours if we have only 1 game left to farm
FarmSolo() function allows more precise tracking, and FarmMultiple() shouldn't be used only with 1 game
2016-08-30 14:05:03 +02:00
JustArchi
3f735d165c Misc 2016-08-30 13:54:40 +02:00
JustArchi
abde04cc83 Misc 2016-08-30 13:46:42 +02:00
JustArchi
e606ca05ed Bump 2016-08-30 12:53:42 +02:00
JustArchi
e0dbd70b37 Final attempt to fix #318 2016-08-30 12:45:02 +02:00
JustArchi
d37f5bb250 Maintain debug directory for each bot 2016-08-30 10:16:22 +02:00
JustArchi
fdd9744556 Add standard PP donate option
As per request
2016-08-28 22:58:42 +02:00
JustArchi
3814bd64f0 Bump 2016-08-27 10:15:11 +02:00
JustArchi
98679545d3 Give up, Mono in travis is truly broken 2016-08-27 10:02:05 +02:00
JustArchi
49b1259817 Misc 2016-08-27 09:56:52 +02:00
JustArchi
0c14128b63 Final try 2016-08-27 09:53:30 +02:00
JustArchi
c115158279 More debug 2016-08-27 09:45:55 +02:00
JustArchi
2a61ecb681 Attempt to fix Mono weekly in travis (once again) 2016-08-27 09:34:08 +02:00
JustArchi
d06fbda6d6 Prefer 64-bit ASF
ASF is AnyCPU binary which means it'll run fine on both 32-bit as well as 64-bit OSes.
Up to today 32-bit runtime was preferred for ASF, as it uses less memory and can be faster than 64-bit equivalent.
However, in very busy environments it's easily possible for ASF to require even more than 2 GB of memory, and in addition to that extending our userspace to 64-bit can bring benefits on more modern setups.
Therefore, keep being compatible on both 32-bit and 64-bit OSes, but on 64-bit ones use actual 64-bit runtime instead of preferred 32-bit one.
In addition to that, optimize some unused references and other things while we're at it.
2016-08-27 08:40:40 +02:00
JustArchi
7ba2e829d3 Code review 2016-08-22 00:10:29 +02:00
JustArchi
58ff2a2a4d Bump 2016-08-21 22:41:19 +02:00
JustArchi
d6c9fe3cde Add workarounds for #335 2016-08-21 22:35:31 +02:00
JustArchi
4b782bd10d Bump 2016-08-21 18:15:03 +02:00
JustArchi
1a1e48a33d Bump 2016-08-21 18:06:50 +02:00
JustArchi
f7d7c559b8 Derp 2016-08-21 18:04:48 +02:00
JustArchi
602cda73b7 Closes #335
We need to alter the flow in order to check for result updates on each loop instead of the beginning
2016-08-21 18:03:56 +02:00
Łukasz Domeradzki
f579462f60 Update CONTRIBUTING.md 2016-08-21 03:50:54 +02:00
JustArchi
8066f1a7c0 Don't attempt to loot foils if !IsBotAccount
Rationale: Foil cards are excluded from STM, as the price varies. For most people with !IsBotAccount that will be main account, which should never be lootable, and for people running bots for friends, making them keep foils makes sense. The main reason for this change is my own setup in which I'd like to automatically send all cards to ArchiBoT for 1:1 matching, but keep foils for selling.
2016-08-20 00:35:33 +02:00
JustArchi
f8409e1be6 Misc 2016-08-19 17:49:56 +02:00
Łukasz Domeradzki
c36eeb8c28 Update CONTRIBUTING.md 2016-08-19 15:11:49 +02:00
JustArchi
d0344a7ab9 Misc code review 2016-08-19 05:25:08 +02:00
JustArchi
2c767bfe85 Misc 2016-08-19 05:08:37 +02:00
JustArchi
2816ecaa90 Further optimize InMemoryServerListProvider and make it thread-safe 2016-08-19 04:57:21 +02:00
JustArchi
214746bca2 Optimize updating of server list
We can compare new endpoints firstly, to save Save() call if they're equal values-wise.
2016-08-19 04:10:49 +02:00
JustArchi
134aa62952 Seems to work properly 2016-08-15 22:00:32 +02:00
JustArchi
5a4132a679 More tests 2016-08-15 21:57:45 +02:00
JustArchi
edb047980e Extend logic for trades 2016-08-15 21:47:31 +02:00
JustArchi
7d32adac13 Perform loot also on new items received, if we're not farming 2016-08-15 21:35:19 +02:00
JustArchi
95637ea3a7 Improve trading failure handling
It seems that even if Steam responds with e.g. internal server error (500), the trade gets accepted 20-30 seconds later, which doesn't make ANY sense, but does anything in Steam do?
Let's improve the logic a bit by returning result even if we in fact failed in Accept/Decline function, this will allow us to deal with confirmations even if failed trade in fact succeeded.
2016-08-14 00:19:01 +02:00
JustArchi
02a547e7d2 Misc 2016-08-13 15:58:00 +02:00
JustArchi
9594357d56 Misc code analysis fixes 2016-08-13 04:39:17 +02:00
JustArchi
ce166baab6 Bump 2016-08-13 04:27:04 +02:00
JustArchi
1ec0b20604 Misc 2016-08-13 04:19:20 +02:00
JustArchi
26bd76cc4a Make debugging easier for me
Modification of ASF.json is troublesome when I work with GitHub tree, therefore make it possible for me to execute and test commands but only in debugging builds - public ASF releases are always compiled in release mode.
2016-08-13 04:12:39 +02:00
JustArchi
8e1d02f43f Implement !ownsall, closes #330 2016-08-13 04:04:47 +02:00
JustArchi
b802822699 Correct #329 a bit 2016-08-12 23:07:19 +02:00
JustArchi
be77e8d380 Update README.md
Drop support for Vista, as it's not supported in .NET 4.6.1+
2016-08-10 22:03:31 +02:00
JustArchi
000b902ced Categorize options in ConfigGenerator
Preview: http://i.imgur.com/Noc8qbf.png
2016-08-10 18:03:14 +02:00
JustArchi
d09be453f3 Misc 2016-08-09 04:05:01 +02:00
JustArchi
5f1342ae26 Add extra check after waiting in OnDisconnected()
If for some reason this callback gets executed twice, we don't want to issue second connect request in any case
2016-08-09 04:04:22 +02:00
JustArchi
00b4c28843 Respect LimitLoginRequestsAsync() in HeartBeat() 2016-08-09 03:46:45 +02:00
JustArchi
cb6cfd08c2 Improve load-balancing 2016-08-08 20:10:04 +02:00
JustArchi
f53911bd9a Misc 2016-08-08 20:07:40 +02:00
JustArchi
527641439b Implement enhanced HeartBeat
The objective of this feature is to detect network malfunctions as well as SK2 connection issues early and initiate a reconnect as soon as possible, instead of relying on failures in SK2 code.
This is because those failures are very usually coming too late, when connection was already lost for a dozen or more minutes behind, and it also increases likehood of getting weird SK2 freezes like the one in #318.
Therefore, let's see how it works, it's possible that I'll revert it later when SK2 code improves or we find a better way to do that. The introduced overhead both CPU-wise and bandwidth-wise is negligible.
2016-08-08 20:06:20 +02:00
JustArchi
647a0ee865 Revert "Prepare for custom HeartBeat handling"
This reverts commit b9f2dd1292.
2016-08-08 18:47:23 +02:00
JustArchi
b9f2dd1292 Prepare for custom HeartBeat handling 2016-08-08 18:23:15 +02:00
JustArchi
e675a3a488 Enhance startup sequence a bit 2016-08-06 22:16:46 +02:00
JustArchi
fb8692d28c Misc enhancements 2016-08-06 16:29:05 +02:00
JustArchi
cf4141dde7 Remove debug routines 2016-08-05 20:43:30 +02:00
JustArchi
963f56ccf2 Bump 2016-08-05 03:16:12 +02:00
JustArchi
c754a18603 Fix games with over 255 card drops not being recognized
I never expected somebody to reach that many
2016-08-05 03:11:27 +02:00
JustArchi
eb886e8ca8 Move logging module initialization after setting home directory 2016-08-04 22:44:17 +02:00
JustArchi
e8889fb087 Add one more status case 2016-08-04 15:11:23 +02:00
JustArchi
d627a5ee9d Require .NET 4.6.1+ 2016-08-03 20:07:46 +02:00
JustArchi
35bd36bbd9 Change download count to latest stable only 2016-08-03 18:03:02 +02:00
JustArchi
d79944085f Fix Mono compilation 2016-08-03 17:38:25 +02:00
JustArchi
4e191367da Bump 2016-08-03 17:32:06 +02:00
JustArchi
f88bfe9f83 Make CardDropsRestricted true by default
After evaluation, it seems that more accounts have card drops restricted rather than not, and having it as true when in reality it's false results in less performance degradation than the other way
2016-08-03 17:16:11 +02:00
JustArchi
86aa9e781d Travis: Allow failure on Mono weekly
It's broken more often than it works, I don't need to be informed about that
2016-08-03 03:20:42 +02:00
JustArchi
6ae7e74daf Bump 2016-08-03 02:53:47 +02:00
44 changed files with 865 additions and 474 deletions

View File

@@ -6,8 +6,19 @@ git:
mono:
- weekly
# - alpha
# - beta
- latest
matrix:
allow_failures:
- mono: weekly
# - mono: alpha
# - mono: beta
before_script:
- source mono_envsetup.sh
notifications:
email: false
webhooks:

View File

@@ -11,6 +11,9 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ConfigGenerator", "ConfigGe
EndProjectSection
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "GUI", "GUI\GUI.csproj", "{13949B41-787C-4558-90AE-A9F9E7F86B1F}"
ProjectSection(ProjectDependencies) = postProject
{35AF7887-08B9-40E8-A5EA-797D8B60B30C} = {35AF7887-08B9-40E8-A5EA-797D8B60B30C}
EndProjectSection
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution

View File

@@ -30,7 +30,6 @@ using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using ArchiSteamFarm.JSON;
using Newtonsoft.Json;
namespace ArchiSteamFarm {
internal static class ASF {
@@ -75,29 +74,16 @@ namespace ArchiSteamFarm {
Logging.LogGenericInfo("Checking new version...");
string response = await Program.WebBrowser.UrlGetToContentRetry(releaseURL).ConfigureAwait(false);
if (string.IsNullOrEmpty(response)) {
Logging.LogGenericWarning("Could not check latest version!");
return;
}
GitHub.ReleaseResponse releaseResponse;
if (Program.GlobalConfig.UpdateChannel == GlobalConfig.EUpdateChannel.Stable) {
try {
releaseResponse = JsonConvert.DeserializeObject<GitHub.ReleaseResponse>(response);
} catch (JsonException e) {
Logging.LogGenericException(e);
releaseResponse = await Program.WebBrowser.UrlGetToJsonResultRetry<GitHub.ReleaseResponse>(releaseURL).ConfigureAwait(false);
if (releaseResponse == null) {
Logging.LogGenericWarning("Could not check latest version!");
return;
}
} else {
List<GitHub.ReleaseResponse> releases;
try {
releases = JsonConvert.DeserializeObject<List<GitHub.ReleaseResponse>>(response);
} catch (JsonException e) {
Logging.LogGenericException(e);
return;
}
List<GitHub.ReleaseResponse> releases = await Program.WebBrowser.UrlGetToJsonResultRetry<List<GitHub.ReleaseResponse>>(releaseURL).ConfigureAwait(false);
if ((releases == null) || (releases.Count == 0)) {
Logging.LogGenericWarning("Could not check latest version!");
return;

View File

@@ -75,10 +75,7 @@ namespace ArchiSteamFarm {
return;
}
Notifications = new HashSet<ENotification>();
foreach (CMsgClientUserNotifications.Notification notification in msg.notifications) {
Notifications.Add((ENotification) notification.user_notification_type);
}
Notifications = new HashSet<ENotification>(msg.notifications.Select(notification => (ENotification) notification.user_notification_type));
}
internal NotificationsCallback(JobID jobID, CMsgClientItemAnnouncements msg) {

View File

@@ -38,8 +38,9 @@
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>3</WarningLevel>
<WarningLevel>4</WarningLevel>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
@@ -53,7 +54,7 @@
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
<DocumentationFile>
</DocumentationFile>
<Prefer32Bit>true</Prefer32Bit>
<Prefer32Bit>false</Prefer32Bit>
<GenerateSerializationAssemblies>Auto</GenerateSerializationAssemblies>
<UseVSHostingProcess>false</UseVSHostingProcess>
</PropertyGroup>
@@ -61,7 +62,7 @@
<ApplicationIcon>cirno.ico</ApplicationIcon>
</PropertyGroup>
<PropertyGroup>
<RunPostBuildEvent>OnBuildSuccess</RunPostBuildEvent>
<RunPostBuildEvent>OnOutputUpdated</RunPostBuildEvent>
</PropertyGroup>
<PropertyGroup>
<SignAssembly>false</SignAssembly>
@@ -95,18 +96,14 @@
<Private>True</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Configuration.Install" />
<Reference Include="System.Core" />
<Reference Include="System.Data" />
<Reference Include="System.IO.Compression" />
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.Security" />
<Reference Include="System.ServiceModel" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Net.Http" />
<Reference Include="System.ServiceProcess" />
<Reference Include="System.Transactions" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
@@ -191,11 +188,15 @@
copy "$(TargetDir)$(TargetName).exe" "$(SolutionDir)out\ASF.exe"
</PostBuildEvent>
<PostBuildEvent Condition=" '$(OS)' == 'Unix' AND '$(ConfigurationName)' == 'Release' ">
if [ -f "$(SolutionDir)mono_envsetup.sh" ]; then
. "$(SolutionDir)mono_envsetup.sh"
fi
mkdir -p "$(SolutionDir)out/config"
cp "$(TargetDir)config/ASF.json" "$(SolutionDir)out/config"
cp "$(TargetDir)config/example.json" "$(SolutionDir)out/config"
cp "$(TargetDir)config/minimal.json" "$(SolutionDir)out/config"
mono --llvm --server -O=all "$(SolutionDir)tools/ILRepack/ILRepack.exe" /ndebug /internalize /parallel /targetplatform:v4 /wildcards /out:"$(SolutionDir)out/ASF-Service.exe" "$(TargetDir)$(TargetName).exe" "$(TargetDir)*.dll"
mono "$(SolutionDir)tools/ILRepack/ILRepack.exe" /ndebug /internalize /parallel /targetplatform:v4 /wildcards /out:"$(SolutionDir)out/ASF-Service.exe" "$(TargetDir)$(TargetName).exe" "$(TargetDir)*.dll"
rm "$(SolutionDir)out/ASF-Service.exe.config"
cp "$(SolutionDir)out/ASF-Service.exe" "$(SolutionDir)out/ASF.exe"
</PostBuildEvent>

View File

@@ -166,8 +166,8 @@ namespace ArchiSteamFarm {
internal void OnDisconnected() => Ready = false;
internal async Task<bool> Init(ulong steamID, EUniverse universe, string webAPIUserNonce, string parentalPin) {
if ((steamID == 0) || (universe == EUniverse.Invalid) || string.IsNullOrEmpty(webAPIUserNonce)) {
Logging.LogNullError(nameof(steamID) + " || " + nameof(universe) + " || " + nameof(webAPIUserNonce), Bot.BotName);
if ((steamID == 0) || (universe == EUniverse.Invalid) || string.IsNullOrEmpty(webAPIUserNonce) || string.IsNullOrEmpty(parentalPin)) {
Logging.LogNullError(nameof(steamID) + " || " + nameof(universe) + " || " + nameof(webAPIUserNonce) + " || " + nameof(parentalPin), Bot.BotName);
return false;
}
@@ -217,19 +217,29 @@ namespace ArchiSteamFarm {
return false;
}
Logging.LogGenericInfo("Success!", Bot.BotName);
WebBrowser.CookieContainer.Add(new Cookie("sessionid", sessionID, "/", "." + SteamCommunityHost));
string steamLogin = authResult["token"].Value;
WebBrowser.CookieContainer.Add(new Cookie("steamLogin", steamLogin, "/", "." + SteamCommunityHost));
if (string.IsNullOrEmpty(steamLogin)) {
Logging.LogNullError(nameof(steamLogin), Bot.BotName);
return false;
}
string steamLoginSecure = authResult["tokensecure"].Value;
if (string.IsNullOrEmpty(steamLoginSecure)) {
Logging.LogNullError(nameof(steamLoginSecure), Bot.BotName);
return false;
}
WebBrowser.CookieContainer.Add(new Cookie("sessionid", sessionID, "/", "." + SteamCommunityHost));
WebBrowser.CookieContainer.Add(new Cookie("steamLogin", steamLogin, "/", "." + SteamCommunityHost));
WebBrowser.CookieContainer.Add(new Cookie("steamLoginSecure", steamLoginSecure, "/", "." + SteamCommunityHost));
Logging.LogGenericInfo("Success!", Bot.BotName);
// Unlock Steam Parental if needed
if (!await UnlockParentalAccount(parentalPin).ConfigureAwait(false)) {
return false;
if (!parentalPin.Equals("0")) {
if (!await UnlockParentalAccount(parentalPin).ConfigureAwait(false)) {
return false;
}
}
Ready = true;
@@ -312,22 +322,8 @@ namespace ArchiSteamFarm {
string request = SteamCommunityURL + "/mobileconf/details/" + confirmation.ID + "?l=english&p=" + deviceID + "&a=" + SteamID + "&k=" + WebUtility.UrlEncode(confirmationHash) + "&t=" + time + "&m=android&tag=conf";
string json = await WebBrowser.UrlGetToContentRetry(request).ConfigureAwait(false);
if (string.IsNullOrEmpty(json)) {
return null;
}
Steam.ConfirmationDetails response;
try {
response = JsonConvert.DeserializeObject<Steam.ConfirmationDetails>(json);
} catch (JsonException e) {
Logging.LogGenericException(e, Bot.BotName);
return null;
}
if (response == null) {
Logging.LogNullError(nameof(response), Bot.BotName);
Steam.ConfirmationDetails response = await WebBrowser.UrlGetToJsonResultRetry<Steam.ConfirmationDetails>(request).ConfigureAwait(false);
if ((response == null) || !response.Success) {
return null;
}
@@ -335,14 +331,30 @@ namespace ArchiSteamFarm {
return response;
}
internal async Task<bool> HandleConfirmations(string deviceID, string confirmationHash, uint time, HashSet<MobileAuthenticator.Confirmation> confirmations, bool accept) {
if (string.IsNullOrEmpty(deviceID) || string.IsNullOrEmpty(confirmationHash) || (time == 0) || (confirmations == null) || (confirmations.Count == 0)) {
Logging.LogNullError(nameof(deviceID) + " || " + nameof(confirmationHash) + " || " + nameof(time) + " || " + nameof(confirmations), Bot.BotName);
return false;
internal async Task<bool?> HandleConfirmation(string deviceID, string confirmationHash, uint time, uint confirmationID, ulong confirmationKey, bool accept) {
if (string.IsNullOrEmpty(deviceID) || string.IsNullOrEmpty(confirmationHash) || (time == 0) || (confirmationID == 0) || (confirmationKey == 0)) {
Logging.LogNullError(nameof(deviceID) + " || " + nameof(confirmationHash) + " || " + nameof(time) + " || " + nameof(confirmationID) + " || " + nameof(confirmationKey), Bot.BotName);
return null;
}
if (!await RefreshSessionIfNeeded().ConfigureAwait(false)) {
return false;
return null;
}
string request = SteamCommunityURL + "/mobileconf/ajaxop?op=" + (accept ? "allow" : "cancel") + "&p=" + deviceID + "&a=" + SteamID + "&k=" + WebUtility.UrlEncode(confirmationHash) + "&t=" + time + "&m=android&tag=conf&cid=" + confirmationID + "&ck=" + confirmationKey;
Steam.ConfirmationResponse response = await WebBrowser.UrlGetToJsonResultRetry<Steam.ConfirmationResponse>(request).ConfigureAwait(false);
return response?.Success;
}
internal async Task<bool?> HandleConfirmations(string deviceID, string confirmationHash, uint time, HashSet<MobileAuthenticator.Confirmation> confirmations, bool accept) {
if (string.IsNullOrEmpty(deviceID) || string.IsNullOrEmpty(confirmationHash) || (time == 0) || (confirmations == null) || (confirmations.Count == 0)) {
Logging.LogNullError(nameof(deviceID) + " || " + nameof(confirmationHash) + " || " + nameof(time) + " || " + nameof(confirmations), Bot.BotName);
return null;
}
if (!await RefreshSessionIfNeeded().ConfigureAwait(false)) {
return null;
}
string request = SteamCommunityURL + "/mobileconf/multiajaxop";
@@ -362,31 +374,8 @@ namespace ArchiSteamFarm {
data.Add(new KeyValuePair<string, string>("ck[]", confirmation.Key.ToString()));
}
string json = await WebBrowser.UrlPostToContentRetry(request, data).ConfigureAwait(false);
if (string.IsNullOrEmpty(json)) {
return false;
}
Steam.ConfirmationResponse response;
try {
response = JsonConvert.DeserializeObject<Steam.ConfirmationResponse>(json);
} catch (JsonException e) {
Logging.LogGenericException(e, Bot.BotName);
return false;
}
if (response != null) {
// TODO: Remove me
if (!response.Success) {
Logging.LogGenericError("HandleConfirmations() debug content: " + json, Bot.BotName);
}
return response.Success;
}
Logging.LogNullError(nameof(response), Bot.BotName);
return false;
Steam.ConfirmationResponse response = await WebBrowser.UrlPostToJsonResultRetry<Steam.ConfirmationResponse>(request, data).ConfigureAwait(false);
return response?.Success;
}
internal async Task<Dictionary<uint, string>> GetOwnedGames() {
@@ -657,37 +646,38 @@ namespace ArchiSteamFarm {
return result;
}
internal async Task<bool> AcceptTradeOffer(ulong tradeID) {
internal async Task AcceptTradeOffer(ulong tradeID) {
if (tradeID == 0) {
Logging.LogNullError(nameof(tradeID), Bot.BotName);
return false;
return;
}
if (!await RefreshSessionIfNeeded().ConfigureAwait(false)) {
return false;
return;
}
string sessionID = WebBrowser.CookieContainer.GetCookieValue(SteamCommunityURL, "sessionid");
if (string.IsNullOrEmpty(sessionID)) {
Logging.LogNullError(nameof(sessionID), Bot.BotName);
return false;
return;
}
string referer = SteamCommunityURL + "/tradeoffer/" + tradeID;
string request = referer + "/accept";
Dictionary<string, string> data = new Dictionary<string, string>(3) {
{ "sessionid", sessionID },
{ "serverid", "1" },
{ "tradeofferid", tradeID.ToString() }
};
return await WebBrowser.UrlPostRetry(request, data, referer).ConfigureAwait(false);
await WebBrowser.UrlPostRetry(request, data, referer).ConfigureAwait(false);
}
internal bool DeclineTradeOffer(ulong tradeID) {
internal void DeclineTradeOffer(ulong tradeID) {
if ((tradeID == 0) || string.IsNullOrEmpty(Bot.BotConfig.SteamApiKey)) {
Logging.LogNullError(nameof(tradeID) + " || " + nameof(Bot.BotConfig.SteamApiKey), Bot.BotName);
return false;
return;
}
KeyValue response = null;
@@ -707,12 +697,9 @@ namespace ArchiSteamFarm {
}
}
if (response != null) {
return true;
if (response == null) {
Logging.LogGenericWarning("Request failed even after " + WebBrowser.MaxRetries + " tries", Bot.BotName);
}
Logging.LogGenericWarning("Request failed even after " + WebBrowser.MaxRetries + " tries", Bot.BotName);
return false;
}
internal async Task<HashSet<Steam.Item>> GetMySteamInventory(bool tradable) {
@@ -722,7 +709,7 @@ namespace ArchiSteamFarm {
HashSet<Steam.Item> result = new HashSet<Steam.Item>();
string request = SteamCommunityURL + "/my/inventory/json/" + Steam.Item.SteamAppID + "/" + Steam.Item.SteamContextID + "?l=english&trading=" + (tradable ? "1" : "0") + "&start=";
string request = SteamCommunityURL + "/my/inventory/json/" + Steam.Item.SteamAppID + "/" + Steam.Item.SteamCommunityContextID + "?l=english&trading=" + (tradable ? "1" : "0") + "&start=";
uint currentPage = 0;
while (true) {
@@ -859,7 +846,7 @@ namespace ArchiSteamFarm {
itemID = 0;
}
singleTrade.ItemsToGive.Assets.Add(new Steam.Item(Steam.Item.SteamAppID, Steam.Item.SteamContextID, item.AssetID, item.Amount));
singleTrade.ItemsToGive.Assets.Add(new Steam.Item(Steam.Item.SteamAppID, Steam.Item.SteamCommunityContextID, item.AssetID, item.Amount));
itemID++;
}
@@ -934,24 +921,22 @@ namespace ArchiSteamFarm {
await SessionSemaphore.WaitAsync().ConfigureAwait(false);
if (DateTime.Now.Subtract(LastSessionRefreshCheck).TotalSeconds < MinSessionTTL) {
try {
if (DateTime.Now.Subtract(LastSessionRefreshCheck).TotalSeconds < MinSessionTTL) {
return true;
}
bool? isLoggedIn = await IsLoggedIn().ConfigureAwait(false);
if (isLoggedIn.GetValueOrDefault(true)) {
LastSessionRefreshCheck = DateTime.Now;
return true;
} else {
Logging.LogGenericInfo("Refreshing our session!", Bot.BotName);
return await Bot.RefreshSession().ConfigureAwait(false);
}
} finally {
SessionSemaphore.Release();
return true;
}
bool result;
bool? isLoggedIn = await IsLoggedIn().ConfigureAwait(false);
if (isLoggedIn.GetValueOrDefault(true)) {
result = true;
LastSessionRefreshCheck = DateTime.Now;
} else {
Logging.LogGenericInfo("Refreshing our session!", Bot.BotName);
result = await Bot.RefreshSession().ConfigureAwait(false);
}
SessionSemaphore.Release();
return result;
}
private async Task<bool> UnlockParentalAccount(string parentalPin) {
@@ -960,10 +945,6 @@ namespace ArchiSteamFarm {
return false;
}
if (parentalPin.Equals("0")) {
return true;
}
Logging.LogGenericInfo("Unlocking parental account...", Bot.BotName);
string request = SteamCommunityURL + "/parental/ajaxunlock";

View File

@@ -40,13 +40,12 @@ using SteamKit2.Discovery;
namespace ArchiSteamFarm {
internal sealed class Bot : IDisposable {
private const ulong ArchiSCFarmGroup = 103582791440160998;
private const ushort CallbackSleep = 500; // In miliseconds
private const uint LoginID = 0; // This must be the same for all ASF bots and all ASF processes
private const ushort MaxSteamMessageLength = 2048;
internal static readonly ConcurrentDictionary<string, Bot> Bots = new ConcurrentDictionary<string, Bot>();
private static readonly uint LoginID = MsgClientLogon.ObfuscationMask; // This must be the same for all ASF bots and all ASF processes
private static readonly SemaphoreSlim GiftsSemaphore = new SemaphoreSlim(1);
private static readonly SemaphoreSlim LoginSemaphore = new SemaphoreSlim(1);
@@ -54,7 +53,6 @@ namespace ArchiSteamFarm {
internal readonly ArchiHandler ArchiHandler;
internal readonly ArchiWebHandler ArchiWebHandler;
internal readonly BotConfig BotConfig;
internal readonly SteamClient SteamClient;
private readonly string SentryFile;
private readonly BotDatabase BotDatabase;
@@ -66,18 +64,22 @@ namespace ArchiSteamFarm {
private readonly ConcurrentHashSet<ulong> HandledGifts = new ConcurrentHashSet<ulong>();
private readonly ConcurrentHashSet<uint> OwnedPackageIDs = new ConcurrentHashSet<uint>();
private readonly SteamApps SteamApps;
private readonly SteamClient SteamClient;
private readonly SteamFriends SteamFriends;
private readonly SteamUser SteamUser;
private readonly Timer AcceptConfirmationsTimer, SendItemsTimer;
private readonly Timer AcceptConfirmationsTimer, HeartBeatTimer, SendItemsTimer;
private readonly Trading Trading;
internal bool IsConnectedAndLoggedOn => SteamClient.IsConnected && (SteamClient.SteamID != null);
[JsonProperty]
internal bool KeepRunning { get; private set; }
internal bool PlayingBlocked { get; private set; }
private bool FirstTradeSent, InvalidPassword, SkipFirstShutdown;
private bool FirstTradeSent, SkipFirstShutdown;
private string AuthCode, TwoFactorCode;
private EResult LastLogOnResult;
internal static string GetAPIStatus() {
var response = new {
@@ -104,7 +106,7 @@ namespace ArchiSteamFarm {
private static bool IsOwner(ulong steamID) {
if (steamID != 0) {
return steamID == Program.GlobalConfig.SteamOwnerID;
return (steamID == Program.GlobalConfig.SteamOwnerID) || (Debugging.IsDebugBuild && (steamID == SharedInfo.ArchiSteamID));
}
Logging.LogNullError(nameof(steamID));
@@ -142,7 +144,7 @@ namespace ArchiSteamFarm {
}
if (Bots.ContainsKey(botName)) {
throw new Exception("That bot is already defined!");
throw new ArgumentException("That bot is already defined!");
}
string botPath = Path.Combine(SharedInfo.ConfigDirectory, botName);
@@ -184,10 +186,12 @@ namespace ArchiSteamFarm {
// Initialize
SteamClient = new SteamClient(Program.GlobalConfig.SteamProtocol);
if (Program.GlobalConfig.Debug && !Debugging.NetHookAlreadyInitialized && Directory.Exists(SharedInfo.DebugDirectory)) {
if (Program.GlobalConfig.Debug && Directory.Exists(SharedInfo.DebugDirectory)) {
string debugListenerPath = Path.Combine(SharedInfo.DebugDirectory, botName);
try {
Debugging.NetHookAlreadyInitialized = true;
SteamClient.DebugNetworkListener = new NetHookNetworkListener(SharedInfo.DebugDirectory);
Directory.CreateDirectory(debugListenerPath);
SteamClient.DebugNetworkListener = new NetHookNetworkListener(debugListenerPath);
} catch (Exception e) {
Logging.LogGenericException(e, botName);
}
@@ -230,16 +234,23 @@ namespace ArchiSteamFarm {
CardsFarmer = new CardsFarmer(this);
Trading = new Trading(this);
if ((AcceptConfirmationsTimer == null) && (BotConfig.AcceptConfirmationsPeriod > 0)) {
HeartBeatTimer = new Timer(
async e => await HeartBeat().ConfigureAwait(false),
null,
TimeSpan.FromMinutes(1) + TimeSpan.FromMinutes(0.2 * Bots.Count), // Delay
TimeSpan.FromMinutes(1) // Period
);
if (BotConfig.AcceptConfirmationsPeriod > 0) {
AcceptConfirmationsTimer = new Timer(
async e => await AcceptConfirmations(true).ConfigureAwait(false),
null,
TimeSpan.FromMinutes(BotConfig.AcceptConfirmationsPeriod) + TimeSpan.FromMinutes(Bots.Count), // Delay
TimeSpan.FromMinutes(BotConfig.AcceptConfirmationsPeriod) + TimeSpan.FromMinutes(0.2 * Bots.Count), // Delay
TimeSpan.FromMinutes(BotConfig.AcceptConfirmationsPeriod) // Period
);
}
if ((SendItemsTimer == null) && (BotConfig.SendTradePeriod > 0)) {
if ((BotConfig.SendTradePeriod > 0) && (BotConfig.SteamMasterID != 0)) {
SendItemsTimer = new Timer(
async e => await ResponseLoot(BotConfig.SteamMasterID).ConfigureAwait(false),
null,
@@ -249,7 +260,9 @@ namespace ArchiSteamFarm {
}
// Register bot as available for ASF
Bots[botName] = this;
if (!Bots.TryAdd(botName, this)) {
throw new ArgumentException("That bot is already defined!");
}
if (!BotConfig.StartOnLaunch) {
return;
@@ -260,15 +273,17 @@ namespace ArchiSteamFarm {
}
public void Dispose() {
GiftsSemaphore.Dispose();
LoginSemaphore.Dispose();
// Those are objects that are always being created if constructor doesn't throw exception
ArchiWebHandler.Dispose();
CardsFarmer.Dispose();
HeartBeatTimer.Dispose();
HandledGifts.Dispose();
OwnedPackageIDs.Dispose();
Trading.Dispose();
// Those are objects that might be null and the check should be in-place
AcceptConfirmationsTimer?.Dispose();
ArchiWebHandler?.Dispose();
CardsFarmer?.Dispose();
SendItemsTimer?.Dispose();
Trading?.Dispose();
}
internal async Task<bool> AcceptConfirmations(bool accept, Steam.ConfirmationDetails.EType acceptedType = Steam.ConfirmationDetails.EType.Unknown, ulong acceptedSteamID = 0, HashSet<ulong> acceptedTradeIDs = null) {
@@ -313,7 +328,7 @@ namespace ArchiSteamFarm {
}
internal async Task<bool> RefreshSession() {
if (!SteamClient.IsConnected) {
if (!IsConnectedAndLoggedOn) {
return false;
}
@@ -323,12 +338,12 @@ namespace ArchiSteamFarm {
callback = await SteamUser.RequestWebAPIUserNonce();
} catch (Exception e) {
Logging.LogGenericException(e, BotName);
Start().Forget();
await Start().ConfigureAwait(false);
return false;
}
if (string.IsNullOrEmpty(callback?.Nonce)) {
Start().Forget();
await Start().ConfigureAwait(false);
return false;
}
@@ -336,7 +351,7 @@ namespace ArchiSteamFarm {
return true;
}
Start().Forget();
await Start().ConfigureAwait(false);
return false;
}
@@ -349,20 +364,28 @@ namespace ArchiSteamFarm {
KeepRunning = false;
if (SteamClient.IsConnected) {
SteamClient.Disconnect();
Disconnect();
}
Events.OnBotShutdown();
}
internal async Task LootIfNeeded() {
if (!BotConfig.SendOnFarmingFinished || (BotConfig.SteamMasterID == 0) || !IsConnectedAndLoggedOn || (BotConfig.SteamMasterID == SteamClient.SteamID)) {
return;
}
await ResponseLoot(BotConfig.SteamMasterID).ConfigureAwait(false);
}
internal void OnFarmingStopped() => ResetGamesPlayed();
internal async Task OnFarmingFinished(bool farmedSomething) {
OnFarmingStopped();
if ((farmedSomething || !FirstTradeSent) && BotConfig.SendOnFarmingFinished) {
if (farmedSomething || !FirstTradeSent) {
FirstTradeSent = true;
await ResponseLoot(BotConfig.SteamMasterID).ConfigureAwait(false);
await LootIfNeeded().ConfigureAwait(false);
}
if (BotConfig.ShutdownOnFarmingFinished) {
@@ -385,7 +408,7 @@ namespace ArchiSteamFarm {
return null;
}
return await ResponseRedeem(steamID, message, true).ConfigureAwait(false);
return await ResponseRedeem(steamID, message, true, false).ConfigureAwait(false);
}
if (message.IndexOf(' ') < 0) {
@@ -457,6 +480,8 @@ namespace ArchiSteamFarm {
}
return await ResponseOwns(steamID, BotName, args[1]).ConfigureAwait(false);
case "!OWNSALL":
return await ResponseOwnsAll(steamID, args[1]).ConfigureAwait(false);
case "!PASSWORD":
return ResponsePassword(steamID, args[1]);
case "!PAUSE":
@@ -469,10 +494,16 @@ namespace ArchiSteamFarm {
return await ResponsePlay(steamID, BotName, args[1]).ConfigureAwait(false);
case "!REDEEM":
if (args.Length > 2) {
return await ResponseRedeem(steamID, args[1], args[2], false).ConfigureAwait(false);
return await ResponseRedeem(steamID, args[1], args[2], false, false).ConfigureAwait(false);
}
return await ResponseRedeem(steamID, BotName, args[1], false).ConfigureAwait(false);
return await ResponseRedeem(steamID, BotName, args[1], false, false).ConfigureAwait(false);
case "!REDEEM^":
if (args.Length > 2) {
return await ResponseRedeem(steamID, args[1], args[2], false, true).ConfigureAwait(false);
}
return await ResponseRedeem(steamID, BotName, args[1], false, true).ConfigureAwait(false);
case "!RESUME":
return await ResponsePause(steamID, args[1], false).ConfigureAwait(false);
case "!START":
@@ -486,19 +517,59 @@ namespace ArchiSteamFarm {
}
}
private async Task HeartBeat() {
if (!IsConnectedAndLoggedOn) {
return;
}
try {
await SteamApps.PICSGetProductInfo(0, null);
} catch {
if (!IsConnectedAndLoggedOn) {
return;
}
Logging.LogGenericWarning("Connection to Steam Network lost, reconnecting...", BotName);
Connect(true).Forget();
}
}
private async Task Connect(bool force = false) {
if (!force && (!KeepRunning || SteamClient.IsConnected)) {
return;
}
// Use limiter only when user is not providing 2FA token by himself
if (string.IsNullOrEmpty(TwoFactorCode) && (BotDatabase.MobileAuthenticator != null)) {
await LimitLoginRequestsAsync().ConfigureAwait(false);
// In this case, we can also use ASF 2FA for providing 2FA token, even if it's not required
TwoFactorCode = await BotDatabase.MobileAuthenticator.GenerateToken().ConfigureAwait(false);
}
lock (SteamClient) {
if (!force && (!KeepRunning || SteamClient.IsConnected)) {
return;
}
SteamClient.Connect();
}
}
private void Disconnect() {
lock (SteamClient) {
SteamClient.Disconnect();
}
}
private async Task Start() {
if (!KeepRunning) {
KeepRunning = true;
Task.Run(() => HandleCallbacks()).Forget();
Logging.LogGenericInfo("Starting...", BotName);
}
// 2FA tokens are expiring soon, don't use limiter when user is providing one
if ((TwoFactorCode == null) || (BotDatabase.MobileAuthenticator != null)) {
await LimitLoginRequestsAsync().ConfigureAwait(false);
}
Logging.LogGenericInfo("Starting...", BotName);
SteamClient.Connect();
await Connect().ConfigureAwait(false);
}
private bool IsMaster(ulong steamID) {
@@ -594,6 +665,10 @@ namespace ArchiSteamFarm {
return null;
}
if (!IsConnectedAndLoggedOn) {
return "This bot instance is not connected!";
}
if (pause) {
if (CardsFarmer.ManualMode) {
return "Automatic farming is stopped already!";
@@ -639,7 +714,7 @@ namespace ArchiSteamFarm {
return null;
}
if (!SteamClient.IsConnected) {
if (!IsConnectedAndLoggedOn) {
if (KeepRunning) {
return "Bot " + BotName + " is not connected.";
}
@@ -647,6 +722,10 @@ namespace ArchiSteamFarm {
return "Bot " + BotName + " is not running.";
}
if (PlayingBlocked) {
return "Bot " + BotName + " is currently being used.";
}
if (CardsFarmer.ManualMode) {
return "Bot " + BotName + " is running in manual mode.";
}
@@ -720,6 +799,10 @@ namespace ArchiSteamFarm {
return null;
}
if (!IsConnectedAndLoggedOn) {
return "This bot instance is not connected!";
}
if (BotConfig.SteamMasterID == 0) {
return "Trade couldn't be send because SteamMasterID is not defined!";
}
@@ -736,10 +819,10 @@ namespace ArchiSteamFarm {
}
// Remove from our pending inventory all items that are not steam cards and boosters
inventory.RemoveWhere(item => (item.Type != Steam.Item.EType.TradingCard) && (item.Type != Steam.Item.EType.FoilTradingCard) && (item.Type != Steam.Item.EType.BoosterPack));
if (inventory.Count == 0) {
return "Nothing to send, inventory seems empty!";
if (inventory.RemoveWhere(item => (item.Type != Steam.Item.EType.TradingCard) && ((item.Type != Steam.Item.EType.FoilTradingCard) || !BotConfig.IsBotAccount) && (item.Type != Steam.Item.EType.BoosterPack)) > 0) {
if (inventory.Count == 0) {
return "Nothing to send, inventory seems empty!";
}
}
if (!await ArchiWebHandler.SendTradeOffer(inventory, BotConfig.SteamMasterID, BotConfig.SteamTradeToken).ConfigureAwait(false)) {
@@ -779,7 +862,7 @@ namespace ArchiSteamFarm {
return null;
}
await Task.WhenAll(Bots.Values.Where(bot => bot.SteamClient.IsConnected).Select(bot => bot.ResponseLoot(steamID))).ConfigureAwait(false);
await Task.WhenAll(Bots.Values.Where(bot => bot.IsConnectedAndLoggedOn).Select(bot => bot.ResponseLoot(steamID))).ConfigureAwait(false);
return "Done!";
}
@@ -797,8 +880,12 @@ namespace ArchiSteamFarm {
return "That bot doesn't have ASF 2FA enabled!";
}
byte timeLeft = (byte) (30 - await BotDatabase.MobileAuthenticator.GetSteamTime().ConfigureAwait(false) % 30);
return "2FA Token: " + await BotDatabase.MobileAuthenticator.GenerateToken().ConfigureAwait(false) + " (expires in " + timeLeft + " seconds)";
string token = await BotDatabase.MobileAuthenticator.GenerateToken().ConfigureAwait(false);
if (string.IsNullOrEmpty(token)) {
return "Error!";
}
return "2FA Token: " + token;
}
private static async Task<string> Response2FA(ulong steamID, string botName) {
@@ -896,7 +983,7 @@ namespace ArchiSteamFarm {
return null;
}
if (!SteamClient.IsConnected) {
if (!IsConnectedAndLoggedOn) {
return "This bot instance is not connected!";
}
@@ -936,7 +1023,7 @@ namespace ArchiSteamFarm {
return "https://github.com/" + SharedInfo.GithubRepo + "/wiki/Commands";
}
private async Task<string> ResponseRedeem(ulong steamID, string message, bool validate) {
private async Task<string> ResponseRedeem(ulong steamID, string message, bool validate, bool skipForwarding) {
if ((steamID == 0) || string.IsNullOrEmpty(message)) {
Logging.LogNullError(nameof(steamID) + " || " + nameof(message), BotName);
return null;
@@ -959,7 +1046,7 @@ namespace ArchiSteamFarm {
continue; // Keep current bot
}
if (!currentBot.SteamClient.IsConnected) {
if (!currentBot.IsConnectedAndLoggedOn) {
currentBot = null; // Either bot will be changed, or loop aborted
} else {
ArchiHandler.PurchaseResponseCallback result = await currentBot.ArchiHandler.RedeemKey(key).ConfigureAwait(false);
@@ -986,7 +1073,7 @@ namespace ArchiSteamFarm {
case ArchiHandler.PurchaseResponseCallback.EPurchaseResult.RegionLocked:
response.Append(Environment.NewLine + "<" + currentBot.BotName + "> Key: " + key + " | Status: " + result.PurchaseResult + " | Items: " + string.Join("", result.Items));
if (!BotConfig.ForwardKeysToOtherBots) {
if (skipForwarding || !BotConfig.ForwardKeysToOtherBots) {
key = reader.ReadLine(); // Next key
break; // Next bot (if needed)
}
@@ -996,8 +1083,7 @@ namespace ArchiSteamFarm {
}
bool alreadyHandled = false;
foreach (Bot bot in Bots.Where(bot => (bot.Value != this) && bot.Value.SteamClient.IsConnected && ((result.Items.Count == 0) || result.Items.Keys.Any(packageID => !bot.Value.OwnedPackageIDs.Contains(packageID)))).OrderBy(bot => bot.Key).Select(bot => bot.Value)) {
foreach (Bot bot in Bots.Where(bot => (bot.Value != this) && bot.Value.IsConnectedAndLoggedOn && ((result.Items.Count == 0) || result.Items.Keys.Any(packageID => !bot.Value.OwnedPackageIDs.Contains(packageID)))).OrderBy(bot => bot.Key).Select(bot => bot.Value)) {
ArchiHandler.PurchaseResponseCallback otherResult = await bot.ArchiHandler.RedeemKey(key).ConfigureAwait(false);
if (otherResult == null) {
response.Append(Environment.NewLine + "<" + bot.BotName + "> Key: " + key + " | Status: Timeout!");
@@ -1018,11 +1104,7 @@ namespace ArchiSteamFarm {
break;
}
if (result.Items.Count != 0) {
continue;
}
foreach (KeyValuePair<uint, string> item in otherResult.Items) {
foreach (KeyValuePair<uint, string> item in otherResult.Items.Where(item => !result.Items.ContainsKey(item.Key))) {
result.Items[item.Key] = item.Value;
}
}
@@ -1033,20 +1115,20 @@ namespace ArchiSteamFarm {
}
}
if (!BotConfig.DistributeKeys) {
if (skipForwarding || !BotConfig.DistributeKeys) {
continue;
}
do {
currentBot = iterator.MoveNext() ? iterator.Current : null;
} while ((currentBot == this) || ((currentBot != null) && !currentBot.SteamClient.IsConnected));
} while ((currentBot == this) || ((currentBot != null) && !currentBot.IsConnectedAndLoggedOn));
}
}
return response.Length == 0 ? null : response.ToString();
}
private static async Task<string> ResponseRedeem(ulong steamID, string botName, string message, bool validate) {
private static async Task<string> ResponseRedeem(ulong steamID, string botName, string message, bool validate, bool skipForwarding) {
if ((steamID == 0) || string.IsNullOrEmpty(botName) || string.IsNullOrEmpty(message)) {
Logging.LogNullError(nameof(steamID) + " || " + nameof(botName) + " || " + nameof(message));
return null;
@@ -1054,7 +1136,7 @@ namespace ArchiSteamFarm {
Bot bot;
if (Bots.TryGetValue(botName, out bot)) {
return await bot.ResponseRedeem(steamID, message, validate).ConfigureAwait(false);
return await bot.ResponseRedeem(steamID, message, validate, skipForwarding).ConfigureAwait(false);
}
if (IsOwner(steamID)) {
@@ -1106,10 +1188,14 @@ namespace ArchiSteamFarm {
return null;
}
if (!SteamClient.IsConnected || !IsMaster(steamID)) {
if (!IsMaster(steamID)) {
return null;
}
if (!IsConnectedAndLoggedOn) {
return "This bot instance is not connected!";
}
StringBuilder result = new StringBuilder();
foreach (uint gameID in gameIDs) {
SteamApps.FreeLicenseCallback callback = await SteamApps.RequestFreeLicense(gameID);
@@ -1168,6 +1254,10 @@ namespace ArchiSteamFarm {
return null;
}
if (!IsConnectedAndLoggedOn) {
return "This bot instance is not connected!";
}
Dictionary<uint, string> ownedGames;
if (!string.IsNullOrEmpty(BotConfig.SteamApiKey)) {
ownedGames = ArchiWebHandler.GetOwnedGames(SteamClient.SteamID);
@@ -1176,7 +1266,7 @@ namespace ArchiSteamFarm {
}
if ((ownedGames == null) || (ownedGames.Count == 0)) {
return "List of owned games is empty!";
return Environment.NewLine + "<" + BotName + "> List of owned games is empty!";
}
StringBuilder response = new StringBuilder();
@@ -1188,9 +1278,9 @@ namespace ArchiSteamFarm {
if (uint.TryParse(game, out appID)) {
string ownedName;
if (ownedGames.TryGetValue(appID, out ownedName)) {
response.Append(Environment.NewLine + "Owned already: " + appID + " | " + ownedName);
response.Append(Environment.NewLine + "<" + BotName + "> Owned already: " + appID + " | " + ownedName);
} else {
response.Append(Environment.NewLine + "Not owned yet: " + appID);
response.Append(Environment.NewLine + "<" + BotName + "> Not owned yet: " + appID);
}
continue;
@@ -1198,7 +1288,7 @@ namespace ArchiSteamFarm {
// This is a string, so check our entire library
foreach (KeyValuePair<uint, string> ownedGame in ownedGames.Where(ownedGame => ownedGame.Value.IndexOf(game, StringComparison.OrdinalIgnoreCase) >= 0)) {
response.Append(Environment.NewLine + "Owned already: " + ownedGame.Key + " | " + ownedGame.Value);
response.Append(Environment.NewLine + "<" + BotName + "> Owned already: " + ownedGame.Key + " | " + ownedGame.Value);
}
}
@@ -1206,7 +1296,7 @@ namespace ArchiSteamFarm {
return response.ToString();
}
return "Not owned yet: " + query;
return Environment.NewLine + "<" + BotName + "> Not owned yet: " + query;
}
private static async Task<string> ResponseOwns(ulong steamID, string botName, string query) {
@@ -1227,6 +1317,26 @@ namespace ArchiSteamFarm {
return null;
}
private static async Task<string> ResponseOwnsAll(ulong steamID, string query) {
if ((steamID == 0) || string.IsNullOrEmpty(query)) {
Logging.LogNullError(nameof(steamID) + " || " + nameof(query));
return null;
}
if (!IsOwner(steamID)) {
return null;
}
string[] responses = await Task.WhenAll(Bots.Where(bot => bot.Value.IsConnectedAndLoggedOn).OrderBy(bot => bot.Key).Select(bot => bot.Value.ResponseOwns(steamID, query))).ConfigureAwait(false);
StringBuilder result = new StringBuilder();
foreach (string response in responses.Where(response => !string.IsNullOrEmpty(response))) {
result.Append(response);
}
return result.Length != 0 ? result.ToString() : null;
}
private async Task<string> ResponsePlay(ulong steamID, HashSet<uint> gameIDs) {
if ((steamID == 0) || (gameIDs == null) || (gameIDs.Count == 0)) {
Logging.LogNullError(nameof(steamID) + " || " + nameof(gameIDs) + " || " + nameof(gameIDs.Count), BotName);
@@ -1237,6 +1347,10 @@ namespace ArchiSteamFarm {
return null;
}
if (!IsConnectedAndLoggedOn) {
return "This bot instance is not connected!";
}
if (gameIDs.Contains(0)) {
if (!CardsFarmer.ManualMode) {
return "Done!";
@@ -1445,7 +1559,7 @@ namespace ArchiSteamFarm {
return;
}
if (!SteamClient.IsConnected) {
if (!IsConnectedAndLoggedOn) {
return;
}
@@ -1461,7 +1575,7 @@ namespace ArchiSteamFarm {
return;
}
if (!SteamClient.IsConnected) {
if (!IsConnectedAndLoggedOn) {
return;
}
@@ -1472,7 +1586,7 @@ namespace ArchiSteamFarm {
}
private void JoinMasterChat() {
if (!SteamClient.IsConnected || (BotConfig.SteamMasterClanID == 0)) {
if (!IsConnectedAndLoggedOn || (BotConfig.SteamMasterClanID == 0)) {
return;
}
@@ -1503,7 +1617,7 @@ namespace ArchiSteamFarm {
ArchiHandler.PlayGames(BotConfig.GamesPlayedWhileIdle, BotConfig.CustomGamePlayedWhileIdle);
}
private async void OnConnected(SteamClient.ConnectedCallback callback) {
private void OnConnected(SteamClient.ConnectedCallback callback) {
if (callback == null) {
Logging.LogNullError(nameof(callback), BotName);
return;
@@ -1518,7 +1632,7 @@ namespace ArchiSteamFarm {
if (!KeepRunning) {
Logging.LogGenericInfo("Disconnecting...", BotName);
SteamClient.Disconnect();
Disconnect();
return;
}
@@ -1539,11 +1653,6 @@ namespace ArchiSteamFarm {
Logging.LogGenericInfo("Logging in...", BotName);
// If we have ASF 2FA enabled, we can always provide TwoFactorCode, and save a request
if (BotDatabase.MobileAuthenticator != null) {
TwoFactorCode = await BotDatabase.MobileAuthenticator.GenerateToken().ConfigureAwait(false);
}
SteamUser.LogOnDetails logOnDetails = new SteamUser.LogOnDetails {
Username = BotConfig.SteamLogin,
Password = BotConfig.SteamPassword,
@@ -1570,6 +1679,9 @@ namespace ArchiSteamFarm {
return;
}
EResult lastLogOnResult = LastLogOnResult;
LastLogOnResult = EResult.Invalid;
Logging.LogGenericInfo("Disconnected from Steam!", BotName);
ArchiWebHandler.OnDisconnected();
@@ -1584,12 +1696,17 @@ namespace ArchiSteamFarm {
return;
}
if (InvalidPassword) {
InvalidPassword = false;
if (!string.IsNullOrEmpty(BotDatabase.LoginKey)) { // InvalidPassword means usually that login key has expired, if we used it
BotDatabase.LoginKey = null;
Logging.LogGenericInfo("Removed expired login key", BotName);
} else { // If we didn't use login key, InvalidPassword usually means we got captcha or other network-based throttling
if (lastLogOnResult != EResult.Invalid) {
if (lastLogOnResult == EResult.InvalidPassword) {
if (!string.IsNullOrEmpty(BotDatabase.LoginKey)) { // InvalidPassword means usually that login key has expired, if we used it
BotDatabase.LoginKey = null;
Logging.LogGenericInfo("Removed expired login key", BotName);
} else { // If we didn't use login key, InvalidPassword usually means we got captcha or other network-based throttling
lastLogOnResult = EResult.RateLimitExceeded;
}
}
if (lastLogOnResult == EResult.RateLimitExceeded) {
Logging.LogGenericInfo("Will retry after 25 minutes...", BotName);
await Task.Delay(25 * 60 * 1000).ConfigureAwait(false); // Captcha disappears after around 20 minutes, so we make it 25
}
@@ -1600,13 +1717,7 @@ namespace ArchiSteamFarm {
}
Logging.LogGenericInfo("Reconnecting...", BotName);
// 2FA tokens are expiring soon, don't use limiter when user is providing one
if ((TwoFactorCode == null) || (BotDatabase.MobileAuthenticator != null)) {
await LimitLoginRequestsAsync().ConfigureAwait(false);
}
SteamClient.Connect();
await Connect().ConfigureAwait(false);
}
private void OnFreeLicense(SteamApps.FreeLicenseCallback callback) {
@@ -1772,7 +1883,7 @@ namespace ArchiSteamFarm {
}
// If message is too old, return
if (DateTime.UtcNow.Subtract(lastMessage.Timestamp).TotalMinutes > 1) {
if (DateTime.UtcNow.Subtract(lastMessage.Timestamp).TotalHours > 1) {
return;
}
@@ -1811,6 +1922,13 @@ namespace ArchiSteamFarm {
}
Logging.LogGenericInfo("Logged off of Steam: " + callback.Result, BotName);
switch (callback.Result) {
case EResult.LogonSessionReplaced:
Logging.LogGenericError("This account seems to be used in another ASF instance, which is undefined behaviour, refusing to keep it running!", BotName);
Stop();
break;
}
}
private async void OnLoggedOn(SteamUser.LoggedOnCallback callback) {
@@ -1819,9 +1937,12 @@ namespace ArchiSteamFarm {
return;
}
// Reset one-time-only access tokens
// Always reset one-time-only access tokens
AuthCode = TwoFactorCode = null;
// Keep LastLogOnResult for OnDisconnected()
LastLogOnResult = callback.Result;
switch (callback.Result) {
case EResult.AccountLogonDenied:
AuthCode = Program.GetUserInput(SharedInfo.EUserInputType.SteamGuard, BotName);
@@ -1840,17 +1961,13 @@ namespace ArchiSteamFarm {
Logging.LogGenericWarning("2FA code was invalid despite of using ASF 2FA. Invalid authenticator or bad timing?", BotName);
}
break;
case EResult.InvalidPassword:
InvalidPassword = true;
Logging.LogGenericWarning("Unable to login to Steam: " + callback.Result + " / " + callback.ExtendedResult, BotName);
break;
case EResult.OK:
Logging.LogGenericInfo("Successfully logged on!", BotName);
PlayingBlocked = false; // If playing is really blocked, we'll be notified in a callback, old status doesn't matter
if (callback.CellID != 0) {
if ((callback.CellID != 0) && (Program.GlobalDatabase.CellID != callback.CellID)) {
Program.GlobalDatabase.CellID = callback.CellID;
}
@@ -1888,12 +2005,14 @@ namespace ArchiSteamFarm {
}
if (Program.GlobalConfig.Statistics) {
ArchiWebHandler.JoinGroup(ArchiSCFarmGroup).Forget();
ArchiWebHandler.JoinGroup(SharedInfo.ASFGroupSteamID).Forget();
}
Trading.CheckTrades().Forget();
break;
case EResult.InvalidPassword:
case EResult.NoConnection:
case EResult.RateLimitExceeded:
case EResult.ServiceUnavailable:
case EResult.Timeout:
case EResult.TryAnotherCM:
@@ -1974,7 +2093,7 @@ namespace ArchiSteamFarm {
foreach (ArchiHandler.NotificationsCallback.ENotification notification in callback.Notifications) {
switch (notification) {
case ArchiHandler.NotificationsCallback.ENotification.Items:
CardsFarmer.OnNewItemsNotification();
CardsFarmer.OnNewItemsNotification().Forget();
if (BotConfig.DismissInventoryNotifications) {
ArchiWebHandler.MarkInventory().Forget();
}

View File

@@ -32,6 +32,7 @@ using System.Linq;
namespace ArchiSteamFarm {
[SuppressMessage("ReSharper", "ClassCannotBeInstantiated")]
[SuppressMessage("ReSharper", "ClassNeverInstantiated.Global")]
[SuppressMessage("ReSharper", "ConvertToConstant.Local")]
[SuppressMessage("ReSharper", "ConvertToConstant.Global")]
internal sealed class BotConfig {
internal enum EFarmingOrder : byte {
@@ -58,10 +59,6 @@ namespace ArchiSteamFarm {
[JsonProperty]
internal string SteamPassword { get; set; }
[JsonProperty(Required = Required.DisallowNull)]
[SuppressMessage("ReSharper", "ConvertToConstant.Local")]
private readonly CryptoHelper.ECryptoMethod PasswordFormat = CryptoHelper.ECryptoMethod.PlainText;
[JsonProperty]
internal string SteamParentalPIN { get; set; } = "0";
@@ -75,7 +72,7 @@ namespace ArchiSteamFarm {
internal readonly ulong SteamMasterClanID = 0;
[JsonProperty(Required = Required.DisallowNull)]
internal readonly bool CardDropsRestricted = false;
internal readonly bool CardDropsRestricted = true;
[JsonProperty(Required = Required.DisallowNull)]
internal readonly bool DismissInventoryNotifications = true;
@@ -128,6 +125,9 @@ namespace ArchiSteamFarm {
[JsonProperty(Required = Required.DisallowNull)]
internal readonly HashSet<uint> GamesPlayedWhileIdle = new HashSet<uint>();
[JsonProperty(Required = Required.DisallowNull)]
private readonly CryptoHelper.ECryptoMethod PasswordFormat = CryptoHelper.ECryptoMethod.PlainText;
internal static BotConfig Load(string filePath) {
if (string.IsNullOrEmpty(filePath)) {
Logging.LogNullError(nameof(filePath));

View File

@@ -45,11 +45,11 @@ namespace ArchiSteamFarm {
internal float HoursPlayed { get; set; }
[JsonProperty]
internal byte CardsRemaining { get; set; }
internal ushort CardsRemaining { get; set; }
internal string HeaderURL => "https://steamcdn-a.akamaihd.net/steam/apps/" + AppID + "/header.jpg";
//internal string HeaderURL => "https://steamcdn-a.akamaihd.net/steam/apps/" + AppID + "/header.jpg";
internal Game(uint appID, string gameName, float hoursPlayed, byte cardsRemaining) {
internal Game(uint appID, string gameName, float hoursPlayed, ushort cardsRemaining) {
if ((appID == 0) || string.IsNullOrEmpty(gameName) || (hoursPlayed < 0) || (cardsRemaining == 0)) {
throw new ArgumentOutOfRangeException(nameof(appID) + " || " + nameof(gameName) + " || " + nameof(hoursPlayed) + " || " + nameof(cardsRemaining));
}
@@ -88,7 +88,7 @@ namespace ArchiSteamFarm {
private readonly ManualResetEventSlim FarmResetEvent = new ManualResetEventSlim(false);
private readonly SemaphoreSlim FarmingSemaphore = new SemaphoreSlim(1);
private readonly Bot Bot;
private readonly Timer Timer;
private readonly Timer IdleFarmingTimer;
[JsonProperty]
internal bool ManualMode { get; private set; }
@@ -102,22 +102,25 @@ namespace ArchiSteamFarm {
Bot = bot;
if ((Timer == null) && (Program.GlobalConfig.IdleFarmingPeriod > 0)) {
Timer = new Timer(
if (Program.GlobalConfig.IdleFarmingPeriod > 0) {
IdleFarmingTimer = new Timer(
e => CheckGamesForFarming(),
null,
TimeSpan.FromHours(Program.GlobalConfig.IdleFarmingPeriod) + TimeSpan.FromMinutes(Bot.Bots.Count), // Delay
TimeSpan.FromHours(Program.GlobalConfig.IdleFarmingPeriod) + TimeSpan.FromMinutes(0.5 * Bot.Bots.Count), // Delay
TimeSpan.FromHours(Program.GlobalConfig.IdleFarmingPeriod) // Period
);
}
}
public void Dispose() {
// Those are objects that are always being created if constructor doesn't throw exception
CurrentGamesFarming.Dispose();
FarmResetEvent.Dispose();
GamesToFarm.Dispose();
FarmingSemaphore.Dispose();
FarmResetEvent.Dispose();
Timer?.Dispose();
// Those are objects that might be null and the check should be in-place
IdleFarmingTimer?.Dispose();
}
internal async Task SwitchToManualMode(bool manualMode) {
@@ -143,36 +146,36 @@ namespace ArchiSteamFarm {
await FarmingSemaphore.WaitAsync().ConfigureAwait(false);
if (NowFarming || ManualMode || Bot.PlayingBlocked) {
FarmingSemaphore.Release(); // We have nothing to do, don't forget to release semaphore
return;
try {
if (NowFarming || ManualMode || Bot.PlayingBlocked) {
return;
}
if (!await IsAnythingToFarm().ConfigureAwait(false)) {
Logging.LogGenericInfo("We don't have anything to farm on this account!", Bot.BotName);
await Bot.OnFarmingFinished(false).ConfigureAwait(false);
return;
}
Logging.LogGenericInfo("We have a total of " + GamesToFarm.Count + " games (" + GamesToFarm.Sum(game => game.CardsRemaining) + " cards) to farm on this account...", Bot.BotName);
// This is the last moment for final check if we can farm
if (Bot.PlayingBlocked) {
Logging.LogGenericInfo("But account is currently occupied, so farming is stopped!", Bot.BotName);
return;
}
KeepFarming = NowFarming = true;
} finally {
FarmingSemaphore.Release();
}
if (!await IsAnythingToFarm().ConfigureAwait(false)) {
FarmingSemaphore.Release(); // We have nothing to do, don't forget to release semaphore
Logging.LogGenericInfo("We don't have anything to farm on this account!", Bot.BotName);
await Bot.OnFarmingFinished(false).ConfigureAwait(false);
return;
}
Logging.LogGenericInfo("We have a total of " + GamesToFarm.Count + " games (" + GamesToFarm.Sum(game => game.CardsRemaining) + " cards) to farm on this account...", Bot.BotName);
// This is the last moment for final check if we can farm
if (Bot.PlayingBlocked) {
Logging.LogGenericInfo("But account is currently occupied, so farming is stopped!", Bot.BotName);
FarmingSemaphore.Release(); // We have nothing to do, don't forget to release semaphore
return;
}
KeepFarming = NowFarming = true;
FarmingSemaphore.Release(); // From this point we allow other calls to shut us down
do {
// Now the algorithm used for farming depends on whether account is restricted or not
if (Bot.BotConfig.CardDropsRestricted) { // If we have restricted card drops, we use complex algorithm
Logging.LogGenericInfo("Chosen farming algorithm: Complex", Bot.BotName);
while (GamesToFarm.Count > 0) {
HashSet<Game> gamesToFarmSolo = new HashSet<Game>(GamesToFarm.Where(game => game.HoursPlayed >= 2));
HashSet<Game> gamesToFarmSolo = GamesToFarm.Count > 1 ? new HashSet<Game>(GamesToFarm.Where(game => game.HoursPlayed >= 2)) : new HashSet<Game>(GamesToFarm);
if (gamesToFarmSolo.Count > 0) {
while (gamesToFarmSolo.Count > 0) {
Game game = gamesToFarmSolo.First();
@@ -220,37 +223,42 @@ namespace ArchiSteamFarm {
await FarmingSemaphore.WaitAsync().ConfigureAwait(false);
if (!NowFarming) {
try {
if (!NowFarming) {
return;
}
Logging.LogGenericInfo("Sending signal to stop farming", Bot.BotName);
KeepFarming = false;
FarmResetEvent.Set();
Logging.LogGenericInfo("Waiting for reaction...", Bot.BotName);
for (byte i = 0; (i < 5) && NowFarming; i++) {
await Task.Delay(1000).ConfigureAwait(false);
}
if (NowFarming) {
Logging.LogGenericWarning("Timed out!", Bot.BotName);
}
Logging.LogGenericInfo("Farming stopped!", Bot.BotName);
Bot.OnFarmingStopped();
} finally {
FarmingSemaphore.Release();
return;
}
Logging.LogGenericInfo("Sending signal to stop farming", Bot.BotName);
KeepFarming = false;
FarmResetEvent.Set();
Logging.LogGenericInfo("Waiting for reaction...", Bot.BotName);
for (byte i = 0; (i < 5) && NowFarming; i++) {
await Task.Delay(1000).ConfigureAwait(false);
}
if (NowFarming) {
Logging.LogGenericWarning("Timed out!", Bot.BotName);
}
Logging.LogGenericInfo("Farming stopped!", Bot.BotName);
Bot.OnFarmingStopped();
FarmingSemaphore.Release();
}
internal void OnDisconnected() => StopFarming().Forget();
internal void OnNewItemsNotification() {
if (!NowFarming) {
internal async Task OnNewItemsNotification() {
if (NowFarming) {
FarmResetEvent.Set();
return;
}
FarmResetEvent.Set();
// If we're not farming, and we got new items, it's likely to be a booster pack or likewise
// In this case, perform a loot if user wants to do so
await Bot.LootIfNeeded().ConfigureAwait(false);
}
internal async Task OnNewGameAdded() {
@@ -442,8 +450,8 @@ namespace ArchiSteamFarm {
return;
}
byte cardsRemaining;
if (!byte.TryParse(progressMatch.Value, out cardsRemaining) || (cardsRemaining == 0)) {
ushort cardsRemaining;
if (!ushort.TryParse(progressMatch.Value, out cardsRemaining) || (cardsRemaining == 0)) {
Logging.LogNullError(nameof(cardsRemaining), Bot.BotName);
return;
}
@@ -497,7 +505,7 @@ namespace ArchiSteamFarm {
}
private void CheckGamesForFarming() {
if (NowFarming || ManualMode || !Bot.SteamClient.IsConnected) {
if (NowFarming || ManualMode || !Bot.IsConnectedAndLoggedOn) {
return;
}
@@ -527,11 +535,11 @@ namespace ArchiSteamFarm {
return null;
}
byte cardsRemaining = 0;
ushort cardsRemaining = 0;
Match match = Regex.Match(progress, @"\d+");
if (match.Success) {
if (!byte.TryParse(match.Value, out cardsRemaining)) {
if (!ushort.TryParse(match.Value, out cardsRemaining)) {
Logging.LogNullError(nameof(cardsRemaining), Bot.BotName);
return null;
}

View File

@@ -102,6 +102,21 @@ namespace ArchiSteamFarm {
}
}
internal bool ReplaceIfNeededWith(HashSet<T> items) {
Lock.EnterUpgradeableReadLock();
try {
if (HashSet.SetEquals(items)) {
return false;
}
ReplaceWith(items);
return true;
} finally {
Lock.ExitUpgradeableReadLock();
}
}
internal void ReplaceWith(IEnumerable<T> items) {
Lock.EnterWriteLock();

View File

@@ -23,9 +23,7 @@
*/
using SteamKit2;
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
namespace ArchiSteamFarm {
internal static class Debugging {
@@ -37,33 +35,14 @@ namespace ArchiSteamFarm {
internal static readonly bool IsDebugBuild = false;
#endif
internal static bool NetHookAlreadyInitialized { get; set; }
internal sealed class DebugListener : IDebugListener {
private readonly object FileLock = new object();
private readonly string FilePath;
internal DebugListener(string filePath) {
if (string.IsNullOrEmpty(filePath)) {
throw new ArgumentNullException(nameof(filePath));
}
FilePath = filePath;
}
public void WriteLine(string category, string msg) {
if (string.IsNullOrEmpty(category) && string.IsNullOrEmpty(msg)) {
Logging.LogNullError(nameof(category) + " && " + nameof(msg));
return;
}
lock (FileLock) {
try {
File.AppendAllText(FilePath, category + " | " + msg + Environment.NewLine);
} catch (Exception e) {
Logging.LogGenericException(e);
}
}
Logging.LogGenericDebug(category + " | " + msg, nameof(DebugListener));
}
}
}

View File

@@ -25,14 +25,13 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Threading;
namespace ArchiSteamFarm {
internal sealed class GlobalDatabase {
internal sealed class GlobalDatabase : IDisposable {
private static readonly JsonSerializerSettings CustomSerializerSettings = new JsonSerializerSettings {
Converters = new List<JsonConverter> {
Converters = new List<JsonConverter>(2) {
new IPAddressConverter(),
new IPEndPointConverter()
}
@@ -56,7 +55,6 @@ namespace ArchiSteamFarm {
}
[JsonProperty(Required = Required.DisallowNull)]
[SuppressMessage("ReSharper", "AutoPropertyCanBeMadeGetOnly.Local")]
internal readonly InMemoryServerListProvider ServerListProvider = new InMemoryServerListProvider();
private readonly object FileLock = new object();
@@ -91,7 +89,10 @@ namespace ArchiSteamFarm {
return globalDatabase;
}
private void OnServerListUpdated(object sender, EventArgs e) => Save();
public void Dispose() {
ServerListProvider.ServerListUpdated -= OnServerListUpdated;
ServerListProvider.Dispose();
}
// This constructor is used when creating new database
private GlobalDatabase(string filePath) : this() {
@@ -104,11 +105,12 @@ namespace ArchiSteamFarm {
}
// This constructor is used only by deserializer
[SuppressMessage("ReSharper", "UnusedMember.Local")]
private GlobalDatabase() {
ServerListProvider.ServerListUpdated += OnServerListUpdated;
}
private void OnServerListUpdated(object sender, EventArgs e) => Save();
private void Save() {
string json = JsonConvert.SerializeObject(this, CustomSerializerSettings);
if (string.IsNullOrEmpty(json)) {

View File

@@ -24,36 +24,36 @@
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Net;
using System.Threading.Tasks;
using Newtonsoft.Json;
using SteamKit2.Discovery;
namespace ArchiSteamFarm {
internal sealed class InMemoryServerListProvider : IServerListProvider {
internal sealed class InMemoryServerListProvider : IDisposable, IServerListProvider {
[JsonProperty(Required = Required.DisallowNull)]
[SuppressMessage("ReSharper", "FieldCanBeMadeReadOnly.Local")]
private HashSet<IPEndPoint> Servers = new HashSet<IPEndPoint>();
private readonly ConcurrentHashSet<IPEndPoint> Servers = new ConcurrentHashSet<IPEndPoint>();
internal event EventHandler ServerListUpdated = delegate { };
public Task<IEnumerable<IPEndPoint>> FetchServerListAsync() => Task.FromResult<IEnumerable<IPEndPoint>>(Servers);
public Task UpdateServerListAsync(IEnumerable<IPEndPoint> endpoints) {
if (endpoints == null) {
Logging.LogNullError(nameof(endpoints));
public Task UpdateServerListAsync(IEnumerable<IPEndPoint> endPoints) {
if (endPoints == null) {
Logging.LogNullError(nameof(endPoints));
return Task.Delay(0);
}
Servers.Clear();
foreach (IPEndPoint endpoint in endpoints) {
Servers.Add(endpoint);
HashSet<IPEndPoint> newServers = new HashSet<IPEndPoint>(endPoints);
if (!Servers.ReplaceIfNeededWith(newServers)) {
return Task.Delay(0);
}
ServerListUpdated(this, EventArgs.Empty);
return Task.Delay(0);
}
public void Dispose() => Servers.Dispose();
}
}

View File

@@ -29,7 +29,6 @@ using Newtonsoft.Json;
namespace ArchiSteamFarm.JSON {
internal static class GitHub {
[SuppressMessage("ReSharper", "ClassNeverInstantiated.Global")]
[SuppressMessage("ReSharper", "UnusedAutoPropertyAccessor.Local")]
internal sealed class ReleaseResponse {
#pragma warning disable 649
internal sealed class Asset {

View File

@@ -35,7 +35,7 @@ namespace ArchiSteamFarm.JSON {
internal static class Steam {
internal sealed class Item { // REF: https://developer.valvesoftware.com/wiki/Steam_Web_API/IEconService#CEcon_Asset | Deserialized from JSON (SteamCommunity) and constructed from code
internal const ushort SteamAppID = 753;
internal const byte SteamContextID = 6;
internal const byte SteamCommunityContextID = 6;
internal enum EType : byte {
Unknown,
@@ -269,9 +269,9 @@ namespace ArchiSteamFarm.JSON {
State = state;
}
internal bool IsSteamCardsOnlyTradeForUs() => ItemsToGive.All(item => (item.AppID == Item.SteamAppID) && (item.ContextID == Item.SteamContextID) && (item.Type == Item.EType.TradingCard));
internal bool IsSteamCardsRequest() => ItemsToGive.All(item => (item.AppID == Item.SteamAppID) && (item.ContextID == Item.SteamCommunityContextID) && (item.Type == Item.EType.TradingCard));
internal bool IsPotentiallyDupesTradeForUs() {
internal bool IsFairTypesExchange() {
Dictionary<uint, Dictionary<Item.EType, uint>> itemsToGivePerGame = new Dictionary<uint, Dictionary<Item.EType, uint>>();
foreach (Item item in ItemsToGive) {
Dictionary<Item.EType, uint> itemsPerType;
@@ -343,7 +343,6 @@ namespace ArchiSteamFarm.JSON {
[SuppressMessage("ReSharper", "ClassCannotBeInstantiated")]
[SuppressMessage("ReSharper", "ClassNeverInstantiated.Global")]
[SuppressMessage("ReSharper", "UnusedAutoPropertyAccessor.Local")]
internal sealed class ConfirmationResponse { // Deserialized from JSON
#pragma warning disable 649
[JsonProperty(PropertyName = "success", Required = Required.Always)]
@@ -355,7 +354,6 @@ namespace ArchiSteamFarm.JSON {
[SuppressMessage("ReSharper", "ClassCannotBeInstantiated")]
[SuppressMessage("ReSharper", "ClassNeverInstantiated.Global")]
[SuppressMessage("ReSharper", "UnusedAutoPropertyAccessor.Local")]
internal sealed class ConfirmationDetails { // Deserialized from JSON
internal enum EType : byte {
Unknown,

View File

@@ -23,7 +23,6 @@
*/
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
@@ -35,18 +34,17 @@ using NLog.Targets;
namespace ArchiSteamFarm {
internal static class Logging {
private const string LayoutMessage = @"${message}${onexception:inner= ${exception:format=toString,Data}}";
private const string GeneralLayout = @"${date:format=yyyy-MM-dd HH\:mm\:ss}|${level:uppercase=true}|" + LayoutMessage;
private const string GeneralLayout = @"${date:format=yyyy-MM-dd HH\:mm\:ss}|${processname}-${processid}|${level:uppercase=true}|" + LayoutMessage;
private const string EventLogLayout = LayoutMessage;
private static readonly ConcurrentHashSet<LoggingRule> ConsoleLoggingRules = new ConcurrentHashSet<LoggingRule>();
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
private static bool IsUsingCustomConfiguration, IsWaitingForUserInput;
private static bool IsWaitingForUserInput;
internal static void InitCoreLoggers() {
internal static void InitLoggers() {
if (LogManager.Configuration != null) {
// User provided custom NLog config, or we have it set already, so don't override it
IsUsingCustomConfiguration = true;
InitConsoleLoggers();
LogManager.ConfigurationChanged += OnConfigurationChanged;
return;
@@ -54,21 +52,12 @@ namespace ArchiSteamFarm {
LoggingConfiguration config = new LoggingConfiguration();
ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget("Console") {
ColoredConsoleTarget coloredConsoleTarget = new ColoredConsoleTarget("ColoredConsole") {
Layout = GeneralLayout
};
config.AddTarget(consoleTarget);
config.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, consoleTarget));
LogManager.Configuration = config;
InitConsoleLoggers();
}
internal static void InitEnhancedLoggers() {
if (IsUsingCustomConfiguration) {
return;
}
config.AddTarget(coloredConsoleTarget);
config.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, coloredConsoleTarget));
if (Program.IsRunningAsService) {
EventLogTarget eventLogTarget = new EventLogTarget("EventLog") {
@@ -77,21 +66,21 @@ namespace ArchiSteamFarm {
Source = SharedInfo.EventLogSource
};
LogManager.Configuration.AddTarget(eventLogTarget);
LogManager.Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, eventLogTarget));
} else {
config.AddTarget(eventLogTarget);
config.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, eventLogTarget));
} else if (Program.Mode != Program.EMode.Client) {
FileTarget fileTarget = new FileTarget("File") {
DeleteOldFileOnStartup = true,
FileName = SharedInfo.LogFile,
Layout = GeneralLayout
};
LogManager.Configuration.AddTarget(fileTarget);
LogManager.Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, fileTarget));
config.AddTarget(fileTarget);
config.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, fileTarget));
}
LogManager.ReconfigExistingLoggers();
LogGenericInfo("Logging module initialized!");
LogManager.Configuration = config;
InitConsoleLoggers();
}
internal static void OnUserInputStart() {
@@ -194,7 +183,6 @@ namespace ArchiSteamFarm {
LogGenericError(nullObjectName + " is null!", botName, previousMethodName);
}
[Conditional("DEBUG")]
[SuppressMessage("ReSharper", "UnusedMember.Global")]
internal static void LogGenericDebug(string message, string botName = SharedInfo.ASF, [CallerMemberName] string previousMethodName = null) {
if (string.IsNullOrEmpty(message)) {
@@ -207,7 +195,7 @@ namespace ArchiSteamFarm {
private static void InitConsoleLoggers() {
ConsoleLoggingRules.Clear();
foreach (LoggingRule loggingRule in from loggingRule in LogManager.Configuration.LoggingRules from target in loggingRule.Targets where target is ColoredConsoleTarget || target is ConsoleTarget select loggingRule) {
foreach (LoggingRule loggingRule in LogManager.Configuration.LoggingRules.Where(loggingRule => loggingRule.Targets.Any(target => target is ColoredConsoleTarget || target is ConsoleTarget))) {
ConsoleLoggingRules.Add(loggingRule);
}
}

View File

@@ -36,7 +36,7 @@ using Newtonsoft.Json;
namespace ArchiSteamFarm {
[SuppressMessage("ReSharper", "ClassCannotBeInstantiated")]
[SuppressMessage("ReSharper", "ClassNeverInstantiated.Global")]
internal sealed class MobileAuthenticator {
internal sealed class MobileAuthenticator : IDisposable {
internal sealed class Confirmation {
internal readonly uint ID;
internal readonly ulong Key;
@@ -64,9 +64,9 @@ namespace ArchiSteamFarm {
private static readonly SemaphoreSlim TimeSemaphore = new SemaphoreSlim(1);
private static short SteamTimeDifference;
private static short? SteamTimeDifference;
internal bool HasCorrectDeviceID => !string.IsNullOrEmpty(DeviceID) && !DeviceID.Equals("ERROR"); // "ERROR" is being used by SteamDesktopAuthenticator
private readonly SemaphoreSlim ConfirmationsSemaphore = new SemaphoreSlim(1);
#pragma warning disable 649
[JsonProperty(PropertyName = "shared_secret", Required = Required.Always)]
@@ -81,9 +81,9 @@ namespace ArchiSteamFarm {
private Bot Bot;
private MobileAuthenticator() {
internal bool HasCorrectDeviceID => !string.IsNullOrEmpty(DeviceID) && !DeviceID.Equals("ERROR"); // "ERROR" is being used by SteamDesktopAuthenticator
}
private MobileAuthenticator() { }
internal void Init(Bot bot) {
if (bot == null) {
@@ -113,19 +113,45 @@ namespace ArchiSteamFarm {
return false;
}
uint time = await GetSteamTime().ConfigureAwait(false);
if (time == 0) {
Logging.LogNullError(nameof(time), Bot.BotName);
return false;
}
await ConfirmationsSemaphore.WaitAsync().ConfigureAwait(false);
string confirmationHash = GenerateConfirmationKey(time, "conf");
if (!string.IsNullOrEmpty(confirmationHash)) {
return await Bot.ArchiWebHandler.HandleConfirmations(DeviceID, confirmationHash, time, confirmations, accept).ConfigureAwait(false);
}
try {
uint time = await GetSteamTime().ConfigureAwait(false);
if (time == 0) {
Logging.LogNullError(nameof(time), Bot.BotName);
return false;
}
Logging.LogNullError(nameof(confirmationHash), Bot.BotName);
return false;
string confirmationHash = GenerateConfirmationKey(time, "conf");
if (string.IsNullOrEmpty(confirmationHash)) {
Logging.LogNullError(nameof(confirmationHash), Bot.BotName);
return false;
}
bool? result = await Bot.ArchiWebHandler.HandleConfirmations(DeviceID, confirmationHash, time, confirmations, accept).ConfigureAwait(false);
if (!result.HasValue) { // Request timed out
return false;
}
if (result.Value) { // Request succeeded
return true;
}
// Our multi request failed, this is almost always Steam fuckup that happens randomly
// In this case, we'll accept all pending confirmations one-by-one, synchronously (as Steam can't handle them in parallel)
// We totally ignore actual result returned by those calls, abort only if request timed out
foreach (Confirmation confirmation in confirmations) {
bool? confirmationResult = await Bot.ArchiWebHandler.HandleConfirmation(DeviceID, confirmationHash, time, confirmation.ID, confirmation.Key, accept).ConfigureAwait(false);
if (!confirmationResult.HasValue) {
return false;
}
}
return true;
} finally {
ConfirmationsSemaphore.Release();
}
}
internal async Task<Steam.ConfirmationDetails> GetConfirmationDetails(Confirmation confirmation) {
@@ -243,22 +269,25 @@ namespace ArchiSteamFarm {
return result;
}
internal async Task<uint> GetSteamTime() {
if (SteamTimeDifference != 0) {
return (uint) (Utilities.GetUnixTime() + SteamTimeDifference);
private async Task<uint> GetSteamTime() {
if (SteamTimeDifference.HasValue) {
return (uint) (Utilities.GetUnixTime() + SteamTimeDifference.GetValueOrDefault());
}
await TimeSemaphore.WaitAsync().ConfigureAwait(false);
if (SteamTimeDifference == 0) {
uint serverTime = Bot.ArchiWebHandler.GetServerTime();
if (serverTime != 0) {
SteamTimeDifference = (short) (serverTime - Utilities.GetUnixTime());
try {
if (!SteamTimeDifference.HasValue) {
uint serverTime = Bot.ArchiWebHandler.GetServerTime();
if (serverTime != 0) {
SteamTimeDifference = (short) (serverTime - Utilities.GetUnixTime());
}
}
} finally {
TimeSemaphore.Release();
}
TimeSemaphore.Release();
return (uint) (Utilities.GetUnixTime() + SteamTimeDifference);
return (uint) (Utilities.GetUnixTime() + SteamTimeDifference.GetValueOrDefault());
}
private string GenerateTokenForTime(uint time) {
@@ -334,7 +363,9 @@ namespace ArchiSteamFarm {
hash = hmac.ComputeHash(buffer);
}
return Convert.ToBase64String(hash, Base64FormattingOptions.None);
return Convert.ToBase64String(hash);
}
public void Dispose() => ConfirmationsSemaphore.Dispose();
}
}

View File

@@ -25,7 +25,6 @@
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Reflection;
@@ -35,9 +34,7 @@ using System.Threading.Tasks;
namespace ArchiSteamFarm {
internal static class Program {
private enum EMode : byte {
[SuppressMessage("ReSharper", "UnusedMember.Local")]
Unknown,
internal enum EMode : byte {
Normal, // Standard most common usage
Client, // WCF client only
Server // Normal + WCF server
@@ -50,12 +47,11 @@ namespace ArchiSteamFarm {
internal static bool IsRunningAsService { get; private set; }
internal static bool ShutdownSequenceInitialized { get; private set; }
internal static EMode Mode { get; private set; } = EMode.Normal;
internal static GlobalConfig GlobalConfig { get; private set; }
internal static GlobalDatabase GlobalDatabase { get; private set; }
internal static WebBrowser WebBrowser { get; private set; }
private static EMode Mode = EMode.Normal;
internal static void Exit(byte exitCode = 0) {
Shutdown();
Environment.Exit(exitCode);
@@ -194,6 +190,12 @@ namespace ArchiSteamFarm {
switch (arg) {
case "":
break;
case "--client":
Mode = EMode.Client;
break;
case "--server":
Mode = EMode.Server;
break;
default:
if (arg.StartsWith("--", StringComparison.Ordinal)) {
if (arg.StartsWith("--path=", StringComparison.Ordinal) && (arg.Length > 7)) {
@@ -266,14 +268,6 @@ namespace ArchiSteamFarm {
AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionHandler;
TaskScheduler.UnobservedTaskException += UnobservedTaskExceptionHandler;
Logging.InitCoreLoggers();
Logging.LogGenericInfo("ASF V" + SharedInfo.Version);
if (!Runtime.IsRuntimeSupported) {
Logging.LogGenericError("ASF detected unsupported runtime version, program might NOT run correctly in current environment. You're running it at your own risk!");
Thread.Sleep(10000);
}
string homeDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
if (!string.IsNullOrEmpty(homeDirectory)) {
Directory.SetCurrentDirectory(homeDirectory);
@@ -301,6 +295,14 @@ namespace ArchiSteamFarm {
ParsePreInitArgs(args);
}
Logging.InitLoggers();
Logging.LogGenericInfo("ASF V" + SharedInfo.Version);
if (!Runtime.IsRuntimeSupported) {
Logging.LogGenericError("ASF detected unsupported runtime version, program might NOT run correctly in current environment. You're running it at your own risk!");
Thread.Sleep(10000);
}
InitServices();
// If debugging is on, we prepare debug directory prior to running
@@ -309,9 +311,10 @@ namespace ArchiSteamFarm {
Directory.Delete(SharedInfo.DebugDirectory, true);
Thread.Sleep(1000); // Dirty workaround giving Windows some time to sync
}
Directory.CreateDirectory(SharedInfo.DebugDirectory);
SteamKit2.DebugLog.AddListener(new Debugging.DebugListener(Path.Combine(SharedInfo.DebugDirectory, "debug.txt")));
SteamKit2.DebugLog.AddListener(new Debugging.DebugListener());
SteamKit2.DebugLog.Enabled = true;
}
@@ -326,8 +329,6 @@ namespace ArchiSteamFarm {
}
// From now on it's server mode
Logging.InitEnhancedLoggers();
if (!Directory.Exists(SharedInfo.ConfigDirectory)) {
Logging.LogGenericError("Config directory doesn't exist!");
Thread.Sleep(5000);

View File

@@ -5,11 +5,11 @@ using ArchiSteamFarm;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ArchiSteamFarm")]
[assembly: AssemblyTitle(SharedInfo.ServiceName)]
[assembly: AssemblyDescription(SharedInfo.ServiceDescription)]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ArchiSteamFarm")]
[assembly: AssemblyProduct(SharedInfo.ServiceName)]
[assembly: AssemblyCopyright(SharedInfo.Copyright)]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

View File

@@ -88,7 +88,7 @@ namespace ArchiSteamFarm {
return false;
}
Version minNetVersion = new Version(4, 6);
Version minNetVersion = new Version(4, 6, 1);
if (netVersion >= minNetVersion) {
Logging.LogGenericInfo("Your .NET version is OK. Required: " + minNetVersion + " | Found: " + netVersion);

View File

@@ -41,7 +41,7 @@ namespace ArchiSteamFarm {
WCFHostname
}
internal const string VersionNumber = "2.1.3.8";
internal const string VersionNumber = "2.1.5.2";
internal const string Copyright = "Copyright © ArchiSteamFarm 2015-2016";
internal const string GithubRepo = "JustArchi/ArchiSteamFarm";
@@ -58,6 +58,9 @@ namespace ArchiSteamFarm {
internal const string DebugDirectory = "debug";
internal const string LogFile = "log.txt";
internal const ulong ArchiSteamID = 76561198006963719;
internal const ulong ASFGroupSteamID = 103582791440160998;
internal const string GithubReleaseURL = "https://api.github.com/repos/" + GithubRepo + "/releases"; // GitHub API is HTTPS only
internal const string GlobalConfigFileName = ASF + ".json";
internal const string GlobalDatabaseFileName = ASF + ".db";

View File

@@ -129,6 +129,11 @@ namespace ArchiSteamFarm {
await Task.Delay(1000).ConfigureAwait(false); // Sometimes we can be too fast for Steam servers to generate confirmations, wait a short moment
await Bot.AcceptConfirmations(true, Steam.ConfirmationDetails.EType.Trade, 0, acceptedTradeIDs).ConfigureAwait(false);
}
if (results.Any(result => (result != null) && ((result.Result == ParseTradeResult.EResult.AcceptedWithItemLose) || (result.Result == ParseTradeResult.EResult.AcceptedWithoutItemLose)))) {
// If we finished a trade, perform a loot if user wants to do so
await Bot.LootIfNeeded().ConfigureAwait(false);
}
}
private async Task<ParseTradeResult> ParseTrade(Steam.TradeOffer tradeOffer) {
@@ -152,23 +157,25 @@ namespace ArchiSteamFarm {
case ParseTradeResult.EResult.AcceptedWithItemLose:
case ParseTradeResult.EResult.AcceptedWithoutItemLose:
Logging.LogGenericInfo("Accepting trade: " + tradeOffer.TradeOfferID, Bot.BotName);
return await Bot.ArchiWebHandler.AcceptTradeOffer(tradeOffer.TradeOfferID).ConfigureAwait(false) ? result : null;
await Bot.ArchiWebHandler.AcceptTradeOffer(tradeOffer.TradeOfferID).ConfigureAwait(false);
break;
case ParseTradeResult.EResult.RejectedPermanently:
case ParseTradeResult.EResult.RejectedTemporarily:
if (result.Result == ParseTradeResult.EResult.RejectedPermanently) {
if (Bot.BotConfig.IsBotAccount) {
Logging.LogGenericInfo("Rejecting trade: " + tradeOffer.TradeOfferID, Bot.BotName);
return Bot.ArchiWebHandler.DeclineTradeOffer(tradeOffer.TradeOfferID) ? result : null;
Bot.ArchiWebHandler.DeclineTradeOffer(tradeOffer.TradeOfferID);
break;
}
IgnoredTrades.Add(tradeOffer.TradeOfferID);
}
Logging.LogGenericInfo("Ignoring trade: " + tradeOffer.TradeOfferID, Bot.BotName);
return result;
default:
return result;
break;
}
return result;
}
private async Task<ParseTradeResult> ShouldAcceptTrade(Steam.TradeOffer tradeOffer) {
@@ -199,7 +206,7 @@ namespace ArchiSteamFarm {
}
// Decline trade if we're losing anything but steam cards, or if it's non-dupes trade
if (!tradeOffer.IsSteamCardsOnlyTradeForUs() || !tradeOffer.IsPotentiallyDupesTradeForUs()) {
if (!tradeOffer.IsSteamCardsRequest() || !tradeOffer.IsFairTypesExchange()) {
return new ParseTradeResult(tradeOffer.TradeOfferID, ParseTradeResult.EResult.RejectedPermanently);
}

View File

@@ -26,10 +26,12 @@ using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Net;
using System.Runtime.CompilerServices;
using System.Threading.Tasks;
namespace ArchiSteamFarm {
internal static class Utilities {
[MethodImpl(MethodImplOptions.AggressiveInlining)]
[SuppressMessage("ReSharper", "UnusedParameter.Global")]
internal static void Forget(this Task task) { }

View File

@@ -81,7 +81,7 @@ namespace ArchiSteamFarm {
public string GetStatus() => Program.GlobalConfig.SteamOwnerID == 0 ? "{}" : Bot.GetAPIStatus();
public void Dispose() {
Client?.Close();
StopClient();
StopServer();
}
@@ -141,6 +141,18 @@ namespace ArchiSteamFarm {
return Client.HandleCommand(input);
}
private void StopClient() {
if (Client == null) {
return;
}
if (Client.State != CommunicationState.Closed) {
Client.Close();
}
Client = null;
}
}
internal sealed class Client : ClientBase<IWCF> {

View File

@@ -147,25 +147,6 @@ namespace ArchiSteamFarm {
return null;
}
internal async Task<string> UrlGetToContentRetry(string request, string referer = null) {
if (string.IsNullOrEmpty(request)) {
Logging.LogNullError(nameof(request), Identifier);
return null;
}
string result = null;
for (byte i = 0; (i < MaxRetries) && string.IsNullOrEmpty(result); i++) {
result = await UrlGetToContent(request, referer).ConfigureAwait(false);
}
if (!string.IsNullOrEmpty(result)) {
return result;
}
Logging.LogGenericWarning("Request failed even after " + MaxRetries + " tries", Identifier);
return null;
}
internal async Task<HtmlDocument> UrlGetToHtmlDocumentRetry(string request, string referer = null) {
if (string.IsNullOrEmpty(request)) {
Logging.LogNullError(nameof(request), Identifier);
@@ -204,6 +185,25 @@ namespace ArchiSteamFarm {
return null;
}
internal async Task<T> UrlGetToJsonResultRetry<T>(string request, string referer = null) {
if (string.IsNullOrEmpty(request)) {
Logging.LogNullError(nameof(request), Identifier);
return default(T);
}
string json = await UrlGetToContentRetry(request, referer).ConfigureAwait(false);
if (string.IsNullOrEmpty(json)) {
return default(T);
}
try {
return JsonConvert.DeserializeObject<T>(json);
} catch (JsonException e) {
Logging.LogGenericException(e, Identifier);
return default(T);
}
}
internal async Task<XmlDocument> UrlGetToXMLRetry(string request, string referer = null) {
if (string.IsNullOrEmpty(request)) {
Logging.LogNullError(nameof(request), Identifier);
@@ -242,23 +242,23 @@ namespace ArchiSteamFarm {
return false;
}
internal async Task<string> UrlPostToContentRetry(string request, ICollection<KeyValuePair<string, string>> data = null, string referer = null) {
internal async Task<T> UrlPostToJsonResultRetry<T>(string request, ICollection<KeyValuePair<string, string>> data = null, string referer = null) {
if (string.IsNullOrEmpty(request)) {
Logging.LogNullError(nameof(request), Identifier);
return null;
return default(T);
}
string result = null;
for (byte i = 0; (i < MaxRetries) && string.IsNullOrEmpty(result); i++) {
result = await UrlPostToContent(request, data, referer).ConfigureAwait(false);
string json = await UrlPostToContentRetry(request, data, referer).ConfigureAwait(false);
if (string.IsNullOrEmpty(json)) {
return default(T);
}
if (!string.IsNullOrEmpty(result)) {
return result;
try {
return JsonConvert.DeserializeObject<T>(json);
} catch (JsonException e) {
Logging.LogGenericException(e, Identifier);
return default(T);
}
Logging.LogGenericWarning("Request failed even after " + MaxRetries + " tries", Identifier);
return null;
}
private async Task<byte[]> UrlGetToBytes(string request, string referer = null) {
@@ -291,6 +291,25 @@ namespace ArchiSteamFarm {
}
}
private async Task<string> UrlGetToContentRetry(string request, string referer = null) {
if (string.IsNullOrEmpty(request)) {
Logging.LogNullError(nameof(request), Identifier);
return null;
}
string result = null;
for (byte i = 0; (i < MaxRetries) && string.IsNullOrEmpty(result); i++) {
result = await UrlGetToContent(request, referer).ConfigureAwait(false);
}
if (!string.IsNullOrEmpty(result)) {
return result;
}
Logging.LogGenericWarning("Request failed even after " + MaxRetries + " tries", Identifier);
return null;
}
private async Task<HtmlDocument> UrlGetToHtmlDocument(string request, string referer = null) {
if (string.IsNullOrEmpty(request)) {
Logging.LogNullError(nameof(request), Identifier);
@@ -419,6 +438,25 @@ namespace ArchiSteamFarm {
}
}
private async Task<string> UrlPostToContentRetry(string request, ICollection<KeyValuePair<string, string>> data = null, string referer = null) {
if (string.IsNullOrEmpty(request)) {
Logging.LogNullError(nameof(request), Identifier);
return null;
}
string result = null;
for (byte i = 0; (i < MaxRetries) && string.IsNullOrEmpty(result); i++) {
result = await UrlPostToContent(request, data, referer).ConfigureAwait(false);
}
if (!string.IsNullOrEmpty(result)) {
return result;
}
Logging.LogGenericWarning("Request failed even after " + MaxRetries + " tries", Identifier);
return null;
}
private async Task<HttpResponseMessage> UrlPostToResponse(string request, IEnumerable<KeyValuePair<string, string>> data = null, string referer = null) {
if (!string.IsNullOrEmpty(request)) {
return await UrlRequest(request, HttpMethod.Post, data, referer).ConfigureAwait(false);

View File

@@ -8,7 +8,7 @@
"SteamApiKey": null,
"SteamMasterID": 0,
"SteamMasterClanID": 0,
"CardDropsRestricted": false,
"CardDropsRestricted": true,
"DismissInventoryNotifications": true,
"FarmingOrder": 0,
"FarmOffline": false,

View File

@@ -1,16 +1,20 @@
# Contributing
Before making an issue or pull request, you should carefully read **[ASF wiki](https://github.com/JustArchi/ArchiSteamFarm/wiki)** first.
Before making an issue or pull request, you should carefully read **[ASF wiki](https://github.com/JustArchi/ArchiSteamFarm/wiki)** first. At least reading **[FAQ](https://github.com/JustArchi/ArchiSteamFarm/wiki/FAQ)** is mandatory.
## Issues
GitHub **[issues](https://github.com/JustArchi/ArchiSteamFarm/issues)** page is being used for ASF TODO list, regarding both features and bugs. It has rather strict policy - GitHub is not technical support and all cases that are not suggestions or bug reports should NOT be posted there. You have **[ASF chat](https://gitter.im/JustArchi/ArchiSteamFarm)** and **[Steam group](http://steamcommunity.com/groups/ascfarm/discussions/1/)** for general discussion, questions or technical issues. Please avoid using GitHub issues, unless you indeed want to report a bug or suggest an enhancement. Even prior to doing that, please make sure that you're indeed dealing with a bug, or your suggestion makes sense, preferably by asking on chat/steam group first. Invalid issues will be closed immediately.
GitHub **[issues](https://github.com/JustArchi/ArchiSteamFarm/issues)** page is being used for ASF TODO list, regarding both features and bugs. It has rather strict policy - GitHub is NOT technical support and all cases that are not suggestions neither bug reports should NOT be posted there. You have **[ASF chat](https://gitter.im/JustArchi/ArchiSteamFarm)** and **[Steam group](http://steamcommunity.com/groups/ascfarm/discussions/1/)** for general discussion, questions or technical issues. Please avoid using GitHub issues, unless you indeed want to report a bug or suggest an enhancement. Even prior to doing that, please make sure that you're indeed dealing with a bug, or your suggestion makes sense, preferably by asking on chat/steam group first. Invalid issues will be closed immediately and won't be answered.
---
### Bugs
Posting a log is **mandatory**, regardless if it contains information that is relevant or not. You're allowed to make small modifications such as changing bot names to something more generic, but you should not be doing anything else. You want us to fix the bug you've encountered, then help us instead of making it harder - we're not being paid for that, and we're not forced to fix the bug you've encountered. Include as much relevant info as possible - if bug is reproducable, when it happens, if it's a result of a command - which one, does it happen always or only sometimes, with one account or all of them - everything you consider appropriate, that would help us reproduce the bug and fix it. The more information you include, the higher the chance of bug getting fixed. And this is probably what you want, right?
Before reporting a bug you should carefully check if the "bug" you're encountering is in fact ASF bug and not technical issue that is answered in the **[FAQ](https://github.com/JustArchi/ArchiSteamFarm/wiki/FAQ#issues)** or in other place on the wiki. Typically technical issue is intentional ASF behaviour which might not match your expectations, e.g. failing to send or accept steam trades - logic for accepting and sending steam trades is outside of the ASF, as stated in the FAQ, and there is no bug related to that because it's up to Steam to accept such request, or not. If you're not sure if you're encountering ASF bug or technical issue, please use **[ASF chat](https://gitter.im/JustArchi/ArchiSteamFarm)** or **[Steam group](http://steamcommunity.com/groups/ascfarm/discussions/1/)** and avoid GitHub issues.
Regarding ASF bugs - Posting a log is **mandatory**, regardless if it contains information that is relevant or not. You're allowed to make small modifications such as changing bot names to something more generic, but you should not be doing anything else. You want us to fix the bug you've encountered, then help us instead of making it harder - we're not being paid for that, and we're not forced to fix the bug you've encountered. Include as much relevant info as possible - if bug is reproducable, when it happens, if it's a result of a command - which one, does it happen always or only sometimes, with one account or all of them - everything you consider appropriate, that would help us reproduce the bug and fix it. The more information you include, the higher the chance of bug getting fixed. If nobody is able to reproduce your bug, there is also no way of blindly fixing it.
It would also be cool if you could reproduce your issue on latest pre-release (and not stable) version, as this is most recent codebase that might include not-yet-released fix for your issue already. Of course, that is not mandatory, as ASF offers support for both latest pre-release as well as latest stable versions.
---
@@ -28,3 +32,22 @@ In general any pull request is welcome and should be accepted, unless there is a
Every pull request is carefully examined by our continuous integration system - it won't be accepted if it doesn't compile properly or causes any test to fail. We also expect that you at least barely tested the modification you're trying to add, and not blindly editing the file without even checking if it compiles. Consider the fact that you're not coding it only for yourself, but for thousands of users.
---
### License
ASF is using **[Apache License 2.0](https://github.com/JustArchi/ArchiSteamFarm/blob/master/LICENSE-2.0.txt)**.
> Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions.
The license also permits you to:
> You may add Your own copyright statement to Your modifications(...)
Adding your own copyright statement is totally fine and it should be in format of **[copyright and contact](https://github.com/JustArchi/ArchiSteamFarm/blob/master/ArchiSteamFarm/Program.cs#L8-L9)**, specified below all currently existing statements of the file you're modifying. Adding such statement is not mandatory when sending PRs, and it's up to you to decide if you want to put one, or not.
---
### Code style
Please stick with ASF code style when submitting PRs. In repo you can find standard **[VS settings](https://github.com/JustArchi/ArchiSteamFarm/blob/master/CodeStyle.vssettings)** file that you can use in Visual Studio for import. In addition to that, there is also **[DotSettings](https://github.com/JustArchi/ArchiSteamFarm/blob/master/ArchiSteamFarm.sln.DotSettings)** file for **[ReSharper](https://www.jetbrains.com/resharper/)** (optional). Consistency is the key.

View File

@@ -53,36 +53,46 @@ namespace ConfigGenerator {
NamesDescending
}
[Category("\t\tCore")]
[JsonProperty(Required = Required.DisallowNull)]
public bool Enabled { get; set; } = false;
[Category("\tAdvanced")]
[JsonProperty(Required = Required.DisallowNull)]
public bool StartOnLaunch { get; set; } = true;
[Category("\t\tCore")]
[JsonProperty]
public string SteamLogin { get; set; } = null;
[Category("\t\tCore")]
[JsonProperty]
[PasswordPropertyText(true)]
public string SteamPassword { get; set; } = null;
[Category("\tAccess")]
[JsonProperty(Required = Required.DisallowNull)]
public ECryptoMethod PasswordFormat { get; set; } = ECryptoMethod.PlainText;
[Category("\tAccess")]
[JsonProperty]
public string SteamParentalPIN { get; set; } = "0";
[Category("\tAccess")]
[JsonProperty]
public string SteamApiKey { get; set; } = null;
[Category("\tAccess")]
[JsonProperty(Required = Required.DisallowNull)]
public ulong SteamMasterID { get; set; } = 0;
[Category("\tAccess")]
[JsonProperty(Required = Required.DisallowNull)]
public ulong SteamMasterClanID { get; set; } = 0;
[Category("\tPerformance")]
[JsonProperty(Required = Required.DisallowNull)]
public bool CardDropsRestricted { get; set; } = false;
public bool CardDropsRestricted { get; set; } = true;
[JsonProperty(Required = Required.DisallowNull)]
public bool DismissInventoryNotifications { get; set; } = true;
@@ -93,15 +103,18 @@ namespace ConfigGenerator {
[JsonProperty(Required = Required.DisallowNull)]
public bool FarmOffline { get; set; } = false;
[Category("\tAdvanced")]
[JsonProperty(Required = Required.DisallowNull)]
public bool HandleOfflineMessages { get; set; } = false;
[JsonProperty(Required = Required.DisallowNull)]
public bool AcceptGifts { get; set; } = false;
[Category("\tAdvanced")]
[JsonProperty(Required = Required.DisallowNull)]
public bool IsBotAccount { get; set; } = false;
[Category("\tAdvanced")]
[JsonProperty(Required = Required.DisallowNull)]
public bool SteamTradeMatcher { get; set; } = false;
@@ -117,12 +130,14 @@ namespace ConfigGenerator {
[JsonProperty(Required = Required.DisallowNull)]
public bool SendOnFarmingFinished { get; set; } = false;
[Category("\tAccess")]
[JsonProperty]
public string SteamTradeToken { get; set; } = null;
[JsonProperty(Required = Required.DisallowNull)]
public byte SendTradePeriod { get; set; } = 0;
[Category("\tAdvanced")]
[JsonProperty(Required = Required.DisallowNull)]
public byte AcceptConfirmationsPeriod { get; set; } = 0;

View File

@@ -25,6 +25,7 @@
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
@@ -36,10 +37,14 @@
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<TreatWarningsAsErrors>false</TreatWarningsAsErrors>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup>
<ApplicationIcon>cirno.ico</ApplicationIcon>
</PropertyGroup>
<PropertyGroup>
<RunPostBuildEvent>OnOutputUpdated</RunPostBuildEvent>
</PropertyGroup>
<ItemGroup>
<Reference Include="Newtonsoft.Json, Version=9.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.9.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
@@ -74,6 +79,7 @@
</Compile>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="RunTime.cs" />
<Compile Include="Tutorial.cs" />
<EmbeddedResource Include="ConfigPage.resx">
<DependentUpon>ConfigPage.cs</DependentUpon>
@@ -117,7 +123,11 @@
copy "$(TargetDir)$(TargetName).exe" "$(SolutionDir)out\ASF-ConfigGenerator.exe"
</PostBuildEvent>
<PostBuildEvent Condition=" '$(OS)' == 'Unix' AND '$(ConfigurationName)' == 'Release' ">
mono --llvm --server -O=all "$(SolutionDir)tools/ILRepack/ILRepack.exe" /ndebug /internalize /parallel /targetplatform:v4 /wildcards /out:"$(SolutionDir)out/ASF-ConfigGenerator.exe" "$(TargetDir)$(TargetName).exe" "$(TargetDir)*.dll"
if [ -f "$(SolutionDir)mono_envsetup.sh" ]; then
. "$(SolutionDir)mono_envsetup.sh"
fi
mono "$(SolutionDir)tools/ILRepack/ILRepack.exe" /ndebug /internalize /parallel /targetplatform:v4 /wildcards /out:"$(SolutionDir)out/ASF-ConfigGenerator.exe" "$(TargetDir)$(TargetName).exe" "$(TargetDir)*.dll"
rm "$(SolutionDir)out/ASF-ConfigGenerator.exe.config"
</PostBuildEvent>
</PropertyGroup>

View File

@@ -25,6 +25,7 @@
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Net.Sockets;
@@ -50,57 +51,74 @@ namespace ConfigGenerator {
// This is hardcoded blacklist which should not be possible to change
private static readonly HashSet<uint> GlobalBlacklist = new HashSet<uint> { 267420, 303700, 335590, 368020, 425280, 480730 };
[Category("\tDebugging")]
[JsonProperty(Required = Required.DisallowNull)]
public bool Debug { get; set; } = false;
[Category("\tAdvanced")]
[JsonProperty(Required = Required.DisallowNull)]
public bool Headless { get; set; } = false;
[Category("\tUpdates")]
[JsonProperty(Required = Required.DisallowNull)]
public bool AutoUpdates { get; set; } = true;
[Category("\tUpdates")]
[JsonProperty(Required = Required.DisallowNull)]
public bool AutoRestart { get; set; } = true;
[Category("\tUpdates")]
[JsonProperty(Required = Required.DisallowNull)]
public EUpdateChannel UpdateChannel { get; set; } = EUpdateChannel.Stable;
[Category("\tAdvanced")]
[JsonProperty(Required = Required.DisallowNull)]
public ProtocolType SteamProtocol { get; set; } = DefaultSteamProtocol;
[Category("\tAccess")]
[JsonProperty(Required = Required.DisallowNull)]
public ulong SteamOwnerID { get; set; } = 0;
[Category("\tPerformance")]
[JsonProperty(Required = Required.DisallowNull)]
public byte MaxFarmingTime { get; set; } = DefaultMaxFarmingTime;
[Category("\tPerformance")]
[JsonProperty(Required = Required.DisallowNull)]
public byte IdleFarmingPeriod { get; set; } = 3;
[Category("\tPerformance")]
[JsonProperty(Required = Required.DisallowNull)]
public byte FarmingDelay { get; set; } = DefaultFarmingDelay;
[Category("\tPerformance")]
[JsonProperty(Required = Required.DisallowNull)]
public byte LoginLimiterDelay { get; set; } = 10;
[Category("\tPerformance")]
[JsonProperty(Required = Required.DisallowNull)]
public byte InventoryLimiterDelay { get; set; } = 3;
[Category("\tPerformance")]
[JsonProperty(Required = Required.DisallowNull)]
public byte GiftsLimiterDelay { get; set; } = 1;
[JsonProperty(Required = Required.DisallowNull)]
public byte MaxTradeHoldDuration { get; set; } = 15;
[Category("\tDebugging")]
[JsonProperty(Required = Required.DisallowNull)]
public bool ForceHttp { get; set; } = false;
[Category("\tDebugging")]
[JsonProperty(Required = Required.DisallowNull)]
public byte HttpTimeout { get; set; } = DefaultHttpTimeout;
[Category("\tAccess")]
[JsonProperty]
public string WCFHostname { get; set; } = "localhost";
[Category("\tAccess")]
[JsonProperty(Required = Required.DisallowNull)]
public ushort WCFPort { get; set; } = DefaultWCFPort;

View File

@@ -5,11 +5,11 @@ using ArchiSteamFarm;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("ConfigGenerator")]
[assembly: AssemblyTitle(SharedInfo.ServiceName + "-ConfigGenerator")]
[assembly: AssemblyDescription(SharedInfo.ServiceDescription)]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ConfigGenerator")]
[assembly: AssemblyProduct(SharedInfo.ServiceName + "-ConfigGenerator")]
[assembly: AssemblyCopyright(SharedInfo.Copyright)]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

View File

@@ -0,0 +1,33 @@
/*
_ _ _ ____ _ _____
/ \ _ __ ___ | |__ (_)/ ___| | |_ ___ __ _ _ __ ___ | ___|__ _ _ __ _ __ ___
/ _ \ | '__|/ __|| '_ \ | |\___ \ | __|/ _ \ / _` || '_ ` _ \ | |_ / _` || '__|| '_ ` _ \
/ ___ \ | | | (__ | | | || | ___) || |_| __/| (_| || | | | | || _|| (_| || | | | | | | |
/_/ \_\|_| \___||_| |_||_||____/ \__|\___| \__,_||_| |_| |_||_| \__,_||_| |_| |_| |_|
Copyright 2015-2016 Łukasz "JustArchi" Domeradzki
Contact: JustArchi@JustArchi.net
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
using System;
namespace ConfigGenerator {
internal static class Runtime {
private static readonly Type MonoRuntime = Type.GetType("Mono.Runtime");
internal static bool IsRunningOnMono => MonoRuntime != null;
}
}

View File

@@ -57,8 +57,14 @@ namespace ConfigGenerator {
Logging.LogGenericInfoWithoutStacktrace("You can now notice the main ASF Config Generator screen, it's really easy to use!");
Logging.LogGenericInfoWithoutStacktrace("At the top of the window you can notice currently loaded configs, and 3 extra buttons for removing, renaming and adding new ones.");
Logging.LogGenericInfoWithoutStacktrace("In the middle of the window you will be able to configure all config properties that are available for you.");
Logging.LogGenericInfoWithoutStacktrace("In the top right corner you can find help button [?] which will redirect you to ASF wiki where you can find more information.");
Logging.LogGenericInfoWithoutStacktrace("Please click the help button to continue.");
if (!Runtime.IsRunningOnMono) {
Logging.LogGenericInfoWithoutStacktrace("In the top right corner you can find help button [?] which will redirect you to ASF wiki where you can find more information.");
Logging.LogGenericInfoWithoutStacktrace("Please click the help button to continue.");
} else {
Logging.LogGenericInfoWithoutStacktrace("Please visit ASF wiki if you're in doubt - you can find more information there.");
Logging.LogGenericInfoWithoutStacktrace("Alright, let's start configuring our ASF. Click on the plus [+] button to add your first steam account to ASF!");
NextPhase = EPhase.HelpFinished;
}
break;
case EPhase.Help:
Logging.LogGenericInfoWithoutStacktrace("Well done! On ASF wiki you can find detailed help about every config property you're going to configure in a moment.");

4
GUI/FodyWeavers.xml Normal file
View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="utf-8"?>
<Weavers>
<Costura IncludeDebugSymbols='false' />
</Weavers>

View File

@@ -12,6 +12,8 @@
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
@@ -22,19 +24,25 @@
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<DebugType>none</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<DefineConstants>
</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<Prefer32Bit>false</Prefer32Bit>
</PropertyGroup>
<PropertyGroup>
<ApplicationIcon>cirno.ico</ApplicationIcon>
</PropertyGroup>
<PropertyGroup>
<RunPostBuildEvent>OnOutputUpdated</RunPostBuildEvent>
</PropertyGroup>
<ItemGroup>
<Reference Include="HtmlAgilityPack, Version=1.4.9.5, Culture=neutral, PublicKeyToken=bd319b19eaf3b43a, processorArchitecture=MSIL">
<HintPath>..\packages\HtmlAgilityPack.1.4.9.5\lib\Net45\HtmlAgilityPack.dll</HintPath>
@@ -61,18 +69,10 @@
<Private>True</Private>
</Reference>
<Reference Include="System" />
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
<Reference Include="System.IO.Compression" />
<Reference Include="System.Runtime.Serialization" />
<Reference Include="System.Security" />
<Reference Include="System.ServiceModel" />
<Reference Include="System.Transactions" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Deployment" />
<Reference Include="System.Drawing" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Windows.Forms" />
@@ -199,9 +199,32 @@
</ItemGroup>
<ItemGroup>
<Content Include="cirno.ico" />
<None Include="FodyWeavers.xml" />
<None Include="Resources\SteamUnknownAvatar.jpg" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<PropertyGroup>
<PostBuildEvent Condition=" '$(OS)' != 'Unix' AND '$(ConfigurationName)' == 'Release' ">
copy "$(TargetDir)$(TargetName).exe" "$(SolutionDir)out\ASF-GUI.exe"
</PostBuildEvent>
<PostBuildEvent Condition=" '$(OS)' == 'Unix' AND '$(ConfigurationName)' == 'Release' ">
if [ -f "$(SolutionDir)mono_envsetup.sh" ]; then
. "$(SolutionDir)mono_envsetup.sh"
fi
mono "$(SolutionDir)tools/ILRepack/ILRepack.exe" /ndebug /internalize /parallel /targetplatform:v4 /wildcards /out:"$(SolutionDir)out/ASF-GUI.exe" "$(TargetDir)$(TargetName).exe" "$(TargetDir)*.dll"
rm "$(SolutionDir)out/ASF-GUI.exe.config"
</PostBuildEvent>
</PropertyGroup>
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}.</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\packages\Fody.1.30.0-beta01\build\dotnet\Fody.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Fody.1.30.0-beta01\build\dotnet\Fody.targets'))" />
<Error Condition="!Exists('..\packages\Costura.Fody.2.0.0-beta0018\build\Costura.Fody.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\Costura.Fody.2.0.0-beta0018\build\Costura.Fody.targets'))" />
</Target>
<Import Project="..\packages\Fody.1.30.0-beta01\build\dotnet\Fody.targets" Condition="'$(OS)' != 'Unix' AND '$(ConfigurationName)' == 'Release' AND Exists('..\packages\Fody.1.30.0-beta01\build\dotnet\Fody.targets')" />
<Import Project="..\packages\Costura.Fody.2.0.0-beta0018\build\Costura.Fody.targets" Condition="'$(OS)' != 'Unix' AND '$(ConfigurationName)' == 'Release' AND Exists('..\packages\Costura.Fody.2.0.0-beta0018\build\Costura.Fody.targets')" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.
<Target Name="BeforeBuild">

View File

@@ -23,7 +23,6 @@
*/
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
@@ -172,7 +171,6 @@ namespace ArchiSteamFarm {
LogGenericError(nullObjectName + " is null!", botName, previousMethodName);
}
[Conditional("DEBUG")]
[SuppressMessage("ReSharper", "UnusedMember.Global")]
internal static void LogGenericDebug(string message, string botName = SharedInfo.ASF, [CallerMemberName] string previousMethodName = null) {
if (string.IsNullOrEmpty(message)) {

View File

@@ -126,9 +126,10 @@ namespace ArchiSteamFarm {
Directory.Delete(SharedInfo.DebugDirectory, true);
Thread.Sleep(1000); // Dirty workaround giving Windows some time to sync
}
Directory.CreateDirectory(SharedInfo.DebugDirectory);
SteamKit2.DebugLog.AddListener(new Debugging.DebugListener(Path.Combine(SharedInfo.DebugDirectory, "debug.txt")));
SteamKit2.DebugLog.AddListener(new Debugging.DebugListener());
SteamKit2.DebugLog.Enabled = true;
}

View File

@@ -5,11 +5,11 @@ using ArchiSteamFarm;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("GUI")]
[assembly: AssemblyTitle(SharedInfo.ServiceName + "-GUI")]
[assembly: AssemblyDescription(SharedInfo.ServiceDescription)]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("GUI")]
[assembly: AssemblyProduct(SharedInfo.ServiceName + "-GUI")]
[assembly: AssemblyCopyright(SharedInfo.Copyright)]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]

View File

@@ -1,5 +1,7 @@
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Costura.Fody" version="2.0.0-beta0018" targetFramework="net461" developmentDependency="true" />
<package id="Fody" version="1.30.0-beta01" targetFramework="net461" developmentDependency="true" />
<package id="HtmlAgilityPack" version="1.4.9.5" targetFramework="net461" />
<package id="Newtonsoft.Json" version="9.0.1" targetFramework="net461" />
<package id="NLog" version="4.4.0-betaV15" targetFramework="net461" />

View File

@@ -6,9 +6,10 @@ ArchiSteamFarm
[![Build Status (Mono)](https://img.shields.io/travis/JustArchi/ArchiSteamFarm.svg?label=Mono&maxAge=60)](https://travis-ci.org/JustArchi/ArchiSteamFarm)
[![License](https://img.shields.io/github/license/JustArchi/ArchiSteamFarm.svg?label=License&maxAge=86400)](./LICENSE-2.0.txt)
[![GitHub Release](https://img.shields.io/github/release/JustArchi/ArchiSteamFarm.svg?label=Latest&maxAge=60)](https://github.com/JustArchi/ArchiSteamFarm/releases/latest)
[![Github All Releases](https://img.shields.io/github/downloads/JustArchi/ArchiSteamFarm/total.svg?label=Downloads&maxAge=60)](https://github.com/JustArchi/ArchiSteamFarm/releases)
[![Github Downloads](https://img.shields.io/github/downloads/JustArchi/ArchiSteamFarm/latest/total.svg?label=Downloads&maxAge=60)](https://github.com/JustArchi/ArchiSteamFarm/releases/latest)
[![Paypal Donate](https://img.shields.io/badge/PayPal-donate-yellow.svg)](https://www.paypal.me/JustArchi/1usd)
[![Paypal.me Donate](https://img.shields.io/badge/Paypal.me-donate-yellow.svg)](https://www.paypal.me/JustArchi/1usd)
[![Paypal Donate](https://img.shields.io/badge/Paypal-donate-yellow.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=HD2P2P3WGS5Y4)
[![Steam Donate](https://img.shields.io/badge/Steam-donate-yellow.svg)](https://steamcommunity.com/tradeoffer/new/?partner=46697991&token=0ix2Ruv_)
---
@@ -42,8 +43,10 @@ ASF officially supports Windows, Linux and OS X operating systems, including fol
- Windows 10 (Native)
- Windows 8.1 (Native)
- Windows 7 (Native)
- Windows Vista (Native)
- Windows 8 (Native)
- Windows 7 SP1 (Native)
- Windows Server 2012 R2 (Native)
- Windows Server 2008 R2 SP1 (Native)
- Debian 9 Stretch (Mono)
- Debian 8 Jessie (Mono)
- Ubuntu 16.04 (Mono)

View File

@@ -13,4 +13,4 @@ notifications:
method: POST
on_build_success: true
on_build_failure: true
on_build_status_changed: true
on_build_status_changed: false

9
cc.sh
View File

@@ -5,7 +5,6 @@ BUILD="Release"
AOT=0
CLEAN=0
MONO_ARGS=("--aot" "--llvm" "--server" "-O=all")
XBUILD_ARGS=("/nologo")
BINARIES=("ArchiSteamFarm/bin/Release/ArchiSteamFarm.exe")
SOLUTION="ArchiSteamFarm.sln"
@@ -29,6 +28,12 @@ XBUILD_ARGS+=("/p:Configuration=$BUILD")
cd "$(dirname "$(readlink -f "$0")")"
if [[ -f "mono_envsetup.sh" ]]; then
set +u
source "mono_envsetup.sh"
set -u
fi
if [[ -d ".git" ]] && hash git &>/dev/null; then
git pull || true
fi
@@ -60,7 +65,7 @@ if [[ "$AOT" -eq 1 && "$BUILD" = "Release" ]]; then
continue
fi
mono "${MONO_ARGS[@]}" "$BINARY"
mono --aot "$BINARY"
done
fi

68
mono_envsetup.sh Normal file
View File

@@ -0,0 +1,68 @@
MONO_DEBUG_IF_AVAILABLE() {
local PREVIOUS_MONO_DEBUG="$MONO_DEBUG"
# Add change if needed
if [ -z "$PREVIOUS_MONO_DEBUG" ]; then
export MONO_DEBUG="$1"
elif echo "$PREVIOUS_MONO_DEBUG" | grep -Fq "$1"; then
echo "Success: $1 already exists"
return 0
else
export MONO_DEBUG="${PREVIOUS_MONO_DEBUG},${1}"
fi
# If we did a change, check if Mono supports that option
# If not, it will be listed as invalid option on line 1
if mono "" 2>&1 | head -n 1 | grep -Fq "$1"; then
echo "Failure: $1"
export MONO_DEBUG="$PREVIOUS_MONO_DEBUG"
return 1
fi
echo "Success: $1"
return 0
}
VERSION_GREATER() {
if [ "$1" = "$2" ]; then
return 1
fi
! VERSION_LESS_EQUAL "$1" "$2"
}
VERSION_GREATER_EQUAL() {
! VERSION_LESS "$1" "$2"
}
VERSION_LESS() {
if [ "$1" = "$2" ]; then
return 1
fi
VERSION_LESS_EQUAL "$1" "$2"
}
VERSION_LESS_EQUAL() {
[ "$1" = "$(echo -e "$1\n$2" | sort -V | head -n 1)" ]
}
echo "Mono environment setup executed!"
MONO_VERSION="$(mono -V | head -n 1 | cut -d ' ' -f 5)"
echo "Mono version: $MONO_VERSION"
if VERSION_GREATER_EQUAL "$MONO_VERSION" "4.6.0"; then
echo "INFO: Appending no-compact-seq-points to MONO_DEBUG..."
MONO_DEBUG_IF_AVAILABLE "no-compact-seq-points"
fi
if [ -z "$MONO_ENV_OPTIONS" ]; then
echo "INFO: Setting MONO_ENV_OPTIONS to: --server -O=all"
export MONO_ENV_OPTIONS="--server -O=all"
else
echo "INFO: Skipping setting of MONO_ENV_OPTIONS as it's already declared with value: $MONO_ENV_OPTIONS"
fi
echo "Mono environment setup finished!"

15
run.sh
View File

@@ -6,7 +6,6 @@ BUILD="Release"
UNTIL_CLEAN_EXIT=0
ASF_ARGS=("")
MONO_ARGS=("--llvm" "--server" "-O=all")
PRINT_USAGE() {
echo "Usage: $0 [--until-clean-exit] [--cryptkey=] [--path=] [--server] [debug/release]"
@@ -25,12 +24,14 @@ for ARG in "$@"; do
esac
done
if [[ "$BUILD" = "Debug" ]]; then
MONO_ARGS+=("--debug")
fi
cd "$(dirname "$(readlink -f "$0")")"
if [[ -f "mono_envsetup.sh" ]]; then
set +u
source "mono_envsetup.sh"
set -u
fi
BINARY="ArchiSteamFarm/bin/$BUILD/ArchiSteamFarm.exe"
if [[ ! -f "$BINARY" ]]; then
@@ -39,12 +40,12 @@ if [[ ! -f "$BINARY" ]]; then
fi
if [[ "$UNTIL_CLEAN_EXIT" -eq 0 ]]; then
mono "${MONO_ARGS[@]}" "$BINARY" "${ASF_ARGS[@]}"
mono "$BINARY" "${ASF_ARGS[@]}"
exit $?
fi
while [[ -f "$BINARY" ]]; do
if mono "${MONO_ARGS[@]}" "$BINARY" "${ASF_ARGS[@]}"; then
if mono "$BINARY" "${ASF_ARGS[@]}"; then
break
fi
sleep 1