Exemple #1
0
        static string RecognizePreferencesResultPage(HttpListenerRequest request, HttpListenerResponse result, SessionInfo session)
        {
            var    getArgs   = HttpUtility.ParseQueryString(request.Url.Query);
            string requestId = getArgs["requestId"];

            if (requestId == null)
            {
                return("{ \"response\" : {\n \"error\" : \"requestId not specified\"\n} }");
            }
            PreferenceInfo recognized = preferences_[requestId];

            if (recognized == null)
            {
                return("{ \"response\" : {\n   \"status\" : \"requestId not found\",\n   \"requestId\" : \"" + requestId + "\"\n} }");
            }
            if (recognized.IngredientPreferences == null)
            {
                return("{ \"response\" : {\n   \"status\" : \"pending\",\n   \"requestId\" : \"" + requestId + "\"\n} }");
            }
            StringBuilder prefs = new StringBuilder();

            prefs.Append("{ \"preferences\" = {\n");
            foreach (Preference p in recognized.IngredientPreferences)
            {
                prefs.AppendFormat("  \"{0}\" : \"{1}\",\n", p.Ingredient, p.Score);
            }
            prefs.Append("} }\n");
            return("{ \"response\" : {\n   \"status\" : \"completed\",\n   \"requestId\" : \"" + requestId + "\",\n   \"result\" : " + prefs.ToString() + "\n} }");
        }
Exemple #2
0
        static string PreferenceImage(HttpListenerRequest request, HttpListenerResponse result, SessionInfo session)
        {
            var    getArgs   = HttpUtility.ParseQueryString(request.Url.Query);
            string requestId = getArgs["requestId"];

            if (null == requestId)
            {
                return("{ response : {\n error : \"requestId is not specified\"\n} }");
            }
            PreferenceInfo p = preferences_[requestId];

            if (null == p)
            {
                return("{ response : {\n error : \"requestId " + requestId + " is not found\"\n} }");
            }
            if (null == p.HaveImage)
            {
                return("{ response : {\n error : \"requestId " + requestId + " does not have an uploaded image\"\n} }");
            }
            if (!System.IO.File.Exists(p.HaveImage))
            {
                return("{ response : {\n error : \"requestId " + requestId + " does not have a file with uploaded image\"\n} }");
            }
            byte[] content = File.ReadAllBytes(p.HaveImage);
            result.ContentType     = "image/jpeg";
            result.ContentEncoding = Encoding.UTF8;
            result.ContentLength64 = content.Length;
            result.OutputStream.Write(content, 0, content.Length);
            return(null);
        }
Exemple #3
0
        static string PreferencePage(HttpListenerRequest request, HttpListenerResponse result, SessionInfo session)
        {
            PreferenceInfo preferences = preferences_[session.User.Username];

            if (null == preferences)
            {
                preferences = new PreferenceInfo();
            }
            return(PreferencePage(request, result, session.User.Username, preferences));
        }
        /// <summary>
        /// When constructed, will read the information from all the user files
        /// </summary>
        public PreferenceRepo(DirectoryInfo location)
        {
            location_ = location;
            if (!location_.Exists)
            {
                location_.Create();
            }
            List <string> images = new List <string>();

            foreach (FileInfo i in location_.GetFiles())
            {
                if (i.FullName.EndsWith(".jpg"))
                {
                    images.Add(i.FullName.Substring(0, i.FullName.Length - 4));
                    continue; // TODO: handle this separately
                }
                try
                {
                    using (FileStream f = i.OpenRead())
                    {
                        PreferenceInfo p = serializer_.Deserialize(f) as PreferenceInfo;
                        if (null != p)
                        {
                            preferences_[i.Name] = p;
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.Error.WriteLine("Cannot read user information from {0}: {1}", i.FullName, e.ToString());
                }
            }
            foreach (var i in images)
            {
                if (preferences_.ContainsKey(i))
                {
                    continue;
                }
                PreferenceInfo p = new PreferenceInfo();
                p.IngredientPreferences = null;
                p.HaveImage             = i + ".jpg";
                FileInfo f         = new FileInfo(p.HaveImage);
                string   requestId = f.Name.Substring(0, f.Name.Length - 4);
                preferences_[requestId] = p;
            }
        }
Exemple #5
0
        private static string TrySavePreferences(HttpListenerRequest request, string username, PreferenceInfo preferences)
        {
            var args = GetPostArgs(request);

            try
            {
                var savingPreferences = args["savePreferences"];
                Dictionary <string, int> preferenceLookup = new Dictionary <string, int>();
                if (preferences.IngredientPreferences != null)
                {
                    foreach (var p in preferences.IngredientPreferences)
                    {
                        preferenceLookup[p.Ingredient] = p.Score;
                    }
                }
                foreach (string key in args.Keys)
                {
                    if (!key.StartsWith("pref_"))
                    {
                        continue;
                    }
                    string ingredientName = key.Substring(5);
                    preferenceLookup[ingredientName] = int.Parse(args[key]);
                }
                preferences.IngredientPreferences = new List <Preference>();
                foreach (var p in preferenceLookup)
                {
                    preferences.IngredientPreferences.Add(new Preference {
                        Ingredient = p.Key, Score = p.Value
                    });
                }
                preferences_[username] = preferences;
                return("<html><head><meta http-equiv=refresh content='0'/></head></html>");
            }
            catch (Exception e)
            {
                return("<html><body><script>alert('" + e.ToString() + "');</script></body></html>");
            }
        }
Exemple #6
0
        static string PreferencePage(HttpListenerRequest request, HttpListenerResponse result, string username, PreferenceInfo preferences)
        {
            // saving preferences?
            if (request.HttpMethod.ToUpper() == "POST")
            {
                return(TrySavePreferences(request, username, preferences));
            }

            // if logged in, discuss preferences
            StringBuilder buffer = new StringBuilder();

            buffer.Append(
                @"
<html>
<title>Preferences</title>
<body style='font-family:tahoma,arial,sans-serif;'>
");
            buffer.AppendLine(
                @"
<form method=post>
<fieldset>");
            if (preferences.IngredientPreferences != null)
            {
                AddLegend(username, buffer);
            }
            else
            {
                buffer.Append("<legend>[ requestId : " + username + " ]</legend>\n");
            }
            buffer.Append(@"
<input type=hidden id='username' value='" + username.Replace("'", "\'") + @"'>
<input type=submit id='savePreferences' name='savePreferences' value='Save Preferences' disabled/>
<script>
var nChanges = 0
function onPrefModified(which,label) {
  ++nChanges;
  document.getElementById('savePreferences').disabled = false;
  document.getElementById('savePreferences').value = 'Save Preferences (' + nChanges + ' changes)';
  var label = document.getElementById(label);
  if (label != null)
    label.style.backgroundColor = 'yellow';
}
</script>
<p>
");
            {
                Dictionary <string, int> preferenceLookup = new Dictionary <string, int>();
                if (preferences.IngredientPreferences != null)
                {
                    foreach (var p in preferences.IngredientPreferences)
                    {
                        preferenceLookup[p.Ingredient] = p.Score;
                    }
                }
                buffer.AppendLine("<table cellpadding=2 border=0><tr>");
                foreach (var column in ingredientsAsColumns_)
                {
                    if (0 == column.Count)
                    {
                        continue;
                    }
                    buffer.AppendLine("<td valign=top align=left><table cellpadding=2>");
                    foreach (var ingredientGroup in column)
                    {
                        buffer.AppendLine("<tr><td colspan=4 aligh=left><u>").AppendLine(ingredientGroup.Key).AppendLine("</u></td></tr>");
                        foreach (var ingredient in ingredientGroup.Value)
                        {
                            int score;
                            if (!preferenceLookup.TryGetValue(ingredient, out score))
                            {
                                score = 0;
                            }
                            buffer.AppendFormat(
                                @"
  <tr>
    <td bgcolor=limegreen title='like'><input type=radio name='pref_{0}' value='+1'{1} onchange='onPrefModified(this,{4});'/></td>
    <td bgcolor=moccasin title='ok'><input type=radio name='pref_{0}' value='0'{2} onchange='onPrefModified(this,{4});'/></td>
    <td bgcolor=salmon title='avoid!'><input type=radio name='pref_{0}' value='-1'{3} onchange='onPrefModified(this,{4});'/></td>
    <td id={4}>{0}</td>
  </tr>
",
                                ingredient,
                                score == +1 ? "checked=checked" : " ",
                                score == 0 ? "checked=checked" : " ",
                                score == -1 ? "checked=checked" : " ",
                                '"' + "lbl_" + ingredient + '"');
                            buffer.AppendLine();
                        }
                        buffer.AppendLine("  <tr><td colspan=4 aligh=left>&nbsp;</td></tr>");
                    }
                    buffer.AppendLine("</table></td>");
                }
                buffer.AppendLine("</td></table>");
            }
            buffer.Append(@"
</fieldset>
</form>
");
            if (preferences.HaveImage != null)
            {
                buffer.Append("<img onclick='window.open(\"/preference_image?requestId=" + username + "\", \"_blank\", \"toolbar=no,scrollbars=yes,resizable=yes,top=10,left=10\");' src=\"/preference_image?requestId=" + username + "\">\n");
            }
            buffer.Append(@"
</body>
</html>
");
            return(buffer.ToString());
        }
Exemple #7
0
        static string RecipePage(HttpListenerRequest request, HttpListenerResponse result, SessionInfo session)
        {
            PreferenceInfo preferences = preferences_[session.User.Username];

            if (null == preferences)
            {
                preferences = new PreferenceInfo();
            }
            Dictionary <string, int> preferenceLookup = new Dictionary <string, int>();

            foreach (var p in preferences.IngredientPreferences)
            {
                preferenceLookup[p.Ingredient] = p.Score;
            }
            var    getArgs       = HttpUtility.ParseQueryString(request.Url.Query);
            double strictness    = Math.Max(1e-4, double.Parse(getArgs["strictness"]));
            var    rankedRecipes = new List <PreferenceScore>();

            foreach (var recipe in recipes_)
            {
                rankedRecipes.Add(GetPreferenceScore(recipe, preferenceLookup, strictness));
            }
            rankedRecipes.Sort();

            StringBuilder buffer = new StringBuilder();

            buffer.Append(
                @"
<html>
<title>")
            .Append(session.User.Username)
            .Append(
                @"'s personalized recipes</title>
<body style='font-family:tahoma,arial,sans-serif;'>
<fieldset>
");
            AddLegend(session.User.Username, buffer);
            foreach (var recipe in rankedRecipes)
            {
                var owp = recipe.Recipe.Recipe.OriginalWebPage;
                buffer.AppendFormat("<br><a href='{2}' target='_blank' title='score: {0:0%}'>{1}</a><br>\n",
                                    recipe.Score, RecipeDownloader.RemoveSpecialCharacters(owp.Name), owp.UrlRoot + owp.Url);
                if (recipe.Positives != null)
                {
                    buffer.Append("<table border=0 cellpadding=0 cellspacing=0><tr><td bgcolor='lightcyan'>");
                    foreach (string entry in recipe.Positives)
                    {
                        buffer.Append("<li>").Append(entry).Append("</li>\n");
                    }
                    buffer.Append("</table>");
                }
                if (recipe.Neutrals != null)
                {
                    buffer.Append("<table border=0 cellpadding=0 cellspacing=0><tr><td bgcolor='ivory'>");
                    foreach (string entry in recipe.Neutrals)
                    {
                        buffer.Append("<li>").Append(entry).Append("</li>\n");
                    }
                    buffer.Append("</table>");
                }
                if (recipe.Negatives != null)
                {
                    buffer.Append("<table border=0 cellpadding=0 cellspacing=0><tr><td bgcolor='peachpuff'>");
                    foreach (string entry in recipe.Negatives)
                    {
                        buffer.Append("<li>").Append(entry).Append("</li>\n");
                    }
                    buffer.Append("</table>");
                }
            }
            buffer.AppendLine(
                @"
</fieldset>
</body>
</html>
");
            return(buffer.ToString());
        }
Exemple #8
0
        static string RecipeJsonPage(HttpListenerRequest request, HttpListenerResponse result, SessionInfo session)
        {
            var args = GetPostArgs(request);

            try
            {
                var preferences = args["preferences"];
                if (null == preferences)
                {
                    throw new ArgumentException("request does not contain post argument 'preferences'");
                }
                var strictnessStr = args["strictness"];
                if (null == strictnessStr)
                {
                    throw new ArgumentException("request does not contain post argument 'strictness'");
                }
                var limitStr = args["limit"];
                if (null == limitStr)
                {
                    throw new ArgumentException("request does not contain post argument 'limit'");
                }
                int limit;
                if (!int.TryParse(limitStr, out limit) || !(0 < limit))
                {
                    throw new ArgumentException("limit " + limitStr + " is not a positive integer");
                }
                double strictness;
                if (!double.TryParse(strictnessStr, out strictness))
                {
                    throw new ArgumentException("strictness " + strictnessStr + " is not a floating-point number");
                }
                strictness = Math.Max(1e-4, strictness);
                var prefs = JsonConvert.DeserializeXNode(preferences);
                Dictionary <string, int> preferenceLookup = new Dictionary <string, int>();
                foreach (var element in prefs.Root.Elements())
                {
                    if (element.HasAttributes)
                    {
                        throw new ArgumentException("preferences:" + element.Name + " has some kind of attributes inside");
                    }
                    if (element.HasElements)
                    {
                        throw new ArgumentException("preferences:" + element.Name + " has some kind of elements inside");
                    }
                    if (element.IsEmpty)
                    {
                        throw new ArgumentException("preferences:" + element.Name + " is empty");
                    }
                    int score;
                    if (!int.TryParse(element.Value, out score))
                    {
                        throw new ArgumentException("preferences:" + element.Name + " has a score of " + element.Value + ", which is not an integer");
                    }
                    preferenceLookup[element.Name.ToString()] = score;
                }
                var rankedRecipes = new List <PreferenceScore>();
                foreach (var recipe in recipes_)
                {
                    rankedRecipes.Add(GetPreferenceScore(recipe, preferenceLookup, strictness));
                }
                rankedRecipes.Sort();
                StringBuilder buffer   = new StringBuilder();
                int           nResults = 0;
                foreach (var recipe in rankedRecipes)
                {
                    ++nResults;
                    if (nResults > limit)
                    {
                        break;
                    }
                    buffer.AppendLine("{");
                    buffer.AppendLine("  \"title\" : \"" + RecipeDownloader.RemoveSpecialCharacters(recipe.Recipe.Recipe.OriginalWebPage.Name) + "\",");
                    buffer.AppendLine("  \"url\" : \"" + recipe.Recipe.Recipe.OriginalWebPage.UrlRoot + recipe.Recipe.Recipe.OriginalWebPage.Url + "\",");
                    buffer.AppendLine("  \"positives\" : [");
                    if (recipe.Positives != null)
                    {
                        foreach (string entry in recipe.Positives)
                        {
                            buffer.Append("    \"").Append(entry).Append("\",").AppendLine();
                        }
                    }
                    buffer.AppendLine("  ],");
                    buffer.AppendLine("  \"neutrals\" : [");
                    if (recipe.Neutrals != null)
                    {
                        foreach (string entry in recipe.Neutrals)
                        {
                            buffer.Append("    \"").Append(entry).Append("\",").AppendLine();
                        }
                    }
                    buffer.AppendLine("  ],");
                    buffer.AppendLine("  \"negatives\" : [");
                    if (recipe.Negatives != null)
                    {
                        foreach (string entry in recipe.Negatives)
                        {
                            buffer.AppendLine("    \"").Append(entry).Append("\",").AppendLine();
                        }
                    }
                    buffer.AppendLine("  ],");
                    buffer.AppendLine("},");
                }
                return("{ \"recipes\" : [\n" + buffer.ToString() + "]\n }\n");
            }
            catch (Exception e)
            {
                StringBuilder preferenceBlob = new StringBuilder();
                if (session.User != null)
                {
                    PreferenceInfo preferences = preferences_[session.User.Username];
                    if (null != preferences)
                    {
                        preferenceBlob.AppendLine("{ \"preferences\" : {");
                        foreach (var p in preferences.IngredientPreferences)
                        {
                            preferenceBlob.AppendLine("    \"" + p.Ingredient + "\" : \"" + p.Score.ToString() + "\",");
                        }
                        preferenceBlob.AppendLine("} }");
                    }
                }
                return
                    ("<html><body>" + e.ToString() + "<br>\n" +
                     "<form method=post>\n" +
                     "strictness:<input type='text' name='strictness' value='1'><br>\n" +
                     "limit:<input type='text' name='limit' value='15'><br>\n" +
                     "preferences:<br><textarea name=preferences rows=20 cols=80>" + preferenceBlob.ToString() + "</textarea><br>\n" +
                     "<input type=submit>\n" +
                     "</form>\n" +
                     "</body></html>");
            }
        }
        public string SaveImageFile(Encoding enc, String boundary, Stream input)
        {
            string username = null;
            string filename = null;

            do
            {
                username = Guid.NewGuid().ToString();
                filename = location_.FullName + "\\" + username + ".jpg";
            }while (System.IO.File.Exists(filename));

            Byte[] boundaryBytes = enc.GetBytes(boundary);
            Int32  boundaryLen   = boundaryBytes.Length;

            using (FileStream output = new FileStream(filename, FileMode.Create, FileAccess.Write))
            {
                Byte[] buffer   = new Byte[1024];
                Int32  len      = input.Read(buffer, 0, 1024);
                Int32  startPos = -1;

                // Find start boundary
                while (true)
                {
                    if (len == 0)
                    {
                        throw new Exception("Start Boundaray Not Found");
                    }

                    startPos = IndexOf(buffer, len, boundaryBytes);
                    if (startPos >= 0)
                    {
                        break;
                    }
                    else
                    {
                        Array.Copy(buffer, len - boundaryLen, buffer, 0, boundaryLen);
                        len = input.Read(buffer, boundaryLen, 1024 - boundaryLen);
                    }
                }

                // Skip four lines (Boundary, Content-Disposition, Content-Type, and a blank)
                for (Int32 i = 0; i < 4; i++)
                {
                    while (true)
                    {
                        if (len == 0)
                        {
                            throw new Exception("Preamble not Found.");
                        }

                        startPos = Array.IndexOf(buffer, enc.GetBytes("\n")[0], startPos);
                        if (startPos >= 0)
                        {
                            startPos++;
                            break;
                        }
                        else
                        {
                            len = input.Read(buffer, 0, 1024);
                        }
                    }
                }

                Array.Copy(buffer, startPos, buffer, 0, len - startPos);
                len = len - startPos;

                while (true)
                {
                    Int32 endPos = IndexOf(buffer, len, boundaryBytes);
                    if (endPos >= 0)
                    {
                        if (endPos > 0)
                        {
                            output.Write(buffer, 0, endPos - 2);
                        }
                        break;
                    }
                    else if (len <= boundaryLen)
                    {
                        throw new Exception("End Boundaray Not Found");
                    }
                    else
                    {
                        output.Write(buffer, 0, len - boundaryLen);
                        Array.Copy(buffer, len - boundaryLen, buffer, 0, boundaryLen);
                        len = input.Read(buffer, boundaryLen, 1024 - boundaryLen) + boundaryLen;
                    }
                }
            }

            lock (preferences_)
            {
                PreferenceInfo i = new PreferenceInfo();
                i.IngredientPreferences = null;
                i.HaveImage             = filename;
                preferences_[username]  = i;
            }
            return(username);
        }