initial checkin · 5ec99d42c0 - SVN.BY: Go Git Service
Tiernan OToole 8 anni fa
parent
commit
5ec99d42c0

+ 22 - 0
B2Uploader.sln

@@ -0,0 +1,22 @@
1
+
2
+Microsoft Visual Studio Solution File, Format Version 12.00
3
+# Visual Studio 14
4
+VisualStudioVersion = 14.0.23107.0
5
+MinimumVisualStudioVersion = 10.0.40219.1
6
+Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "B2Uploader", "B2Uploader\B2Uploader.csproj", "{A5D41169-C2EE-4B5E-A2D8-B63E485597A6}"
7
+EndProject
8
+Global
9
+	GlobalSection(SolutionConfigurationPlatforms) = preSolution
10
+		Debug|Any CPU = Debug|Any CPU
11
+		Release|Any CPU = Release|Any CPU
12
+	EndGlobalSection
13
+	GlobalSection(ProjectConfigurationPlatforms) = postSolution
14
+		{A5D41169-C2EE-4B5E-A2D8-B63E485597A6}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
15
+		{A5D41169-C2EE-4B5E-A2D8-B63E485597A6}.Debug|Any CPU.Build.0 = Debug|Any CPU
16
+		{A5D41169-C2EE-4B5E-A2D8-B63E485597A6}.Release|Any CPU.ActiveCfg = Release|Any CPU
17
+		{A5D41169-C2EE-4B5E-A2D8-B63E485597A6}.Release|Any CPU.Build.0 = Release|Any CPU
18
+	EndGlobalSection
19
+	GlobalSection(SolutionProperties) = preSolution
20
+		HideSolutionNode = FALSE
21
+	EndGlobalSection
22
+EndGlobal

+ 6 - 0
B2Uploader/App.config

@@ -0,0 +1,6 @@
1
+<?xml version="1.0" encoding="utf-8" ?>
2
+<configuration>
3
+    <startup> 
4
+        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
5
+    </startup>
6
+</configuration>

+ 65 - 0
B2Uploader/B2Uploader.csproj

@@ -0,0 +1,65 @@
1
+<?xml version="1.0" encoding="utf-8"?>
2
+<Project ToolsVersion="14.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
3
+  <Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
4
+  <PropertyGroup>
5
+    <Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
6
+    <Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
7
+    <ProjectGuid>{A5D41169-C2EE-4B5E-A2D8-B63E485597A6}</ProjectGuid>
8
+    <OutputType>Exe</OutputType>
9
+    <AppDesignerFolder>Properties</AppDesignerFolder>
10
+    <RootNamespace>B2Uploader</RootNamespace>
11
+    <AssemblyName>B2Uploader</AssemblyName>
12
+    <TargetFrameworkVersion>v4.5.2</TargetFrameworkVersion>
13
+    <FileAlignment>512</FileAlignment>
14
+    <AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
15
+  </PropertyGroup>
16
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
17
+    <PlatformTarget>AnyCPU</PlatformTarget>
18
+    <DebugSymbols>true</DebugSymbols>
19
+    <DebugType>full</DebugType>
20
+    <Optimize>false</Optimize>
21
+    <OutputPath>bin\Debug\</OutputPath>
22
+    <DefineConstants>DEBUG;TRACE</DefineConstants>
23
+    <ErrorReport>prompt</ErrorReport>
24
+    <WarningLevel>4</WarningLevel>
25
+  </PropertyGroup>
26
+  <PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
27
+    <PlatformTarget>AnyCPU</PlatformTarget>
28
+    <DebugType>pdbonly</DebugType>
29
+    <Optimize>true</Optimize>
30
+    <OutputPath>bin\Release\</OutputPath>
31
+    <DefineConstants>TRACE</DefineConstants>
32
+    <ErrorReport>prompt</ErrorReport>
33
+    <WarningLevel>4</WarningLevel>
34
+  </PropertyGroup>
35
+  <ItemGroup>
36
+    <Reference Include="Newtonsoft.Json, Version=7.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
37
+      <HintPath>..\packages\Newtonsoft.Json.7.0.1\lib\net45\Newtonsoft.Json.dll</HintPath>
38
+      <Private>True</Private>
39
+    </Reference>
40
+    <Reference Include="System" />
41
+    <Reference Include="System.Core" />
42
+    <Reference Include="System.Xml.Linq" />
43
+    <Reference Include="System.Data.DataSetExtensions" />
44
+    <Reference Include="Microsoft.CSharp" />
45
+    <Reference Include="System.Data" />
46
+    <Reference Include="System.Net.Http" />
47
+    <Reference Include="System.Xml" />
48
+  </ItemGroup>
49
+  <ItemGroup>
50
+    <Compile Include="Program.cs" />
51
+    <Compile Include="Properties\AssemblyInfo.cs" />
52
+  </ItemGroup>
53
+  <ItemGroup>
54
+    <None Include="App.config" />
55
+    <None Include="packages.config" />
56
+  </ItemGroup>
57
+  <Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
58
+  <!-- To modify your build process, add your task inside one of the targets below and uncomment it. 
59
+       Other similar extension points exist, see Microsoft.Common.targets.
60
+  <Target Name="BeforeBuild">
61
+  </Target>
62
+  <Target Name="AfterBuild">
63
+  </Target>
64
+  -->
65
+</Project>

+ 203 - 0
B2Uploader/Program.cs

@@ -0,0 +1,203 @@
1
+using Newtonsoft.Json;
2
+using System;
3
+using System.Collections.Generic;
4
+using System.IO;
5
+using System.Linq;
6
+using System.Net;
7
+using System.Security.Cryptography;
8
+using System.Text;
9
+using System.Threading.Tasks;
10
+
11
+namespace B2Uploader
12
+{
13
+    class Program
14
+    {
15
+        static void Main(string[] args)
16
+        {
17
+            if(args.Count() != 3)
18
+            {
19
+                Console.WriteLine("Need accountID, AppKey and Folder to upload");
20
+                return;
21
+            }
22
+
23
+            if (!Directory.Exists(args[2]))
24
+            {
25
+                Console.WriteLine("Directory to upload MUST EXIST!");
26
+                return;
27
+            }
28
+
29
+            var auth = AuthorizeUser(args[0], args[1]);
30
+            var buckets = ListBuckets(new ListBucketsRequest() { accountId = auth.accountId }, auth.authorizationToken, auth.apiUrl);
31
+
32
+            var bucket = buckets.buckets.First();
33
+
34
+            foreach(string s in Directory.GetFiles(args[2]))
35
+            {
36
+                var uploadURL = GetUploadURL(new GetUploadURLRequest { bucketId = bucket.bucketId }, auth.authorizationToken, auth.apiUrl);
37
+                var response = UploadFile(uploadURL.authorizationToken, "b2/x-auto", s, uploadURL.uploadUrl);
38
+            }
39
+
40
+
41
+
42
+        }
43
+
44
+        static AuthorizeResponse AuthorizeUser(string accountId, string applicationKey)
45
+        {            
46
+            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://api.backblaze.com/b2api/v1/b2_authorize_account");
47
+            string credentials = Convert.ToBase64String(Encoding.UTF8.GetBytes(accountId + ":" + applicationKey));
48
+            webRequest.Headers.Add("Authorization", "Basic " + credentials);
49
+            webRequest.ContentType = "application/json; charset=utf-8";
50
+            WebResponse response = (HttpWebResponse)webRequest.GetResponse();
51
+            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
52
+            response.Close();
53
+            return JsonConvert.DeserializeObject<AuthorizeResponse>(responseString);
54
+        }
55
+
56
+        static ListBucketsResponse ListBuckets(ListBucketsRequest request, string authToken, string apiURL)
57
+        {            
58
+            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(apiURL + "/b2api/v1/b2_list_buckets");
59
+            string body = JsonConvert.SerializeObject(request);
60
+            var data = Encoding.UTF8.GetBytes(body);
61
+            webRequest.Method = "POST";
62
+            webRequest.Headers.Add("Authorization", authToken);
63
+            webRequest.ContentType = "application/json; charset=utf-8";
64
+            webRequest.ContentLength = data.Length;
65
+            using (var stream = webRequest.GetRequestStream())
66
+            {
67
+                stream.Write(data, 0, data.Length);
68
+                stream.Close();
69
+            }
70
+            WebResponse response = (HttpWebResponse)webRequest.GetResponse();
71
+            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
72
+            response.Close();
73
+
74
+            return JsonConvert.DeserializeObject<ListBucketsResponse>(responseString);
75
+        }
76
+
77
+        static GetUploadURLResponse GetUploadURL(GetUploadURLRequest request, string apiUrl, string authToken)
78
+        {          
79
+            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(apiUrl + "/b2api/v1/b2_get_upload_url");
80
+            string body = JsonConvert.SerializeObject(request);
81
+            var data = Encoding.UTF8.GetBytes(body);
82
+            webRequest.Method = "POST";
83
+            webRequest.Headers.Add("Authorization", authToken);
84
+            webRequest.ContentType = "application/json; charset=utf-8";
85
+            webRequest.ContentLength = data.Length;
86
+            using (var stream = webRequest.GetRequestStream())
87
+            {
88
+                stream.Write(data, 0, data.Length);
89
+                stream.Close();
90
+            }
91
+            WebResponse response = (HttpWebResponse)webRequest.GetResponse();
92
+            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
93
+            response.Close();
94
+            return JsonConvert.DeserializeObject<GetUploadURLResponse>(responseString);
95
+        }
96
+
97
+        static UploadFileResponse UploadFile(string authToken, string contentType, string filePath, string uploadUrl)
98
+        {
99
+            SHA1 sha = SHA1.Create();
100
+
101
+            byte[] bytes = File.ReadAllBytes(filePath);
102
+
103
+            String sha1 = ASCIIEncoding.ASCII.GetString(sha.ComputeHash(bytes));
104
+            
105
+            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(uploadUrl);
106
+            webRequest.Method = "POST";
107
+            webRequest.Headers.Add("Authorization", authToken);
108
+            webRequest.Headers.Add("X-Bz-File-Name", filePath.Replace('\\','_'));
109
+            webRequest.Headers.Add("X-Bz-Content-Sha1", sha1);
110
+            webRequest.ContentType = contentType;
111
+            using (var stream = webRequest.GetRequestStream())
112
+            {
113
+                stream.Write(bytes, 0, bytes.Length);
114
+                stream.Close();
115
+            }
116
+            WebResponse response = (HttpWebResponse)webRequest.GetResponse();
117
+            var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
118
+            response.Close();
119
+            var resp = JsonConvert.DeserializeObject<UploadFileResponse>(responseString);
120
+
121
+            if(resp.contentSha1 == sha1)
122
+            {
123
+                Console.WriteLine(responseString);
124
+                return resp;
125
+            }
126
+            else
127
+            {
128
+                //something went wrong!
129
+                return null;
130
+            }
131
+        }
132
+    }
133
+
134
+    public class AuthorizeResponse
135
+    {        
136
+        public string accountId { get; set; }
137
+        public string apiUrl { get; set; }
138
+        public string authorizationToken { get; set; }
139
+        public string downloadUrl { get; set; }   
140
+    }
141
+
142
+    public class CreateBucketResponse
143
+    {
144
+        public string bucketId { get; set; }
145
+        public string accountId { get; set; }
146
+        public string bucketName { get; set; }
147
+        public string bucketType { get; set; }
148
+    }
149
+
150
+    public class CreateBucketRequest
151
+    {
152
+        public string accountId { get; set; }
153
+        public string bucketName { get; set; }
154
+        public string bucketType { get; set; }
155
+    }
156
+
157
+    public class GetUploadURLRequest
158
+    {
159
+        public string bucketId { get; set; }
160
+    }
161
+
162
+    public class GetUploadURLResponse
163
+    {
164
+        public string bucketId { get; set; }
165
+        public string uploadUrl { get; set; }
166
+        public string authorizationToken { get; set; }
167
+    }
168
+
169
+    public class ListBucketsRequest
170
+    {
171
+        public string accountId { get; set; }
172
+    }
173
+
174
+    public class ListBucketsResponse
175
+    {
176
+        public List<Bucket> buckets { get; set; }
177
+    }
178
+
179
+    public class Bucket
180
+    {
181
+        public string bucketId { get; set; }
182
+        public string accountId { get; set; }
183
+        public string bucketName { get; set; }
184
+        public string bucketType { get; set; }
185
+    }
186
+
187
+    public class FileInfo
188
+    {
189
+        public string author { get; set; }
190
+    }
191
+
192
+    public class UploadFileResponse
193
+    {
194
+        public string fileId { get; set; }
195
+        public string fileName { get; set; }
196
+        public string accountId { get; set; }
197
+        public string bucketId { get; set; }
198
+        public int contentLength { get; set; }
199
+        public string contentSha1 { get; set; }
200
+        public string contentType { get; set; }
201
+        public FileInfo fileInfo { get; set; }
202
+    }
203
+}

+ 36 - 0
B2Uploader/Properties/AssemblyInfo.cs

@@ -0,0 +1,36 @@
1
+using System.Reflection;
2
+using System.Runtime.CompilerServices;
3
+using System.Runtime.InteropServices;
4
+
5
+// General Information about an assembly is controlled through the following 
6
+// set of attributes. Change these attribute values to modify the information
7
+// associated with an assembly.
8
+[assembly: AssemblyTitle("B2Uploader")]
9
+[assembly: AssemblyDescription("")]
10
+[assembly: AssemblyConfiguration("")]
11
+[assembly: AssemblyCompany("")]
12
+[assembly: AssemblyProduct("B2Uploader")]
13
+[assembly: AssemblyCopyright("Copyright ©  2015")]
14
+[assembly: AssemblyTrademark("")]
15
+[assembly: AssemblyCulture("")]
16
+
17
+// Setting ComVisible to false makes the types in this assembly not visible 
18
+// to COM components.  If you need to access a type in this assembly from 
19
+// COM, set the ComVisible attribute to true on that type.
20
+[assembly: ComVisible(false)]
21
+
22
+// The following GUID is for the ID of the typelib if this project is exposed to COM
23
+[assembly: Guid("a5d41169-c2ee-4b5e-a2d8-b63e485597a6")]
24
+
25
+// Version information for an assembly consists of the following four values:
26
+//
27
+//      Major Version
28
+//      Minor Version 
29
+//      Build Number
30
+//      Revision
31
+//
32
+// You can specify all the values or you can default the Build and Revision Numbers 
33
+// by using the '*' as shown below:
34
+// [assembly: AssemblyVersion("1.0.*")]
35
+[assembly: AssemblyVersion("1.0.0.0")]
36
+[assembly: AssemblyFileVersion("1.0.0.0")]

+ 4 - 0
B2Uploader/packages.config

@@ -0,0 +1,4 @@
1
+<?xml version="1.0" encoding="utf-8"?>
2
+<packages>
3
+  <package id="Newtonsoft.Json" version="7.0.1" targetFramework="net452" />
4
+</packages>