Beispiel #1
0
        //public object Get(Files request)
        //{
        //    var targetFile = GetAndValidateExistingPath(request);

        //    var isDirectory = Directory.Exists(targetFile.FullName);

        //    if (!isDirectory && request.ForDownload)
        //        return new HttpResult(targetFile, asAttachment: true);

        //    var response = isDirectory
        //        ? new FilesResponse { Directory = GetFolderResult(targetFile.FullName) }
        //        : new FilesResponse { File = GetFileResult(targetFile) };

        //    return response;
        //}

        //		[AddHeader(ContentType = "text/json")]
        public object Post(Files request)
        {
            //var container = ServiceStackHost.Instance.Container;

            //			var response = new MyPerson { };
            var response  = "";
            var message   = "";
            var uuid      = "";
            var token     = "";
            var targetDir = GetPath(request);

            var isExistingFile = targetDir.Exists &&
                                 (targetDir.Attributes & FileAttributes.Directory) != FileAttributes.Directory;

            if (isExistingFile)
            {
                throw new NotSupportedException(
                          "POST only supports uploading new files. Use PUT to replace contents of an existing file");
            }

            if (!Directory.Exists(targetDir.FullName))
            {
                Directory.CreateDirectory(targetDir.FullName);
            }

            if (base.Request.Files.Length == 0)
            {
                //				message = "No files uploaded.";
            }

            foreach (var key in base.Request.FormData.AllKeys)
            {
                foreach (var val in base.Request.FormData.GetValues(key))
                {
                    if (key == "uuid")
                    {
                        uuid = val;
                        Console.WriteLine(string.Format("{0}: {1}", key, val) + " uuid set to: " + uuid);
                    }
                    else if (key == "key")
                    {
                        token = val;
                        Console.WriteLine(string.Format("{0}: {1}", key, val) + " token set to: " + token);
                    }
                }
            }

            Response jsonResponse = new Response();

            if (token == "noel.honeybee.galvanic")
            {
                foreach (var uploadedFile in base.Request.Files)
                {
                    var newFilePath = Path.Combine(targetDir.FullName, uploadedFile.FileName) + ".png";
                    //					if (uploadedFile.StartsWith("verify") {
                    //					}
                    uploadedFile.SaveTo(newFilePath);

                    // Enroll visitor with unknown identity
                    Guid g;
                    // Create and display the value of two GUIDs.
                    g = Guid.NewGuid();
                    DateTime date1 = DateTime.Now;
                    Console.WriteLine("Starting Enroll:  " + date1);
                    MyPerson probe = SourceAfisIdentify.Enroll(newFilePath, g.ToString(), Afis);
                    // Look up the probe using Threshold = 10
                    Afis.Threshold = 10;
                    DateTime date2 = DateTime.Now;
                    var      list  = FingerprintDatabase.people;
                    //Console.WriteLine("Identifying {0} in Database of {1} persons...", probe.Name, list.Count + " at " + date2);
                    Console.WriteLine("{0} : Identifying {1} in Database of {2} persons...", date2, probe.Name, list.Count);

                    MyPerson match = Afis.Identify(probe, list).FirstOrDefault() as MyPerson;

                    DateTime date3         = DateTime.Now;
                    var      diffInSeconds = (date3 - date2).TotalSeconds;
                    Console.WriteLine("Enroll time:  " + diffInSeconds + " seconds");
                    diffInSeconds = (date2 - date1).TotalSeconds;
                    Console.WriteLine("Total enroll + match time:  " + diffInSeconds + " seconds");


                    // Null result means that there is no candidate with similarity score above threshold
                    if (match == null)
                    {
                        message = "NoMatch";
                        jsonResponse.StatusCode = 4;
                        jsonResponse.Error      = message;
                        jsonResponse.UID        = g.ToString();
                        Console.WriteLine(message);
                        //Database.Add (probe);
                        FingerprintDatabase.AddData(probe);
                        String url = "http://localhost:5984/prints/" + g.ToString();
                        //					String data = "{_id: " + "\"" + g.ToString ()  + "\"" + ", fileName:" + "\""  + uploadedFile.FileName + "\""  + "}";
                        var person = new MyPerson();
                        //					person.Filename = uploadedFile.FileName;
                        person.Uuid = g.ToString();
                        List <Fingerprint>       probleFingerprints = probe.Fingerprints;
                        List <SimpleFingerprint> fingerprints       = new List <SimpleFingerprint>();

                        foreach (var print in probleFingerprints)
                        {
                            byte[] template = print.Template;
                            // Convert the binary input into Base64 UUEncoded output.
                            string base64String = null;
                            try
                            {
                                base64String = System.Convert.ToBase64String(template, 0, template.Length);
                            }
                            catch (System.ArgumentNullException)
                            {
                                System.Console.WriteLine("Binary data array is null.");
                            }

                            SimpleFingerprint fprint = new SimpleFingerprint();
                            fprint.Base64Template = base64String;
                            fprint.Filename       = uploadedFile.FileName;
                            DateTime dateUploaded = DateTime.Now;
                            string   isoJson      = JsonConvert.SerializeObject(dateUploaded, Formatting.None, new IsoDateTimeConverter()
                            {
                                DateTimeFormat = "yyyy-MM-dd hh:mm:ss"
                            });
                            fprint.DateUploaded = isoJson;
                            //fingerprints.Add (fprint);
                            person.simpleFingerprint = fprint;
                        }

                        person.SimpleFingerprints = fingerprints;

                        var json = NServiceKit.Text.JsonSerializer.SerializeToString(person);
                        Console.WriteLine(json);
                        WebClient client = new WebClient();
                        try
                        {
                            client.UploadString(url, "PUT", json);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex);
                        }
                        string jsonString = JsonConvert.SerializeObject(jsonResponse);
                        response = jsonString;
                    }
                    else
                    {
                        // Print out any non-null result
                        Console.WriteLine("Probe {0} matches registered person {1}", probe.Uuid, match.Uuid);

                        // Compute similarity score
                        DateTime date4 = DateTime.Now;
                        float    score = Afis.Verify(probe, match);
                        Console.WriteLine("Similarity score between {0} and {1} = {2:F3}", probe.Uuid, match.Uuid, score);
                        DateTime date5 = DateTime.Now;
                        diffInSeconds = (date5 - date4).TotalSeconds;
                        Console.WriteLine("Verify time:  " + diffInSeconds + " seconds");
                        message = "Match: " + probe.Name + " matches " + match.Name + " Score: " + score;

                        jsonResponse.StatusCode = 1;
                        jsonResponse.Error      = null;
                        jsonResponse.UID        = match.Uuid;
                        jsonResponse.Threshold  = score;

                        string jsonString = JsonConvert.SerializeObject(jsonResponse);
                        response = jsonString;
                    }
                }
            }
            else
            {
                jsonResponse.Error = "Auth error.";
                string jsonString = JsonConvert.SerializeObject(jsonResponse);
                response = jsonString;
            }
            return(response);
        }
Beispiel #2
0
        //public object Get(Files request)
        //{
        //    var targetFile = GetAndValidateExistingPath(request);

        //    var isDirectory = Directory.Exists(targetFile.FullName);

        //    if (!isDirectory && request.ForDownload)
        //        return new HttpResult(targetFile, asAttachment: true);

        //    var response = isDirectory
        //        ? new FilesResponse { Directory = GetFolderResult(targetFile.FullName) }
        //        : new FilesResponse { File = GetFileResult(targetFile) };

        //    return response;
        //}

		//		[AddHeader(ContentType = "text/json")]
		public object Post(Files request)
		{
			//var container = ServiceStackHost.Instance.Container;

			//			var response = new MyPerson { };
			var response = "";
			var message = "";
			var uuid = "";
			var token = "";
			var targetDir = GetPath(request);

			var isExistingFile = targetDir.Exists
										  && (targetDir.Attributes & FileAttributes.Directory) != FileAttributes.Directory;

			if (isExistingFile)
				throw new NotSupportedException(
					"POST only supports uploading new files. Use PUT to replace contents of an existing file");

			if (!Directory.Exists(targetDir.FullName))
				Directory.CreateDirectory(targetDir.FullName);

			if (base.Request.Files.Length == 0)
			{
				//				message = "No files uploaded.";
			}

			foreach (var key in base.Request.FormData.AllKeys)
			{
				foreach (var val in base.Request.FormData.GetValues(key))
				{
					if (key == "uuid")
					{
						uuid = val;
						Console.WriteLine(string.Format("{0}: {1}", key, val) + " uuid set to: " + uuid);
					}
					else if (key == "key")
					{
						token = val;
						Console.WriteLine(string.Format("{0}: {1}", key, val) + " token set to: " + token);
					}
				}
			}

			Response jsonResponse = new Response();

			if (token == "noel.honeybee.galvanic")
			{
				foreach (var uploadedFile in base.Request.Files)
				{
					var newFilePath = Path.Combine(targetDir.FullName, uploadedFile.FileName) + ".png";
					//					if (uploadedFile.StartsWith("verify") {
					//					}
					uploadedFile.SaveTo(newFilePath);

					// Enroll visitor with unknown identity
					Guid g;
					// Create and display the value of two GUIDs.
					g = Guid.NewGuid();
					DateTime date1 = DateTime.Now;
					Console.WriteLine("Starting Enroll:  " + date1);
					MyPerson probe = SourceAfisIdentify.Enroll(newFilePath, g.ToString(), Afis);
					// Look up the probe using Threshold = 10
					Afis.Threshold = 10;
					DateTime date2 = DateTime.Now;
					var list = FingerprintDatabase.people;
					//Console.WriteLine("Identifying {0} in Database of {1} persons...", probe.Name, list.Count + " at " + date2);
					Console.WriteLine("{0} : Identifying {1} in Database of {2} persons...", date2, probe.Name, list.Count);

					MyPerson match = Afis.Identify(probe, list).FirstOrDefault() as MyPerson;

					DateTime date3 = DateTime.Now;
					var diffInSeconds = (date3 - date2).TotalSeconds;
					Console.WriteLine("Enroll time:  " + diffInSeconds + " seconds");
					diffInSeconds = (date2 - date1).TotalSeconds;
					Console.WriteLine("Total enroll + match time:  " + diffInSeconds + " seconds");


					// Null result means that there is no candidate with similarity score above threshold
					if (match == null)
					{
						message = "NoMatch";
						jsonResponse.StatusCode = 4;
						jsonResponse.Error = message;
						jsonResponse.UID = g.ToString();
						Console.WriteLine(message);
						//Database.Add (probe);
						FingerprintDatabase.AddData(probe);
						String url = "http://localhost:5984/prints/" + g.ToString();
						//					String data = "{_id: " + "\"" + g.ToString ()  + "\"" + ", fileName:" + "\""  + uploadedFile.FileName + "\""  + "}";
						var person = new MyPerson();
						//					person.Filename = uploadedFile.FileName;
						person.Uuid = g.ToString();
						List<Fingerprint> probleFingerprints = probe.Fingerprints;
						List<SimpleFingerprint> fingerprints = new List<SimpleFingerprint>();

						foreach (var print in probleFingerprints)
						{
							byte[] template = print.Template;
							// Convert the binary input into Base64 UUEncoded output. 
							string base64String = null;
							try
							{
								base64String = System.Convert.ToBase64String(template, 0, template.Length);
							}
							catch (System.ArgumentNullException)
							{
								System.Console.WriteLine("Binary data array is null.");
							}

							SimpleFingerprint fprint = new SimpleFingerprint();
							fprint.Base64Template = base64String;
							fprint.Filename = uploadedFile.FileName;
							DateTime dateUploaded = DateTime.Now;
							string isoJson = JsonConvert.SerializeObject(dateUploaded, Formatting.None, new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd hh:mm:ss" });
							fprint.DateUploaded = isoJson;
							//fingerprints.Add (fprint);
							person.simpleFingerprint = fprint;
						}

						person.SimpleFingerprints = fingerprints;

						var json = NServiceKit.Text.JsonSerializer.SerializeToString(person);
						Console.WriteLine(json);
						WebClient client = new WebClient();
						try
						{
							client.UploadString(url, "PUT", json);
						}
						catch (Exception ex)
						{
							Console.WriteLine(ex);
						}
						string jsonString = JsonConvert.SerializeObject(jsonResponse);
						response = jsonString;
					}
					else {
						// Print out any non-null result
						Console.WriteLine("Probe {0} matches registered person {1}", probe.Uuid, match.Uuid);

						// Compute similarity score
						DateTime date4 = DateTime.Now;
						float score = Afis.Verify(probe, match);
						Console.WriteLine("Similarity score between {0} and {1} = {2:F3}", probe.Uuid, match.Uuid, score);
						DateTime date5 = DateTime.Now;
						diffInSeconds = (date5 - date4).TotalSeconds;
						Console.WriteLine("Verify time:  " + diffInSeconds + " seconds");
						message = "Match: " + probe.Name + " matches " + match.Name + " Score: " + score;

						jsonResponse.StatusCode = 1;
						jsonResponse.Error = null;
						jsonResponse.UID = match.Uuid;
						jsonResponse.Threshold = score;

						string jsonString = JsonConvert.SerializeObject(jsonResponse);
						response = jsonString;
					}
				}
			}
			else {
				jsonResponse.Error = "Auth error.";
				string jsonString = JsonConvert.SerializeObject(jsonResponse);
				response = jsonString;
			}
			return response;
		}