public void TestAsin()
 {
     WebQueryFactory wqf = new WebQueryFactory(null);
     IWebQuery wq = wqf.FromAlbumDescriptor(Albums[0][0]);
     wq.NeedCoverArt = true;
     var res = _Amf.Search(wq, new CancellationToken ()).ToList();
     Assert.That(res.Count, Is.EqualTo(1));
     var ress = res.FirstOrDefault();
     Assert.That(ress, Is.Not.Null);
     AssertAlbumDescriptor(ress.FindItem,Albums[1][0],  AlbumDescriptorCompareMode.AlbumandTrackMD);
 }
        public void TestName1()
        {
            WebQueryFactory wqf = new WebQueryFactory(null);
            IWebQuery wq = wqf.FromAlbumDescriptor(Albums[0][1]);
            wq.NeedCoverArt = false;
            var res = _Amf.Search(wq, new CancellationToken()).ToList();
            Assert.That(res.Count, Is.AtLeast(1));
            //var ress = res.FirstOrDefault(a => a.FindItem.Asin == "B000038I5D");

            var ress = res.FirstOrDefault(
                a => a.FindItem.Asin == "B000038I5D" ||
                a.FindItem.Asin == "B00006BNF2" ||
                a.FindItem.Asin == "B00F5AH8QY");

            Assert.That(ress, Is.Not.Null);
            //AssertAlbumDescriptor(ress.FindItem,Albums[1][1],  AlbumDescriptorCompareMode.AlbumandTrackMD);

        }
        public void StringAlbumParserTester()
        {
            int i = 0;
            foreach(IFullAlbumDescriptor ifua in AlbumsOld[0])
            {
                Discogs2Finder dh = new Discogs2Finder(new StandardWebSettings());
                IWebQuery iwq = new WebQueryFactory(null).FromAlbumDescriptor(ifua);
                //iwq.NeedCoverArt = true;
                iwq.NeedCoverArt = false;
                var res = dh.Search(iwq, new CancellationToken ());
                if (i==0)
                {
                    res.Any().Should().BeTrue();
                }
                
                if (i == 1)
                {
                    List<Match<AlbumDescriptor>> reses = res.ToList();
                    Assert.That(reses.Count, Is.EqualTo(1));
                    Assert.That(reses[0].FindItem.Genre, Is.EqualTo("Jazz"));
                    Assert.That(reses[0].FindItem.Name, Is.EqualTo(ifua.Name));

                    //InternetFinder idf = new InternetFinder(Context.WebServicesManager);
                    //idf.Query = iwq;
                    //idf.Compute(true);

                    //List<WebMatch<IFullAlbumDescriptor>> ress = idf.Result.Found;
                    //Assert.That(ress.Count, Is.AtLeast(1));
                    //WebMatch<IFullAlbumDescriptor> discogs = ress.Where(o => o.WebProvider == "Discogs").FirstOrDefault();
                    //Assert.That(discogs, Is.Not.Null);
                    //AssertAlbumDescriptor(reses[0].FindItem, discogs.FindItem, AlbumDescriptorCompareMode.AlbumandTrackMD);
                }
                i++;
                dh.Dispose();
            }

 
        }
        public void Test_LetsGoHaking_NotNullStreamResponse_ResponseK0_MultipleReasons()
        {
            //arrange 
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("210 ok.");
            sb.AppendLine("rock d009fb1f The Beatles / White Album");
            sb.AppendLine("rock d239fb1f The Beatles / White Albumss");
            sb.AppendLine("rock d639fb1f The Beatles / White Albumss");
            sb.AppendLine("rock d839fb1f The Beatles / White Albumss");

            IInternetProvider wrb = Substitute.For<IInternetProvider>();
            IHttpWebRequest first = IHttpWebRequestOKBuilder(sb.ToString());
            IHttpWebRequest second = IHttpWebRequestOKBuilder("titi");
            IHttpWebRequest third = IHttpWebRequestOKBuilder((Stream)null);
            IHttpWebRequest fourth = IHttpWebRequestOKBuilder("500 ko");
            IHttpWebRequest finth = IHttpWebRequestOKBuilder("590 ko");

            wrb.CreateHttpRequest(Arg.Any<string>()).Returns(first, second, third, fourth, finth);
            InternetProvider.InternetHelper = wrb;

            FreedbFinder fdb = new FreedbFinder(new ManualSettings().WebUserSettings);

            Fake cdif = new Fake(_Track_frame_offsets, _Disc_length, _ID);

            IWebQuery iwq = new WebQueryFactory(null).FromCDInfo(cdif);
            iwq.NeedCoverArt = false;

            fdb.MonitorEvents();

            //act
            List<Match<AlbumDescriptor>> reses = fdb.Search(iwq, new CancellationToken()).ToList();

            //assert
            Assert.That(reses.Count, Is.EqualTo(0));
            fdb.ShouldRaise("OnInternetError");

            fdb.Dispose();

        }
        public void Test_LetsGoHaking_NotNullStreamResponse_Sever500()
        {
            //arrange 

            SetUpMyFakeAnswer("500 ko");

            FreedbFinder fdb = new FreedbFinder(new ManualSettings().WebUserSettings);

            Fake cdif = new Fake(_Track_frame_offsets, _Disc_length, _ID);

            IWebQuery iwq = new WebQueryFactory(null).FromCDInfo(cdif);
            iwq.NeedCoverArt = false;

            fdb.MonitorEvents();

            //act
            List<Match<AlbumDescriptor>> reses = fdb.Search(iwq, new CancellationToken()).ToList();

            //assert
            Assert.That(reses.Count, Is.EqualTo(0));
  
            fdb.Dispose();

        }
        public void Test_LetsGoHaking_NotNullStreamResponse()
        {
            //arrange 
            IInternetProvider wrb = Substitute.For<IInternetProvider>();
            IHttpWebRequest wr = Substitute.For<IHttpWebRequest>();
            wr.Headers.Returns(new System.Collections.Specialized.NameValueCollection());
            wr.GetRequestStream().Returns(new MemoryStream());

            IHttpWebResponse wres = Substitute.For<IHttpWebResponse>();
            wres.StatusCode.Returns(HttpStatusCode.OK);
            wres.GetResponseStream().Returns(new MemoryStream());
            wr.GetResponse().Returns(wres);


            wrb.CreateHttpRequest(Arg.Any<string>()).Returns(wr);

            InternetProvider.InternetHelper = wrb;


            FreedbFinder fdb = new FreedbFinder(new ManualSettings().WebUserSettings);

            Fake cdif = new Fake(_Track_frame_offsets, _Disc_length, _ID);


            IWebQuery iwq = new WebQueryFactory(null).FromCDInfo(cdif);
            iwq.NeedCoverArt = false;

            fdb.MonitorEvents();

            //act
            List<Match<AlbumDescriptor>> reses = fdb.Search(iwq, new CancellationToken()).ToList();

            //assert
            Assert.That(reses.Count, Is.EqualTo(0));
            fdb.ShouldRaise("OnInternetError").WithSender(fdb);

            fdb.Dispose();

        }
        public void Test()
        {
            FreedbFinder fdb = new FreedbFinder(new ManualSettings().WebUserSettings);

            Fake cdif = new Fake(_Track_frame_offsets, _Disc_length, _ID);


            IWebQuery iwq = new WebQueryFactory(null).FromCDInfo(cdif);
            iwq.NeedCoverArt = false;
            List<Match<AlbumDescriptor>> reses = fdb.Search(iwq, new CancellationToken()).ToList();


            Assert.That(reses.Count, Is.EqualTo(1));
            this.AssertAlbumDescriptor(reses[0].FindItem, AlbumsOld[1][0], AlbumDescriptorCompareMode.AlbumandTrackMD);

            fdb.Dispose();

        }
        public void TestName2()
        {
            WebQueryFactory wqf = new WebQueryFactory(null);
            IWebQuery wq = wqf.FromAlbumDescriptor(Albums[0][2]);
            wq.NeedCoverArt = false;
            var res = _Amf.Search(wq, new CancellationToken()).ToList();
            Assert.That(res.Count, Is.AtLeast(1));
            //a.FindItem.Asin == "B000002ADT" ||
            var ress = res.Where(a=>a.FindItem.TrackDescriptors.Count==5).FirstOrDefault(a =>  a.FindItem.Asin == "B00000DS40" || a.FindItem.Asin == "B003R9PDT4");
            Assert.That(ress, Is.Not.Null);
            //AssertAlbumDescriptor(ress.FindItem, Albums[1][2], AlbumDescriptorCompareMode.AlbumandTrackMD);

            AssertAlbumDescriptor(ress.FindItem, Albums[1][3], AlbumDescriptorCompareMode.AlbumandTrackMD);
        }
        protected override ImporterConverterAbstract GetNext(IEventListener iel, CancellationToken iCancellationToken)
        {
            int CDnumber = _IMusicConverter.GetDriverNumber(_Driver);

            if (!CDHelper.CanOpenCDDoor(CDnumber))
            {
                //ca pue un lecteur de cd qu'on ne peut pas ouvrir
                //je ne fair rien dans ce cas (cle 3G?)
                Trace.WriteLine("Problem due to device detected as CD driver");
                return null;
            }

            using (CDLocker cdl = CDLocker.GetLocker(CDnumber))
            {
                if (!cdl.IsOK)
                {
                    iel.Report(new NoCDInsertedArgs());
                    Trace.WriteLine("CD driver not ready");
                    return null;
                }

                if (!CDHelper.IsCDAudio(CDnumber))
                {
                    iel.Report(new NoCDAudioInsertedArgs());
                    System.Diagnostics.Trace.WriteLine("CD not audio");
                    return null;
                }

                iel.Report(new CDIndentifyingProgessEventArgs());

                CDInfoHandler cih = new CDInfoHandler(CDnumber);

                IEnumerable<MatchAlbum> albums = Context.FindFromHashes(cih.IDs.RawHash);
                if (albums.Any())
                {
                    OtherAlbumsConfirmationNeededEventArgs error = new OtherAlbumsConfirmationNeededEventArgs(albums);
                    iel.Report(error);

                    System.Diagnostics.Trace.WriteLine("CD potentially aleady imported");

                    if (!error.Continue)
                    {
                        System.Diagnostics.Trace.WriteLine("stopping import");
                        return null;
                    }
                }

                IWebQuery webq = Context.Session.WebQueryFactory.FromCDInfo(cih);
                webq.NeedCoverArt = false;
                IInternetFinder ifn = Context.Session.GetInternetFinder(webq);
                ifn.Compute(iCancellationToken,null);

                AmbigueousCDInformationArgs acfi = new AmbigueousCDInformationArgs(ifn.Result.Found, AlbumDescriptor.CreateBasicFromCD(cih, Context));

                iel.Report(acfi);

                if (!acfi.Continue)
                    return null;

                AlbumDescriptor ifad = acfi.SelectedInfo as AlbumDescriptor;

                iel.Report(new CDImportingProgessEventArgs(ifad.Name));

                ifad.MergeIDsFromCDInfos(cih);

                IMusicfilesConverter IMC = _IMusicConverter.GetCDMusicConverter(ifad, Context.Folders.File, false, CDnumber);

                if (IMC == null)
                {
                    TimeSpan ts = TimeSpan.FromSeconds(7);
                    int repeat = 0;
                    int Maxtent = 3;
                    while ((IMC == null) && (repeat < Maxtent))
                    {
                        bool Forcebute = repeat == (Maxtent - 1);
                        Thread.Sleep(ts);
                        IMC = _IMusicConverter.GetCDMusicConverter(ifad, Context.Folders.File, Forcebute, CDnumber);
                        repeat++;
                        Trace.WriteLine(string.Format("Trial {0} to get CDMusicConverter, Forcebute {1} success {2}", repeat, Forcebute, (IMC == null)));
                        ts = TimeSpan.FromSeconds(ts.TotalSeconds * 3);
                    }

                    if (IMC == null)
                    {
                        System.Diagnostics.Trace.WriteLine("no importer returned");
                        iel.Report(new CDInUse());
                        return null;
                    }
                }

                Action ParrallelCoverLoading = null;

                IList<WebMatch<IFullAlbumDescriptor>> resultwithimage = null;

                if (acfi.PreprocessedWebInfo != null)
                {
                    resultwithimage = acfi.PreprocessedWebInfo;
                    ParrallelCoverLoading = () => acfi.PreprocessedWebInfo.Apply(wr => wr.FindItem.LoadImages());
                }
                else
                {
                    IWebQuery webqim = new WebQueryFactory(Context.Session).FromAlbumDescriptor(ifad);
                    webqim.NeedCoverArt = true;

                    IInternetFinder ifni = Context.Session.GetInternetFinder(webqim);

                    resultwithimage = new List<WebMatch<IFullAlbumDescriptor>>();

                    if (ifad.HasImage())
                    {
                        resultwithimage.Add(new WebMatch<IFullAlbumDescriptor>(ifad, MatchPrecision.Suspition, acfi.Provider));
                    }

                    ParrallelCoverLoading = () => { ifad.LoadImages(); ifni.Compute(iCancellationToken,null); resultwithimage.AddCollection(ifni.Result.Found); };
                }

                int TN = ifad.TrackDescriptors.Count;

                IAsyncResult ias = ParrallelCoverLoading.BeginInvoke(null, null);

                bool feedbacknegative = false;

                IProgress<TrackConverted> progress = new SimpleProgress<TrackConverted>
                ( (e) =>
                    {
                        iel.Report(new ConvertProgessEventArgs(ifad.Name, (int)e.Track.TrackNumber, TN));
                        if (e.OK)
                        {
                            _TDs.Add(e.Track);
                        }
                        else
                        {
                            feedbacknegative = true;
                            iel.OnFactorisableError<UnableToConvertFile>(e.Track.Name);
                        }
                    }
                );

                bool convres = IMC.ConvertTomp3(progress, iCancellationToken);

                if ((convres == false) && (_TDs.Count == 0) && (feedbacknegative == false))
                {
                    iel.Report(new CDUnknownErrorArgs());
                    return null;
                }

                if (iCancellationToken.IsCancellationRequested)
                {
                    return null;
                }

                if (!ias.IsCompleted)
                {
                    iel.Report(new CDImportingProgessAdditionalCoverInfoEventArgs(ifad));
                }

                if (_OpenCDDoorOnComplete)
                    CDHelper.OpenCDDoor();

                bool okfound = ias.AsyncWaitHandle.WaitOne(TimeSpan.FromMinutes(3), false);
                //j'attends pas plus de 1 minute apres avoir grave le cd pour trouver
                //les pochettes sur internet
 
                Trace.WriteLine(string.Format("CD import cover from internet time out result (false:timedout): {0}!", okfound));

                if (resultwithimage != null)
                {             
                    int tracknumber = ifad.RawTrackDescriptors.Count;           
                    var images = resultwithimage.Where(wr => ((wr.FindItem.MatchTrackNumberOnDisk(tracknumber)) && (wr.FindItem.Images != null) && (wr.FindItem.Images.Count > 0))).ToList();

                    if (images.Count > 0)
                    {
                        Trace.WriteLine(string.Format("{0} Image(s) found!!", images.Count));

                        CDCoverInformationArgs cdfi = new CDCoverInformationArgs(images, ifad);
                        iel.Report(cdfi);
                    }
                    else
                    {
                        Trace.WriteLine(string.Format("Information found but no matching image found for CD:{0} !",ifad));
                    }
                }
                else
                {
                    Trace.WriteLine("No image found for CD!");
                }

                Trace.WriteLine("Import CD OK");

                return new MusicWithMetadaImporter(_TDs.ToArray(), new List<string>(), new ICDInfosHelperAdpt(ifad));
            }
        }