Exemple #1
0
        private States SearchImage(WebClientx wc, KisboFile file, StreamWriter writer, CancellationToken token)
        {
            string body;

            Size oldSize;

            try
            {
                using (var img = Image.FromFile(file.OriginalFilePath))
                    file.SetBeforeResolution(oldSize = img.Size);
            }
            catch
            {
                return(States.Error);
            }

            try
            {
                {
                    var origBoundary = "-----" + Guid.NewGuid().ToString("N");
                    var boundary     = "--" + origBoundary;

                    var info = new FileInfo(file.OriginalFilePath);

                    // DELETE BOM
                    writer.BaseStream.SetLength(0);
                    writer.WriteLine(boundary);
                    writer.WriteLine("Content-Disposition: form-data; name=\"encoded_image\"; filename=\"{0}\"", info.Name);
                    writer.WriteLine("Content-Type: application/octet-stream");
                    writer.WriteLine();
                    using (var fileStream = info.OpenRead())
                        fileStream.CopyTo(writer.BaseStream, 4096);
                    writer.WriteLine();
                    writer.WriteLine(boundary + "--");

                    writer.BaseStream.Position = 0;

                    do
                    {
                        if (token.IsCancellationRequested)
                        {
                            return(States.Error);
                        }

                        if (!this.m_search.WaitOne(0))
                        {
                            file.State = States.WaitSearch;
                            file.SetStatus();

                            this.m_search.WaitOne();
                            if (token.IsCancellationRequested)
                            {
                                return(States.Error);
                            }

                            file.State = States.Working;
                            file.SetStatus();
                        }

                        body = wc.UploadData(new Uri(this.m_googleUri, "/searchbyimage/upload"), writer.BaseStream, "multipart/form-data; boundary=" + origBoundary);
                        if (body == null)
                        {
                            return(States.Error);
                        }

                        if (body.IndexOf("topstuff", StringComparison.OrdinalIgnoreCase) == -1)
                        {
                            body = null;

                            if (this.m_search.WaitOne(0))
                            {
                                file.State = States.WaitSearch;
                                file.SetStatus();

                                this.m_search.Reset();
                                Thread.Sleep(60 * 1000);
                                this.m_search.Set();

                                if (token.IsCancellationRequested)
                                {
                                    return(States.Error);
                                }

                                file.State = States.Working;
                                file.SetStatus();
                            }
                        }
                    } while (body == null);
                }

                file.GoogleUrl = wc.ResponseUri.AbsoluteUri;

                var html = new HtmlDocument();
                html.LoadHtml(body);
                var docNode = html.DocumentNode;

                bool succ = false;
                foreach (var card_section_node in docNode.SelectNodes(@"//div[contains(@class,'card-section')]"))
                {
                    foreach (var a_node in card_section_node.SelectNodes(".//a"))
                    {
                        var href = a_node.Attributes["href"];
                        if (href == null)
                        {
                            continue;
                        }

                        if (href.Value.IndexOf("tbs=") == -1)
                        {
                            continue;
                        }

                        if ((body = wc.DownloadString(new Uri(this.m_googleUri, href.Value.Replace("&", "&")))) == null)
                        {
                            return(States.Error);
                        }

                        html.LoadHtml(body);
                        docNode = html.DocumentNode;

                        succ = true;
                        break;
                    }
                }

                if (!succ)
                {
                    return(States.NoResult);
                }

                string newExtension = null, newPath, tempPath = null, dir;
                Guid   guid;
                RGMeta rgMeta;

                foreach (var rg_meta_node in docNode.SelectNodes(@"//div[contains(@class,'rg_meta')]"))
                {
                    if (file.Removed)
                    {
                        break;
                    }

                    if (token.IsCancellationRequested)
                    {
                        return(States.Error);
                    }

                    try
                    {
                        rgMeta = RGMeta.Parse(rg_meta_node.InnerHtml);
                        if (rgMeta.Width <= oldSize.Width ||
                            rgMeta.Height <= oldSize.Height)
                        {
                            continue;
                        }

                        tempPath = Path.GetTempFileName();

                        using (var fileStream = File.OpenWrite(tempPath))
                        {
                            fileStream.SetLength(0);
                            if (!wc.DownloadData(rgMeta.ImageUrl, fileStream, rgMeta.ImageUrl.AbsoluteUri))
                            {
                                continue;
                            }
                        }

                        if (file.Removed)
                        {
                            break;
                        }
                        using (var img = Image.FromFile(tempPath))
                        {
                            guid = img.RawFormat.Guid;

                            if (guid == ImageFormat.Bmp.Guid)
                            {
                                newExtension = ".bmp";
                            }
                            else if (guid == ImageFormat.Gif.Guid)
                            {
                                newExtension = ".gif";
                            }
                            else if (guid == ImageFormat.Jpeg.Guid)
                            {
                                newExtension = ".jpg";
                            }
                            else if (guid == ImageFormat.Png.Guid)
                            {
                                newExtension = ".png";
                            }

                            if (img.Width <= oldSize.Width ||
                                img.Height <= oldSize.Height)
                            {
                                continue;
                            }

                            file.SetAfterResolution(img.Size);
                        }

                        if (file.Removed)
                        {
                            break;
                        }

                        dir = Path.Combine(Path.GetDirectoryName(file.OriginalFilePath), "kisbo-original");
                        if (!Directory.Exists(dir))
                        {
                            Directory.CreateDirectory(dir);
                        }

                        File.Move(file.OriginalFilePath, GetSafeFileName(Path.Combine(dir, Path.GetFileName(file.OriginalFilePath))));

                        newPath = Path.ChangeExtension(file.OriginalFilePath, newExtension);
                        File.Move(tempPath, GetSafeFileName(newPath));

                        file.NewFilePath = newPath;

                        return(States.Complete);
                    }
                    catch
                    {
                    }
                    finally
                    {
                        try
                        {
                            File.Delete(tempPath);
                        }
                        catch
                        {
                        }
                    }
                }

                return(States.Pass);
            }
            catch
            {
                return(States.Error);
            }
        }
Exemple #2
0
        private void SearchWorker(object oIndex)
        {
            var token = this.m_cancel.Token;
            var index = (int)oIndex;

#if DEBUG
            Thread.CurrentThread.Name = "SearchWorker " + index;
#endif

            KisboFile file;
            int       i;
            bool      complete;
            States    result;

            using (var wc = new WebClientx(token))
                using (var buff = new MemoryStream(1024 * 1024))
                {
                    var writer = new StreamWriter(buff, Encoding.UTF8)
                    {
                        AutoFlush = true, NewLine = "\r\n"
                    };

                    try
                    {
                        while (!token.IsCancellationRequested)
                        {
                            this.m_pauseHandler.WaitOne();
                            this.m_newItemHandler.WaitOne();

                            if (token.IsCancellationRequested)
                            {
                                return;
                            }

                            if (buff.Capacity > 2 * 1024 * 1024)
                            {
                                buff.SetLength(0);
                                buff.Capacity = 1024 * 1024;
                            }

                            lock (this.m_lock)
                            {
                                Debug.WriteLine("SearchWorker {0} Lock", index);

                                file     = null;
                                complete = true;
                                for (i = 0; i < this.m_list.Count; ++i)
                                {
                                    if (token.IsCancellationRequested)
                                    {
                                        return;
                                    }

                                    if (!this.m_list[i].Worked)
                                    {
                                        complete = false;
                                    }

                                    if (this.m_list[i].State == States.Wait)
                                    {
                                        file       = this.m_list[i];
                                        file.State = States.Working;
                                        break;
                                    }
                                }

                                if (complete)
                                {
                                    Interlocked.Exchange(ref this.m_taskbarVal, 0);
                                    Interlocked.Exchange(ref this.m_taskbarMax, 0);
                                    this.m_newItemHandler.Reset();

                                    for (i = 0; i < this.m_list.Count; ++i)
                                    {
                                        this.m_list[i].NotTodo = true;
                                    }
                                }

                                Debug.WriteLine("SearchWorker {0} Unlock", index);
                            }

                            if (complete)
                            {
                                this.SetProgress();

                                this.Invoke(new Action <int, string, string, ToolTipIcon>(this.ctlNotify.ShowBalloonTip), 5000, this.Text, "작업을 끝냈어요!!", ToolTipIcon.Info);
                                continue;
                            }

                            if (token.IsCancellationRequested)
                            {
                                return;
                            }

                            if (file != null)
                            {
                                file.SetStatus();
                                result = SearchImage(wc, file, writer, token);

                                if (token.IsCancellationRequested)
                                {
                                    return;
                                }

                                file.State = result;
                                file.SetStatus();

                                Interlocked.Increment(ref this.m_taskbarVal);

                                this.SetProgress();
                            }
                            else
                            {
                                Thread.Sleep(50);
                            }
                        }
                    }
                    catch
                    {
                    }
                }
        }