Example #1
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="url"></param>
		/// <exception cref="UnauthorizedAccessException"></exception>
		/// <returns></returns>
		public async Task<ScannerProcess> CreateProcessAsync(string url)
		{
			if (this.Token == null)
				throw new UnauthorizedAccessException("Empty token!");
			else
				this.Token.Validate();

			using (HttpClient client = new HttpClient())
			{
				client.SetCopyleaksClient(HttpContentTypes.Json, this.Token);

				CreateCommandRequest req = new CreateCommandRequest() { URL = url };

				HttpResponseMessage msg;
				if (File.Exists(url))
				{
					FileInfo localFile = new FileInfo(url);
					// Local file. Need to upload it to the server.

					using (var content = new MultipartFormDataContent("Upload----" + DateTime.UtcNow.ToString(CultureInfo.InvariantCulture)))
					{
						using (FileStream stream = File.OpenRead(url))
						{
							content.Add(new StreamContent(stream, (int)stream.Length), "document", Path.GetFileName(url));
							msg = client.PostAsync(Resources.ServiceVersion + "/detector/create-by-file", content).Result;
						}
					}
				}
				else
				{
					// Internet path. Just submit it to the server.
					HttpContent content = new StringContent(
						JsonConvert.SerializeObject(req),
						Encoding.UTF8,
						HttpContentTypes.Json);
					msg = client.PostAsync(Resources.ServiceVersion + "/detector/create-by-url", content).Result;
				}

				if (!msg.IsSuccessStatusCode)
				{
					var errorJson = await msg.Content.ReadAsStringAsync();
					var errorObj = JsonConvert.DeserializeObject<BadResponse>(errorJson);
					if (errorObj == null)
						throw new CommandFailedException(msg.StatusCode);
					else
						throw new CommandFailedException(errorObj.Message, msg.StatusCode);
				}

				string json = await msg.Content.ReadAsStringAsync();

				CreateResourceResponse response = JsonConvert.DeserializeObject<CreateResourceResponse>(json);
				return new ScannerProcess(this.Token, response.ProcessId);
			}
		}
		/// <summary>
		/// Log-in into copyleaks authentication system.
		/// </summary>
		/// <param name="username">User name</param>
		/// <param name="apiKey">Password</param>
		/// <returns>Login Token to use while accessing resources.</returns>
		/// <exception cref="ArgumentException">Occur when the username and\or password is empty</exception>
		/// <exception cref="JsonException">ALON</exception>
		public static LoginToken Login(string username, string apiKey)
		{
#if !DEBUG // For testing purposes
			if (string.IsNullOrEmpty(username))
				throw new ArgumentException("Username is mandatory.", "username");
			else if (string.IsNullOrEmpty(apiKey))
				throw new ArgumentException("Password is mandatory.", "password");
#endif

			LoginToken token;
			using (HttpClient client = new HttpClient())
			{
				client.SetCopyleaksClient(HttpContentTypes.UrlEncoded);
				HttpResponseMessage msg = client.PostAsync(LOGIN_PAGE, new FormUrlEncodedContent(new[]
					{
						new KeyValuePair<string, string>("username", username),
						new KeyValuePair<string, string>("apikey", apiKey)
					})).Result;

				if (!msg.IsSuccessStatusCode)
				{
					string errorResponse = msg.Content.ReadAsStringAsync().Result;
					BadLoginResponse response = JsonConvert.DeserializeObject<BadLoginResponse>(errorResponse);
					if (response == null)
						throw new JsonException("Unable to process server response.");
					else
						throw new CommandFailedException(response.Message, msg.StatusCode);
				}

				string json = msg.Content.ReadAsStringAsync().Result;

				if (string.IsNullOrEmpty(json))
					throw new JsonException("This request could not be processed.");

				token = JsonConvert.DeserializeObject<LoginToken>(json);
				if (token == null)
					throw new JsonException("Unable to process server response.");
			}

			return token;
		}
Example #3
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="url">The url of the content to scan</param>
		/// <exception cref="UnauthorizedAccessException">When security-token is undefined or expired</exception>
		/// <exception cref="ArgumentOutOfRangeException">When the input url schema is diffrent then HTTP and HTTPS</exception>
		/// <returns></returns>
		public ScannerProcess CreateByUrl(Uri url, Uri httpCallback = null)
		{
			if (this.Token == null)
				throw new UnauthorizedAccessException("Empty token!");
			else
				this.Token.Validate();

			if (url.Scheme != "http" && url.Scheme != "https")
				throw new ArgumentOutOfRangeException(nameof(url), "Allowed protocols: HTTP, HTTPS");

			using (HttpClient client = new HttpClient())
			{
				client.SetCopyleaksClient(HttpContentTypes.Json, this.Token);

				CreateCommandRequest req = new CreateCommandRequest() { URL = url.AbsoluteUri };

				HttpResponseMessage msg;
				// Internet path. Just submit it to the server.
				HttpContent content = new StringContent(
					JsonConvert.SerializeObject(req),
					Encoding.UTF8,
					HttpContentTypes.Json);

				if (httpCallback != null)
					client.DefaultRequestHeaders.Add("Http-Callback", httpCallback.AbsoluteUri); // Add HTTP callback to the request header.

				msg = client.PostAsync(Resources.ServiceVersion + "/detector/create-by-url", content).Result;

				if (!msg.IsSuccessStatusCode)
				{
					var errorJson = msg.Content.ReadAsStringAsync().Result;
					var errorObj = JsonConvert.DeserializeObject<BadResponse>(errorJson);
					if (errorObj == null)
						throw new CommandFailedException(msg.StatusCode);
					else
						throw new CommandFailedException(errorObj.Message, msg.StatusCode);
				}

				string json = msg.Content.ReadAsStringAsync().Result;

				CreateResourceResponse response = JsonConvert.DeserializeObject<CreateResourceResponse>(json);
				return new ScannerProcess(this.Token, response.ProcessId);
			}
		}
Example #4
0
		/// <summary>
		/// 
		/// </summary>
		/// <param name="localfile"></param>
		/// <exception cref="UnauthorizedAccessException"></exception>
		/// <returns></returns>
		public ScannerProcess CreateByOcr(FileInfo localfile, Uri httpCallback = null)
		{
			if (this.Token == null)
				throw new UnauthorizedAccessException("Empty token!");
			else
				this.Token.Validate();

			if (!localfile.Exists)
				throw new FileNotFoundException("File not found!", localfile.FullName);

			using (HttpClient client = new HttpClient())
			{
				client.SetCopyleaksClient(HttpContentTypes.Json, this.Token);

				CreateCommandRequest req = new CreateCommandRequest()
				{
					URL = localfile.FullName
				};

				if (httpCallback != null)
					client.DefaultRequestHeaders.Add("Http-Callback", httpCallback.AbsoluteUri); // Add HTTP callback to the request header.

				HttpResponseMessage msg;
				// Local file. Need to upload it to the server.

				using (var content = new MultipartFormDataContent("Upload----" + DateTime.UtcNow.ToString(CultureInfo.InvariantCulture)))
				using (FileStream stream = localfile.OpenRead())
				{
					content.Add(new StreamContent(stream, (int)stream.Length), "document", Path.GetFileName(localfile.Name));
					msg = client.PostAsync(Resources.ServiceVersion + "/detector/create-by-file-ocr", content).Result;
				}

				if (!msg.IsSuccessStatusCode)
				{
					var errorJson = msg.Content.ReadAsStringAsync().Result;
					var errorObj = JsonConvert.DeserializeObject<BadResponse>(errorJson);
					if (errorObj == null)
						throw new CommandFailedException(msg.StatusCode);
					else
						throw new CommandFailedException(errorObj.Message, msg.StatusCode);
				}

				string json = msg.Content.ReadAsStringAsync().Result;

				CreateResourceResponse response = JsonConvert.DeserializeObject<CreateResourceResponse>(json);
				return new ScannerProcess(this.Token, response.ProcessId);
			}
		}
		public static async Task<uint> CountCreditsAsync(LoginToken token)
		{
			token.Validate();

			if (token == null)
				throw new ArgumentNullException("token");

			using (HttpClient client = new HttpClient())
			{
				client.SetCopyleaksClient(HttpContentTypes.Json, token);

				HttpResponseMessage msg = await client.GetAsync(string.Format("{0}/account/count-credits", Resources.ServiceVersion));
				if (!msg.IsSuccessStatusCode)
				{
					string errorResponse = await msg.Content.ReadAsStringAsync();
					BadLoginResponse response = JsonConvert.DeserializeObject<BadLoginResponse>(errorResponse);
					if (response == null)
						throw new JsonException("Unable to process server response.");
					else
						throw new CommandFailedException(response.Message, msg.StatusCode);
				}

				string json = await msg.Content.ReadAsStringAsync();

				if (string.IsNullOrEmpty(json))
					throw new JsonException("This request could not be processed.");

				CountCreditsResponse res = JsonConvert.DeserializeObject<CountCreditsResponse>(json);
				if (token == null)
					throw new JsonException("Unable to process server response.");

				return res.Amount;
			}
		}