mirror of
https://github.com/JustArchiNET/ArchiSteamFarm.git
synced 2025-12-17 23:10:30 +00:00
Compare commits
102 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f3868b9acc | ||
|
|
7c3d195fd4 | ||
|
|
4d7294feac | ||
|
|
6877abed6e | ||
|
|
5353d755a0 | ||
|
|
d2dff449d1 | ||
|
|
d526c6c1ce | ||
|
|
49fc908f0f | ||
|
|
b3162ce390 | ||
|
|
9a2a37f2fc | ||
|
|
a90b3afcdd | ||
|
|
6c903b2433 | ||
|
|
00558441fe | ||
|
|
7e10e6ba81 | ||
|
|
3995b3a083 | ||
|
|
e6c9c3f0a9 | ||
|
|
c8fc25111e | ||
|
|
6b3cf5e788 | ||
|
|
afbd8d12b4 | ||
|
|
e8e393b320 | ||
|
|
84db370516 | ||
|
|
173148ce25 | ||
|
|
0fd0528fd0 | ||
|
|
664a0e0758 | ||
|
|
6454e3ee12 | ||
|
|
33f4a82dd5 | ||
|
|
9bd6532411 | ||
|
|
b89d2977f8 | ||
|
|
25b557d5d1 | ||
|
|
3e34fabfaf | ||
|
|
fc49e8ffa7 | ||
|
|
48a5eeec29 | ||
|
|
7fa176ef7b | ||
|
|
bfaa99a8a9 | ||
|
|
1ff4ed026e | ||
|
|
1703bbfb68 | ||
|
|
a6a2e1605d | ||
|
|
c0c61913c2 | ||
|
|
fb2437d75d | ||
|
|
499e55c473 | ||
|
|
dfd4513b16 | ||
|
|
f873da7236 | ||
|
|
59360c5b60 | ||
|
|
750c34189a | ||
|
|
7c3f5beb3a | ||
|
|
8dfe095dae | ||
|
|
53022632e0 | ||
|
|
29a916e5ad | ||
|
|
44b3a518bd | ||
|
|
1fe60e7037 | ||
|
|
27ad98492f | ||
|
|
e3386c5b29 | ||
|
|
021ac470d3 | ||
|
|
b4fb0bf9a6 | ||
|
|
b63dd1035c | ||
|
|
f577e1a6cb | ||
|
|
34ffb975b6 | ||
|
|
5a3b132d5e | ||
|
|
ef29b6f33d | ||
|
|
e8335ac183 | ||
|
|
90339fb276 | ||
|
|
88759303dd | ||
|
|
befe01ca59 | ||
|
|
c9cc728da3 | ||
|
|
a81a59396d | ||
|
|
df3fcfb1df | ||
|
|
e097b33d89 | ||
|
|
db6e775b10 | ||
|
|
b53c41a0f9 | ||
|
|
fec4873843 | ||
|
|
1e2efe38f1 | ||
|
|
3e0dfac091 | ||
|
|
36d745aece | ||
|
|
7896e7924e | ||
|
|
5b3c730d51 | ||
|
|
f3aee0c34f | ||
|
|
47389f67b8 | ||
|
|
19e72c93c1 | ||
|
|
164240641b | ||
|
|
337c397505 | ||
|
|
137e8d1f63 | ||
|
|
fed3ac3404 | ||
|
|
3ba90e5d6d | ||
|
|
71227168cf | ||
|
|
2545e7bbf3 | ||
|
|
411f796fab | ||
|
|
fa6dbed593 | ||
|
|
a0ba148005 | ||
|
|
abe3beaee7 | ||
|
|
7c9e5d818e | ||
|
|
571b0dc936 | ||
|
|
0a13d341b7 | ||
|
|
18790c57a1 | ||
|
|
abcded9287 | ||
|
|
a17682e4e2 | ||
|
|
cd0d0a94a1 | ||
|
|
639067d04f | ||
|
|
03885babf6 | ||
|
|
33b42fb76c | ||
|
|
d30d90a5b0 | ||
|
|
30ca6ce7ef | ||
|
|
a1d2996039 |
8
.gitignore
vendored
8
.gitignore
vendored
@@ -1,3 +1,11 @@
|
||||
#################
|
||||
## ArchiSteamFarm
|
||||
#################
|
||||
|
||||
# Ignore all config files, apart from example.xml
|
||||
ArchiSteamFarm/config/*
|
||||
!ArchiSteamFarm/config/example.xml
|
||||
|
||||
#################
|
||||
## Eclipse
|
||||
#################
|
||||
|
||||
@@ -5,6 +5,8 @@ VisualStudioVersion = 14.0.23107.0
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "ArchiSteamFarm", "ArchiSteamFarm\ArchiSteamFarm.csproj", "{35AF7887-08B9-40E8-A5EA-797D8B60B30C}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SteamAuth", "SteamAuth\SteamAuth.csproj", "{5AD0934E-F6C4-4AE5-83AF-C788313B2A87}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
@@ -15,6 +17,10 @@ Global
|
||||
{35AF7887-08B9-40E8-A5EA-797D8B60B30C}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{35AF7887-08B9-40E8-A5EA-797D8B60B30C}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{35AF7887-08B9-40E8-A5EA-797D8B60B30C}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{5AD0934E-F6C4-4AE5-83AF-C788313B2A87}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{5AD0934E-F6C4-4AE5-83AF-C788313B2A87}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{5AD0934E-F6C4-4AE5-83AF-C788313B2A87}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{5AD0934E-F6C4-4AE5-83AF-C788313B2A87}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<configuration>
|
||||
<startup>
|
||||
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
|
||||
</startup>
|
||||
</configuration>
|
||||
<startup>
|
||||
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2"/>
|
||||
</startup>
|
||||
</configuration>
|
||||
|
||||
@@ -1,33 +1,65 @@
|
||||
using SteamKit2;
|
||||
/*
|
||||
_ _ _ ____ _ _____
|
||||
/ \ _ __ ___ | |__ (_)/ ___| | |_ ___ __ _ _ __ ___ | ___|__ _ _ __ _ __ ___
|
||||
/ _ \ | '__|/ __|| '_ \ | |\___ \ | __|/ _ \ / _` || '_ ` _ \ | |_ / _` || '__|| '_ ` _ \
|
||||
/ ___ \ | | | (__ | | | || | ___) || |_| __/| (_| || | | | | || _|| (_| || | | | | | | |
|
||||
/_/ \_\|_| \___||_| |_||_||____/ \__|\___| \__,_||_| |_| |_||_| \__,_||_| |_| |_| |_|
|
||||
|
||||
Copyright 2015 Ł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 SteamKit2;
|
||||
using SteamKit2.Internal;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
|
||||
namespace ArchiSteamFarm {
|
||||
internal sealed class ArchiHandler : ClientMsgHandler {
|
||||
|
||||
internal sealed class PurchaseResponseCallback : CallbackMsg {
|
||||
internal enum EPurchaseResult {
|
||||
Unknown,
|
||||
OK,
|
||||
Unknown = -1,
|
||||
OK = 0,
|
||||
AlreadyOwned = 9,
|
||||
RegionLockedKey = 13,
|
||||
InvalidKey = 14,
|
||||
DuplicatedKey = 15,
|
||||
BaseGameRequired = 24,
|
||||
OnCooldown = 53
|
||||
}
|
||||
|
||||
internal EResult Result { get; private set; }
|
||||
internal EPurchaseResult PurchaseResult { get; private set; }
|
||||
internal int ErrorCode { get; private set; }
|
||||
internal byte[] ReceiptInfo { get; private set; }
|
||||
internal KeyValue ReceiptInfo { get; private set; } = new KeyValue();
|
||||
internal Dictionary<uint, string> Items { get; private set; } = new Dictionary<uint, string>();
|
||||
|
||||
internal PurchaseResponseCallback(CMsgClientPurchaseResponse body) {
|
||||
Result = (EResult) body.eresult;
|
||||
ErrorCode = body.purchase_result_details;
|
||||
ReceiptInfo = body.purchase_receipt_info;
|
||||
PurchaseResult = (EPurchaseResult) body.purchase_result_details;
|
||||
|
||||
if (Result == EResult.OK) {
|
||||
PurchaseResult = EPurchaseResult.OK;
|
||||
} else {
|
||||
PurchaseResult = (EPurchaseResult) ErrorCode;
|
||||
using (MemoryStream ms = new MemoryStream(body.purchase_receipt_info)) {
|
||||
if (!ReceiptInfo.TryReadAsBinary(ms)) {
|
||||
return;
|
||||
}
|
||||
|
||||
foreach (KeyValue lineItem in ReceiptInfo["lineitems"].Children) {
|
||||
Items.Add((uint) lineItem["PackageID"].AsUnsignedLong(), lineItem["ItemDescription"].AsString());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -41,15 +73,7 @@ namespace ArchiSteamFarm {
|
||||
internal ENotificationType NotificationType { get; private set; }
|
||||
|
||||
internal NotificationCallback(CMsgClientUserNotifications.Notification body) {
|
||||
uint notificationType = body.user_notification_type;
|
||||
switch (notificationType) {
|
||||
case 1:
|
||||
NotificationType = (ENotificationType) notificationType;
|
||||
break;
|
||||
default:
|
||||
NotificationType = ENotificationType.Unknown;
|
||||
break;
|
||||
}
|
||||
NotificationType = (ENotificationType) body.user_notification_type;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,14 +91,30 @@ namespace ArchiSteamFarm {
|
||||
Client.Send(request);
|
||||
}
|
||||
|
||||
internal void PlayGames(params ulong[] gameIDs) {
|
||||
internal void PlayGames(params uint[] gameIDs) {
|
||||
var request = new ClientMsgProtobuf<CMsgClientGamesPlayed>(EMsg.ClientGamesPlayed);
|
||||
foreach (ulong gameID in gameIDs) {
|
||||
if (gameID != 0) {
|
||||
request.Body.games_played.Add(new CMsgClientGamesPlayed.GamePlayed {
|
||||
game_id = new GameID(gameID),
|
||||
});
|
||||
foreach (uint gameID in gameIDs) {
|
||||
if (gameID == 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
request.Body.games_played.Add(new CMsgClientGamesPlayed.GamePlayed {
|
||||
game_id = new GameID(gameID),
|
||||
});
|
||||
}
|
||||
Client.Send(request);
|
||||
}
|
||||
|
||||
internal void PlayGames(ICollection<uint> gameIDs) {
|
||||
var request = new ClientMsgProtobuf<CMsgClientGamesPlayed>(EMsg.ClientGamesPlayed);
|
||||
foreach (uint gameID in gameIDs) {
|
||||
if (gameID == 0) {
|
||||
continue;
|
||||
}
|
||||
|
||||
request.Body.games_played.Add(new CMsgClientGamesPlayed.GamePlayed {
|
||||
game_id = new GameID(gameID),
|
||||
});
|
||||
}
|
||||
Client.Send(request);
|
||||
}
|
||||
@@ -87,15 +127,17 @@ namespace ArchiSteamFarm {
|
||||
}
|
||||
|
||||
public sealed override void HandleMsg(IPacketMsg packetMsg) {
|
||||
if (packetMsg != null) {
|
||||
switch (packetMsg.MsgType) {
|
||||
case EMsg.ClientPurchaseResponse:
|
||||
HandlePurchaseResponse(packetMsg);
|
||||
break;
|
||||
case EMsg.ClientUserNotifications:
|
||||
HandleUserNotifications(packetMsg);
|
||||
break;
|
||||
}
|
||||
if (packetMsg == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
switch (packetMsg.MsgType) {
|
||||
case EMsg.ClientPurchaseResponse:
|
||||
HandlePurchaseResponse(packetMsg);
|
||||
break;
|
||||
case EMsg.ClientUserNotifications:
|
||||
HandleUserNotifications(packetMsg);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -110,5 +152,60 @@ namespace ArchiSteamFarm {
|
||||
Client.PostCallback(new NotificationCallback(notification));
|
||||
}
|
||||
}
|
||||
|
||||
// TODO: Please remove me entirely once https://github.com/SteamRE/SteamKit/pull/217 gets merged
|
||||
internal void HackedLogOn(uint id, SteamUser.LogOnDetails details) {
|
||||
if (details == null) {
|
||||
throw new ArgumentNullException("details");
|
||||
}
|
||||
|
||||
if (string.IsNullOrEmpty(details.Username) || (string.IsNullOrEmpty(details.Password) && string.IsNullOrEmpty(details.LoginKey))) {
|
||||
throw new ArgumentException("LogOn requires a username and password to be set in 'details'.");
|
||||
}
|
||||
|
||||
if (!string.IsNullOrEmpty(details.LoginKey) && !details.ShouldRememberPassword) {
|
||||
// Prevent consumers from screwing this up.
|
||||
// If should_remember_password is false, the login_key is ignored server-side.
|
||||
// The inverse is not applicable (you can log in with should_remember_password and no login_key).
|
||||
throw new ArgumentException("ShouldRememberPassword is required to be set to true in order to use LoginKey.");
|
||||
}
|
||||
|
||||
if (!Client.IsConnected) {
|
||||
return;
|
||||
}
|
||||
|
||||
var logon = new ClientMsgProtobuf<CMsgClientLogon>(EMsg.ClientLogon);
|
||||
|
||||
SteamID steamId = new SteamID(details.AccountID, details.AccountInstance, Client.ConnectedUniverse, EAccountType.Individual);
|
||||
|
||||
logon.ProtoHeader.client_sessionid = 0;
|
||||
logon.ProtoHeader.steamid = steamId.ConvertToUInt64();
|
||||
|
||||
logon.Body.obfustucated_private_ip = id;
|
||||
|
||||
logon.Body.account_name = details.Username;
|
||||
logon.Body.password = details.Password;
|
||||
logon.Body.should_remember_password = details.ShouldRememberPassword;
|
||||
|
||||
logon.Body.protocol_version = MsgClientLogon.CurrentProtocol;
|
||||
logon.Body.client_os_type = (uint) details.ClientOSType;
|
||||
logon.Body.client_language = details.ClientLanguage;
|
||||
logon.Body.cell_id = details.CellID;
|
||||
|
||||
logon.Body.steam2_ticket_request = details.RequestSteam2Ticket;
|
||||
|
||||
logon.Body.client_package_version = 1771;
|
||||
|
||||
// steam guard
|
||||
logon.Body.auth_code = details.AuthCode;
|
||||
logon.Body.two_factor_code = details.TwoFactorCode;
|
||||
|
||||
logon.Body.login_key = details.LoginKey;
|
||||
|
||||
logon.Body.sha_sentryfile = details.SentryFileHash;
|
||||
logon.Body.eresult_sentryfile = (int) (details.SentryFileHash != null ? EResult.OK : EResult.FileNotFound);
|
||||
|
||||
Client.Send(logon);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -9,8 +9,24 @@
|
||||
<AppDesignerFolder>Properties</AppDesignerFolder>
|
||||
<RootNamespace>ArchiSteamFarm</RootNamespace>
|
||||
<AssemblyName>ArchiSteamFarm</AssemblyName>
|
||||
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
|
||||
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
|
||||
<FileAlignment>512</FileAlignment>
|
||||
<IsWebBootstrapper>false</IsWebBootstrapper>
|
||||
<PublishUrl>publish\</PublishUrl>
|
||||
<Install>true</Install>
|
||||
<InstallFrom>Disk</InstallFrom>
|
||||
<UpdateEnabled>false</UpdateEnabled>
|
||||
<UpdateMode>Foreground</UpdateMode>
|
||||
<UpdateInterval>7</UpdateInterval>
|
||||
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
|
||||
<UpdatePeriodically>false</UpdatePeriodically>
|
||||
<UpdateRequired>false</UpdateRequired>
|
||||
<MapFileExtensions>true</MapFileExtensions>
|
||||
<ApplicationRevision>0</ApplicationRevision>
|
||||
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
|
||||
<UseApplicationTrust>false</UseApplicationTrust>
|
||||
<BootstrapperEnabled>true</BootstrapperEnabled>
|
||||
<TargetFrameworkProfile />
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||
<PlatformTarget>AnyCPU</PlatformTarget>
|
||||
@@ -24,18 +40,35 @@
|
||||
</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>
|
||||
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
|
||||
<DocumentationFile>
|
||||
</DocumentationFile>
|
||||
<Prefer32Bit>true</Prefer32Bit>
|
||||
<GenerateSerializationAssemblies>Auto</GenerateSerializationAssemblies>
|
||||
<UseVSHostingProcess>false</UseVSHostingProcess>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup>
|
||||
<ApplicationIcon>cirno.ico</ApplicationIcon>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup>
|
||||
<RunPostBuildEvent>OnBuildSuccess</RunPostBuildEvent>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="HtmlAgilityPack, Version=1.4.9.0, Culture=neutral, PublicKeyToken=bd319b19eaf3b43a, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\HtmlAgilityPack.1.4.9\lib\Net45\HtmlAgilityPack.dll</HintPath>
|
||||
<Private>True</Private>
|
||||
</Reference>
|
||||
<Reference Include="Newtonsoft.Json, Version=8.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\Newtonsoft.Json.8.0.1-beta3\lib\net45\Newtonsoft.Json.dll</HintPath>
|
||||
<Private>True</Private>
|
||||
</Reference>
|
||||
<Reference Include="protobuf-net, Version=2.0.0.668, Culture=neutral, PublicKeyToken=257b51d87d2e4d67, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\protobuf-net.2.0.0.668\lib\net40\protobuf-net.dll</HintPath>
|
||||
<Private>True</Private>
|
||||
@@ -59,6 +92,7 @@
|
||||
<Compile Include="Bot.cs" />
|
||||
<Compile Include="CardsFarmer.cs" />
|
||||
<Compile Include="CMsgClientClanInviteAction.cs" />
|
||||
<Compile Include="Debugging.cs" />
|
||||
<Compile Include="Logging.cs" />
|
||||
<Compile Include="Program.cs" />
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
@@ -66,12 +100,49 @@
|
||||
<Compile Include="SteamTradeOffer.cs" />
|
||||
<Compile Include="Trading.cs" />
|
||||
<Compile Include="Utilities.cs" />
|
||||
<Compile Include="WebBrowser.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="App.config" />
|
||||
<None Include="packages.config" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<BootstrapperPackage Include=".NETFramework,Version=v4.5">
|
||||
<Visible>False</Visible>
|
||||
<ProductName>Microsoft .NET Framework 4.5 %28x86 and x64%29</ProductName>
|
||||
<Install>true</Install>
|
||||
</BootstrapperPackage>
|
||||
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
|
||||
<Visible>False</Visible>
|
||||
<ProductName>.NET Framework 3.5 SP1</ProductName>
|
||||
<Install>false</Install>
|
||||
</BootstrapperPackage>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Content Include="cirno.ico" />
|
||||
<Content Include="config\example.xml">
|
||||
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
|
||||
</Content>
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<ProjectReference Include="..\SteamAuth\SteamAuth.csproj">
|
||||
<Project>{5ad0934e-f6c4-4ae5-83af-c788313b2a87}</Project>
|
||||
<Name>SteamAuth</Name>
|
||||
</ProjectReference>
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
|
||||
<PropertyGroup>
|
||||
<PreBuildEvent>
|
||||
</PreBuildEvent>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup>
|
||||
<PostBuildEvent Condition=" '$(OS)' != 'Unix' ">if $(ConfigurationName) == Release (
|
||||
mkdir "$(TargetDir)out" "$(TargetDir)out\config"
|
||||
copy "$(TargetDir)config\example.xml" "$(TargetDir)out\config"
|
||||
"$(SolutionDir)tools\ILMerge.exe" /out:"$(TargetDir)out\ASF.exe" "$(TargetDir)$(TargetName).exe" "$(TargetDir)*.dll" /target:exe /targetplatform:v4,C:\Windows\Microsoft.NET\Framework64\v4.0.30319 /wildcards
|
||||
del "$(TargetDir)out\ASF.pdb"
|
||||
)</PostBuildEvent>
|
||||
</PropertyGroup>
|
||||
<!-- 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">
|
||||
|
||||
@@ -1,21 +1,47 @@
|
||||
using HtmlAgilityPack;
|
||||
/*
|
||||
_ _ _ ____ _ _____
|
||||
/ \ _ __ ___ | |__ (_)/ ___| | |_ ___ __ _ _ __ ___ | ___|__ _ _ __ _ __ ___
|
||||
/ _ \ | '__|/ __|| '_ \ | |\___ \ | __|/ _ \ / _` || '_ ` _ \ | |_ / _` || '__|| '_ ` _ \
|
||||
/ ___ \ | | | (__ | | | || | ___) || |_| __/| (_| || | | | | || _|| (_| || | | | | | | |
|
||||
/_/ \_\|_| \___||_| |_||_||____/ \__|\___| \__,_||_| |_| |_||_| \__,_||_| |_| |_| |_|
|
||||
|
||||
Copyright 2015 Ł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 HtmlAgilityPack;
|
||||
using SteamKit2;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ArchiSteamFarm {
|
||||
internal class ArchiWebHandler {
|
||||
private const int Timeout = 1000 * 15; // In miliseconds
|
||||
internal sealed class ArchiWebHandler {
|
||||
private const int Timeout = 1000 * WebBrowser.HttpTimeout; // In miliseconds
|
||||
|
||||
private readonly Bot Bot;
|
||||
private readonly string ApiKey;
|
||||
private readonly Dictionary<string, string> SteamCookieDictionary = new Dictionary<string, string>();
|
||||
|
||||
private ulong SteamID;
|
||||
private string VanityURL;
|
||||
private readonly Dictionary<string, string> SteamCookieDictionary = new Dictionary<string, string>();
|
||||
|
||||
// This is required because home_process request must be done on final URL
|
||||
private string GetHomeProcess() {
|
||||
@@ -23,17 +49,21 @@ namespace ArchiSteamFarm {
|
||||
return "http://steamcommunity.com/id/" + VanityURL + "/home_process";
|
||||
} else if (SteamID != 0) {
|
||||
return "http://steamcommunity.com/profiles/" + SteamID + "/home_process";
|
||||
} else {
|
||||
return null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
internal ArchiWebHandler(Bot bot, string apiKey) {
|
||||
Bot = bot;
|
||||
ApiKey = apiKey;
|
||||
|
||||
if (!string.IsNullOrEmpty(apiKey) && !apiKey.Equals("null")) {
|
||||
ApiKey = apiKey;
|
||||
}
|
||||
}
|
||||
|
||||
internal void Init(SteamClient steamClient, string webAPIUserNonce, string vanityURL) {
|
||||
if (steamClient == null || steamClient.SteamID == null || string.IsNullOrEmpty(webAPIUserNonce) || string.IsNullOrEmpty(vanityURL)) {
|
||||
internal async Task Init(SteamClient steamClient, string webAPIUserNonce, string vanityURL, string parentalPin) {
|
||||
if (steamClient == null || steamClient.SteamID == null || string.IsNullOrEmpty(webAPIUserNonce)) {
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -95,10 +125,36 @@ namespace ArchiSteamFarm {
|
||||
SteamCookieDictionary.Add("steamLoginSecure", steamLoginSecure);
|
||||
SteamCookieDictionary.Add("birthtime", "-473356799"); // ( ͡° ͜ʖ ͡°)
|
||||
|
||||
Bot.Trading.CheckTrades();
|
||||
if (!string.IsNullOrEmpty(parentalPin) && !parentalPin.Equals("0")) {
|
||||
Logging.LogGenericInfo(Bot.BotName, "Unlocking parental account...");
|
||||
Dictionary<string, string> postData = new Dictionary<string, string>() {
|
||||
{"pin", parentalPin}
|
||||
};
|
||||
|
||||
HttpResponseMessage response = await WebBrowser.UrlPost("https://steamcommunity.com/parental/ajaxunlock", postData, SteamCookieDictionary, "https://steamcommunity.com/").ConfigureAwait(false);
|
||||
if (response != null && response.IsSuccessStatusCode) {
|
||||
Logging.LogGenericInfo(Bot.BotName, "Success!");
|
||||
|
||||
var setCookieValues = response.Headers.GetValues("Set-Cookie");
|
||||
foreach (string setCookieValue in setCookieValues) {
|
||||
if (setCookieValue.Contains("steamparental=")) {
|
||||
string setCookie = setCookieValue.Substring(setCookieValue.IndexOf("steamparental=") + 14);
|
||||
setCookie = setCookie.Substring(0, setCookie.IndexOf(';'));
|
||||
SteamCookieDictionary.Add("steamparental", setCookie);
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
Logging.LogGenericInfo(Bot.BotName, "Failed!");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal List<SteamTradeOffer> GetTradeOffers() {
|
||||
if (ApiKey == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
KeyValue response;
|
||||
using (dynamic iEconService = WebAPI.GetInterface("IEconService")) {
|
||||
// Timeout
|
||||
@@ -134,7 +190,9 @@ namespace ArchiSteamFarm {
|
||||
is_our_offer = trade["is_our_offer"].AsBoolean(),
|
||||
time_created = trade["time_created"].AsInteger(),
|
||||
time_updated = trade["time_updated"].AsInteger(),
|
||||
from_real_time_trade = trade["from_real_time_trade"].AsBoolean()
|
||||
from_real_time_trade = trade["from_real_time_trade"].AsBoolean(),
|
||||
escrow_end_date = trade["escrow_end_date"].AsInteger(),
|
||||
confirmation_method = (SteamTradeOffer.ETradeOfferConfirmationMethod) trade["confirmation_method"].AsInteger()
|
||||
};
|
||||
foreach (KeyValue item in trade["items_to_give"].Children) {
|
||||
tradeOffer.items_to_give.Add(new SteamItem {
|
||||
@@ -162,9 +220,50 @@ namespace ArchiSteamFarm {
|
||||
}
|
||||
result.Add(tradeOffer);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
internal async Task JoinClan(ulong clanID) {
|
||||
if (clanID == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
string sessionID;
|
||||
if (!SteamCookieDictionary.TryGetValue("sessionid", out sessionID)) {
|
||||
return;
|
||||
}
|
||||
|
||||
string request = "http://steamcommunity.com/gid/" + clanID;
|
||||
|
||||
Dictionary<string, string> postData = new Dictionary<string, string>() {
|
||||
{"sessionID", sessionID},
|
||||
{"action", "join"}
|
||||
};
|
||||
|
||||
await WebBrowser.UrlPost(request, postData, SteamCookieDictionary).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
internal async Task LeaveClan(ulong clanID) {
|
||||
if (clanID == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
string sessionID;
|
||||
if (!SteamCookieDictionary.TryGetValue("sessionid", out sessionID)) {
|
||||
return;
|
||||
}
|
||||
|
||||
string request = GetHomeProcess();
|
||||
Dictionary<string, string> postData = new Dictionary<string, string>() {
|
||||
{"sessionID", sessionID},
|
||||
{"action", "leaveGroup"},
|
||||
{"groupId", clanID.ToString()}
|
||||
};
|
||||
|
||||
await WebBrowser.UrlPost(request, postData, SteamCookieDictionary).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
internal async Task<bool> AcceptTradeOffer(ulong tradeID) {
|
||||
if (tradeID == 0) {
|
||||
return false;
|
||||
@@ -184,10 +283,32 @@ namespace ArchiSteamFarm {
|
||||
{"tradeofferid", tradeID.ToString()}
|
||||
};
|
||||
|
||||
return await Utilities.UrlPostRequest(request, postData, SteamCookieDictionary, referer).ConfigureAwait(false);
|
||||
HttpResponseMessage result = await WebBrowser.UrlPost(request, postData, SteamCookieDictionary, referer).ConfigureAwait(false);
|
||||
if (result == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
bool success = result.IsSuccessStatusCode;
|
||||
|
||||
if (!success) {
|
||||
Logging.LogGenericWarning(Bot.BotName, "Request failed, reason: " + result.ReasonPhrase);
|
||||
switch (result.StatusCode) {
|
||||
case HttpStatusCode.InternalServerError:
|
||||
Logging.LogGenericWarning(Bot.BotName, "That might be caused by 7-days trade lock from new device");
|
||||
Logging.LogGenericWarning(Bot.BotName, "Try again in 7 days, declining that offer for now");
|
||||
DeclineTradeOffer(tradeID);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return success;
|
||||
}
|
||||
|
||||
internal bool DeclineTradeOffer(ulong tradeID) {
|
||||
if (ApiKey == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (tradeID == 0) {
|
||||
return false;
|
||||
}
|
||||
@@ -213,39 +334,20 @@ namespace ArchiSteamFarm {
|
||||
return response != null; // Steam API doesn't respond with any error code, assume any response is a success
|
||||
}
|
||||
|
||||
internal async Task LeaveClan(ulong clanID) {
|
||||
if (clanID == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
string sessionID;
|
||||
if (!SteamCookieDictionary.TryGetValue("sessionid", out sessionID)) {
|
||||
return;
|
||||
}
|
||||
|
||||
string request = GetHomeProcess();
|
||||
Dictionary<string, string> postData = new Dictionary<string, string>() {
|
||||
{"sessionID", sessionID},
|
||||
{"action", "leaveGroup"},
|
||||
{"groupId", clanID.ToString()}
|
||||
};
|
||||
await Utilities.UrlPostRequest(request, postData, SteamCookieDictionary).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
internal async Task<HtmlDocument> GetBadgePage(int page) {
|
||||
HtmlDocument result = null;
|
||||
if (SteamID != 0 && page != 0) {
|
||||
result = await Utilities.UrlToHtmlDocument("http://steamcommunity.com/profiles/" + SteamID + "/badges?p=" + page, SteamCookieDictionary).ConfigureAwait(false);
|
||||
if (SteamID == 0 || page == 0) {
|
||||
return null;
|
||||
}
|
||||
return result;
|
||||
|
||||
return await WebBrowser.UrlGetToHtmlDocument("http://steamcommunity.com/profiles/" + SteamID + "/badges?p=" + page, SteamCookieDictionary).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
internal async Task<HtmlDocument> GetGameCardsPage(ulong appID) {
|
||||
HtmlDocument result = null;
|
||||
if (SteamID != 0 && appID != 0) {
|
||||
result = await Utilities.UrlToHtmlDocument("http://steamcommunity.com/profiles/" + SteamID + "/gamecards/" + appID, SteamCookieDictionary).ConfigureAwait(false);
|
||||
if (SteamID == 0 || appID == 0) {
|
||||
return null;
|
||||
}
|
||||
return result;
|
||||
|
||||
return await WebBrowser.UrlGetToHtmlDocument("http://steamcommunity.com/profiles/" + SteamID + "/gamecards/" + appID, SteamCookieDictionary).ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
701
ArchiSteamFarm/Bot.cs
Normal file → Executable file
701
ArchiSteamFarm/Bot.cs
Normal file → Executable file
@@ -1,90 +1,134 @@
|
||||
using SteamKit2;
|
||||
/*
|
||||
_ _ _ ____ _ _____
|
||||
/ \ _ __ ___ | |__ (_)/ ___| | |_ ___ __ _ _ __ ___ | ___|__ _ _ __ _ __ ___
|
||||
/ _ \ | '__|/ __|| '_ \ | |\___ \ | __|/ _ \ / _` || '_ ` _ \ | |_ / _` || '__|| '_ ` _ \
|
||||
/ ___ \ | | | (__ | | | || | ___) || |_| __/| (_| || | | | | || _|| (_| || | | | | | | |
|
||||
/_/ \_\|_| \___||_| |_||_||____/ \__|\___| \__,_||_| |_| |_||_| \__,_||_| |_| |_| |_|
|
||||
|
||||
Copyright 2015 Ł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 Newtonsoft.Json;
|
||||
using SteamAuth;
|
||||
using SteamKit2;
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.IO;
|
||||
using System.Security.Cryptography;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
using System.Xml;
|
||||
|
||||
namespace ArchiSteamFarm {
|
||||
internal class Bot {
|
||||
private const byte CallbackSleep = 100; // In miliseconds
|
||||
internal sealed class Bot {
|
||||
private const ushort CallbackSleep = 500; // In miliseconds
|
||||
|
||||
private readonly Dictionary<string, string> Config = new Dictionary<string, string>();
|
||||
private static readonly ConcurrentDictionary<string, Bot> Bots = new ConcurrentDictionary<string, Bot>();
|
||||
|
||||
private readonly string ConfigFile, LoginKeyFile, MobileAuthenticatorFile, SentryFile;
|
||||
|
||||
internal readonly string BotName;
|
||||
private readonly string ConfigFile;
|
||||
private readonly string SentryFile;
|
||||
|
||||
private readonly CardsFarmer CardsFarmer;
|
||||
|
||||
internal ulong BotID { get; private set; }
|
||||
private string AuthCode, TwoFactorAuth;
|
||||
private bool LoggedInElsewhere = false;
|
||||
private bool IsRunning = false;
|
||||
private string AuthCode, LoginKey, TwoFactorAuth;
|
||||
|
||||
internal ArchiHandler ArchiHandler { get; private set; }
|
||||
internal ArchiWebHandler ArchiWebHandler { get; private set; }
|
||||
internal CallbackManager CallbackManager { get; private set; }
|
||||
internal CardsFarmer CardsFarmer { get; private set; }
|
||||
internal SteamClient SteamClient { get; private set; }
|
||||
internal SteamFriends SteamFriends { get; private set; }
|
||||
internal SteamGuardAccount SteamGuardAccount { get; private set; }
|
||||
internal SteamUser SteamUser { get; private set; }
|
||||
internal Trading Trading { get; private set; }
|
||||
|
||||
// Config variables
|
||||
private bool Enabled { get { return bool.Parse(Config["Enabled"]); } }
|
||||
private string SteamLogin { get { return Config["SteamLogin"]; } }
|
||||
private string SteamPassword { get { return Config["SteamPassword"]; } }
|
||||
private string SteamNickname { get { return Config["SteamNickname"]; } }
|
||||
private string SteamApiKey { get { return Config["SteamApiKey"]; } }
|
||||
internal ulong SteamMasterID { get { return ulong.Parse(Config["SteamMasterID"]); } }
|
||||
internal ulong SteamMasterClanID { get { return ulong.Parse(Config["SteamMasterClanID"]); } }
|
||||
internal bool Enabled { get; private set; } = false;
|
||||
internal string SteamLogin { get; private set; } = "null";
|
||||
internal string SteamPassword { get; private set; } = "null";
|
||||
internal string SteamNickname { get; private set; } = "null";
|
||||
internal string SteamApiKey { get; private set; } = "null";
|
||||
internal string SteamParentalPIN { get; private set; } = "0";
|
||||
internal ulong SteamMasterID { get; private set; } = 0;
|
||||
internal ulong SteamMasterClanID { get; private set; } = 0;
|
||||
internal bool CardDropsRestricted { get; private set; } = false;
|
||||
internal bool UseAsfAsMobileAuthenticator { get; private set; } = false;
|
||||
internal bool ShutdownOnFarmingFinished { get; private set; } = false;
|
||||
internal HashSet<uint> Blacklist { get; private set; } = new HashSet<uint> { 303700, 335590, 368020 };
|
||||
internal bool Statistics { get; private set; } = true;
|
||||
|
||||
private static bool IsValidCdKey(string key) {
|
||||
if (string.IsNullOrEmpty(key)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (key.Length != 17 && key.Length != 29) {
|
||||
return false;
|
||||
}
|
||||
|
||||
for (byte i = 5; i < key.Length; i += 6) {
|
||||
if (key[i] != '-') {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
internal static int GetRunningBotsCount() {
|
||||
return Bots.Count;
|
||||
}
|
||||
|
||||
internal static async Task ShutdownAllBots() {
|
||||
List<Task> tasks = new List<Task>();
|
||||
foreach (Bot bot in Bots.Values) {
|
||||
tasks.Add(Task.Run(async () => await bot.Shutdown().ConfigureAwait(false)));
|
||||
}
|
||||
await Task.WhenAll(tasks).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
internal Bot(string botName) {
|
||||
if (Bots.ContainsKey(botName)) {
|
||||
return;
|
||||
}
|
||||
|
||||
internal Bot (string botName) {
|
||||
BotName = botName;
|
||||
CardsFarmer = new CardsFarmer(this);
|
||||
|
||||
ConfigFile = Path.Combine(Program.ConfigDirectoryPath, BotName + ".xml");
|
||||
LoginKeyFile = Path.Combine(Program.ConfigDirectoryPath, BotName + ".key");
|
||||
MobileAuthenticatorFile = Path.Combine(Program.ConfigDirectoryPath, BotName + ".auth");
|
||||
SentryFile = Path.Combine(Program.ConfigDirectoryPath, BotName + ".bin");
|
||||
|
||||
ReadConfig();
|
||||
if (!ReadConfig()) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!Enabled) {
|
||||
return;
|
||||
}
|
||||
Start();
|
||||
}
|
||||
|
||||
private void ReadConfig() {
|
||||
using (XmlReader reader = XmlReader.Create(ConfigFile)) {
|
||||
while (reader.Read()) {
|
||||
if (reader.NodeType != XmlNodeType.Element) {
|
||||
continue;
|
||||
}
|
||||
|
||||
string key = reader.Name;
|
||||
if (string.IsNullOrEmpty(key)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
string value = reader.GetAttribute("value");
|
||||
if (string.IsNullOrEmpty(value)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
Config.Add(key, value);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal void Start() {
|
||||
if (SteamClient != null) {
|
||||
return;
|
||||
}
|
||||
Bots.AddOrUpdate(BotName, this, (key, value) => this);
|
||||
|
||||
// Initialize
|
||||
SteamClient = new SteamClient();
|
||||
|
||||
ArchiHandler = new ArchiHandler();
|
||||
SteamClient.AddHandler(ArchiHandler);
|
||||
SteamClient.AddHandler(ArchiHandler);
|
||||
|
||||
CallbackManager = new CallbackManager(SteamClient);
|
||||
CallbackManager.Subscribe<SteamClient.ConnectedCallback>(OnConnected);
|
||||
@@ -94,43 +138,379 @@ namespace ArchiSteamFarm {
|
||||
CallbackManager.Subscribe<SteamFriends.FriendsListCallback>(OnFriendsList);
|
||||
CallbackManager.Subscribe<SteamFriends.FriendMsgCallback>(OnFriendMsg);
|
||||
|
||||
if (UseAsfAsMobileAuthenticator && File.Exists(MobileAuthenticatorFile)) {
|
||||
SteamGuardAccount = JsonConvert.DeserializeObject<SteamGuardAccount>(File.ReadAllText(MobileAuthenticatorFile));
|
||||
}
|
||||
|
||||
SteamUser = SteamClient.GetHandler<SteamUser>();
|
||||
CallbackManager.Subscribe<SteamUser.AccountInfoCallback>(OnAccountInfo);
|
||||
CallbackManager.Subscribe<SteamUser.LoggedOffCallback>(OnLoggedOff);
|
||||
CallbackManager.Subscribe<SteamUser.LoggedOnCallback>(OnLoggedOn);
|
||||
CallbackManager.Subscribe<SteamUser.LoginKeyCallback>(OnLoginKey);
|
||||
CallbackManager.Subscribe<SteamUser.UpdateMachineAuthCallback>(OnMachineAuth);
|
||||
|
||||
CallbackManager.Subscribe<ArchiHandler.NotificationCallback>(OnNotification);
|
||||
CallbackManager.Subscribe<ArchiHandler.PurchaseResponseCallback>(OnPurchaseResponse);
|
||||
|
||||
ArchiWebHandler = new ArchiWebHandler(this, SteamApiKey);
|
||||
CardsFarmer = new CardsFarmer(this);
|
||||
Trading = new Trading(this);
|
||||
|
||||
SteamClient.Connect();
|
||||
Task.Run(() => HandleCallbacks());
|
||||
// Start
|
||||
var fireAndForget = Task.Run(async () => await Start().ConfigureAwait(false));
|
||||
}
|
||||
|
||||
internal void Stop() {
|
||||
if (SteamClient == null) {
|
||||
internal void AcceptAllConfirmations() {
|
||||
if (SteamGuardAccount == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
SteamClient.Disconnect();
|
||||
SteamClient = null;
|
||||
CallbackManager = null;
|
||||
SteamGuardAccount.RefreshSession();
|
||||
|
||||
try {
|
||||
foreach (Confirmation confirmation in SteamGuardAccount.FetchConfirmations()) {
|
||||
if (SteamGuardAccount.AcceptConfirmation(confirmation)) {
|
||||
Logging.LogGenericInfo(BotName, "Accepting confirmation: Success!");
|
||||
} else {
|
||||
Logging.LogGenericWarning(BotName, "Accepting confirmation: Failed!");
|
||||
}
|
||||
}
|
||||
} catch (SteamGuardAccount.WGTokenInvalidException) {
|
||||
Logging.LogGenericWarning(BotName, "Accepting confirmation: Failed!");
|
||||
Logging.LogGenericWarning(BotName, "Confirmation could not be accepted because of invalid token exception");
|
||||
Logging.LogGenericWarning(BotName, "If issue persists, consider removing and readding ASF 2FA");
|
||||
}
|
||||
}
|
||||
|
||||
internal void PlayGame(params ulong[] gameIDs) {
|
||||
ArchiHandler.PlayGames(gameIDs);
|
||||
private bool LinkMobileAuthenticator() {
|
||||
if (SteamGuardAccount != null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
Logging.LogGenericNotice(BotName, "Linking new ASF MobileAuthenticator...");
|
||||
UserLogin userLogin = new UserLogin(SteamLogin, SteamPassword);
|
||||
LoginResult loginResult;
|
||||
while ((loginResult = userLogin.DoLogin()) != LoginResult.LoginOkay) {
|
||||
switch (loginResult) {
|
||||
case LoginResult.NeedEmail:
|
||||
userLogin.EmailCode = Program.GetUserInput(BotName, Program.EUserInputType.SteamGuard);
|
||||
break;
|
||||
default:
|
||||
Logging.LogGenericError(BotName, "Unhandled situation: " + loginResult);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
AuthenticatorLinker authenticatorLinker = new AuthenticatorLinker(userLogin.Session);
|
||||
|
||||
AuthenticatorLinker.LinkResult linkResult;
|
||||
while ((linkResult = authenticatorLinker.AddAuthenticator()) != AuthenticatorLinker.LinkResult.AwaitingFinalization) {
|
||||
switch (linkResult) {
|
||||
case AuthenticatorLinker.LinkResult.MustProvidePhoneNumber:
|
||||
authenticatorLinker.PhoneNumber = Program.GetUserInput(BotName, Program.EUserInputType.PhoneNumber);
|
||||
break;
|
||||
default:
|
||||
Logging.LogGenericError(BotName, "Unhandled situation: " + linkResult);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
SteamGuardAccount = authenticatorLinker.LinkedAccount;
|
||||
|
||||
try {
|
||||
File.WriteAllText(MobileAuthenticatorFile, JsonConvert.SerializeObject(SteamGuardAccount));
|
||||
} catch (Exception e) {
|
||||
Logging.LogGenericException(BotName, e);
|
||||
return false;
|
||||
}
|
||||
|
||||
AuthenticatorLinker.FinalizeResult finalizeResult = authenticatorLinker.FinalizeAddAuthenticator(Program.GetUserInput(BotName, Program.EUserInputType.SMS));
|
||||
if (finalizeResult != AuthenticatorLinker.FinalizeResult.Success) {
|
||||
Logging.LogGenericError(BotName, "Unhandled situation: " + finalizeResult);
|
||||
DelinkMobileAuthenticator();
|
||||
return false;
|
||||
}
|
||||
|
||||
Logging.LogGenericInfo(BotName, "Successfully linked ASF as new mobile authenticator for this account!");
|
||||
Program.GetUserInput(BotName, Program.EUserInputType.RevocationCode, SteamGuardAccount.RevocationCode);
|
||||
return true;
|
||||
}
|
||||
|
||||
private bool DelinkMobileAuthenticator() {
|
||||
if (SteamGuardAccount == null) {
|
||||
return false;
|
||||
}
|
||||
|
||||
bool result = SteamGuardAccount.DeactivateAuthenticator();
|
||||
SteamGuardAccount = null;
|
||||
File.Delete(MobileAuthenticatorFile);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
private bool ReadConfig() {
|
||||
if (!File.Exists(ConfigFile)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
using (XmlReader reader = XmlReader.Create(ConfigFile)) {
|
||||
while (reader.Read()) {
|
||||
if (reader.NodeType != XmlNodeType.Element) {
|
||||
continue;
|
||||
}
|
||||
|
||||
string key = reader.Name;
|
||||
if (string.IsNullOrEmpty(key)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
string value = reader.GetAttribute("value");
|
||||
if (string.IsNullOrEmpty(value)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
switch (key) {
|
||||
case "Enabled":
|
||||
Enabled = bool.Parse(value);
|
||||
break;
|
||||
case "SteamLogin":
|
||||
SteamLogin = value;
|
||||
break;
|
||||
case "SteamPassword":
|
||||
SteamPassword = value;
|
||||
break;
|
||||
case "SteamNickname":
|
||||
SteamNickname = value;
|
||||
break;
|
||||
case "SteamApiKey":
|
||||
SteamApiKey = value;
|
||||
break;
|
||||
case "SteamParentalPIN":
|
||||
SteamParentalPIN = value;
|
||||
break;
|
||||
case "SteamMasterID":
|
||||
SteamMasterID = ulong.Parse(value);
|
||||
break;
|
||||
case "SteamMasterClanID":
|
||||
SteamMasterClanID = ulong.Parse(value);
|
||||
break;
|
||||
case "UseAsfAsMobileAuthenticator":
|
||||
UseAsfAsMobileAuthenticator = bool.Parse(value);
|
||||
break;
|
||||
case "CardDropsRestricted":
|
||||
CardDropsRestricted = bool.Parse(value);
|
||||
break;
|
||||
case "ShutdownOnFarmingFinished":
|
||||
ShutdownOnFarmingFinished = bool.Parse(value);
|
||||
break;
|
||||
case "Blacklist":
|
||||
Blacklist.Clear();
|
||||
foreach (string appID in value.Split(',')) {
|
||||
Blacklist.Add(uint.Parse(appID));
|
||||
}
|
||||
break;
|
||||
case "Statistics":
|
||||
Statistics = bool.Parse(value);
|
||||
break;
|
||||
default:
|
||||
Logging.LogGenericWarning(BotName, "Unrecognized config value: " + key + "=" + value);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (Exception e) {
|
||||
Logging.LogGenericException(BotName, e);
|
||||
Logging.LogGenericError(BotName, "Your config for this bot instance is invalid, it won't run!");
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
internal async Task Start() {
|
||||
if (IsRunning) {
|
||||
return;
|
||||
}
|
||||
|
||||
IsRunning = true;
|
||||
|
||||
Logging.LogGenericInfo(BotName, "Starting...");
|
||||
|
||||
// 2FA tokens are expiring soon, use limiter only when we don't have any pending
|
||||
if (TwoFactorAuth == null) {
|
||||
await Program.LimitSteamRequestsAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
SteamClient.Connect();
|
||||
|
||||
var fireAndForget = Task.Run(() => HandleCallbacks());
|
||||
}
|
||||
|
||||
internal async Task Stop() {
|
||||
if (!IsRunning) {
|
||||
return;
|
||||
}
|
||||
|
||||
await CardsFarmer.StopFarming().ConfigureAwait(false);
|
||||
IsRunning = false;
|
||||
SteamClient.Disconnect();
|
||||
}
|
||||
|
||||
internal async Task<bool> Shutdown(string botName = null) {
|
||||
Bot bot;
|
||||
|
||||
if (string.IsNullOrEmpty(botName)) {
|
||||
bot = this;
|
||||
} else {
|
||||
if (!Bots.TryGetValue(botName, out bot)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
await bot.Stop().ConfigureAwait(false);
|
||||
Bots.TryRemove(botName, out bot);
|
||||
|
||||
Program.OnBotShutdown();
|
||||
return true;
|
||||
}
|
||||
|
||||
internal async Task OnFarmingFinished() {
|
||||
if (ShutdownOnFarmingFinished) {
|
||||
await Shutdown().ConfigureAwait(false);
|
||||
}
|
||||
}
|
||||
|
||||
private void HandleCallbacks() {
|
||||
TimeSpan timeSpan = TimeSpan.FromMilliseconds(CallbackSleep);
|
||||
while (CallbackManager != null) {
|
||||
while (IsRunning) {
|
||||
CallbackManager.RunWaitCallbacks(timeSpan);
|
||||
}
|
||||
}
|
||||
|
||||
private void SendMessageToUser(ulong steamID, string message) {
|
||||
if (steamID == 0 || string.IsNullOrEmpty(message)) {
|
||||
return;
|
||||
}
|
||||
|
||||
SteamFriends.SendChatMessage(steamID, EChatEntryType.ChatMsg, message);
|
||||
}
|
||||
|
||||
|
||||
private void ResponseStatus(ulong steamID, string botName = null) {
|
||||
if (steamID == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
Bot bot;
|
||||
|
||||
if (string.IsNullOrEmpty(botName)) {
|
||||
bot = this;
|
||||
} else {
|
||||
if (!Bots.TryGetValue(botName, out bot)) {
|
||||
SendMessageToUser(steamID, "Couldn't find any bot named " + botName + "!");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (bot.CardsFarmer.CurrentGamesFarming.Count > 0) {
|
||||
SendMessageToUser(steamID, "Bot " + bot.BotName + " is currently farming appIDs: " + string.Join(", ", bot.CardsFarmer.CurrentGamesFarming) + " and has a total of " + bot.CardsFarmer.GamesToFarm.Count + " games left to farm");
|
||||
}
|
||||
SendMessageToUser(steamID, "Currently " + Bots.Count + " bots are running");
|
||||
}
|
||||
|
||||
private void Response2FA(ulong steamID, string botName = null) {
|
||||
if (steamID == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
Bot bot;
|
||||
|
||||
if (string.IsNullOrEmpty(botName)) {
|
||||
bot = this;
|
||||
} else {
|
||||
if (!Bots.TryGetValue(botName, out bot)) {
|
||||
SendMessageToUser(steamID, "Couldn't find any bot named " + botName + "!");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (bot.SteamGuardAccount == null) {
|
||||
SendMessageToUser(steamID, "That bot doesn't have ASF 2FA enabled!");
|
||||
return;
|
||||
}
|
||||
|
||||
long timeLeft = 30 - TimeAligner.GetSteamTime() % 30;
|
||||
SendMessageToUser(steamID, "2FA Token: " + bot.SteamGuardAccount.GenerateSteamGuardCode() + " (expires in " + timeLeft + " seconds)");
|
||||
}
|
||||
|
||||
private void Response2FAOff(ulong steamID, string botName = null) {
|
||||
if (steamID == 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
Bot bot;
|
||||
|
||||
if (string.IsNullOrEmpty(botName)) {
|
||||
bot = this;
|
||||
} else {
|
||||
if (!Bots.TryGetValue(botName, out bot)) {
|
||||
SendMessageToUser(steamID, "Couldn't find any bot named " + botName + "!");
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
if (bot.SteamGuardAccount == null) {
|
||||
SendMessageToUser(steamID, "That bot doesn't have ASF 2FA enabled!");
|
||||
return;
|
||||
}
|
||||
|
||||
if (bot.DelinkMobileAuthenticator()) {
|
||||
SendMessageToUser(steamID, "Done! Bot is no longer using ASF 2FA");
|
||||
} else {
|
||||
SendMessageToUser(steamID, "Something went wrong!");
|
||||
}
|
||||
}
|
||||
|
||||
private void ResponseStart(ulong steamID, string botName) {
|
||||
if (steamID == 0 || string.IsNullOrEmpty(botName)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (Bots.ContainsKey(botName)) {
|
||||
SendMessageToUser(steamID, "That bot instance is already running!");
|
||||
return;
|
||||
}
|
||||
|
||||
new Bot(botName);
|
||||
if (Bots.ContainsKey(botName)) {
|
||||
SendMessageToUser(steamID, "Done!");
|
||||
} else {
|
||||
SendMessageToUser(steamID, "That bot instance failed to start, make sure that XML config exists and bot is active!");
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ResponseStop(ulong steamID, string botName) {
|
||||
if (steamID == 0 || string.IsNullOrEmpty(botName)) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!Bots.ContainsKey(botName)) {
|
||||
SendMessageToUser(steamID, "That bot instance is already inactive!");
|
||||
return;
|
||||
}
|
||||
|
||||
if (await Shutdown(botName).ConfigureAwait(false)) {
|
||||
SendMessageToUser(steamID, "Done!");
|
||||
} else {
|
||||
SendMessageToUser(steamID, "That bot instance failed to shutdown!");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
private void OnConnected(SteamClient.ConnectedCallback callback) {
|
||||
if (callback == null) {
|
||||
return;
|
||||
@@ -143,28 +523,64 @@ namespace ArchiSteamFarm {
|
||||
|
||||
Logging.LogGenericInfo(BotName, "Connected to Steam!");
|
||||
|
||||
if (File.Exists(LoginKeyFile)) {
|
||||
LoginKey = File.ReadAllText(LoginKeyFile);
|
||||
}
|
||||
|
||||
byte[] sentryHash = null;
|
||||
if (File.Exists(SentryFile)) {
|
||||
byte[] sentryFileContent = File.ReadAllBytes(SentryFile);
|
||||
sentryHash = CryptoHelper.SHAHash(sentryFileContent);
|
||||
}
|
||||
|
||||
SteamUser.LogOn(new SteamUser.LogOnDetails {
|
||||
if (SteamLogin.Equals("null")) {
|
||||
SteamLogin = Program.GetUserInput(BotName, Program.EUserInputType.Login);
|
||||
}
|
||||
|
||||
if (SteamPassword.Equals("null") && string.IsNullOrEmpty(LoginKey)) {
|
||||
SteamPassword = Program.GetUserInput(BotName, Program.EUserInputType.Password);
|
||||
}
|
||||
|
||||
// TODO: We should use SteamUser.LogOn with proper LoginID once https://github.com/SteamRE/SteamKit/pull/217 gets merged
|
||||
ArchiHandler.HackedLogOn(0xBAADF00D, new SteamUser.LogOnDetails {
|
||||
Username = SteamLogin,
|
||||
Password = SteamPassword,
|
||||
AuthCode = AuthCode,
|
||||
LoginKey = LoginKey,
|
||||
TwoFactorCode = TwoFactorAuth,
|
||||
SentryFileHash = sentryHash
|
||||
SentryFileHash = sentryHash,
|
||||
ShouldRememberPassword = true
|
||||
});
|
||||
}
|
||||
|
||||
private void OnDisconnected(SteamClient.DisconnectedCallback callback) {
|
||||
private async void OnDisconnected(SteamClient.DisconnectedCallback callback) {
|
||||
if (callback == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!IsRunning) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (SteamClient == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
await CardsFarmer.StopFarming().ConfigureAwait(false);
|
||||
|
||||
Logging.LogGenericWarning(BotName, "Disconnected from Steam, reconnecting...");
|
||||
Thread.Sleep(TimeSpan.FromMilliseconds(CallbackSleep));
|
||||
|
||||
// 2FA tokens are expiring soon, use limiter only when we don't have any pending
|
||||
if (TwoFactorAuth == null) {
|
||||
await Program.LimitSteamRequestsAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
if (LoggedInElsewhere) {
|
||||
LoggedInElsewhere = false;
|
||||
Logging.LogGenericWarning(BotName, "Account is being used elsewhere, will try reconnecting in 5 minutes...");
|
||||
await Utilities.SleepAsync(5 * 60 * 1000).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
SteamClient.Connect();
|
||||
}
|
||||
|
||||
@@ -181,7 +597,7 @@ namespace ArchiSteamFarm {
|
||||
SteamID steamID = friend.SteamID;
|
||||
switch (steamID.AccountType) {
|
||||
case EAccountType.Clan:
|
||||
//ArchiHandler.AcceptClanInvite(steamID);
|
||||
ArchiHandler.DeclineClanInvite(steamID);
|
||||
break;
|
||||
default:
|
||||
if (steamID == SteamMasterID) {
|
||||
@@ -194,7 +610,7 @@ namespace ArchiSteamFarm {
|
||||
}
|
||||
}
|
||||
|
||||
private void OnFriendMsg(SteamFriends.FriendMsgCallback callback) {
|
||||
private async void OnFriendMsg(SteamFriends.FriendMsgCallback callback) {
|
||||
if (callback == null) {
|
||||
return;
|
||||
}
|
||||
@@ -213,8 +629,63 @@ namespace ArchiSteamFarm {
|
||||
return;
|
||||
}
|
||||
|
||||
if (message.Length == 17 && message[5] == '-' && message[11] == '-') {
|
||||
if (IsValidCdKey(message)) {
|
||||
ArchiHandler.RedeemKey(message);
|
||||
return;
|
||||
}
|
||||
|
||||
if (!message.StartsWith("!")) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!message.Contains(" ")) {
|
||||
switch (message) {
|
||||
case "!2fa":
|
||||
Response2FA(steamID);
|
||||
break;
|
||||
case "!2faoff":
|
||||
Response2FAOff(steamID);
|
||||
break;
|
||||
case "!exit":
|
||||
await ShutdownAllBots().ConfigureAwait(false);
|
||||
break;
|
||||
case "!farm":
|
||||
SendMessageToUser(steamID, "Please wait...");
|
||||
await CardsFarmer.StartFarming().ConfigureAwait(false);
|
||||
SendMessageToUser(steamID, "Done!");
|
||||
break;
|
||||
case "!restart":
|
||||
await Program.Restart().ConfigureAwait(false);
|
||||
break;
|
||||
case "!status":
|
||||
ResponseStatus(steamID);
|
||||
break;
|
||||
case "!stop":
|
||||
await Shutdown().ConfigureAwait(false);
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
string[] args = message.Split(' ');
|
||||
switch (args[0]) {
|
||||
case "!2fa":
|
||||
Response2FA(steamID, args[1]);
|
||||
break;
|
||||
case "!2faoff":
|
||||
Response2FAOff(steamID, args[1]);
|
||||
break;
|
||||
case "!redeem":
|
||||
ArchiHandler.RedeemKey(args[1]);
|
||||
break;
|
||||
case "!start":
|
||||
ResponseStart(steamID, args[1]);
|
||||
break;
|
||||
case "!stop":
|
||||
await ResponseStop(steamID, args[1]).ConfigureAwait(false);
|
||||
break;
|
||||
case "!status":
|
||||
ResponseStatus(steamID, args[1]);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -232,6 +703,14 @@ namespace ArchiSteamFarm {
|
||||
}
|
||||
|
||||
Logging.LogGenericInfo(BotName, "Logged off of Steam: " + callback.Result);
|
||||
|
||||
switch (callback.Result) {
|
||||
case EResult.AlreadyLoggedInElsewhere:
|
||||
case EResult.LoggedInElsewhere:
|
||||
case EResult.LogonSessionReplaced:
|
||||
LoggedInElsewhere = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private async void OnLoggedOn(SteamUser.LoggedOnCallback callback) {
|
||||
@@ -239,39 +718,90 @@ namespace ArchiSteamFarm {
|
||||
return;
|
||||
}
|
||||
|
||||
if (callback.ClientSteamID != 0) {
|
||||
BotID = callback.ClientSteamID;
|
||||
}
|
||||
|
||||
EResult result = callback.Result;
|
||||
switch (result) {
|
||||
case EResult.AccountLogonDenied:
|
||||
AuthCode = Program.GetSteamGuardCode(SteamLogin, false);
|
||||
AuthCode = Program.GetUserInput(SteamLogin, Program.EUserInputType.SteamGuard);
|
||||
break;
|
||||
case EResult.AccountLoginDeniedNeedTwoFactor:
|
||||
TwoFactorAuth = Program.GetSteamGuardCode(SteamLogin, true);
|
||||
if (SteamGuardAccount == null) {
|
||||
TwoFactorAuth = Program.GetUserInput(SteamLogin, Program.EUserInputType.TwoFactorAuthentication);
|
||||
} else {
|
||||
TwoFactorAuth = SteamGuardAccount.GenerateSteamGuardCode();
|
||||
}
|
||||
break;
|
||||
case EResult.InvalidPassword:
|
||||
Logging.LogGenericWarning(BotName, "Unable to login to Steam: " + result + ", will retry after a longer while");
|
||||
await Stop().ConfigureAwait(false);
|
||||
|
||||
// InvalidPassword means that we must assume login key has expired
|
||||
LoginKey = null;
|
||||
File.Delete(LoginKeyFile);
|
||||
|
||||
// InvalidPassword also means that we might get captcha or other network-based throttling
|
||||
await Utilities.SleepAsync(25 * 60 * 1000).ConfigureAwait(false); // Captcha disappears after around 20 minutes, so we make it 25
|
||||
|
||||
// After all of that, try again
|
||||
await Start().ConfigureAwait(false);
|
||||
break;
|
||||
case EResult.OK:
|
||||
Logging.LogGenericInfo(BotName, "Successfully logged on!");
|
||||
SteamFriends.SetPersonaName(SteamNickname);
|
||||
ArchiWebHandler.Init(SteamClient, callback.WebAPIUserNonce, callback.VanityURL);
|
||||
|
||||
ulong clanID = SteamMasterClanID;
|
||||
if (clanID != 0) {
|
||||
SteamFriends.JoinChat(clanID);
|
||||
}
|
||||
if (UseAsfAsMobileAuthenticator && TwoFactorAuth == null && SteamGuardAccount == null) {
|
||||
LinkMobileAuthenticator();
|
||||
}
|
||||
|
||||
// Reset one-time-only access tokens
|
||||
AuthCode = null;
|
||||
TwoFactorAuth = null;
|
||||
|
||||
if (!SteamNickname.Equals("null")) {
|
||||
SteamFriends.SetPersonaName(SteamNickname);
|
||||
}
|
||||
|
||||
if (SteamParentalPIN.Equals("null")) {
|
||||
SteamParentalPIN = Program.GetUserInput(BotName, Program.EUserInputType.SteamParentalPIN);
|
||||
}
|
||||
|
||||
await ArchiWebHandler.Init(SteamClient, callback.WebAPIUserNonce, callback.VanityURL, SteamParentalPIN).ConfigureAwait(false);
|
||||
|
||||
if (SteamMasterClanID != 0) {
|
||||
await ArchiWebHandler.JoinClan(SteamMasterClanID).ConfigureAwait(false);
|
||||
SteamFriends.JoinChat(SteamMasterClanID);
|
||||
}
|
||||
|
||||
if (Statistics) {
|
||||
await ArchiWebHandler.JoinClan(Program.ArchiSCFarmGroup).ConfigureAwait(false);
|
||||
SteamFriends.JoinChat(Program.ArchiSCFarmGroup);
|
||||
}
|
||||
|
||||
Trading.CheckTrades();
|
||||
|
||||
await CardsFarmer.StartFarming().ConfigureAwait(false);
|
||||
break;
|
||||
case EResult.ServiceUnavailable:
|
||||
case EResult.Timeout:
|
||||
case EResult.TryAnotherCM:
|
||||
Logging.LogGenericWarning(BotName, "Unable to login to Steam: " + result + ", retrying...");
|
||||
await Stop().ConfigureAwait(false);
|
||||
await Start().ConfigureAwait(false);
|
||||
break;
|
||||
default:
|
||||
Logging.LogGenericWarning(BotName, "Unable to login to Steam: " + callback.Result + " / " + callback.ExtendedResult + ", retrying...");
|
||||
Stop();
|
||||
Thread.Sleep(5000);
|
||||
Start();
|
||||
Logging.LogGenericWarning(BotName, "Unable to login to Steam: " + result);
|
||||
await Shutdown().ConfigureAwait(false);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
private void OnLoginKey(SteamUser.LoginKeyCallback callback) {
|
||||
if (callback == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
File.WriteAllText(LoginKeyFile, callback.LoginKey);
|
||||
SteamUser.AcceptNewLoginKey(callback);
|
||||
}
|
||||
|
||||
private void OnMachineAuth(SteamUser.UpdateMachineAuthCallback callback) {
|
||||
if (callback == null) {
|
||||
return;
|
||||
@@ -306,6 +836,8 @@ namespace ArchiSteamFarm {
|
||||
OneTimePassword = callback.OneTimePassword,
|
||||
SentryFileHash = sentryHash,
|
||||
});
|
||||
|
||||
Logging.LogGenericInfo(BotName, "Sentryfile updated successfully!");
|
||||
}
|
||||
|
||||
private void OnNotification(ArchiHandler.NotificationCallback callback) {
|
||||
@@ -326,7 +858,8 @@ namespace ArchiSteamFarm {
|
||||
}
|
||||
|
||||
var purchaseResult = callback.PurchaseResult;
|
||||
SteamFriends.SendChatMessage(SteamMasterID, EChatEntryType.ChatMsg, "Status: " + purchaseResult);
|
||||
var items = callback.Items;
|
||||
SendMessageToUser(SteamMasterID, "Status: " + purchaseResult + " | Items: " + string.Join("", items));
|
||||
|
||||
if (purchaseResult == ArchiHandler.PurchaseResponseCallback.EPurchaseResult.OK) {
|
||||
await CardsFarmer.StartFarming().ConfigureAwait(false);
|
||||
|
||||
@@ -1,30 +1,47 @@
|
||||
using SteamKit2;
|
||||
/*
|
||||
_ _ _ ____ _ _____
|
||||
/ \ _ __ ___ | |__ (_)/ ___| | |_ ___ __ _ _ __ ___ | ___|__ _ _ __ _ __ ___
|
||||
/ _ \ | '__|/ __|| '_ \ | |\___ \ | __|/ _ \ / _` || '_ ` _ \ | |_ / _` || '__|| '_ ` _ \
|
||||
/ ___ \ | | | (__ | | | || | ___) || |_| __/| (_| || | | | | || _|| (_| || | | | | | | |
|
||||
/_/ \_\|_| \___||_| |_||_||____/ \__|\___| \__,_||_| |_| |_||_| \__,_||_| |_| |_| |_|
|
||||
|
||||
Copyright 2015 Ł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 SteamKit2;
|
||||
using SteamKit2.Internal;
|
||||
using System.IO;
|
||||
|
||||
namespace ArchiSteamFarm {
|
||||
/// <summary>
|
||||
/// Message used to Accept or Decline a group(clan) invite.
|
||||
/// </summary>
|
||||
internal sealed class CMsgClientClanInviteAction : ISteamSerializableMessage, ISteamSerializable {
|
||||
EMsg ISteamSerializableMessage.GetEMsg() {
|
||||
return EMsg.ClientAcknowledgeClanInvite;
|
||||
}
|
||||
|
||||
public CMsgClientClanInviteAction() {
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Group invited to.
|
||||
/// </summary>
|
||||
internal ulong GroupID = 0;
|
||||
|
||||
/// <summary>
|
||||
/// To accept or decline the invite.
|
||||
/// </summary>
|
||||
internal bool AcceptInvite = true;
|
||||
|
||||
public CMsgClientClanInviteAction() { }
|
||||
|
||||
void ISteamSerializable.Serialize(Stream stream) {
|
||||
if (stream == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
BinaryWriter binaryWriter = new BinaryWriter(stream);
|
||||
binaryWriter.Write(GroupID);
|
||||
@@ -35,6 +52,10 @@ namespace ArchiSteamFarm {
|
||||
}
|
||||
|
||||
void ISteamSerializable.Deserialize(Stream stream) {
|
||||
if (stream == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
BinaryReader binaryReader = new BinaryReader(stream);
|
||||
GroupID = binaryReader.ReadUInt64();
|
||||
|
||||
331
ArchiSteamFarm/CardsFarmer.cs
Normal file → Executable file
331
ArchiSteamFarm/CardsFarmer.cs
Normal file → Executable file
@@ -1,34 +1,168 @@
|
||||
using HtmlAgilityPack;
|
||||
/*
|
||||
_ _ _ ____ _ _____
|
||||
/ \ _ __ ___ | |__ (_)/ ___| | |_ ___ __ _ _ __ ___ | ___|__ _ _ __ _ __ ___
|
||||
/ _ \ | '__|/ __|| '_ \ | |\___ \ | __|/ _ \ / _` || '_ ` _ \ | |_ / _` || '__|| '_ ` _ \
|
||||
/ ___ \ | | | (__ | | | || | ___) || |_| __/| (_| || | | | | || _|| (_| || | | | | | | |
|
||||
/_/ \_\|_| \___||_| |_||_||____/ \__|\___| \__,_||_| |_| |_||_| \__,_||_| |_| |_| |_|
|
||||
|
||||
Copyright 2015 Ł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 HtmlAgilityPack;
|
||||
using System;
|
||||
using System.Collections.Concurrent;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ArchiSteamFarm {
|
||||
internal class CardsFarmer {
|
||||
internal sealed class CardsFarmer {
|
||||
private const byte StatusCheckSleep = 5; // In minutes, how long to wait before checking the appID again
|
||||
private const ushort MaxFarmingTime = 600; // In minutes, how long ASF is allowed to farm one game in solo mode
|
||||
|
||||
private readonly ManualResetEvent FarmResetEvent = new ManualResetEvent(false);
|
||||
private readonly SemaphoreSlim Semaphore = new SemaphoreSlim(1);
|
||||
|
||||
private readonly Bot Bot;
|
||||
private bool NowFarming;
|
||||
private readonly AutoResetEvent AutoResetEvent = new AutoResetEvent(false);
|
||||
private readonly Timer Timer;
|
||||
|
||||
internal readonly ConcurrentDictionary<uint, double> GamesToFarm = new ConcurrentDictionary<uint, double>();
|
||||
internal readonly List<uint> CurrentGamesFarming = new List<uint>();
|
||||
|
||||
private volatile bool NowFarming = false;
|
||||
|
||||
internal CardsFarmer(Bot bot) {
|
||||
Bot = bot;
|
||||
|
||||
Timer = new Timer(
|
||||
async e => await CheckGamesForFarming().ConfigureAwait(false),
|
||||
null,
|
||||
TimeSpan.FromMinutes(15), // Delay
|
||||
TimeSpan.FromMinutes(15) // Period
|
||||
);
|
||||
}
|
||||
|
||||
internal static List<uint> GetGamesToFarmSolo(ConcurrentDictionary<uint, double> gamesToFarm) {
|
||||
if (gamesToFarm == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
List<uint> result = new List<uint>();
|
||||
foreach (KeyValuePair<uint, double> keyValue in gamesToFarm) {
|
||||
if (keyValue.Value >= 2) {
|
||||
result.Add(keyValue.Key);
|
||||
}
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
internal static uint GetAnyGameToFarm(ConcurrentDictionary<uint, double> gamesToFarm) {
|
||||
if (gamesToFarm == null) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
foreach (uint appID in gamesToFarm.Keys) {
|
||||
return appID;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
internal bool FarmMultiple() {
|
||||
if (GamesToFarm.Count == 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
double maxHour = -1;
|
||||
|
||||
foreach (double hour in GamesToFarm.Values) {
|
||||
if (hour > maxHour) {
|
||||
maxHour = hour;
|
||||
}
|
||||
}
|
||||
|
||||
CurrentGamesFarming.Clear();
|
||||
foreach (uint appID in GamesToFarm.Keys) {
|
||||
CurrentGamesFarming.Add(appID);
|
||||
}
|
||||
|
||||
Logging.LogGenericInfo(Bot.BotName, "Now farming: " + string.Join(", ", GamesToFarm.Keys));
|
||||
if (Farm(maxHour, GamesToFarm.Keys)) {
|
||||
return true;
|
||||
} else {
|
||||
CurrentGamesFarming.Clear();
|
||||
NowFarming = false;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
internal async Task<bool> FarmSolo(uint appID) {
|
||||
if (appID == 0) {
|
||||
return true;
|
||||
}
|
||||
|
||||
CurrentGamesFarming.Clear();
|
||||
CurrentGamesFarming.Add(appID);
|
||||
|
||||
Logging.LogGenericInfo(Bot.BotName, "Now farming: " + appID);
|
||||
if (await Farm(appID).ConfigureAwait(false)) {
|
||||
double hours;
|
||||
GamesToFarm.TryRemove(appID, out hours);
|
||||
return true;
|
||||
} else {
|
||||
CurrentGamesFarming.Clear();
|
||||
NowFarming = false;
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
internal async Task StartFarming() {
|
||||
await StopFarming().ConfigureAwait(false);
|
||||
|
||||
await Semaphore.WaitAsync().ConfigureAwait(false);
|
||||
|
||||
if (NowFarming) {
|
||||
Semaphore.Release();
|
||||
return;
|
||||
}
|
||||
|
||||
Logging.LogGenericInfo(Bot.BotName, "Checking badges...");
|
||||
|
||||
// Find the number of badge pages
|
||||
HtmlDocument badgesDocument = await Bot.ArchiWebHandler.GetBadgePage(1).ConfigureAwait(false);
|
||||
if (badgesDocument == null) {
|
||||
Logging.LogGenericWarning(Bot.BotName, "Could not get badges information, farming is stopped!");
|
||||
Semaphore.Release();
|
||||
return;
|
||||
}
|
||||
|
||||
var maxPages = 1;
|
||||
HtmlNodeCollection badgesPagesNodeCollection = badgesDocument.DocumentNode.SelectNodes("//a[@class='pagelink']");
|
||||
if (badgesPagesNodeCollection != null) {
|
||||
maxPages = (byte) (badgesPagesNodeCollection.Count / 2 + 1); // Don't do this at home
|
||||
maxPages = (badgesPagesNodeCollection.Count / 2) + 1; // Don't do this at home
|
||||
}
|
||||
|
||||
// Find APPIDs we need to farm
|
||||
List<uint> appIDs = new List<uint>();
|
||||
for (var page = 1; page <= maxPages; page++) {
|
||||
Logging.LogGenericInfo(Bot.BotName, "Checking page: " + page + "/" + maxPages);
|
||||
|
||||
if (page > 1) { // Because we fetched page number 1 already
|
||||
badgesDocument = await Bot.ArchiWebHandler.GetBadgePage(page).ConfigureAwait(false);
|
||||
if (badgesDocument == null) {
|
||||
@@ -38,35 +172,138 @@ namespace ArchiSteamFarm {
|
||||
|
||||
HtmlNodeCollection badgesPageNodes = badgesDocument.DocumentNode.SelectNodes("//a[@class='btn_green_white_innerfade btn_small_thin']");
|
||||
if (badgesPageNodes == null) {
|
||||
break;
|
||||
continue;
|
||||
}
|
||||
|
||||
GamesToFarm.Clear();
|
||||
foreach (HtmlNode badgesPageNode in badgesPageNodes) {
|
||||
string steamLink = badgesPageNode.GetAttributeValue("href", null);
|
||||
if (steamLink == null) {
|
||||
page = maxPages; // Break from outer loop
|
||||
break;
|
||||
continue;
|
||||
}
|
||||
|
||||
uint appID = (uint) Utilities.OnlyNumbers(steamLink);
|
||||
if (appID == 0) {
|
||||
page = maxPages; // Break from outer loop
|
||||
break;
|
||||
continue;
|
||||
}
|
||||
|
||||
appIDs.Add(appID);
|
||||
if (Bot.Blacklist.Contains(appID)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// We assume that every game has at least 2 hours played, until we actually check them
|
||||
GamesToFarm.AddOrUpdate(appID, 2, (key, value) => 2);
|
||||
}
|
||||
}
|
||||
|
||||
// Start farming
|
||||
while (appIDs.Count > 0) {
|
||||
uint appID = appIDs[0];
|
||||
if (await Farm(appID).ConfigureAwait(false)) {
|
||||
appIDs.Remove(appID);
|
||||
} else {
|
||||
break;
|
||||
// If we have restricted card drops, actually do check all games that are left to farm
|
||||
if (Bot.CardDropsRestricted) {
|
||||
foreach (uint appID in GamesToFarm.Keys) {
|
||||
Logging.LogGenericInfo(Bot.BotName, "Checking hours of appID: " + appID);
|
||||
HtmlDocument appPage = await Bot.ArchiWebHandler.GetGameCardsPage(appID).ConfigureAwait(false);
|
||||
if (appPage == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
HtmlNode appNode = appPage.DocumentNode.SelectSingleNode("//div[@class='badge_title_stats_playtime']");
|
||||
if (appNode == null) {
|
||||
continue;
|
||||
}
|
||||
|
||||
string hoursString = appNode.InnerText;
|
||||
if (string.IsNullOrEmpty(hoursString)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
hoursString = Regex.Match(hoursString, @"[0-9\.,]+").Value;
|
||||
double hours;
|
||||
|
||||
if (string.IsNullOrEmpty(hoursString)) {
|
||||
hours = 0;
|
||||
} else {
|
||||
hours = double.Parse(hoursString, CultureInfo.InvariantCulture);
|
||||
}
|
||||
|
||||
GamesToFarm[appID] = hours;
|
||||
}
|
||||
}
|
||||
|
||||
Logging.LogGenericInfo(Bot.BotName, "Farming in progress...");
|
||||
|
||||
NowFarming = GamesToFarm.Count > 0;
|
||||
Semaphore.Release();
|
||||
|
||||
// Now the algorithm used for farming depends on whether account is restricted or not
|
||||
if (Bot.CardDropsRestricted) {
|
||||
// If we have restricted card drops, we use complex algorithm, which prioritizes farming solo titles >= 2 hours, then all at once, until any game hits mentioned 2 hours
|
||||
Logging.LogGenericInfo(Bot.BotName, "Chosen farming algorithm: Complex");
|
||||
while (GamesToFarm.Count > 0) {
|
||||
List<uint> gamesToFarmSolo = GetGamesToFarmSolo(GamesToFarm);
|
||||
if (gamesToFarmSolo.Count > 0) {
|
||||
while (gamesToFarmSolo.Count > 0) {
|
||||
uint appID = gamesToFarmSolo[0];
|
||||
bool success = await FarmSolo(appID).ConfigureAwait(false);
|
||||
if (success) {
|
||||
Logging.LogGenericInfo(Bot.BotName, "Done farming: " + appID);
|
||||
gamesToFarmSolo.Remove(appID);
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
bool success = FarmMultiple();
|
||||
if (success) {
|
||||
Logging.LogGenericInfo(Bot.BotName, "Done farming: " + string.Join(", ", GamesToFarm.Keys));
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// If we have unrestricted card drops, we use simple algorithm and farm cards one-by-one
|
||||
Logging.LogGenericInfo(Bot.BotName, "Chosen farming algorithm: Simple");
|
||||
while (GamesToFarm.Count > 0) {
|
||||
uint appID = GetAnyGameToFarm(GamesToFarm);
|
||||
bool success = await FarmSolo(appID).ConfigureAwait(false);
|
||||
if (success) {
|
||||
Logging.LogGenericInfo(Bot.BotName, "Done farming: " + appID);
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
CurrentGamesFarming.Clear();
|
||||
NowFarming = false;
|
||||
Logging.LogGenericInfo(Bot.BotName, "Farming finished!");
|
||||
await Bot.OnFarmingFinished().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
internal async Task StopFarming() {
|
||||
await Semaphore.WaitAsync().ConfigureAwait(false);
|
||||
|
||||
if (!NowFarming) {
|
||||
Semaphore.Release();
|
||||
return;
|
||||
}
|
||||
|
||||
Logging.LogGenericInfo(Bot.BotName, "Sending signal to stop farming");
|
||||
FarmResetEvent.Set();
|
||||
while (NowFarming) {
|
||||
Logging.LogGenericInfo(Bot.BotName, "Waiting for reaction...");
|
||||
await Utilities.SleepAsync(1000).ConfigureAwait(false);
|
||||
}
|
||||
FarmResetEvent.Reset();
|
||||
Logging.LogGenericInfo(Bot.BotName, "Farming stopped!");
|
||||
Semaphore.Release();
|
||||
}
|
||||
|
||||
private async Task CheckGamesForFarming() {
|
||||
if (NowFarming || CurrentGamesFarming.Count > 0 || GamesToFarm.Count > 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
await StartFarming().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
private async Task<bool?> ShouldFarm(ulong appID) {
|
||||
@@ -81,28 +318,56 @@ namespace ArchiSteamFarm {
|
||||
return result;
|
||||
}
|
||||
|
||||
private async Task<bool> Farm(ulong appID) {
|
||||
if (NowFarming) {
|
||||
AutoResetEvent.Set();
|
||||
Thread.Sleep(1000);
|
||||
AutoResetEvent.Reset();
|
||||
}
|
||||
private async Task<bool> Farm(uint appID) {
|
||||
Bot.ArchiHandler.PlayGames(appID);
|
||||
|
||||
bool success = true;
|
||||
|
||||
bool? keepFarming = await ShouldFarm(appID).ConfigureAwait(false);
|
||||
while (keepFarming == null || keepFarming.Value) {
|
||||
if (!NowFarming) {
|
||||
NowFarming = true;
|
||||
Bot.PlayGame(appID);
|
||||
}
|
||||
if (AutoResetEvent.WaitOne(1000 * 60 * 5)) {
|
||||
for (ushort farmingTime = 0; farmingTime <= MaxFarmingTime && (!keepFarming.HasValue || keepFarming.Value); farmingTime += StatusCheckSleep) {
|
||||
Logging.LogGenericInfo(Bot.BotName, "Still farming: " + appID);
|
||||
if (FarmResetEvent.WaitOne(1000 * 60 * StatusCheckSleep)) {
|
||||
success = false;
|
||||
break;
|
||||
}
|
||||
keepFarming = await ShouldFarm(appID).ConfigureAwait(false);
|
||||
}
|
||||
Bot.PlayGame(0);
|
||||
NowFarming = false;
|
||||
|
||||
Bot.ArchiHandler.PlayGames(0);
|
||||
Logging.LogGenericInfo(Bot.BotName, "Stopped farming: " + appID);
|
||||
return success;
|
||||
}
|
||||
|
||||
private bool Farm(double maxHour, ICollection<uint> appIDs) {
|
||||
if (maxHour >= 2) {
|
||||
return true;
|
||||
}
|
||||
|
||||
Bot.ArchiHandler.PlayGames(appIDs);
|
||||
|
||||
bool success = true;
|
||||
while (maxHour < 2) {
|
||||
Logging.LogGenericInfo(Bot.BotName, "Still farming: " + string.Join(", ", appIDs));
|
||||
if (FarmResetEvent.WaitOne(1000 * 60 * StatusCheckSleep)) {
|
||||
success = false;
|
||||
break;
|
||||
}
|
||||
|
||||
// Don't forget to update our GamesToFarm hours
|
||||
double timePlayed = StatusCheckSleep / 60.0;
|
||||
foreach (KeyValuePair<uint, double> keyValue in GamesToFarm) {
|
||||
if (!appIDs.Contains(keyValue.Key)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
GamesToFarm[keyValue.Key] = keyValue.Value + timePlayed;
|
||||
}
|
||||
|
||||
maxHour += timePlayed;
|
||||
}
|
||||
|
||||
Bot.ArchiHandler.PlayGames(0);
|
||||
Logging.LogGenericInfo(Bot.BotName, "Stopped farming: " + string.Join(", ", appIDs));
|
||||
return success;
|
||||
}
|
||||
}
|
||||
|
||||
41
ArchiSteamFarm/Debugging.cs
Normal file
41
ArchiSteamFarm/Debugging.cs
Normal file
@@ -0,0 +1,41 @@
|
||||
/*
|
||||
_ _ _ ____ _ _____
|
||||
/ \ _ __ ___ | |__ (_)/ ___| | |_ ___ __ _ _ __ ___ | ___|__ _ _ __ _ __ ___
|
||||
/ _ \ | '__|/ __|| '_ \ | |\___ \ | __|/ _ \ / _` || '_ ` _ \ | |_ / _` || '__|| '_ ` _ \
|
||||
/ ___ \ | | | (__ | | | || | ___) || |_| __/| (_| || | | | | || _|| (_| || | | | | | | |
|
||||
/_/ \_\|_| \___||_| |_||_||____/ \__|\___| \__,_||_| |_| |_||_| \__,_||_| |_| |_| |_|
|
||||
|
||||
Copyright 2015 Ł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.Diagnostics;
|
||||
|
||||
namespace ArchiSteamFarm {
|
||||
internal static class Debugging {
|
||||
internal static bool IsDebugBuild { get; private set; } = false;
|
||||
internal static bool IsReleaseBuild { get { return !IsDebugBuild; } }
|
||||
|
||||
static Debugging() {
|
||||
MarkIfDebug();
|
||||
}
|
||||
|
||||
[Conditional("DEBUG")]
|
||||
private static void MarkIfDebug() {
|
||||
IsDebugBuild = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,37 @@
|
||||
using System;
|
||||
/*
|
||||
_ _ _ ____ _ _____
|
||||
/ \ _ __ ___ | |__ (_)/ ___| | |_ ___ __ _ _ __ ___ | ___|__ _ _ __ _ __ ___
|
||||
/ _ \ | '__|/ __|| '_ \ | |\___ \ | __|/ _ \ / _` || '_ ` _ \ | |_ / _` || '__|| '_ ` _ \
|
||||
/ ___ \ | | | (__ | | | || | ___) || |_| __/| (_| || | | | | || _|| (_| || | | | | | | |
|
||||
/_/ \_\|_| \___||_| |_||_||____/ \__|\___| \__,_||_| |_| |_||_| \__,_||_| |_| |_| |_|
|
||||
|
||||
Copyright 2015 Ł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;
|
||||
using System.Diagnostics;
|
||||
using System.Runtime.CompilerServices;
|
||||
|
||||
namespace ArchiSteamFarm {
|
||||
internal static class Logging {
|
||||
private static void Log(string message) {
|
||||
Console.WriteLine(DateTime.Now + " " + message);
|
||||
lock (Program.ConsoleLock) {
|
||||
Console.WriteLine(DateTime.Now + " " + message);
|
||||
}
|
||||
}
|
||||
|
||||
internal static void LogGenericError(string botName, string message, [CallerMemberName] string previousMethodName = "") {
|
||||
@@ -23,16 +50,18 @@ namespace ArchiSteamFarm {
|
||||
Log("[*] INFO: " + previousMethodName + "() <" + botName + "> " + message);
|
||||
}
|
||||
|
||||
internal static void LogGenericNotice(string botName, string message, [CallerMemberName] string previousMethodName = "") {
|
||||
Log("[*] NOTICE: " + previousMethodName + "() <" + botName + "> " + message);
|
||||
}
|
||||
|
||||
[Conditional("DEBUG")]
|
||||
internal static void LogGenericDebug(string botName, string message, [CallerMemberName] string previousMethodName = "") {
|
||||
Log("[#] DEBUG: " + previousMethodName + "() <" + botName + "> " + message);
|
||||
}
|
||||
|
||||
[Conditional("DEBUG")]
|
||||
internal static void LogGenericDebug(string message, [CallerMemberName] string previousMethodName = "") {
|
||||
LogGenericDebug("DEBUG", message, previousMethodName);
|
||||
}
|
||||
|
||||
internal static void LogNullError(string nullObjectName, [CallerMemberName] string previousMethodName = "") {
|
||||
LogGenericError(nullObjectName + " is null!", previousMethodName);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,58 +1,190 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
/*
|
||||
_ _ _ ____ _ _____
|
||||
/ \ _ __ ___ | |__ (_)/ ___| | |_ ___ __ _ _ __ ___ | ___|__ _ _ __ _ __ ___
|
||||
/ _ \ | '__|/ __|| '_ \ | |\___ \ | __|/ _ \ / _` || '_ ` _ \ | |_ / _` || '__|| '_ ` _ \
|
||||
/ ___ \ | | | (__ | | | || | ___) || |_| __/| (_| || | | | | || _|| (_| || | | | | | | |
|
||||
/_/ \_\|_| \___||_| |_||_||____/ \__|\___| \__,_||_| |_| |_||_| \__,_||_| |_| |_| |_|
|
||||
|
||||
Copyright 2015 Ł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 Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Reflection;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ArchiSteamFarm {
|
||||
internal static class Program {
|
||||
internal enum EUserInputType {
|
||||
Login,
|
||||
Password,
|
||||
PhoneNumber,
|
||||
SMS,
|
||||
SteamGuard,
|
||||
SteamParentalPIN,
|
||||
RevocationCode,
|
||||
TwoFactorAuthentication,
|
||||
}
|
||||
|
||||
private const string LatestGithubReleaseURL = "https://api.github.com/repos/JustArchi/ArchiSteamFarm/releases/latest";
|
||||
|
||||
internal const ulong ArchiSCFarmGroup = 103582791440160998;
|
||||
internal const string ConfigDirectoryPath = "config";
|
||||
private static readonly HashSet<Bot> Bots = new HashSet<Bot>();
|
||||
|
||||
private static readonly SemaphoreSlim SteamSemaphore = new SemaphoreSlim(1);
|
||||
private static readonly ManualResetEvent ShutdownResetEvent = new ManualResetEvent(false);
|
||||
private static readonly Assembly Assembly = Assembly.GetExecutingAssembly();
|
||||
private static readonly string ExecutablePath = Assembly.Location;
|
||||
private static readonly AssemblyName AssemblyName = Assembly.GetName();
|
||||
//private static readonly string ExeName = AssemblyName.Name + ".exe";
|
||||
|
||||
internal static readonly string Version = AssemblyName.Version.ToString();
|
||||
internal static readonly object ConsoleLock = new object();
|
||||
|
||||
internal static void Exit(int exitCode = 0) {
|
||||
ShutdownAllBots();
|
||||
private static async Task CheckForUpdate() {
|
||||
JObject response = await WebBrowser.UrlGetToJObject(LatestGithubReleaseURL).ConfigureAwait(false);
|
||||
if (response == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
string remoteVersion = response["tag_name"].ToString();
|
||||
if (string.IsNullOrEmpty(remoteVersion)) {
|
||||
return;
|
||||
}
|
||||
|
||||
string localVersion = Version;
|
||||
|
||||
Logging.LogGenericNotice("", "Local version: " + localVersion);
|
||||
Logging.LogGenericNotice("", "Remote version: " + remoteVersion);
|
||||
|
||||
int comparisonResult = localVersion.CompareTo(remoteVersion);
|
||||
if (comparisonResult < 0) {
|
||||
Logging.LogGenericNotice("", "New version is available!");
|
||||
Logging.LogGenericNotice("", "Consider updating yourself!");
|
||||
await Utilities.SleepAsync(5000).ConfigureAwait(false);
|
||||
} else if (comparisonResult > 0) {
|
||||
Logging.LogGenericNotice("", "You're currently using pre-release version!");
|
||||
Logging.LogGenericNotice("", "Be careful!");
|
||||
}
|
||||
}
|
||||
|
||||
internal static async Task Exit(int exitCode = 0) {
|
||||
await Bot.ShutdownAllBots().ConfigureAwait(false);
|
||||
Environment.Exit(exitCode);
|
||||
}
|
||||
|
||||
internal static string GetSteamGuardCode(string botLogin, bool twoFactorAuthentication) {
|
||||
internal static async Task Restart() {
|
||||
await Bot.ShutdownAllBots().ConfigureAwait(false);
|
||||
System.Diagnostics.Process.Start(ExecutablePath);
|
||||
Environment.Exit(0);
|
||||
}
|
||||
|
||||
internal static async Task LimitSteamRequestsAsync() {
|
||||
await SteamSemaphore.WaitAsync().ConfigureAwait(false);
|
||||
await Utilities.SleepAsync(5 * 1000).ConfigureAwait(false); // We must add some delay to not get caught by Steam anty-DoS
|
||||
SteamSemaphore.Release();
|
||||
}
|
||||
|
||||
internal static string GetUserInput(string botLogin, EUserInputType userInputType, string extraInformation = null) {
|
||||
string result;
|
||||
lock (ConsoleLock) {
|
||||
if (twoFactorAuthentication) {
|
||||
Console.Write("<" + botLogin + "> Please enter your 2 factor auth code from your authenticator app: ");
|
||||
} else {
|
||||
Console.Write("<" + botLogin + "> Please enter the auth code sent to your email : ");
|
||||
switch (userInputType) {
|
||||
case EUserInputType.Login:
|
||||
Console.Write("<" + botLogin + "> Please enter your login: ");
|
||||
break;
|
||||
case EUserInputType.Password:
|
||||
Console.Write("<" + botLogin + "> Please enter your password: ");
|
||||
break;
|
||||
case EUserInputType.PhoneNumber:
|
||||
Console.Write("<" + botLogin + "> Please enter your full phone number (e.g. +1234567890): ");
|
||||
break;
|
||||
case EUserInputType.SMS:
|
||||
Console.Write("<" + botLogin + "> Please enter SMS code sent on your mobile: ");
|
||||
break;
|
||||
case EUserInputType.SteamGuard:
|
||||
Console.Write("<" + botLogin + "> Please enter the auth code sent to your email: ");
|
||||
break;
|
||||
case EUserInputType.SteamParentalPIN:
|
||||
Console.Write("<" + botLogin + "> Please enter steam parental PIN: ");
|
||||
break;
|
||||
case EUserInputType.RevocationCode:
|
||||
Console.WriteLine("<" + botLogin + "> PLEASE WRITE DOWN YOUR REVOCATION CODE: " + extraInformation);
|
||||
Console.WriteLine("<" + botLogin + "> THIS IS THE ONLY WAY TO NOT GET LOCKED OUT OF YOUR ACCOUNT!");
|
||||
Console.Write("<" + botLogin + "> Hit enter once ready...");
|
||||
break;
|
||||
case EUserInputType.TwoFactorAuthentication:
|
||||
Console.Write("<" + botLogin + "> Please enter your 2 factor auth code from your authenticator app: ");
|
||||
break;
|
||||
}
|
||||
return Console.ReadLine();
|
||||
result = Console.ReadLine();
|
||||
Console.Clear(); // For security purposes
|
||||
}
|
||||
return result.Trim(); // Get rid of all whitespace characters
|
||||
}
|
||||
|
||||
internal static async void OnBotShutdown() {
|
||||
if (Bot.GetRunningBotsCount() == 0) {
|
||||
Logging.LogGenericInfo("Main", "No bots are running, exiting");
|
||||
await Utilities.SleepAsync(5000).ConfigureAwait(false); // This might be the only message user gets, consider giving him some time
|
||||
ShutdownResetEvent.Set();
|
||||
}
|
||||
}
|
||||
|
||||
private static void ShutdownAllBots() {
|
||||
lock (Bots) {
|
||||
foreach (Bot bot in Bots) {
|
||||
bot.Stop();
|
||||
}
|
||||
Bots.Clear();
|
||||
}
|
||||
private static void InitServices() {
|
||||
WebBrowser.Init();
|
||||
}
|
||||
|
||||
private static void Main(string[] args) {
|
||||
for (var i = 0; i < 4 && !Directory.Exists(ConfigDirectoryPath); i++) {
|
||||
Directory.SetCurrentDirectory("..");
|
||||
Logging.LogGenericInfo("Main", "Archi's Steam Farm, version " + Version);
|
||||
|
||||
InitServices();
|
||||
|
||||
Task.Run(async () => await CheckForUpdate().ConfigureAwait(false)).Wait();
|
||||
|
||||
// Allow loading configs from source tree if it's a debug build
|
||||
if (Debugging.IsDebugBuild) {
|
||||
for (var i = 0; i < 4; i++) {
|
||||
Directory.SetCurrentDirectory("..");
|
||||
if (Directory.Exists(ConfigDirectoryPath)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (!Directory.Exists(ConfigDirectoryPath)) {
|
||||
Logging.LogGenericError("Main", "Config directory doesn't exist!");
|
||||
Console.ReadLine();
|
||||
Exit(1);
|
||||
Task.Run(async () => await Exit(1).ConfigureAwait(false)).Wait();
|
||||
}
|
||||
|
||||
lock (Bots) {
|
||||
foreach (var configFile in Directory.EnumerateFiles(ConfigDirectoryPath, "*.xml")) {
|
||||
string botName = Path.GetFileNameWithoutExtension(configFile);
|
||||
Bots.Add(new Bot(botName));
|
||||
foreach (var configFile in Directory.EnumerateFiles(ConfigDirectoryPath, "*.xml")) {
|
||||
string botName = Path.GetFileNameWithoutExtension(configFile);
|
||||
Bot bot = new Bot(botName);
|
||||
if (!bot.Enabled) {
|
||||
Logging.LogGenericInfo(botName, "Not starting this instance because it's disabled in config file");
|
||||
}
|
||||
}
|
||||
|
||||
Thread.Sleep(Timeout.Infinite);
|
||||
// Check if we got any bots running
|
||||
OnBotShutdown();
|
||||
|
||||
ShutdownResetEvent.WaitOne();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,7 +10,7 @@ using System.Runtime.InteropServices;
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[assembly: AssemblyCompany("")]
|
||||
[assembly: AssemblyProduct("ArchiSteamFarm")]
|
||||
[assembly: AssemblyCopyright("Copyright © 2015")]
|
||||
[assembly: AssemblyCopyright("Copyright © Łukasz Domeradzki 2015")]
|
||||
[assembly: AssemblyTrademark("")]
|
||||
[assembly: AssemblyCulture("")]
|
||||
|
||||
@@ -32,5 +32,5 @@ using System.Runtime.InteropServices;
|
||||
// You can specify all the values or you can default the Build and Revision Numbers
|
||||
// by using the '*' as shown below:
|
||||
// [assembly: AssemblyVersion("1.0.*")]
|
||||
[assembly: AssemblyVersion("1.0.0.0")]
|
||||
[assembly: AssemblyFileVersion("1.0.0.0")]
|
||||
[assembly: AssemblyVersion("0.9.0.0")]
|
||||
[assembly: AssemblyFileVersion("0.9.0.0")]
|
||||
|
||||
@@ -1,4 +1,28 @@
|
||||
namespace ArchiSteamFarm {
|
||||
/*
|
||||
_ _ _ ____ _ _____
|
||||
/ \ _ __ ___ | |__ (_)/ ___| | |_ ___ __ _ _ __ ___ | ___|__ _ _ __ _ __ ___
|
||||
/ _ \ | '__|/ __|| '_ \ | |\___ \ | __|/ _ \ / _` || '_ ` _ \ | |_ / _` || '__|| '_ ` _ \
|
||||
/ ___ \ | | | (__ | | | || | ___) || |_| __/| (_| || | | | | || _|| (_| || | | | | | | |
|
||||
/_/ \_\|_| \___||_| |_||_||____/ \__|\___| \__,_||_| |_| |_||_| \__,_||_| |_| |_| |_|
|
||||
|
||||
Copyright 2015 Ł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.
|
||||
|
||||
*/
|
||||
|
||||
namespace ArchiSteamFarm {
|
||||
internal sealed class SteamItem {
|
||||
// REF: https://developer.valvesoftware.com/wiki/Steam_Web_API/IEconService
|
||||
internal string appid { get; set; }
|
||||
|
||||
@@ -1,4 +1,28 @@
|
||||
using SteamKit2;
|
||||
/*
|
||||
_ _ _ ____ _ _____
|
||||
/ \ _ __ ___ | |__ (_)/ ___| | |_ ___ __ _ _ __ ___ | ___|__ _ _ __ _ __ ___
|
||||
/ _ \ | '__|/ __|| '_ \ | |\___ \ | __|/ _ \ / _` || '_ ` _ \ | |_ / _` || '__|| '_ ` _ \
|
||||
/ ___ \ | | | (__ | | | || | ___) || |_| __/| (_| || | | | | || _|| (_| || | | | | | | |
|
||||
/_/ \_\|_| \___||_| |_||_||____/ \__|\___| \__,_||_| |_| |_||_| \__,_||_| |_| |_| |_|
|
||||
|
||||
Copyright 2015 Ł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 SteamKit2;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace ArchiSteamFarm {
|
||||
@@ -15,7 +39,14 @@ namespace ArchiSteamFarm {
|
||||
Declined,
|
||||
InvalidItems,
|
||||
EmailPending,
|
||||
EmailCanceled
|
||||
EmailCanceled,
|
||||
OnHold
|
||||
}
|
||||
|
||||
internal enum ETradeOfferConfirmationMethod {
|
||||
Invalid,
|
||||
Email,
|
||||
MobileApp
|
||||
}
|
||||
|
||||
internal string tradeofferid { get; set; }
|
||||
@@ -29,13 +60,19 @@ namespace ArchiSteamFarm {
|
||||
internal int time_created { get; set; }
|
||||
internal int time_updated { get; set; }
|
||||
internal bool from_real_time_trade { get; set; }
|
||||
internal int escrow_end_date { get; set; }
|
||||
internal ETradeOfferConfirmationMethod confirmation_method { get; set; }
|
||||
|
||||
// Extra
|
||||
private ulong _OtherSteamID64 = 0;
|
||||
internal ulong OtherSteamID64 {
|
||||
get {
|
||||
return new SteamID((uint) accountid_other, EUniverse.Public, EAccountType.Individual).ConvertToUInt64();
|
||||
if (_OtherSteamID64 == 0 && accountid_other != 0) {
|
||||
_OtherSteamID64 = new SteamID((uint) accountid_other, EUniverse.Public, EAccountType.Individual).ConvertToUInt64();
|
||||
}
|
||||
|
||||
return _OtherSteamID64;
|
||||
}
|
||||
private set { }
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,44 +1,68 @@
|
||||
using System.Collections.Generic;
|
||||
/*
|
||||
_ _ _ ____ _ _____
|
||||
/ \ _ __ ___ | |__ (_)/ ___| | |_ ___ __ _ _ __ ___ | ___|__ _ _ __ _ __ ___
|
||||
/ _ \ | '__|/ __|| '_ \ | |\___ \ | __|/ _ \ / _` || '_ ` _ \ | |_ / _` || '__|| '_ ` _ \
|
||||
/ ___ \ | | | (__ | | | || | ___) || |_| __/| (_| || | | | | || _|| (_| || | | | | | | |
|
||||
/_/ \_\|_| \___||_| |_||_||____/ \__|\___| \__,_||_| |_| |_||_| \__,_||_| |_| |_| |_|
|
||||
|
||||
Copyright 2015 Ł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.Collections.Generic;
|
||||
using System.Threading;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ArchiSteamFarm {
|
||||
internal sealed class Trading {
|
||||
private Bot Bot;
|
||||
private readonly Bot Bot;
|
||||
private readonly SemaphoreSlim Semaphore = new SemaphoreSlim(1);
|
||||
private volatile byte ParsingTasks = 0;
|
||||
private SemaphoreSlim semaphore = new SemaphoreSlim(1);
|
||||
|
||||
internal Trading(Bot bot) {
|
||||
Bot = bot;
|
||||
}
|
||||
|
||||
internal void CheckTrades() {
|
||||
internal async void CheckTrades() {
|
||||
if (ParsingTasks < 2) {
|
||||
ParsingTasks++;
|
||||
Task.Run(() => ParseActiveTrades());
|
||||
|
||||
await Semaphore.WaitAsync().ConfigureAwait(false);
|
||||
await ParseActiveTrades().ConfigureAwait(false);
|
||||
Semaphore.Release();
|
||||
|
||||
ParsingTasks--;
|
||||
}
|
||||
}
|
||||
|
||||
private async Task ParseActiveTrades() {
|
||||
await semaphore.WaitAsync().ConfigureAwait(false);
|
||||
|
||||
List<SteamTradeOffer> tradeOffers = Bot.ArchiWebHandler.GetTradeOffers();
|
||||
if (tradeOffers != null) {
|
||||
List<Task> tasks = new List<Task>();
|
||||
foreach (SteamTradeOffer tradeOffer in tradeOffers) {
|
||||
if (tradeOffer.trade_offer_state == SteamTradeOffer.ETradeOfferState.Active) {
|
||||
Task task = Task.Run(async () => {
|
||||
await ParseTrade(tradeOffer).ConfigureAwait(false);
|
||||
});
|
||||
tasks.Add(task);
|
||||
}
|
||||
}
|
||||
|
||||
await Task.WhenAll(tasks).ConfigureAwait(false);
|
||||
if (tradeOffers == null) {
|
||||
return;
|
||||
}
|
||||
|
||||
ParsingTasks--;
|
||||
semaphore.Release();
|
||||
List<Task> tasks = new List<Task>();
|
||||
foreach (SteamTradeOffer tradeOffer in tradeOffers) {
|
||||
if (tradeOffer.trade_offer_state == SteamTradeOffer.ETradeOfferState.Active) {
|
||||
tasks.Add(Task.Run(async () => await ParseTrade(tradeOffer).ConfigureAwait(false)));
|
||||
}
|
||||
}
|
||||
|
||||
await Task.WhenAll(tasks).ConfigureAwait(false);
|
||||
Bot.AcceptAllConfirmations();
|
||||
}
|
||||
|
||||
private async Task ParseTrade(SteamTradeOffer tradeOffer) {
|
||||
@@ -51,21 +75,18 @@ namespace ArchiSteamFarm {
|
||||
return;
|
||||
}
|
||||
|
||||
ulong steamID = tradeOffer.OtherSteamID64;
|
||||
bool success = false;
|
||||
bool tradeAccepted = false;
|
||||
bool success, tradeAccepted;
|
||||
|
||||
if (tradeOffer.items_to_give.Count == 0 || steamID == Bot.SteamMasterID) {
|
||||
if (tradeOffer.items_to_give.Count == 0 || tradeOffer.OtherSteamID64 == Bot.SteamMasterID) {
|
||||
tradeAccepted = true;
|
||||
Logging.LogGenericInfo(Bot.BotName, "Accepting trade: " + tradeID);
|
||||
success = await Bot.ArchiWebHandler.AcceptTradeOffer(tradeID).ConfigureAwait(false);
|
||||
} else {
|
||||
tradeAccepted = false;
|
||||
Logging.LogGenericInfo(Bot.BotName, "Rejecting trade: " + tradeID);
|
||||
success = Bot.ArchiWebHandler.DeclineTradeOffer(tradeID);
|
||||
}
|
||||
|
||||
if (!success) {
|
||||
Logging.LogGenericWarning(Bot.BotName, "Response to trade " + tradeID + " failed!");
|
||||
}
|
||||
|
||||
if (tradeAccepted && success) {
|
||||
// Do whatever we want with success
|
||||
}
|
||||
|
||||
@@ -1,117 +1,60 @@
|
||||
using HtmlAgilityPack;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Globalization;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
/*
|
||||
_ _ _ ____ _ _____
|
||||
/ \ _ __ ___ | |__ (_)/ ___| | |_ ___ __ _ _ __ ___ | ___|__ _ _ __ _ __ ___
|
||||
/ _ \ | '__|/ __|| '_ \ | |\___ \ | __|/ _ \ / _` || '_ ` _ \ | |_ / _` || '__|| '_ ` _ \
|
||||
/ ___ \ | | | (__ | | | || | ___) || |_| __/| (_| || | | | | || _|| (_| || | | | | | | |
|
||||
/_/ \_\|_| \___||_| |_||_||____/ \__|\___| \__,_||_| |_| |_||_| \__,_||_| |_| |_| |_|
|
||||
|
||||
Copyright 2015 Ł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.Text.RegularExpressions;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace ArchiSteamFarm {
|
||||
internal static class Utilities {
|
||||
internal static async Task SleepAsync(int miliseconds) {
|
||||
await Task.Delay(miliseconds).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
internal static ulong OnlyNumbers(string inputString) {
|
||||
if (string.IsNullOrEmpty(inputString)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
string resultString;
|
||||
try {
|
||||
Regex regexObj = new Regex(@"[^\d]");
|
||||
resultString = regexObj.Replace(inputString, "");
|
||||
} catch (ArgumentException e) {
|
||||
Logging.LogGenericException("Utilities", e);
|
||||
string resultString = OnlyNumbersString(inputString);
|
||||
if (string.IsNullOrEmpty(resultString)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
ulong result = ulong.Parse(resultString, CultureInfo.InvariantCulture);
|
||||
return result;
|
||||
}
|
||||
|
||||
internal static async Task<HttpResponseMessage> UrlToHttpResponse(string websiteAddress, Dictionary<string, string> cookieVariables) {
|
||||
HttpResponseMessage result = null;
|
||||
if (!string.IsNullOrEmpty(websiteAddress)) {
|
||||
try {
|
||||
using (HttpClientHandler clientHandler = new HttpClientHandler { UseCookies = false }) {
|
||||
using (HttpClient client = new HttpClient(clientHandler)) {
|
||||
client.Timeout = TimeSpan.FromSeconds(10);
|
||||
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, websiteAddress);
|
||||
if (cookieVariables != null) {
|
||||
StringBuilder cookie = new StringBuilder();
|
||||
foreach (KeyValuePair<string, string> cookieVariable in cookieVariables) {
|
||||
cookie.Append(cookieVariable.Key + "=" + cookieVariable.Value + ";");
|
||||
}
|
||||
requestMessage.Headers.Add("Cookie", cookie.ToString());
|
||||
}
|
||||
HttpResponseMessage responseMessage = await client.SendAsync(requestMessage).ConfigureAwait(false);
|
||||
if (responseMessage != null) {
|
||||
responseMessage.EnsureSuccessStatusCode();
|
||||
result = responseMessage;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
}
|
||||
ulong result;
|
||||
if (!ulong.TryParse(resultString, out result)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
internal static async Task<HttpResponseMessage> UrlToHttpResponse(string websiteAddress) {
|
||||
return await UrlToHttpResponse(websiteAddress, null).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
internal static async Task<HtmlDocument> UrlToHtmlDocument(string websiteAddress, Dictionary<string, string> cookieVariables) {
|
||||
HtmlDocument result = null;
|
||||
if (!string.IsNullOrEmpty(websiteAddress)) {
|
||||
try {
|
||||
HttpResponseMessage responseMessage = await UrlToHttpResponse(websiteAddress, cookieVariables).ConfigureAwait(false);
|
||||
if (responseMessage != null) {
|
||||
string source = await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false);
|
||||
if (!string.IsNullOrEmpty(source)) {
|
||||
source = WebUtility.HtmlDecode(source);
|
||||
result = new HtmlDocument();
|
||||
result.LoadHtml(source);
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
}
|
||||
internal static string OnlyNumbersString(string text) {
|
||||
if (string.IsNullOrEmpty(text)) {
|
||||
return null;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
internal static async Task<HtmlDocument> UrlToHtmlDocument(string websiteAddress) {
|
||||
return await UrlToHtmlDocument(websiteAddress, null).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
internal static async Task<bool> UrlPostRequest(string request, Dictionary<string, string> postData, Dictionary<string, string> cookieVariables, string referer = null) {
|
||||
bool result = false;
|
||||
if (!string.IsNullOrEmpty(request)) {
|
||||
try {
|
||||
using (HttpClientHandler clientHandler = new HttpClientHandler { UseCookies = false }) {
|
||||
using (HttpClient client = new HttpClient(clientHandler)) {
|
||||
client.Timeout = TimeSpan.FromSeconds(15);
|
||||
HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Post, request);
|
||||
requestMessage.Content = new FormUrlEncodedContent(postData);
|
||||
if (cookieVariables != null && cookieVariables.Count > 0) {
|
||||
StringBuilder cookie = new StringBuilder();
|
||||
foreach (KeyValuePair<string, string> cookieVariable in cookieVariables) {
|
||||
cookie.Append(cookieVariable.Key + "=" + cookieVariable.Value + ";");
|
||||
}
|
||||
requestMessage.Headers.Add("Cookie", cookie.ToString());
|
||||
}
|
||||
if (referer != null) {
|
||||
requestMessage.Headers.Referrer = new Uri(referer);
|
||||
}
|
||||
HttpResponseMessage responseMessage = await client.SendAsync(requestMessage).ConfigureAwait(false);
|
||||
if (responseMessage != null) {
|
||||
result = responseMessage.IsSuccessStatusCode;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
}
|
||||
}
|
||||
return result;
|
||||
return Regex.Replace(text, @"[^\d]", "");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
247
ArchiSteamFarm/WebBrowser.cs
Normal file
247
ArchiSteamFarm/WebBrowser.cs
Normal file
@@ -0,0 +1,247 @@
|
||||
/*
|
||||
_ _ _ ____ _ _____
|
||||
/ \ _ __ ___ | |__ (_)/ ___| | |_ ___ __ _ _ __ ___ | ___|__ _ _ __ _ __ ___
|
||||
/ _ \ | '__|/ __|| '_ \ | |\___ \ | __|/ _ \ / _` || '_ ` _ \ | |_ / _` || '__|| '_ ` _ \
|
||||
/ ___ \ | | | (__ | | | || | ___) || |_| __/| (_| || | | | | || _|| (_| || | | | | | | |
|
||||
/_/ \_\|_| \___||_| |_||_||____/ \__|\___| \__,_||_| |_| |_||_| \__,_||_| |_| |_| |_|
|
||||
|
||||
Copyright 2015 Ł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 HtmlAgilityPack;
|
||||
using Newtonsoft.Json.Linq;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
using System.Xml;
|
||||
|
||||
namespace ArchiSteamFarm {
|
||||
internal static class WebBrowser {
|
||||
internal const byte HttpTimeout = 180; // In seconds
|
||||
|
||||
private static readonly HttpClientHandler HttpClientHandler = new HttpClientHandler { UseCookies = false };
|
||||
private static readonly HttpClient HttpClient = new HttpClient(HttpClientHandler) { Timeout = TimeSpan.FromSeconds(HttpTimeout) };
|
||||
|
||||
internal static void Init() {
|
||||
HttpClient.DefaultRequestHeaders.UserAgent.ParseAdd("ArchiSteamFarm/" + Program.Version);
|
||||
|
||||
// Don't limit maximum number of allowed concurrent connections
|
||||
// It's application's responsibility to handle that stuff
|
||||
ServicePointManager.DefaultConnectionLimit = int.MaxValue;
|
||||
|
||||
// Don't use Expect100Continue, we don't need to do that
|
||||
ServicePointManager.Expect100Continue = false;
|
||||
}
|
||||
|
||||
private static async Task<HttpResponseMessage> UrlRequest(string request, HttpMethod httpMethod, Dictionary<string, string> data = null, Dictionary<string, string> cookies = null, string referer = null) {
|
||||
if (string.IsNullOrEmpty(request) || httpMethod == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
HttpRequestMessage requestMessage = new HttpRequestMessage(httpMethod, request);
|
||||
|
||||
if (httpMethod == HttpMethod.Post && data != null) {
|
||||
requestMessage.Content = new FormUrlEncodedContent(data);
|
||||
}
|
||||
|
||||
if (cookies != null && cookies.Count > 0) {
|
||||
StringBuilder cookieHeader = new StringBuilder();
|
||||
foreach (KeyValuePair<string, string> cookie in cookies) {
|
||||
cookieHeader.Append(cookie.Key + "=" + cookie.Value + ";");
|
||||
}
|
||||
requestMessage.Headers.Add("Cookie", cookieHeader.ToString());
|
||||
}
|
||||
|
||||
if (referer != null) {
|
||||
requestMessage.Headers.Referrer = new Uri(referer);
|
||||
}
|
||||
|
||||
HttpResponseMessage responseMessage;
|
||||
|
||||
try {
|
||||
responseMessage = await HttpClient.SendAsync(requestMessage).ConfigureAwait(false);
|
||||
} catch { // Request failed, we don't need to know the exact reason, swallow exception
|
||||
return null;
|
||||
}
|
||||
|
||||
if (responseMessage == null || !responseMessage.IsSuccessStatusCode) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return responseMessage;
|
||||
}
|
||||
|
||||
internal static async Task<HttpResponseMessage> UrlGet(string request, Dictionary<string, string> cookies = null, string referer = null) {
|
||||
if (string.IsNullOrEmpty(request)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return await UrlRequest(request, HttpMethod.Get, null, cookies, referer).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
internal static async Task<HttpResponseMessage> UrlPost(string request, Dictionary<string, string> postData = null, Dictionary<string, string> cookies = null, string referer = null) {
|
||||
if (string.IsNullOrEmpty(request)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return await UrlRequest(request, HttpMethod.Post, postData, cookies, referer).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
internal static async Task<HtmlDocument> HttpResponseToHtmlDocument(HttpResponseMessage httpResponse) {
|
||||
if (httpResponse == null || httpResponse.Content == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
string content = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
|
||||
if (string.IsNullOrEmpty(content)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
content = WebUtility.HtmlDecode(content);
|
||||
HtmlDocument htmlDocument = new HtmlDocument();
|
||||
htmlDocument.LoadHtml(content);
|
||||
|
||||
return htmlDocument;
|
||||
}
|
||||
|
||||
internal static async Task<string> UrlGetToContent(string request, Dictionary<string, string> cookies = null, string referer = null) {
|
||||
if (string.IsNullOrEmpty(request)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
HttpResponseMessage responseMessage = await UrlGet(request, cookies, referer).ConfigureAwait(false);
|
||||
if (responseMessage == null || responseMessage.Content == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
internal static async Task<string> UrlPostToContent(string request, Dictionary<string, string> postData = null, Dictionary<string, string> cookies = null, string referer = null) {
|
||||
if (string.IsNullOrEmpty(request)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
HttpResponseMessage responseMessage = await UrlPost(request, postData, cookies, referer).ConfigureAwait(false);
|
||||
if (responseMessage == null || responseMessage.Content == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return await responseMessage.Content.ReadAsStringAsync().ConfigureAwait(false);
|
||||
}
|
||||
|
||||
internal static async Task<string> UrlGetToTitle(string request, Dictionary<string, string> cookies = null, string referer = null) {
|
||||
if (string.IsNullOrEmpty(request)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
HtmlDocument htmlDocument = await UrlGetToHtmlDocument(request, cookies, referer).ConfigureAwait(false);
|
||||
if (htmlDocument == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
HtmlNode htmlNode = htmlDocument.DocumentNode.SelectSingleNode("//head/title");
|
||||
if (htmlNode == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return htmlNode.InnerText;
|
||||
}
|
||||
|
||||
internal static async Task<HtmlDocument> UrlGetToHtmlDocument(string request, Dictionary<string, string> cookies = null, string referer = null) {
|
||||
if (string.IsNullOrEmpty(request)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
HttpResponseMessage httpResponse = await UrlGet(request, cookies, referer).ConfigureAwait(false);
|
||||
if (httpResponse == null) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return await HttpResponseToHtmlDocument(httpResponse).ConfigureAwait(false);
|
||||
}
|
||||
|
||||
internal static async Task<JArray> UrlGetToJArray(string request, Dictionary<string, string> cookies = null, string referer = null) {
|
||||
if (string.IsNullOrEmpty(request)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
string content = await UrlGetToContent(request, cookies, referer).ConfigureAwait(false);
|
||||
if (string.IsNullOrEmpty(content)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
JArray jArray;
|
||||
|
||||
try {
|
||||
jArray = JArray.Parse(content);
|
||||
} catch (Exception e) {
|
||||
Logging.LogGenericException("WebBrowser", e);
|
||||
return null;
|
||||
}
|
||||
|
||||
return jArray;
|
||||
}
|
||||
|
||||
internal static async Task<JObject> UrlGetToJObject(string request, Dictionary<string, string> cookies = null, string referer = null) {
|
||||
if (string.IsNullOrEmpty(request)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
string content = await UrlGetToContent(request, cookies, referer).ConfigureAwait(false);
|
||||
if (string.IsNullOrEmpty(content)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
JObject jObject;
|
||||
|
||||
try {
|
||||
jObject = JObject.Parse(content);
|
||||
} catch (Exception e) {
|
||||
Logging.LogGenericException("WebBrowser", e);
|
||||
return null;
|
||||
}
|
||||
|
||||
return jObject;
|
||||
}
|
||||
|
||||
internal static async Task<XmlDocument> UrlGetToXML(string request, Dictionary<string, string> cookies = null, string referer = null) {
|
||||
if (string.IsNullOrEmpty(request)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
string content = await UrlGetToContent(request, cookies, referer).ConfigureAwait(false);
|
||||
if (string.IsNullOrEmpty(content)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
XmlDocument xmlDocument = new XmlDocument();
|
||||
|
||||
try {
|
||||
xmlDocument.LoadXml(content);
|
||||
} catch (XmlException e) {
|
||||
Logging.LogGenericException("WebBrowser", e);
|
||||
return null;
|
||||
}
|
||||
|
||||
return xmlDocument;
|
||||
}
|
||||
}
|
||||
}
|
||||
BIN
ArchiSteamFarm/cirno.ico
Normal file
BIN
ArchiSteamFarm/cirno.ico
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 361 KiB |
@@ -1,16 +1,81 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<configuration>
|
||||
<!-- Every bot should have it's own unique .xml configuration file, this is example on which you can base on -->
|
||||
|
||||
<!-- Every bot should have it's own unique .xml configuration file, this is example on which you can base on -->
|
||||
<!-- Notice, if you use special characters reserved for XML, you should escape them -->
|
||||
<!-- Escape table: [& - &] | [" - "] | [' - '] | [< - <] | [> - >] -->
|
||||
<!-- So e.g. if your SteamPassword is "foo&" you should write value="foo&" -->
|
||||
|
||||
<Enabled value="true"/> <!-- Master switch to turn account on and off -->
|
||||
<!-- Type of the property is a tip for you that defines what values you can use -->
|
||||
<!-- bool - Boolean value that can be only "true" or "false" -->
|
||||
<!-- string - Any sequence of characters, unless stated otherwise (keep in mind escape table above), with special treatment of "null" value -->
|
||||
<!-- uint - 32-bit unsigned integer, used mostly for steam appID -->
|
||||
<!-- ulong - 64-bit unsigned (long) integer, used mostly for representing steamID64 -->
|
||||
<!-- HashSet(uint) - Comma-separated list of unique 32-bit unsigned integers -->
|
||||
|
||||
<!-- Steam -->
|
||||
<SteamLogin value="Foo"/> <!-- This is your steam login, the one you use for logging in to steam -->
|
||||
<SteamPassword value="Bar"/> <!-- This is your steam password, the one you use for logging in to steam -->
|
||||
<SteamNickname value="ArchiSteamFarmer"/> <!-- This is your steam nickname, the one you want to use for bot. Can be anything up to 32 characters -->
|
||||
<SteamApiKey value="FFFFFFFF"/> <!-- Get one at https://steamcommunity.com/dev/apikey -->
|
||||
<SteamMasterID value="76561198006963719"/> <!-- This is steamID of the master, aka the "root" user being able to execute any command -->
|
||||
<SteamMasterClanID value="0"/> <!-- If you want from the bot to join particular chat of given clan, set it here, otherwise leave at 0 -->
|
||||
<!-- Master switch to turn account on and off, set to "true" after you're done -->
|
||||
<!-- TIP: This bot instance won't run unless below switch is set to "true" -->
|
||||
<Enabled type="bool" value="false"/>
|
||||
|
||||
<!-- This is your steam login, the one you use for logging in to steam -->
|
||||
<!-- TIP: You can use "null" if you wish to enter login on every startup -->
|
||||
<SteamLogin type="string" value="null"/>
|
||||
|
||||
<!-- This is your steam password, the one you use for logging in to steam -->
|
||||
<!-- TIP: You can use "null" if you wish to enter password on every startup -->
|
||||
<SteamPassword type="string" value="null"/>
|
||||
|
||||
<!-- This is steam nickname, the one you want to use for bot. Can be anything up to 32 characters -->
|
||||
<!-- TIP: You can use "null" if you wish to preserve your actual nickname -->
|
||||
<SteamNickname type="string" value="null"/>
|
||||
|
||||
<!-- This is your bot's API key, get one at https://steamcommunity.com/dev/apikey while logged in as bot, domain doesn't matter -->
|
||||
<!-- TIP: You can use "null", but it will disable all API-based functionalities such as trading -->
|
||||
<SteamApiKey type="string" value="null"/>
|
||||
|
||||
<!-- This is your parental PIN if you use steam parental functionality -->
|
||||
<!-- TIP: Most likely you don't want to change it. You can use "null" if you wish to enter PIN on every startup, 0 means there is no PIN -->
|
||||
<SteamParentalPIN type="string" value="0"/>
|
||||
|
||||
<!-- This is steamID64 of the bot-master - you, for example "76561198006963719" -->
|
||||
<!-- You can get one e.g. by logging in to http://steamrep.com/ -->
|
||||
<!-- TIP: You can use "0", but bot won't accept steam cd-keys or trades from anybody" -->
|
||||
<SteamMasterID type="ulong" value="0"/>
|
||||
|
||||
<!-- This is steamID64 of the master clan (group). If defined, bot will join the group and the chat automatically after logging in -->
|
||||
<!-- The easiest way to get one is to check groups on your profile: http://steamcommunity.com/my/profile" -->
|
||||
<!-- Then copying the URL of "Leave group" link, it will look like this: javascript:leaveGroupPrompt('103582791440160998','Archi\'s SC Farm') -->
|
||||
<!-- The steamID64 we're looking for is there, in above example: "103582791440160998" -->
|
||||
<!-- TIP: If you don't have your own farming group, most likely you don't want to change it, 0 means there is no master group defined -->
|
||||
<SteamMasterClanID type="ulong" value="0"/>
|
||||
|
||||
<!-- This switch defines if you want to use built-in ASF two-factor-authentication (ASF 2FA) for this account -->
|
||||
<!-- The one and only purpose for this function is automating steam logins and steam trades, so you won't need to enter 2FA codes all the time -->
|
||||
<!-- This however defeats the whole purpose of two-factor-auth, and should be used on alt accounts ONLY -->
|
||||
<!-- You should read full documentation, along with explanation here: https://github.com/JustArchi/ArchiSteamFarm/wiki/Escrow -->
|
||||
<!-- WARNING, this option can potentially LOCK OUT YOUR ACCOUNT! If you don't fully understand this feature, DON'T USE IT! -->
|
||||
<UseAsfAsMobileAuthenticator type="bool" value="false"/>
|
||||
|
||||
<!-- This switch defines if the account has card drops restricted -->
|
||||
<!-- Restricted card drops means that the account doesn't receive any steam cards until it plays the game for at least 2 hours -->
|
||||
<!-- As there is no magical way to detect it by ASF, I made this option config-based switch -->
|
||||
<!-- TIP: Based on this parameter, ASF will try to choose the most optimal cards farming algorithm for this account -->
|
||||
<CardDropsRestricted type="bool" value="false"/>
|
||||
|
||||
<!-- This switch defines if bot should disconnect once farming is finished -->
|
||||
<!-- When no bots are active, ASF will shutdown as well -->
|
||||
<!-- Some people may want to keep their bots 24/7, other disconnect them after job is done -->
|
||||
<!-- Choose yourself what you prefer -->
|
||||
<ShutdownOnFarmingFinished type="bool" value="false"/>
|
||||
|
||||
<!-- Comma-separated list of IDs that should not be considered for farming -->
|
||||
<!-- Default value includes appIDs that are wrongly appearing on the profile, e.g. Monster Summer Sale -->
|
||||
<!-- TIP: Most likely you don't want to change it -->
|
||||
<Blacklist type="HashSet(uint)" value="303700,335590,368020"/>
|
||||
|
||||
<!-- This switch enables statistics for me - bot will join Archi's SC Farm group and chat -->
|
||||
<!-- Consider leaving it at "true", this way I can check how many running bots are active -->
|
||||
<!-- That directly affects my willings to work on the project, as I can see how many users are actually using it -->
|
||||
<!-- TIP: Group link is http://steamcommunity.com/groups/ascfarm -->
|
||||
<Statistics type="bool" value="true"/>
|
||||
</configuration>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<packages>
|
||||
<package id="HtmlAgilityPack" version="1.4.9" targetFramework="net45" />
|
||||
<package id="Newtonsoft.Json" version="8.0.1-beta3" targetFramework="net45" />
|
||||
<package id="protobuf-net" version="2.0.0.668" targetFramework="net45" />
|
||||
<package id="SteamKit2" version="1.6.5" targetFramework="net45" />
|
||||
</packages>
|
||||
202
LICENSE-2.0.txt
Normal file
202
LICENSE-2.0.txt
Normal file
@@ -0,0 +1,202 @@
|
||||
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. 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.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright 2015 Łukasz "JustArchi" Domeradzki
|
||||
|
||||
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.
|
||||
65
README.md
65
README.md
@@ -1,26 +1,57 @@
|
||||
# ArchiSteamFarm
|
||||
ArchiSteamFarm
|
||||
===================
|
||||
|
||||
Big work-in-progress
|
||||
ASF is a C# application that allows you to farm steam cards using multiple steam accounts simultaneously. Unlike idle master which works only on one account at given time, requires steam client running in background, and launches additional processes imitiating "game playing" status, ASF doesn't require any steam client running in the background, doesn't launch any additional processes and is made to handle unlimited steam accounts at once. In addition to that, it's meant to be run on servers or other desktop-less machines, and features full Mono support, which makes it possible to launch on any Mono-supported operating system, such as Windows, Linux or OS X. ASF is based on, and possible, thanks to [SteamKit2](https://github.com/SteamRE/SteamKit).
|
||||
|
||||
Allows you to farm steam cards using multiple accounts simultaneously.
|
||||
**Core features:**
|
||||
|
||||
Each account is defined by it's own XML config in "config" directory.
|
||||
|
||||
Current functions:
|
||||
- Does not need Steam client running, or even a GUI. Fully based on SteamKit2 and reverse-engineered Steam protocol.
|
||||
- Automatically farm steam cards using any number of active accounts
|
||||
- Automatically farm available games using any number of active accounts
|
||||
- Automatically accept friend requests sent from master
|
||||
- Automatically accept all trades coming from master
|
||||
- Automatically accept all steam cd-keys sent via chat from master
|
||||
- SteamGuard / 2-factor-authentication support
|
||||
- Full Mono support, tested on Debian "9.0" Stretch (testing)
|
||||
- Possibility to choose the most efficient cards farming algorithm, based on given account
|
||||
- SteamGuard / SteamParental / 2FA support
|
||||
- Update notifications
|
||||
- Full Mono support, cross-OS compatibility
|
||||
|
||||
TODO:
|
||||
- Smart multi-games farming till every game reaches 2 hours, then one-by-one (similar to Idle Master) - Backend code is already here, just missing the logic and tests.
|
||||
- Possible integration with SteamTradeMatcher, bot can detect dupes and trade them automatically. Again, backend code is already here, just missing actual implementation.
|
||||
- Automatic sending of steam trades to master, after game is fully farmed.
|
||||
- Probably much more
|
||||
**Setting up:**
|
||||
|
||||
This is big WIP, so feel free to send pull requests if you wish.
|
||||
Each ASF bot is defined in it's own XML config file in `config` directory. ASF comes with included ```example.xml``` config file, on which you should base all of your bots. Simply copy ```example.xml``` to a new file, and edit properties inside. Don't forget to switch ```Enabled``` property to ```true``` once you're done, as this is the master switch which enables configured bot to launch. The most minimalistic setup to make ASF working is changing only ```Enabled```, ```SteamLogin``` and ```SteamPassword``` properties, everything else is more or less optional to enable additional features.
|
||||
|
||||
I'll release some releases later, when everything is tested and code cleaned up.
|
||||
ASF expects exclusive access to all steam accounts it's using, which means that you should not use the account which is currently being used by ASF at the same time. You may however ```!start``` and ```!stop``` bots during farming, as well as use config property such as ```ShutdownOnFarmingFinished``` which will automatically release account after farming is done.
|
||||
|
||||
After you set up all your bots (their configs), you should launch ```ASF.exe```. If your accounts require additional steps to unlock, such as Steam guard code, you'll need to enter those too after ASF tries to launch given bot. If everything ended properly, you should notice in the console output, as well as on your Steam, that all of your bots automatically started cards farming.
|
||||
|
||||
ASF doesn't require and doesn't interfere in any way with Steam client, which means that you can be logged in to Steam client as your primary account with e.g. Idle Master in the background, and launch ASF for all other accounts (your alts) at the same time.
|
||||
|
||||
**Current Commands:**
|
||||
|
||||
- `!2fa` Generates temporary 2FA token for current bot instance
|
||||
- `!2fa <BOT>` Generates temporary 2FA token for given bot instance
|
||||
- `!2faoff` Deactivates 2FA for current bot instance
|
||||
- `!2faoff <BOT>` Deactivates 2FA for given bot instance
|
||||
- `!exit` Stops whole ASF
|
||||
- `!farm` Restarts cards farming module. ASF automatically executes that if any cd-key is successfully claimed
|
||||
- `!redeem <KEY>` Redeems cd-key on current bot instance. You can also paste cd-key directly to the chat
|
||||
- `!start <BOT>` Starts given bot instance
|
||||
- `!status` Prints current status of ASF
|
||||
- `!stop` Stops current bot instance
|
||||
- `!stop <BOT>` Stops given bot instance
|
||||
|
||||
> Commands can be executed via a private chat with your bot.
|
||||
> Remember that bot accepts commands only from ```SteamMasterID```. That property can be configured in the config.
|
||||
|
||||
**Supported / Tested Operating-Systems:**
|
||||
|
||||
- Windows 10 Professional/Enterprise Edition (Native)
|
||||
- Windows 8.1 Professional (Native)
|
||||
- Windows 7 Ultimate (Native)
|
||||
- Debian 9.0 Stretch (Mono)
|
||||
- Debian 8.1 Jessie (Mono)
|
||||
- OS X 10.11.1 (Mono)
|
||||
|
||||
However, any operating system [listed here](http://www.mono-project.com/docs/about-mono/supported-platforms/) should run ASF flawlessly.
|
||||
|
||||
**Need help or more info?**
|
||||
|
||||
Head over to our [wiki](https://github.com/JustArchi/ArchiSteamFarm/wiki) then.
|
||||
|
||||
12
SteamAuth/APIEndpoints.cs
Normal file
12
SteamAuth/APIEndpoints.cs
Normal file
@@ -0,0 +1,12 @@
|
||||
namespace SteamAuth
|
||||
{
|
||||
public static class APIEndpoints
|
||||
{
|
||||
public const string STEAMAPI_BASE = "https://api.steampowered.com";
|
||||
public const string COMMUNITY_BASE = "https://steamcommunity.com";
|
||||
public const string MOBILEAUTH_BASE = STEAMAPI_BASE + "/IMobileAuthService/%s/v0001";
|
||||
public static string MOBILEAUTH_GETWGTOKEN = MOBILEAUTH_BASE.Replace("%s", "GetWGToken");
|
||||
public const string TWO_FACTOR_BASE = STEAMAPI_BASE + "/ITwoFactorService/%s/v0001";
|
||||
public static string TWO_FACTOR_TIME_QUERY = TWO_FACTOR_BASE.Replace("%s", "QueryTime");
|
||||
}
|
||||
}
|
||||
247
SteamAuth/AuthenticatorLinker.cs
Normal file
247
SteamAuth/AuthenticatorLinker.cs
Normal file
@@ -0,0 +1,247 @@
|
||||
using Newtonsoft.Json;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Specialized;
|
||||
using System.Linq;
|
||||
using System.Net;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SteamAuth
|
||||
{
|
||||
/// <summary>
|
||||
/// Handles the linking process for a new mobile authenticator.
|
||||
/// </summary>
|
||||
public class AuthenticatorLinker
|
||||
{
|
||||
|
||||
|
||||
/// <summary>
|
||||
/// Set to register a new phone number when linking. If a phone number is not set on the account, this must be set. If a phone number is set on the account, this must be null.
|
||||
/// </summary>
|
||||
public string PhoneNumber = null;
|
||||
|
||||
/// <summary>
|
||||
/// Randomly-generated device ID. Should only be generated once per linker.
|
||||
/// </summary>
|
||||
public string DeviceID { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// After the initial link step, if successful, this will be the SteamGuard data for the account. PLEASE save this somewhere after generating it; it's vital data.
|
||||
/// </summary>
|
||||
public SteamGuardAccount LinkedAccount { get; private set; }
|
||||
|
||||
/// <summary>
|
||||
/// True if the authenticator has been fully finalized.
|
||||
/// </summary>
|
||||
public bool Finalized = false;
|
||||
|
||||
private SessionData _session;
|
||||
private CookieContainer _cookies;
|
||||
|
||||
public AuthenticatorLinker(SessionData session)
|
||||
{
|
||||
this._session = session;
|
||||
this.DeviceID = _generateDeviceID();
|
||||
|
||||
this._cookies = new CookieContainer();
|
||||
session.AddCookies(_cookies);
|
||||
}
|
||||
|
||||
public LinkResult AddAuthenticator()
|
||||
{
|
||||
bool hasPhone = _hasPhoneAttached();
|
||||
if (hasPhone && PhoneNumber != null)
|
||||
return LinkResult.MustRemovePhoneNumber;
|
||||
if (!hasPhone && PhoneNumber == null)
|
||||
return LinkResult.MustProvidePhoneNumber;
|
||||
|
||||
if (!hasPhone)
|
||||
{
|
||||
if (!_addPhoneNumber())
|
||||
{
|
||||
return LinkResult.GeneralFailure;
|
||||
}
|
||||
}
|
||||
|
||||
var postData = new NameValueCollection();
|
||||
postData.Add("access_token", _session.OAuthToken);
|
||||
postData.Add("steamid", _session.SteamID.ToString());
|
||||
postData.Add("authenticator_type", "1");
|
||||
postData.Add("device_identifier", this.DeviceID);
|
||||
postData.Add("sms_phone_id", "1");
|
||||
|
||||
string response = SteamWeb.MobileLoginRequest(APIEndpoints.STEAMAPI_BASE + "/ITwoFactorService/AddAuthenticator/v0001", "POST", postData);
|
||||
if (response == null) return LinkResult.GeneralFailure;
|
||||
|
||||
var addAuthenticatorResponse = JsonConvert.DeserializeObject<AddAuthenticatorResponse>(response);
|
||||
if (addAuthenticatorResponse == null || addAuthenticatorResponse.Response == null || addAuthenticatorResponse.Response.Status != 1)
|
||||
{
|
||||
return LinkResult.GeneralFailure;
|
||||
}
|
||||
|
||||
this.LinkedAccount = addAuthenticatorResponse.Response;
|
||||
LinkedAccount.Session = this._session;
|
||||
LinkedAccount.DeviceID = this.DeviceID;
|
||||
|
||||
return LinkResult.AwaitingFinalization;
|
||||
}
|
||||
|
||||
public FinalizeResult FinalizeAddAuthenticator(string smsCode)
|
||||
{
|
||||
bool smsCodeGood = false;
|
||||
|
||||
var postData = new NameValueCollection();
|
||||
postData.Add("steamid", _session.SteamID.ToString());
|
||||
postData.Add("access_token", _session.OAuthToken);
|
||||
postData.Add("activation_code", smsCode);
|
||||
postData.Add("authenticator_code", "");
|
||||
int tries = 0;
|
||||
while (tries <= 30)
|
||||
{
|
||||
postData.Set("authenticator_code", tries == 0 ? "" : LinkedAccount.GenerateSteamGuardCode());
|
||||
postData.Add("authenticator_time", TimeAligner.GetSteamTime().ToString());
|
||||
|
||||
if(smsCodeGood)
|
||||
postData.Set("activation_code", "");
|
||||
|
||||
string response = SteamWeb.MobileLoginRequest(APIEndpoints.STEAMAPI_BASE + "/ITwoFactorService/FinalizeAddAuthenticator/v0001", "POST", postData);
|
||||
if (response == null) return FinalizeResult.GeneralFailure;
|
||||
|
||||
var finalizeResponse = JsonConvert.DeserializeObject<FinalizeAuthenticatorResponse>(response);
|
||||
|
||||
if (finalizeResponse == null || finalizeResponse.Response == null)
|
||||
{
|
||||
return FinalizeResult.GeneralFailure;
|
||||
}
|
||||
|
||||
if(finalizeResponse.Response.Status == 89)
|
||||
{
|
||||
return FinalizeResult.BadSMSCode;
|
||||
}
|
||||
|
||||
if(finalizeResponse.Response.Status == 88)
|
||||
{
|
||||
if(tries >= 30)
|
||||
{
|
||||
return FinalizeResult.UnableToGenerateCorrectCodes;
|
||||
}
|
||||
}
|
||||
|
||||
if (!finalizeResponse.Response.Success)
|
||||
{
|
||||
return FinalizeResult.GeneralFailure;
|
||||
}
|
||||
|
||||
if (finalizeResponse.Response.WantMore)
|
||||
{
|
||||
smsCodeGood = true;
|
||||
tries++;
|
||||
continue;
|
||||
}
|
||||
|
||||
this.LinkedAccount.FullyEnrolled = true;
|
||||
return FinalizeResult.Success;
|
||||
}
|
||||
|
||||
return FinalizeResult.GeneralFailure;
|
||||
}
|
||||
|
||||
private bool _addPhoneNumber()
|
||||
{
|
||||
var postData = new NameValueCollection();
|
||||
postData.Add("op", "add_phone_number");
|
||||
postData.Add("arg", PhoneNumber);
|
||||
postData.Add("sessionid", _session.SessionID);
|
||||
|
||||
string response = SteamWeb.Request(APIEndpoints.COMMUNITY_BASE + "/steamguard/phoneajax", "POST", postData, _cookies);
|
||||
if (response == null) return false;
|
||||
|
||||
var addPhoneNumberResponse = JsonConvert.DeserializeObject<AddPhoneResponse>(response);
|
||||
return addPhoneNumberResponse.Success;
|
||||
}
|
||||
|
||||
private bool _hasPhoneAttached()
|
||||
{
|
||||
var postData = new NameValueCollection();
|
||||
postData.Add("op", "has_phone");
|
||||
postData.Add("arg", "null");
|
||||
postData.Add("sessionid", _session.SessionID);
|
||||
|
||||
string response = SteamWeb.Request(APIEndpoints.COMMUNITY_BASE + "/steamguard/phoneajax", "POST", postData, _cookies);
|
||||
if (response == null) return false;
|
||||
|
||||
var hasPhoneResponse = JsonConvert.DeserializeObject<HasPhoneResponse>(response);
|
||||
return hasPhoneResponse.HasPhone;
|
||||
}
|
||||
|
||||
public enum LinkResult
|
||||
{
|
||||
MustProvidePhoneNumber, //No phone number on the account
|
||||
MustRemovePhoneNumber, //A phone number is already on the account
|
||||
AwaitingFinalization, //Must provide an SMS code
|
||||
GeneralFailure //General failure (really now!)
|
||||
}
|
||||
|
||||
public enum FinalizeResult
|
||||
{
|
||||
BadSMSCode,
|
||||
UnableToGenerateCorrectCodes,
|
||||
Success,
|
||||
GeneralFailure
|
||||
}
|
||||
|
||||
private class AddAuthenticatorResponse
|
||||
{
|
||||
[JsonProperty("response")]
|
||||
public SteamGuardAccount Response { get; set; }
|
||||
}
|
||||
|
||||
private class FinalizeAuthenticatorResponse
|
||||
{
|
||||
[JsonProperty("response")]
|
||||
public FinalizeAuthenticatorInternalResponse Response { get; set; }
|
||||
|
||||
internal class FinalizeAuthenticatorInternalResponse
|
||||
{
|
||||
[JsonProperty("status")]
|
||||
public int Status { get; set; }
|
||||
|
||||
[JsonProperty("server_time")]
|
||||
public long ServerTime { get; set; }
|
||||
|
||||
[JsonProperty("want_more")]
|
||||
public bool WantMore { get; set; }
|
||||
|
||||
[JsonProperty("success")]
|
||||
public bool Success { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
private class HasPhoneResponse
|
||||
{
|
||||
[JsonProperty("has_phone")]
|
||||
public bool HasPhone { get; set; }
|
||||
}
|
||||
|
||||
private class AddPhoneResponse
|
||||
{
|
||||
[JsonProperty("success")]
|
||||
public bool Success { get; set; }
|
||||
}
|
||||
|
||||
private string _generateDeviceID()
|
||||
{
|
||||
using (var sha1 = new SHA1Managed())
|
||||
{
|
||||
RNGCryptoServiceProvider secureRandom = new RNGCryptoServiceProvider();
|
||||
byte[] randomBytes = new byte[8];
|
||||
secureRandom.GetBytes(randomBytes);
|
||||
|
||||
byte[] hashedBytes = sha1.ComputeHash(randomBytes);
|
||||
return "android:" + BitConverter.ToString(hashedBytes).Replace("-", "");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
15
SteamAuth/Confirmation.cs
Normal file
15
SteamAuth/Confirmation.cs
Normal file
@@ -0,0 +1,15 @@
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Linq;
|
||||
using System.Text;
|
||||
using System.Threading.Tasks;
|
||||
|
||||
namespace SteamAuth
|
||||
{
|
||||
public class Confirmation
|
||||
{
|
||||
public string ConfirmationID;
|
||||
public string ConfirmationKey;
|
||||
public string ConfirmationDescription;
|
||||
}
|
||||
}
|
||||
36
SteamAuth/Properties/AssemblyInfo.cs
Normal file
36
SteamAuth/Properties/AssemblyInfo.cs
Normal file
@@ -0,0 +1,36 @@
|
||||
using System.Reflection;
|
||||
using System.Runtime.CompilerServices;
|
||||
using System.Runtime.InteropServices;
|
||||
|
||||
// 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("SteamAuth")]
|
||||
[assembly: AssemblyDescription("")]
|
||||
[assembly: AssemblyConfiguration("")]
|
||||
[assembly: AssemblyCompany("")]
|
||||
[assembly: AssemblyProduct("SteamAuth")]
|
||||
[assembly: AssemblyCopyright("Copyright © 2015")]
|
||||
[assembly: AssemblyTrademark("")]
|
||||
[assembly: AssemblyCulture("")]
|
||||
|
||||
// Setting ComVisible to false makes the types in this assembly not visible
|
||||
// to COM components. If you need to access a type in this assembly from
|
||||
// COM, set the ComVisible attribute to true on that type.
|
||||
[assembly: ComVisible(false)]
|
||||
|
||||
// The following GUID is for the ID of the typelib if this project is exposed to COM
|
||||
[assembly: Guid("5ad0934e-f6c4-4ae5-83af-c788313b2a87")]
|
||||
|
||||
// Version information for an assembly consists of the following four values:
|
||||
//
|
||||
// Major Version
|
||||
// Minor Version
|
||||
// Build Number
|
||||
// Revision
|
||||
//
|
||||
// You can specify all the values or you can default the Build and Revision Numbers
|
||||
// by using the '*' as shown below:
|
||||
// [assembly: AssemblyVersion("1.0.*")]
|
||||
[assembly: AssemblyVersion("1.0.0.0")]
|
||||
[assembly: AssemblyFileVersion("1.0.0.0")]
|
||||
40
SteamAuth/SessionData.cs
Normal file
40
SteamAuth/SessionData.cs
Normal file
@@ -0,0 +1,40 @@
|
||||
using System.Net;
|
||||
|
||||
namespace SteamAuth
|
||||
{
|
||||
public class SessionData
|
||||
{
|
||||
public string SessionID { get; set; }
|
||||
|
||||
public string SteamLogin { get; set; }
|
||||
|
||||
public string SteamLoginSecure { get; set; }
|
||||
|
||||
public string WebCookie { get; set; }
|
||||
|
||||
public string OAuthToken { get; set; }
|
||||
|
||||
public ulong SteamID { get; set; }
|
||||
|
||||
public void AddCookies(CookieContainer cookies)
|
||||
{
|
||||
cookies.Add(new Cookie("mobileClientVersion", "0 (2.1.3)", "/", ".steamcommunity.com"));
|
||||
cookies.Add(new Cookie("mobileClient", "android", "/", ".steamcommunity.com"));
|
||||
|
||||
cookies.Add(new Cookie("steamid", SteamID.ToString(), "/", ".steamcommunity.com"));
|
||||
cookies.Add(new Cookie("steamLogin", SteamLogin, "/", ".steamcommunity.com")
|
||||
{
|
||||
HttpOnly = true
|
||||
});
|
||||
|
||||
cookies.Add(new Cookie("steamLoginSecure", SteamLoginSecure, "/", ".steamcommunity.com")
|
||||
{
|
||||
HttpOnly = true,
|
||||
Secure = true
|
||||
});
|
||||
cookies.Add(new Cookie("Steam_Language", "english", "/", ".steamcommunity.com"));
|
||||
cookies.Add(new Cookie("dob", "", "/", ".steamcommunity.com"));
|
||||
cookies.Add(new Cookie("sessionid", this.SessionID, "/", ".steamcommunity.com"));
|
||||
}
|
||||
}
|
||||
}
|
||||
69
SteamAuth/SteamAuth.csproj
Normal file
69
SteamAuth/SteamAuth.csproj
Normal file
@@ -0,0 +1,69 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
|
||||
<PropertyGroup>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||
<ProjectGuid>{5AD0934E-F6C4-4AE5-83AF-C788313B2A87}</ProjectGuid>
|
||||
<OutputType>Library</OutputType>
|
||||
<AppDesignerFolder>Properties</AppDesignerFolder>
|
||||
<RootNamespace>SteamAuth</RootNamespace>
|
||||
<AssemblyName>SteamAuth</AssemblyName>
|
||||
<TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
|
||||
<FileAlignment>512</FileAlignment>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
<DebugType>full</DebugType>
|
||||
<Optimize>false</Optimize>
|
||||
<OutputPath>bin\Debug\</OutputPath>
|
||||
<DefineConstants>DEBUG;TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
|
||||
<DebugType>pdbonly</DebugType>
|
||||
<Optimize>true</Optimize>
|
||||
<OutputPath>bin\Release\</OutputPath>
|
||||
<DefineConstants>TRACE</DefineConstants>
|
||||
<ErrorReport>prompt</ErrorReport>
|
||||
<WarningLevel>4</WarningLevel>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="Newtonsoft.Json, Version=8.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
|
||||
<HintPath>..\packages\Newtonsoft.Json.8.0.1-beta3\lib\net45\Newtonsoft.Json.dll</HintPath>
|
||||
<Private>True</Private>
|
||||
</Reference>
|
||||
<Reference Include="System" />
|
||||
<Reference Include="System.Core" />
|
||||
<Reference Include="System.Xml.Linq" />
|
||||
<Reference Include="System.Data.DataSetExtensions" />
|
||||
<Reference Include="Microsoft.CSharp" />
|
||||
<Reference Include="System.Data" />
|
||||
<Reference Include="System.Net.Http" />
|
||||
<Reference Include="System.Xml" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<Compile Include="APIEndpoints.cs" />
|
||||
<Compile Include="AuthenticatorLinker.cs" />
|
||||
<Compile Include="Confirmation.cs" />
|
||||
<Compile Include="Properties\AssemblyInfo.cs" />
|
||||
<Compile Include="SessionData.cs" />
|
||||
<Compile Include="SteamGuardAccount.cs" />
|
||||
<Compile Include="SteamWeb.cs" />
|
||||
<Compile Include="TimeAligner.cs" />
|
||||
<Compile Include="UserLogin.cs" />
|
||||
<Compile Include="Util.cs" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
<None Include="packages.config" />
|
||||
</ItemGroup>
|
||||
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.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">
|
||||
</Target>
|
||||
<Target Name="AfterBuild">
|
||||
</Target>
|
||||
-->
|
||||
</Project>
|
||||
28
SteamAuth/SteamAuth.sln
Normal file
28
SteamAuth/SteamAuth.sln
Normal file
@@ -0,0 +1,28 @@
|
||||
|
||||
Microsoft Visual Studio Solution File, Format Version 12.00
|
||||
# Visual Studio 14
|
||||
VisualStudioVersion = 14.0.23107.0
|
||||
MinimumVisualStudioVersion = 10.0.40219.1
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "SteamAuth", "SteamAuth.csproj", "{5AD0934E-F6C4-4AE5-83AF-C788313B2A87}"
|
||||
EndProject
|
||||
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TestBed", "..\TestBed\TestBed.csproj", "{8A732227-C090-4011-9F0A-51180CFE6271}"
|
||||
EndProject
|
||||
Global
|
||||
GlobalSection(SolutionConfigurationPlatforms) = preSolution
|
||||
Debug|Any CPU = Debug|Any CPU
|
||||
Release|Any CPU = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(ProjectConfigurationPlatforms) = postSolution
|
||||
{5AD0934E-F6C4-4AE5-83AF-C788313B2A87}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{5AD0934E-F6C4-4AE5-83AF-C788313B2A87}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{5AD0934E-F6C4-4AE5-83AF-C788313B2A87}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{5AD0934E-F6C4-4AE5-83AF-C788313B2A87}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
{8A732227-C090-4011-9F0A-51180CFE6271}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
|
||||
{8A732227-C090-4011-9F0A-51180CFE6271}.Debug|Any CPU.Build.0 = Debug|Any CPU
|
||||
{8A732227-C090-4011-9F0A-51180CFE6271}.Release|Any CPU.ActiveCfg = Release|Any CPU
|
||||
{8A732227-C090-4011-9F0A-51180CFE6271}.Release|Any CPU.Build.0 = Release|Any CPU
|
||||
EndGlobalSection
|
||||
GlobalSection(SolutionProperties) = preSolution
|
||||
HideSolutionNode = FALSE
|
||||
EndGlobalSection
|
||||
EndGlobal
|
||||
333
SteamAuth/SteamGuardAccount.cs
Normal file
333
SteamAuth/SteamGuardAccount.cs
Normal file
@@ -0,0 +1,333 @@
|
||||
using Newtonsoft.Json;
|
||||
using System;
|
||||
using System.Collections.Generic;
|
||||
using System.Collections.Specialized;
|
||||
using System.Net;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
namespace SteamAuth
|
||||
{
|
||||
public class SteamGuardAccount
|
||||
{
|
||||
[JsonProperty("shared_secret")]
|
||||
public string SharedSecret { get; set; }
|
||||
|
||||
[JsonProperty("serial_number")]
|
||||
public string SerialNumber { get; set; }
|
||||
|
||||
[JsonProperty("revocation_code")]
|
||||
public string RevocationCode { get; set; }
|
||||
|
||||
[JsonProperty("uri")]
|
||||
public string URI { get; set; }
|
||||
|
||||
[JsonProperty("server_time")]
|
||||
public long ServerTime { get; set; }
|
||||
|
||||
[JsonProperty("account_name")]
|
||||
public string AccountName { get; set; }
|
||||
|
||||
[JsonProperty("token_gid")]
|
||||
public string TokenGID { get; set; }
|
||||
|
||||
[JsonProperty("identity_secret")]
|
||||
public string IdentitySecret { get; set; }
|
||||
|
||||
[JsonProperty("secret_1")]
|
||||
public string Secret1 { get; set; }
|
||||
|
||||
[JsonProperty("status")]
|
||||
public int Status { get; set; }
|
||||
|
||||
[JsonProperty("device_id")]
|
||||
public string DeviceID { get; set; }
|
||||
|
||||
/// <summary>
|
||||
/// Set to true if the authenticator has actually been applied to the account.
|
||||
/// </summary>
|
||||
[JsonProperty("fully_enrolled")]
|
||||
public bool FullyEnrolled { get; set; }
|
||||
|
||||
public SessionData Session { get; set; }
|
||||
|
||||
private static byte[] steamGuardCodeTranslations = new byte[] { 50, 51, 52, 53, 54, 55, 56, 57, 66, 67, 68, 70, 71, 72, 74, 75, 77, 78, 80, 81, 82, 84, 86, 87, 88, 89 };
|
||||
|
||||
public bool DeactivateAuthenticator()
|
||||
{
|
||||
var postData = new NameValueCollection();
|
||||
postData.Add("steamid", this.Session.SteamID.ToString());
|
||||
postData.Add("steamguard_scheme", "2");
|
||||
postData.Add("revocation_code", this.RevocationCode);
|
||||
postData.Add("access_token", this.Session.OAuthToken);
|
||||
|
||||
try
|
||||
{
|
||||
string response = SteamWeb.MobileLoginRequest(APIEndpoints.STEAMAPI_BASE + "/ITwoFactorService/RemoveAuthenticator/v0001", "POST", postData);
|
||||
var removeResponse = JsonConvert.DeserializeObject<RemoveAuthenticatorResponse>(response);
|
||||
|
||||
if (removeResponse == null || removeResponse.Response == null || !removeResponse.Response.Success) return false;
|
||||
return true;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
public string GenerateSteamGuardCode()
|
||||
{
|
||||
return GenerateSteamGuardCodeForTime(TimeAligner.GetSteamTime());
|
||||
}
|
||||
|
||||
public string GenerateSteamGuardCodeForTime(long time)
|
||||
{
|
||||
if (this.SharedSecret == null || this.SharedSecret.Length == 0)
|
||||
{
|
||||
return "";
|
||||
}
|
||||
|
||||
byte[] sharedSecretArray = Convert.FromBase64String(this.SharedSecret);
|
||||
byte[] timeArray = new byte[8];
|
||||
|
||||
time /= 30L;
|
||||
|
||||
for (int i = 8; i > 0; i--)
|
||||
{
|
||||
timeArray[i - 1] = (byte)time;
|
||||
time >>= 8;
|
||||
}
|
||||
|
||||
HMACSHA1 hmacGenerator = new HMACSHA1();
|
||||
hmacGenerator.Key = sharedSecretArray;
|
||||
byte[] hashedData = hmacGenerator.ComputeHash(timeArray);
|
||||
byte[] codeArray = new byte[5];
|
||||
try
|
||||
{
|
||||
byte b = (byte)(hashedData[19] & 0xF);
|
||||
int codePoint = (hashedData[b] & 0x7F) << 24 | (hashedData[b + 1] & 0xFF) << 16 | (hashedData[b + 2] & 0xFF) << 8 | (hashedData[b + 3] & 0xFF);
|
||||
|
||||
for (int i = 0; i < 5; ++i)
|
||||
{
|
||||
codeArray[i] = steamGuardCodeTranslations[codePoint % steamGuardCodeTranslations.Length];
|
||||
codePoint /= steamGuardCodeTranslations.Length;
|
||||
}
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
return null; //Change later, catch-alls are bad!
|
||||
}
|
||||
return Encoding.UTF8.GetString(codeArray);
|
||||
}
|
||||
|
||||
public Confirmation[] FetchConfirmations()
|
||||
{
|
||||
string url = this.GenerateConfirmationURL();
|
||||
|
||||
CookieContainer cookies = new CookieContainer();
|
||||
this.Session.AddCookies(cookies);
|
||||
|
||||
string response = SteamWeb.Request(url, "GET", null, cookies);
|
||||
|
||||
/*So you're going to see this abomination and you're going to be upset.
|
||||
It's understandable. But the thing is, regex for HTML -- while awful -- makes this way faster than parsing a DOM, plus we don't need another library.
|
||||
And because the data is always in the same place and same format... It's not as if we're trying to naturally understand HTML here. Just extract strings.
|
||||
I'm sorry. */
|
||||
|
||||
Regex confIDRegex = new Regex("data-confid=\"(\\d+)\"");
|
||||
Regex confKeyRegex = new Regex("data-key=\"(\\d+)\"");
|
||||
Regex confDescRegex = new Regex("<div>((Confirm|Trade with|Sell -) .+)</div>");
|
||||
|
||||
if (response == null || !(confIDRegex.IsMatch(response) && confKeyRegex.IsMatch(response) && confDescRegex.IsMatch(response)))
|
||||
{
|
||||
if (response == null || !response.Contains("<div>Nothing to confirm</div>"))
|
||||
{
|
||||
throw new WGTokenInvalidException();
|
||||
}
|
||||
|
||||
return new Confirmation[0];
|
||||
}
|
||||
|
||||
MatchCollection confIDs = confIDRegex.Matches(response);
|
||||
MatchCollection confKeys = confKeyRegex.Matches(response);
|
||||
MatchCollection confDescs = confDescRegex.Matches(response);
|
||||
|
||||
List<Confirmation> ret = new List<Confirmation>();
|
||||
for (int i = 0; i < confIDs.Count; i++)
|
||||
{
|
||||
string confID = confIDs[i].Groups[1].Value;
|
||||
string confKey = confKeys[i].Groups[1].Value;
|
||||
string confDesc = confDescs[i].Groups[1].Value;
|
||||
Confirmation conf = new Confirmation()
|
||||
{
|
||||
ConfirmationDescription = confDesc,
|
||||
ConfirmationID = confID,
|
||||
ConfirmationKey = confKey
|
||||
};
|
||||
ret.Add(conf);
|
||||
}
|
||||
|
||||
return ret.ToArray();
|
||||
}
|
||||
|
||||
public bool AcceptConfirmation(Confirmation conf)
|
||||
{
|
||||
return _sendConfirmationAjax(conf, "allow");
|
||||
}
|
||||
|
||||
public bool DenyConfirmation(Confirmation conf)
|
||||
{
|
||||
return _sendConfirmationAjax(conf, "cancel");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Refreshes the Steam session. Necessary to perform confirmations if your session has expired or changed.
|
||||
/// </summary>
|
||||
/// <returns></returns>
|
||||
public bool RefreshSession()
|
||||
{
|
||||
string url = APIEndpoints.MOBILEAUTH_GETWGTOKEN;
|
||||
NameValueCollection postData = new NameValueCollection();
|
||||
postData.Add("access_token", this.Session.OAuthToken);
|
||||
|
||||
string response = SteamWeb.Request(url, "POST", postData);
|
||||
if (response == null) return false;
|
||||
|
||||
try
|
||||
{
|
||||
var refreshResponse = JsonConvert.DeserializeObject<RefreshSessionDataResponse>(response);
|
||||
if (refreshResponse == null || refreshResponse.Response == null || String.IsNullOrEmpty(refreshResponse.Response.Token))
|
||||
return false;
|
||||
|
||||
string token = this.Session.SteamID + "%7C%7C" + refreshResponse.Response.Token;
|
||||
string tokenSecure = this.Session.SteamID + "%7C%7C" + refreshResponse.Response.TokenSecure;
|
||||
|
||||
this.Session.SteamLogin = token;
|
||||
this.Session.SteamLoginSecure = tokenSecure;
|
||||
return true;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
private bool _sendConfirmationAjax(Confirmation conf, string op)
|
||||
{
|
||||
string url = APIEndpoints.COMMUNITY_BASE + "/mobileconf/ajaxop";
|
||||
string queryString = "?op=" + op + "&";
|
||||
queryString += GenerateConfirmationQueryParams(op);
|
||||
queryString += "&cid=" + conf.ConfirmationID + "&ck=" + conf.ConfirmationKey;
|
||||
url += queryString;
|
||||
|
||||
CookieContainer cookies = new CookieContainer();
|
||||
this.Session.AddCookies(cookies);
|
||||
string referer = GenerateConfirmationURL();
|
||||
|
||||
string response = SteamWeb.Request(url, "GET", null, cookies, null);
|
||||
if (response == null) return false;
|
||||
|
||||
SendConfirmationResponse confResponse = JsonConvert.DeserializeObject<SendConfirmationResponse>(response);
|
||||
return confResponse.Success;
|
||||
}
|
||||
|
||||
public string GenerateConfirmationURL(string tag = "conf")
|
||||
{
|
||||
string endpoint = APIEndpoints.COMMUNITY_BASE + "/mobileconf/conf?";
|
||||
string queryString = GenerateConfirmationQueryParams(tag);
|
||||
return endpoint + queryString;
|
||||
}
|
||||
|
||||
public string GenerateConfirmationQueryParams(string tag)
|
||||
{
|
||||
long time = TimeAligner.GetSteamTime();
|
||||
return "p=" + this.DeviceID + "&a=" + this.Session.SteamID.ToString() + "&k=" + _generateConfirmationHashForTime(time, tag) + "&t=" + time + "&m=android&tag=" + tag;
|
||||
}
|
||||
|
||||
private string _generateConfirmationHashForTime(long time, string tag)
|
||||
{
|
||||
byte[] decode = Convert.FromBase64String(this.IdentitySecret);
|
||||
int n2 = 8;
|
||||
if (tag != null)
|
||||
{
|
||||
if (tag.Length > 32)
|
||||
{
|
||||
n2 = 8 + 32;
|
||||
}
|
||||
else
|
||||
{
|
||||
n2 = 8 + tag.Length;
|
||||
}
|
||||
}
|
||||
byte[] array = new byte[n2];
|
||||
int n3 = 8;
|
||||
while (true)
|
||||
{
|
||||
int n4 = n3 - 1;
|
||||
if (n3 <= 0)
|
||||
{
|
||||
break;
|
||||
}
|
||||
array[n4] = (byte)time;
|
||||
time >>= 8;
|
||||
n3 = n4;
|
||||
}
|
||||
if (tag != null)
|
||||
{
|
||||
Array.Copy(Encoding.UTF8.GetBytes(tag), 0, array, 8, n2 - 8);
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
HMACSHA1 hmacGenerator = new HMACSHA1();
|
||||
hmacGenerator.Key = decode;
|
||||
byte[] hashedData = hmacGenerator.ComputeHash(array);
|
||||
string encodedData = Convert.ToBase64String(hashedData, Base64FormattingOptions.None);
|
||||
string hash = WebUtility.UrlEncode(encodedData);
|
||||
return hash;
|
||||
}
|
||||
catch (Exception e)
|
||||
{
|
||||
return null; //Fix soon: catch-all is BAD!
|
||||
}
|
||||
}
|
||||
|
||||
//TODO: Determine how to detect an invalid session.
|
||||
public class WGTokenInvalidException : Exception
|
||||
{
|
||||
}
|
||||
|
||||
private class RefreshSessionDataResponse
|
||||
{
|
||||
[JsonProperty("response")]
|
||||
public RefreshSessionDataInternalResponse Response { get; set; }
|
||||
internal class RefreshSessionDataInternalResponse
|
||||
{
|
||||
[JsonProperty("token")]
|
||||
public string Token { get; set; }
|
||||
|
||||
[JsonProperty("token_secure")]
|
||||
public string TokenSecure { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
private class RemoveAuthenticatorResponse
|
||||
{
|
||||
[JsonProperty("response")]
|
||||
public RemoveAuthenticatorInternalResponse Response { get; set; }
|
||||
|
||||
internal class RemoveAuthenticatorInternalResponse
|
||||
{
|
||||
[JsonProperty("success")]
|
||||
public bool Success { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
private class SendConfirmationResponse
|
||||
{
|
||||
[JsonProperty("success")]
|
||||
public bool Success { get; set; }
|
||||
}
|
||||
}
|
||||
}
|
||||
81
SteamAuth/SteamWeb.cs
Normal file
81
SteamAuth/SteamWeb.cs
Normal file
@@ -0,0 +1,81 @@
|
||||
using System;
|
||||
using System.Collections.Specialized;
|
||||
using System.IO;
|
||||
using System.Net;
|
||||
|
||||
namespace SteamAuth
|
||||
{
|
||||
public class SteamWeb
|
||||
{
|
||||
/// <summary>
|
||||
/// Perform a mobile login request
|
||||
/// </summary>
|
||||
/// <param name="url">API url</param>
|
||||
/// <param name="method">GET or POST</param>
|
||||
/// <param name="data">Name-data pairs</param>
|
||||
/// <param name="cookies">current cookie container</param>
|
||||
/// <returns>response body</returns>
|
||||
public static string MobileLoginRequest(string url, string method, NameValueCollection data = null, CookieContainer cookies = null, NameValueCollection headers = null)
|
||||
{
|
||||
return Request(url, method, data, cookies, headers, APIEndpoints.COMMUNITY_BASE + "/mobilelogin?oauth_client_id=DE45CD61&oauth_scope=read_profile%20write_profile%20read_client%20write_client");
|
||||
}
|
||||
|
||||
public static string Request(string url, string method, NameValueCollection data = null, CookieContainer cookies = null, NameValueCollection headers = null, string referer = APIEndpoints.COMMUNITY_BASE)
|
||||
{
|
||||
string query = (data == null ? string.Empty : string.Join("&", Array.ConvertAll(data.AllKeys, key => String.Format("{0}={1}", WebUtility.UrlEncode(key), WebUtility.UrlEncode(data[key])))));
|
||||
if (method == "GET")
|
||||
{
|
||||
url += (url.Contains("?") ? "&" : "?") + query;
|
||||
}
|
||||
|
||||
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
|
||||
request.Method = method;
|
||||
request.Accept = "text/javascript, text/html, application/xml, text/xml, */*";
|
||||
request.UserAgent = "Mozilla/5.0 (Linux; U; Android 4.1.1; en-us; Google Nexus 4 - 4.1.1 - API 16 - 768x1280 Build/JRO03S) AppleWebKit/534.30 (KHTML, like Gecko) Version/4.0 Mobile Safari/534.30";
|
||||
request.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;
|
||||
request.Referer = referer;
|
||||
|
||||
if (headers != null)
|
||||
{
|
||||
request.Headers.Add(headers);
|
||||
}
|
||||
|
||||
if (cookies != null)
|
||||
{
|
||||
request.CookieContainer = cookies;
|
||||
}
|
||||
|
||||
if (method == "POST")
|
||||
{
|
||||
request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
|
||||
request.ContentLength = query.Length;
|
||||
|
||||
StreamWriter requestStream = new StreamWriter(request.GetRequestStream());
|
||||
requestStream.Write(query);
|
||||
requestStream.Close();
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
|
||||
{
|
||||
if (response.StatusCode != HttpStatusCode.OK)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
|
||||
using (StreamReader responseStream = new StreamReader(response.GetResponseStream()))
|
||||
{
|
||||
string responseData = responseStream.ReadToEnd();
|
||||
|
||||
return responseData;
|
||||
}
|
||||
}
|
||||
}
|
||||
catch (WebException ex)
|
||||
{
|
||||
return null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
56
SteamAuth/TimeAligner.cs
Normal file
56
SteamAuth/TimeAligner.cs
Normal file
@@ -0,0 +1,56 @@
|
||||
using System.Net;
|
||||
using Newtonsoft.Json;
|
||||
|
||||
namespace SteamAuth
|
||||
{
|
||||
/// <summary>
|
||||
/// Class to help align system time with the Steam server time. Not super advanced; probably not taking some things into account that it should.
|
||||
/// Necessary to generate up-to-date codes. In general, this will have an error of less than a second, assuming Steam is operational.
|
||||
/// </summary>
|
||||
public class TimeAligner
|
||||
{
|
||||
private static bool _aligned = false;
|
||||
private static int _timeDifference = 0;
|
||||
|
||||
public static long GetSteamTime()
|
||||
{
|
||||
if (!TimeAligner._aligned)
|
||||
{
|
||||
TimeAligner.AlignTime();
|
||||
}
|
||||
return Util.GetSystemUnixTime() + _timeDifference;
|
||||
}
|
||||
|
||||
public static void AlignTime()
|
||||
{
|
||||
long currentTime = Util.GetSystemUnixTime();
|
||||
using (WebClient client = new WebClient())
|
||||
{
|
||||
try
|
||||
{
|
||||
string response = client.UploadString(APIEndpoints.TWO_FACTOR_TIME_QUERY, "steamid=0");
|
||||
TimeQuery query = JsonConvert.DeserializeObject<TimeQuery>(response);
|
||||
TimeAligner._timeDifference = (int)(query.Response.ServerTime - currentTime);
|
||||
TimeAligner._aligned = true;
|
||||
}
|
||||
catch (WebException e)
|
||||
{
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal class TimeQuery
|
||||
{
|
||||
[JsonProperty("response")]
|
||||
internal TimeQueryResponse Response { get; set; }
|
||||
|
||||
internal class TimeQueryResponse
|
||||
{
|
||||
[JsonProperty("server_time")]
|
||||
public long ServerTime { get; set; }
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
}
|
||||
240
SteamAuth/UserLogin.cs
Normal file
240
SteamAuth/UserLogin.cs
Normal file
@@ -0,0 +1,240 @@
|
||||
using Newtonsoft.Json;
|
||||
using System;
|
||||
using System.Collections.Specialized;
|
||||
using System.Net;
|
||||
using System.Security.Cryptography;
|
||||
using System.Text;
|
||||
|
||||
namespace SteamAuth
|
||||
{
|
||||
/// <summary>
|
||||
/// Handles logging the user into the mobile Steam website. Necessary to generate OAuth token and session cookies.
|
||||
/// </summary>
|
||||
public class UserLogin
|
||||
{
|
||||
public string Username;
|
||||
public string Password;
|
||||
public ulong SteamID;
|
||||
|
||||
public bool RequiresCaptcha;
|
||||
public string CaptchaGID = null;
|
||||
public string CaptchaText = null;
|
||||
|
||||
public bool RequiresEmail;
|
||||
public string EmailDomain = null;
|
||||
public string EmailCode = null;
|
||||
|
||||
public bool Requires2FA;
|
||||
public string TwoFactorCode = null;
|
||||
|
||||
public SessionData Session = null;
|
||||
public bool LoggedIn = false;
|
||||
|
||||
private CookieContainer _cookies = new CookieContainer();
|
||||
|
||||
public UserLogin(string username, string password)
|
||||
{
|
||||
this.Username = username;
|
||||
this.Password = password;
|
||||
}
|
||||
|
||||
public LoginResult DoLogin()
|
||||
{
|
||||
var postData = new NameValueCollection();
|
||||
var cookies = _cookies;
|
||||
string response = null;
|
||||
|
||||
if (cookies.Count == 0)
|
||||
{
|
||||
//Generate a SessionID
|
||||
cookies.Add(new Cookie("mobileClientVersion", "0 (2.1.3)", "/", ".steamcommunity.com"));
|
||||
cookies.Add(new Cookie("mobileClient", "android", "/", ".steamcommunity.com"));
|
||||
cookies.Add(new Cookie("Steam_Language", "english", "/", ".steamcommunity.com"));
|
||||
|
||||
NameValueCollection headers = new NameValueCollection();
|
||||
headers.Add("X-Requested-With", "com.valvesoftware.android.steam.community");
|
||||
|
||||
SteamWeb.MobileLoginRequest("https://steamcommunity.com/login?oauth_client_id=DE45CD61&oauth_scope=read_profile%20write_profile%20read_client%20write_client", "GET", null, cookies, headers);
|
||||
}
|
||||
|
||||
postData.Add("username", this.Username);
|
||||
response = SteamWeb.MobileLoginRequest(APIEndpoints.COMMUNITY_BASE + "/login/getrsakey", "POST", postData, cookies);
|
||||
if (response == null) return LoginResult.GeneralFailure;
|
||||
|
||||
var rsaResponse = JsonConvert.DeserializeObject<RSAResponse>(response);
|
||||
|
||||
if (!rsaResponse.Success)
|
||||
{
|
||||
return LoginResult.BadRSA;
|
||||
}
|
||||
|
||||
RNGCryptoServiceProvider secureRandom = new RNGCryptoServiceProvider();
|
||||
byte[] encryptedPasswordBytes;
|
||||
using (var rsaEncryptor = new RSACryptoServiceProvider())
|
||||
{
|
||||
var passwordBytes = Encoding.ASCII.GetBytes(this.Password);
|
||||
var rsaParameters = rsaEncryptor.ExportParameters(false);
|
||||
rsaParameters.Exponent = Util.HexStringToByteArray(rsaResponse.Exponent);
|
||||
rsaParameters.Modulus = Util.HexStringToByteArray(rsaResponse.Modulus);
|
||||
rsaEncryptor.ImportParameters(rsaParameters);
|
||||
encryptedPasswordBytes = rsaEncryptor.Encrypt(passwordBytes, false);
|
||||
}
|
||||
|
||||
string encryptedPassword = Convert.ToBase64String(encryptedPasswordBytes);
|
||||
|
||||
postData.Clear();
|
||||
postData.Add("username", this.Username);
|
||||
postData.Add("password", encryptedPassword);
|
||||
|
||||
postData.Add("twofactorcode", this.TwoFactorCode ?? "");
|
||||
|
||||
postData.Add("captchagid", this.RequiresCaptcha ? this.CaptchaGID : "-1");
|
||||
postData.Add("captcha_text", this.RequiresCaptcha ? this.CaptchaText : "");
|
||||
|
||||
postData.Add("emailsteamid", (this.Requires2FA || this.RequiresEmail) ? this.SteamID.ToString() : "");
|
||||
postData.Add("emailauth", this.RequiresEmail ? this.EmailCode : "");
|
||||
|
||||
postData.Add("rsatimestamp", rsaResponse.Timestamp);
|
||||
postData.Add("remember_login", "false");
|
||||
postData.Add("oauth_client_id", "DE45CD61");
|
||||
postData.Add("oauth_scope", "read_profile write_profile read_client write_client");
|
||||
postData.Add("loginfriendlyname", "#login_emailauth_friendlyname_mobile");
|
||||
postData.Add("donotcache", Util.GetSystemUnixTime().ToString());
|
||||
|
||||
response = SteamWeb.MobileLoginRequest(APIEndpoints.COMMUNITY_BASE + "/login/dologin", "POST", postData, cookies);
|
||||
if (response == null) return LoginResult.GeneralFailure;
|
||||
|
||||
var loginResponse = JsonConvert.DeserializeObject<LoginResponse>(response);
|
||||
|
||||
if (loginResponse.CaptchaNeeded)
|
||||
{
|
||||
this.RequiresCaptcha = true;
|
||||
this.CaptchaGID = loginResponse.CaptchaGID;
|
||||
return LoginResult.NeedCaptcha;
|
||||
}
|
||||
|
||||
if (loginResponse.EmailAuthNeeded)
|
||||
{
|
||||
this.RequiresEmail = true;
|
||||
this.SteamID = loginResponse.EmailSteamID;
|
||||
return LoginResult.NeedEmail;
|
||||
}
|
||||
|
||||
if (loginResponse.TwoFactorNeeded && !loginResponse.Success)
|
||||
{
|
||||
this.Requires2FA = true;
|
||||
return LoginResult.Need2FA;
|
||||
}
|
||||
|
||||
if (loginResponse.OAuthData == null || loginResponse.OAuthData.OAuthToken == null || loginResponse.OAuthData.OAuthToken.Length == 0)
|
||||
{
|
||||
return LoginResult.GeneralFailure;
|
||||
}
|
||||
|
||||
if (!loginResponse.LoginComplete)
|
||||
{
|
||||
return LoginResult.BadCredentials;
|
||||
}
|
||||
else
|
||||
{
|
||||
var readableCookies = cookies.GetCookies(new Uri("https://steamcommunity.com"));
|
||||
var oAuthData = loginResponse.OAuthData;
|
||||
|
||||
SessionData session = new SessionData();
|
||||
session.OAuthToken = oAuthData.OAuthToken;
|
||||
session.SteamID = oAuthData.SteamID;
|
||||
session.SteamLogin = session.SteamID + "%7C%7C" + oAuthData.SteamLogin;
|
||||
session.SteamLoginSecure = session.SteamID + "%7C%7C" + oAuthData.SteamLoginSecure;
|
||||
session.WebCookie = oAuthData.Webcookie;
|
||||
session.SessionID = readableCookies["sessionid"].Value;
|
||||
this.Session = session;
|
||||
this.LoggedIn = true;
|
||||
return LoginResult.LoginOkay;
|
||||
}
|
||||
|
||||
return LoginResult.GeneralFailure;
|
||||
}
|
||||
|
||||
private class LoginResponse
|
||||
{
|
||||
[JsonProperty("success")]
|
||||
public bool Success { get; set; }
|
||||
|
||||
[JsonProperty("login_complete")]
|
||||
public bool LoginComplete { get; set; }
|
||||
|
||||
[JsonProperty("oauth")]
|
||||
public string OAuthDataString { get; set; }
|
||||
|
||||
public OAuth OAuthData
|
||||
{
|
||||
get
|
||||
{
|
||||
return OAuthDataString != null ? JsonConvert.DeserializeObject<OAuth>(OAuthDataString) : null;
|
||||
}
|
||||
}
|
||||
|
||||
[JsonProperty("captcha_needed")]
|
||||
public bool CaptchaNeeded { get; set; }
|
||||
|
||||
[JsonProperty("captcha_gid")]
|
||||
public string CaptchaGID { get; set; }
|
||||
|
||||
[JsonProperty("emailsteamid")]
|
||||
public ulong EmailSteamID { get; set; }
|
||||
|
||||
[JsonProperty("emailauth_needed")]
|
||||
public bool EmailAuthNeeded { get; set; }
|
||||
|
||||
[JsonProperty("requires_twofactor")]
|
||||
public bool TwoFactorNeeded { get; set; }
|
||||
|
||||
internal class OAuth
|
||||
{
|
||||
[JsonProperty("steamid")]
|
||||
public ulong SteamID { get; set; }
|
||||
|
||||
[JsonProperty("oauth_token")]
|
||||
public string OAuthToken { get; set; }
|
||||
|
||||
[JsonProperty("wgtoken")]
|
||||
public string SteamLogin { get; set; }
|
||||
|
||||
[JsonProperty("wgtoken_secure")]
|
||||
public string SteamLoginSecure { get; set; }
|
||||
|
||||
[JsonProperty("webcookie")]
|
||||
public string Webcookie { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
private class RSAResponse
|
||||
{
|
||||
[JsonProperty("success")]
|
||||
public bool Success { get; set; }
|
||||
|
||||
[JsonProperty("publickey_exp")]
|
||||
public string Exponent { get; set; }
|
||||
|
||||
[JsonProperty("publickey_mod")]
|
||||
public string Modulus { get; set; }
|
||||
|
||||
[JsonProperty("timestamp")]
|
||||
public string Timestamp { get; set; }
|
||||
|
||||
[JsonProperty("steamid")]
|
||||
public ulong SteamID { get; set; }
|
||||
}
|
||||
}
|
||||
|
||||
public enum LoginResult
|
||||
{
|
||||
LoginOkay,
|
||||
GeneralFailure,
|
||||
BadRSA,
|
||||
BadCredentials,
|
||||
NeedCaptcha,
|
||||
Need2FA,
|
||||
NeedEmail,
|
||||
}
|
||||
}
|
||||
24
SteamAuth/Util.cs
Normal file
24
SteamAuth/Util.cs
Normal file
@@ -0,0 +1,24 @@
|
||||
using System;
|
||||
using System.Net;
|
||||
|
||||
namespace SteamAuth
|
||||
{
|
||||
public class Util
|
||||
{
|
||||
public static long GetSystemUnixTime()
|
||||
{
|
||||
return (long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalSeconds;
|
||||
}
|
||||
|
||||
public static byte[] HexStringToByteArray(string hex)
|
||||
{
|
||||
int hexLen = hex.Length;
|
||||
byte[] ret = new byte[hexLen / 2];
|
||||
for (int i = 0; i < hexLen; i += 2)
|
||||
{
|
||||
ret[i / 2] = Convert.ToByte(hex.Substring(i, 2), 16);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
}
|
||||
4
SteamAuth/packages.config
Normal file
4
SteamAuth/packages.config
Normal file
@@ -0,0 +1,4 @@
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<packages>
|
||||
<package id="Newtonsoft.Json" version="8.0.1-beta3" targetFramework="net452" />
|
||||
</packages>
|
||||
Binary file not shown.
Binary file not shown.
9653
packages/Newtonsoft.Json.8.0.1-beta3/lib/net20/Newtonsoft.Json.xml
Normal file
9653
packages/Newtonsoft.Json.8.0.1-beta3/lib/net20/Newtonsoft.Json.xml
Normal file
File diff suppressed because it is too large
Load Diff
Binary file not shown.
8796
packages/Newtonsoft.Json.8.0.1-beta3/lib/net35/Newtonsoft.Json.xml
Normal file
8796
packages/Newtonsoft.Json.8.0.1-beta3/lib/net35/Newtonsoft.Json.xml
Normal file
File diff suppressed because it is too large
Load Diff
Binary file not shown.
9103
packages/Newtonsoft.Json.8.0.1-beta3/lib/net40/Newtonsoft.Json.xml
Normal file
9103
packages/Newtonsoft.Json.8.0.1-beta3/lib/net40/Newtonsoft.Json.xml
Normal file
File diff suppressed because it is too large
Load Diff
Binary file not shown.
9103
packages/Newtonsoft.Json.8.0.1-beta3/lib/net45/Newtonsoft.Json.xml
Normal file
9103
packages/Newtonsoft.Json.8.0.1-beta3/lib/net45/Newtonsoft.Json.xml
Normal file
File diff suppressed because it is too large
Load Diff
Binary file not shown.
File diff suppressed because it is too large
Load Diff
Binary file not shown.
File diff suppressed because it is too large
Load Diff
116
packages/Newtonsoft.Json.8.0.1-beta3/tools/install.ps1
Normal file
116
packages/Newtonsoft.Json.8.0.1-beta3/tools/install.ps1
Normal file
@@ -0,0 +1,116 @@
|
||||
param($installPath, $toolsPath, $package, $project)
|
||||
|
||||
# open json.net splash page on package install
|
||||
# don't open if json.net is installed as a dependency
|
||||
|
||||
try
|
||||
{
|
||||
$url = "http://www.newtonsoft.com/json/install?version=" + $package.Version
|
||||
$dte2 = Get-Interface $dte ([EnvDTE80.DTE2])
|
||||
|
||||
if ($dte2.ActiveWindow.Caption -eq "Package Manager Console")
|
||||
{
|
||||
# user is installing from VS NuGet console
|
||||
# get reference to the window, the console host and the input history
|
||||
# show webpage if "install-package newtonsoft.json" was last input
|
||||
|
||||
$consoleWindow = $(Get-VSComponentModel).GetService([NuGetConsole.IPowerConsoleWindow])
|
||||
|
||||
$props = $consoleWindow.GetType().GetProperties([System.Reflection.BindingFlags]::Instance -bor `
|
||||
[System.Reflection.BindingFlags]::NonPublic)
|
||||
|
||||
$prop = $props | ? { $_.Name -eq "ActiveHostInfo" } | select -first 1
|
||||
if ($prop -eq $null) { return }
|
||||
|
||||
$hostInfo = $prop.GetValue($consoleWindow)
|
||||
if ($hostInfo -eq $null) { return }
|
||||
|
||||
$history = $hostInfo.WpfConsole.InputHistory.History
|
||||
|
||||
$lastCommand = $history | select -last 1
|
||||
|
||||
if ($lastCommand)
|
||||
{
|
||||
$lastCommand = $lastCommand.Trim().ToLower()
|
||||
if ($lastCommand.StartsWith("install-package") -and $lastCommand.Contains("newtonsoft.json"))
|
||||
{
|
||||
$dte2.ItemOperations.Navigate($url) | Out-Null
|
||||
}
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
# user is installing from VS NuGet dialog
|
||||
# get reference to the window, then smart output console provider
|
||||
# show webpage if messages in buffered console contains "installing...newtonsoft.json" in last operation
|
||||
|
||||
$instanceField = [NuGet.Dialog.PackageManagerWindow].GetField("CurrentInstance", [System.Reflection.BindingFlags]::Static -bor `
|
||||
[System.Reflection.BindingFlags]::NonPublic)
|
||||
|
||||
$consoleField = [NuGet.Dialog.PackageManagerWindow].GetField("_smartOutputConsoleProvider", [System.Reflection.BindingFlags]::Instance -bor `
|
||||
[System.Reflection.BindingFlags]::NonPublic)
|
||||
|
||||
if ($instanceField -eq $null -or $consoleField -eq $null) { return }
|
||||
|
||||
$instance = $instanceField.GetValue($null)
|
||||
|
||||
if ($instance -eq $null) { return }
|
||||
|
||||
$consoleProvider = $consoleField.GetValue($instance)
|
||||
if ($consoleProvider -eq $null) { return }
|
||||
|
||||
$console = $consoleProvider.CreateOutputConsole($false)
|
||||
|
||||
$messagesField = $console.GetType().GetField("_messages", [System.Reflection.BindingFlags]::Instance -bor `
|
||||
[System.Reflection.BindingFlags]::NonPublic)
|
||||
if ($messagesField -eq $null) { return }
|
||||
|
||||
$messages = $messagesField.GetValue($console)
|
||||
if ($messages -eq $null) { return }
|
||||
|
||||
$operations = $messages -split "=============================="
|
||||
|
||||
$lastOperation = $operations | select -last 1
|
||||
|
||||
if ($lastOperation)
|
||||
{
|
||||
$lastOperation = $lastOperation.ToLower()
|
||||
|
||||
$lines = $lastOperation -split "`r`n"
|
||||
|
||||
$installMatch = $lines | ? { $_.StartsWith("------- installing...newtonsoft.json ") } | select -first 1
|
||||
|
||||
if ($installMatch)
|
||||
{
|
||||
$dte2.ItemOperations.Navigate($url) | Out-Null
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
try
|
||||
{
|
||||
$pmPane = $dte2.ToolWindows.OutputWindow.OutputWindowPanes.Item("Package Manager")
|
||||
|
||||
$selection = $pmPane.TextDocument.Selection
|
||||
$selection.StartOfDocument($false)
|
||||
$selection.EndOfDocument($true)
|
||||
|
||||
if ($selection.Text.StartsWith("Attempting to gather dependencies information for package 'Newtonsoft.Json." + $package.Version + "'"))
|
||||
{
|
||||
# don't show on upgrade
|
||||
if (!$selection.Text.Contains("Removed package"))
|
||||
{
|
||||
$dte2.ItemOperations.Navigate($url) | Out-Null
|
||||
}
|
||||
}
|
||||
}
|
||||
catch
|
||||
{
|
||||
# stop potential errors from bubbling up
|
||||
# worst case the splash page won't open
|
||||
}
|
||||
}
|
||||
|
||||
# still yolo
|
||||
BIN
tools/ILMerge.exe
Normal file
BIN
tools/ILMerge.exe
Normal file
Binary file not shown.
Reference in New Issue
Block a user