MCC/b2uploader: b2uploader - backup to server - SVN.BY: Go Git Service

b2uploader - backup to server

Program.cs 11KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295
  1. using B2Classes;
  2. using CommandLine;
  3. using Newtonsoft.Json;
  4. using System;
  5. using System.Collections.Generic;
  6. using System.IO;
  7. using System.Linq;
  8. using System.Net;
  9. using System.Security.Cryptography;
  10. using System.Text;
  11. using System.Threading;
  12. using System.Threading.Tasks;
  13. namespace B2Uploader
  14. {
  15. class CmdLineOptions
  16. {
  17. [Option('i', "accountid", HelpText = "Account ID", Required=true)]
  18. public string AccountId { get; set; }
  19. [Option('a', "appkey", HelpText = "Application Key", Required=true)]
  20. public string ApplicationKey { get; set; }
  21. [Option('d', "directory", HelpText = "Directory you want to upload", Required = true)]
  22. public string Directory { get; set; }
  23. [Option('m', "multithreads", HelpText = "Number of uploads you want to use at a time. Default is 2", Required = false)]
  24. public int Threads { get; set; }
  25. [Option('r', "recursive", HelpText = "Uploads the directory in Recursive mode. Any sub folders will also be uploaded", Required = false)]
  26. public bool recursive { get; set; }
  27. [Option('v', "verbose", HelpText="Verbose Output")]
  28. public bool Verbose{get;set;}
  29. }
  30. class Program
  31. {
  32. static void Main(string[] args)
  33. {
  34. var result = CommandLine.Parser.Default.ParseArguments<CmdLineOptions>(args);
  35. var existCode = result.MapResult(options => {
  36. if (!Directory.Exists(options.Directory))
  37. {
  38. Console.WriteLine("Directory to upload MUST EXIST!");
  39. return 0;
  40. }
  41. var auth = AuthorizeUser(options.AccountId, options.ApplicationKey);
  42. var buckets = ListBuckets(new ListBucketsRequest() { accountId = auth.accountId }, auth.authorizationToken, auth.apiUrl);
  43. var bucket = buckets.buckets.First();
  44. SearchOption so = SearchOption.TopDirectoryOnly;
  45. if (options.recursive)
  46. {
  47. so = SearchOption.AllDirectories;
  48. }
  49. string[] FilesToProcess = Directory.GetFiles(options.Directory, "*", so);
  50. int maxParallel = 2;
  51. if(options.Threads > 2)
  52. {
  53. maxParallel = options.Threads;
  54. }
  55. Parallel.ForEach(FilesToProcess, new ParallelOptions() { MaxDegreeOfParallelism = maxParallel }, s =>
  56. {
  57. //check if file already exists
  58. string fileName = getValidFilename(s);
  59. var existingFiles = ListFileNames(new ListFileNamesRequest() { bucketId = bucket.bucketId, startFileName = fileName }, auth.apiUrl, auth.authorizationToken);
  60. bool found = false;
  61. foreach (var x in existingFiles.files)
  62. {
  63. if (x.fileName == fileName)
  64. {
  65. //check the file size
  66. System.IO.FileInfo fi = new System.IO.FileInfo(s);
  67. if (fi.Length == x.size)
  68. {
  69. found = true;
  70. break;
  71. }
  72. else
  73. {
  74. //delete old file? could just be an older version... going to upload again...
  75. break;
  76. }
  77. }
  78. }
  79. if (found)
  80. {
  81. Console.WriteLine("File {0} exists already, skipping", fileName);
  82. }
  83. else
  84. {
  85. bool uploaded = false;
  86. int retries = 0;
  87. while (!uploaded && retries < 3)
  88. {
  89. try {
  90. var uploadURL = GetUploadURL(new GetUploadURLRequest { bucketId = bucket.bucketId }, auth.apiUrl, auth.authorizationToken);
  91. var response = UploadFile(uploadURL.authorizationToken, "b2/x-auto", s, uploadURL.uploadUrl);
  92. if(response != null)
  93. {
  94. uploaded = true;
  95. }
  96. }
  97. catch(Exception ex)
  98. {
  99. Console.WriteLine("Uploaded Failed. Retrying");
  100. Console.WriteLine(ex.Message);
  101. uploaded = false;
  102. retries += 1;
  103. Thread.Sleep(TimeSpan.FromSeconds(30));
  104. }
  105. }
  106. if (!uploaded)
  107. {
  108. Console.WriteLine("Uploaded Failed 3 times... Please retry later!");
  109. }
  110. }
  111. });
  112. return 1;
  113. },
  114. errors =>{
  115. Console.WriteLine(errors);
  116. return 1;
  117. });
  118. }
  119. static AuthorizeResponse AuthorizeUser(string accountId, string applicationKey)
  120. {
  121. HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("https://api.backblaze.com/b2api/v1/b2_authorize_account");
  122. string credentials = Convert.ToBase64String(Encoding.UTF8.GetBytes(accountId + ":" + applicationKey));
  123. webRequest.Headers.Add("Authorization", "Basic " + credentials);
  124. webRequest.ContentType = "application/json; charset=utf-8";
  125. WebResponse response = (HttpWebResponse)webRequest.GetResponse();
  126. var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
  127. response.Close();
  128. return JsonConvert.DeserializeObject<AuthorizeResponse>(responseString);
  129. }
  130. static ListBucketsResponse ListBuckets(ListBucketsRequest request, string authToken, string apiUrl)
  131. {
  132. var headers = GetAuthHeaders(authToken);
  133. string responseString = MakeRequest(apiUrl + "/b2api/v1/b2_list_buckets", headers, JsonConvert.SerializeObject(request));
  134. return JsonConvert.DeserializeObject<ListBucketsResponse>(responseString);
  135. }
  136. static List<Tuple<string,string>> GetAuthHeaders(string authToken)
  137. {
  138. List<Tuple<string, string>> headers = new List<Tuple<string, string>>();
  139. headers.Add(new Tuple<string, string>("Authorization", authToken));
  140. return headers;
  141. }
  142. static GetUploadURLResponse GetUploadURL(GetUploadURLRequest request, string apiUrl, string authToken)
  143. {
  144. var headers = GetAuthHeaders(authToken);
  145. string responseString = MakeRequest(apiUrl + "/b2api/v1/b2_get_upload_url", headers, JsonConvert.SerializeObject(request));
  146. return JsonConvert.DeserializeObject<GetUploadURLResponse>(responseString);
  147. }
  148. static string getValidFilename(string input)
  149. {
  150. string fileName = input.Replace('\\', '/');
  151. if (fileName.StartsWith("/"))
  152. {
  153. fileName = fileName.Substring(1);
  154. }
  155. return fileName;
  156. }
  157. static UploadFileResponse UploadFile(string authToken, string contentType, string filePath, string uploadUrl)
  158. {
  159. String sha1 = GetSha1(filePath);
  160. var headers = GetAuthHeaders(authToken);
  161. string fileName = getValidFilename(filePath);
  162. headers.Add(new Tuple<string, string>("X-Bz-File-Name", fileName));
  163. headers.Add(new Tuple<string, string>("X-Bz-Content-Sha1", sha1));
  164. using (FileStream fs = System.IO.File.OpenRead(filePath))
  165. {
  166. string responseString = MakeRequest(uploadUrl, headers, fs, contentType);
  167. var resp = JsonConvert.DeserializeObject<UploadFileResponse>(responseString);
  168. if (resp.contentSha1 == sha1)
  169. {
  170. Console.WriteLine(responseString);
  171. return resp;
  172. }
  173. else
  174. {
  175. //something went wrong!
  176. return null;
  177. }
  178. }
  179. }
  180. static ListFileNamesResponse ListFileNames(ListFileNamesRequest request, string apiUrl, string authToken)
  181. {
  182. var headers = GetAuthHeaders(authToken);
  183. string responseString = MakeRequest(apiUrl + "/b2api/v1/b2_list_file_names", headers, JsonConvert.SerializeObject(request));
  184. return JsonConvert.DeserializeObject<ListFileNamesResponse>(responseString);
  185. }
  186. static string MakeRequest(string url, List<Tuple<string,string>> headers, string data, string contentType = "application/json; charset=urf-8")
  187. {
  188. MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(data));
  189. return MakeRequest(url, headers, ms, contentType);
  190. }
  191. static string MakeRequest(string url, List<Tuple<string,string>> headers, Stream data, string contentType="application/json; charset=utf-8")
  192. {
  193. try
  194. {
  195. HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
  196. req.Method = "POST";
  197. foreach (var head in headers)
  198. {
  199. req.Headers.Add(head.Item1, head.Item2);
  200. }
  201. using (var stream = req.GetRequestStream())
  202. {
  203. data.Position = 0;
  204. req.ContentType = contentType;
  205. data.CopyTo(stream);
  206. data.Flush();
  207. stream.Close();
  208. }
  209. WebResponse response = (HttpWebResponse)req.GetResponse();
  210. var responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
  211. response.Close();
  212. return responseString;
  213. }
  214. catch (Exception ex)
  215. {
  216. Console.WriteLine("Error talking to server: {0}", ex.Message);
  217. Console.WriteLine("URL: {0}", url);
  218. throw;
  219. }
  220. }
  221. private static string GetSha1(string fileName)
  222. {
  223. using (SHA1Managed sha1 = new SHA1Managed())
  224. {
  225. using (FileStream fs = System.IO.File.OpenRead(fileName))
  226. {
  227. var hash = sha1.ComputeHash(fs);
  228. var sb = new StringBuilder(hash.Length * 2);
  229. foreach (byte b in hash)
  230. {
  231. // can be "x2" if you want lowercase
  232. sb.Append(b.ToString("X2"));
  233. }
  234. return sb.ToString();
  235. }
  236. }
  237. }
  238. }
  239. }