public void ContactDB(string server, string userAgent, string driveName, bool ctdb, bool fuzzy, CTDBMetadataSearch metadataSearch)
		{
			this.driveName = driveName;
			this.userAgent = userAgent + " (" + Environment.OSVersion.VersionString + ")" + (driveName != null ? " (" + driveName + ")" : "");
			this.urlbase = "http://" + (server ?? defaultServer);
			this.total = 0;

			HttpWebRequest req = (HttpWebRequest)WebRequest.Create(urlbase
				+ "/lookup2.php"
                + "?version=2"
                + "&ctdb=" + (ctdb ? 1 : 0)
                + "&fuzzy=" + (fuzzy ? 1 : 0)
				+ "&metadata=" + (metadataSearch == CTDBMetadataSearch.None ? "none" : metadataSearch == CTDBMetadataSearch.Fast ? "fast" : metadataSearch == CTDBMetadataSearch.Default ? "default" : "extensive")
				+ "&toc=" + toc.ToString());
			req.Method = "GET";
			req.Proxy = proxy;
			req.UserAgent = this.userAgent;
			req.Timeout = connectTimeout;
			req.ReadWriteTimeout = socketTimeout;
			req.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;

			if (uploadHelper.onProgress != null)
				uploadHelper.onProgress(this, new UploadProgressEventArgs(req.RequestUri.AbsoluteUri, 0));

            this.entries = new List<DBEntry>();
            this.metadata = new List<CTDBResponseMeta>();
			currentReq = req;
			try
			{
				using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
				{
					this.QueryExceptionStatus = WebExceptionStatus.ProtocolError;
					this.QueryResponseStatus = resp.StatusCode;
                    this.QueryExceptionMessage = resp.StatusDescription;
					if (this.QueryResponseStatus == HttpStatusCode.OK)
					{
						XmlSerializer serializer = new XmlSerializer(typeof(CTDBResponse));
						this.total = 0;
						using (Stream responseStream = resp.GetResponseStream())
						{
							CTDBResponse ctdbResp = serializer.Deserialize(responseStream) as CTDBResponse;
							if (ctdbResp.entry != null)
								foreach (var ctdbRespEntry in ctdbResp.entry)
								{
									if (ctdbRespEntry.toc == null)
										continue;
                                    this.total += ctdbRespEntry.confidence;
                                    var entry = new DBEntry(ctdbRespEntry);
									entries.Add(entry);
								}
							if (ctdbResp.metadata != null && ctdbResp.metadata.Length != 0)
								metadata.AddRange(ctdbResp.metadata);
						}
						if (entries.Count == 0)
							this.QueryResponseStatus = HttpStatusCode.NotFound;
						else
							this.QueryExceptionStatus = WebExceptionStatus.Success;
					}
				}
			}
			catch (WebException ex)
			{
				this.QueryExceptionStatus = ex.Status;
				this.QueryExceptionMessage = ex.Message;
                if (this.QueryExceptionStatus == WebExceptionStatus.ProtocolError)
                {
                    this.QueryResponseStatus = (ex.Response as HttpWebResponse).StatusCode;
                    this.QueryExceptionMessage = (ex.Response as HttpWebResponse).StatusDescription;
                }
			}
			catch (Exception ex)
			{
				this.QueryExceptionStatus = WebExceptionStatus.UnknownError;
				this.QueryExceptionMessage = ex.Message;
			}
			finally
			{
				currentReq = null;
			}
		}
        protected CTDBResponse DoSubmit(int confidence, int quality, string artist, string title, string barcode, bool upload, DBEntry confirm, int npar)
        {
            var files = new List<UploadFile>();
            long maxId = 0;
            foreach (var e in this.entries)
            {
                maxId = Math.Max(maxId, e.id);
            }

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(urlbase + "/submit2.php");
            req.Proxy = proxy;
            req.UserAgent = this.userAgent;
            req.Timeout = connectTimeout;
            req.ReadWriteTimeout = socketTimeout;
            NameValueCollection form = new NameValueCollection();
            int offset = 0;
            if (confirm != null)
            {
                offset = -confirm.offset;

#if DEBUG
                // Optional sanity check: should be done by server                
                if (verify.AR.CTDBCRC(offset) != confirm.crc)
                    throw new Exception("crc mismatch");

                if (confirm.trackcrcs != null)
                {
                    bool crcEquals = true;
                    for (int i = 0; i < confirm.trackcrcs.Length; i++)
                        crcEquals &= verify.TrackCRC(i + 1, offset) == confirm.trackcrcs[i];
                    if (!crcEquals)
                        throw new Exception("track crc mismatch");
                }

                var syn2 = verify.AR.GetSyndrome(confirm.Npar, 1, offset);
                bool equals = true;
                for (int i = 0; i < confirm.Npar; i++)
                    equals &= confirm.syndrome[0, i] == syn2[0, i];
                if (!equals)
                    throw new Exception("syndrome mismatch");
#endif
            }
            if (upload)
            {
                files.Add(new UploadFile(new MemoryStream(ParityToSyndrome.Syndrome2Bytes(verify.AR.GetSyndrome(npar, -1, offset))), "parityfile", "data.bin", "application/octet-stream"));
                form.Add("parityfile", "1");
            }
            form.Add("parity", Convert.ToBase64String(ParityToSyndrome.Syndrome2Parity(verify.AR.GetSyndrome(8, 1, offset))));
            form.Add("syndrome", Convert.ToBase64String(ParityToSyndrome.Syndrome2Bytes(verify.AR.GetSyndrome(npar, 1, offset))));
            if (confirm != null)
                form.Add("confirmid", confirm.id.ToString());
            form.Add("ctdb", "2");
            form.Add("npar", npar.ToString());
            form.Add("maxid", maxId.ToString());
            form.Add("toc", toc.ToString());
            form.Add("crc32", ((int)verify.AR.CTDBCRC(offset)).ToString());
            form.Add("trackcrcs", verify.GetTrackCRCs(offset));
            form.Add("confidence", confidence.ToString());
            form.Add("userid", GetUUID());
            form.Add("quality", quality.ToString());
            if (driveName != null && driveName != "") form.Add("drivename", driveName);
            if (barcode != null && barcode != "") form.Add("barcode", barcode);
            if (artist != null && artist != "") form.Add("artist", artist);
            if (title != null && title != "") form.Add("title", title);

            currentReq = req;
            try
            {
                using (HttpWebResponse resp = uploadHelper.Upload(req, files.ToArray(), form))
                {
                    if (resp.StatusCode == HttpStatusCode.OK)
                    {
                        using (Stream s = resp.GetResponseStream())
                        {
                            var serializer = new XmlSerializer(typeof(CTDBResponse));
                            return serializer.Deserialize(s) as CTDBResponse;
                        }
                    }
                    else
                    {
                        return new CTDBResponse() { status = "database access error", message = resp.StatusCode.ToString() };
                    }
                }
            }
            catch (WebException ex)
            {
                return new CTDBResponse() { status = "database access error", message = ex.Message ?? ex.Status.ToString() };
            }
            catch (Exception ex)
            {
                return new CTDBResponse() { status = "database access error", message = ex.Message };
            }
            finally
            {
                currentReq = null;
            }
        }
		public ushort[,] FetchDB(DBEntry entry, int npar, ushort[,] syn)
		{
			string url = entry.hasParity[0] == '/' ? urlbase + entry.hasParity : entry.hasParity;
			HttpWebRequest req = (HttpWebRequest)WebRequest.Create(url);
            int prevLen = syn == null ? 0 : syn.GetLength(1) * entry.stride * 2;
			req.Method = "GET";
			req.Proxy = proxy;
			req.UserAgent = this.userAgent;
			req.Timeout = connectTimeout;
			req.ReadWriteTimeout = socketTimeout;
			req.AutomaticDecompression = DecompressionMethods.None;
            req.AddRange(prevLen, npar * entry.stride * 2 - 1);

			currentReq = req;
            try
            {
                using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
                {
                    if (resp.StatusCode != HttpStatusCode.OK && resp.StatusCode != HttpStatusCode.PartialContent)
                    {
                        entry.httpStatus = resp.StatusCode;
                        return null;
                    }
                    if (resp.StatusCode == HttpStatusCode.OK && resp.ContentLength == entry.Npar * entry.stride * 2)
                    {
                        npar = entry.Npar;
                        prevLen = 0;
                        syn = null;
                    }
                    else if (resp.StatusCode != HttpStatusCode.PartialContent || (resp.ContentLength + prevLen) != npar * entry.stride * 2)
                    {
                        entry.httpStatus = HttpStatusCode.PartialContent;
                        return null;
                    }

                    using (Stream responseStream = resp.GetResponseStream())
                    {
                        byte[] contents = syn == null ? null : ParityToSyndrome.Syndrome2Bytes(syn);
                        Array.Resize(ref contents, prevLen + (int)resp.ContentLength);
                        int pos = prevLen, count = 0;
                        do
                        {
                            if (uploadHelper.onProgress != null)
                                uploadHelper.onProgress(url, new UploadProgressEventArgs(req.RequestUri.AbsoluteUri, ((double)pos) / (entry.Npar * entry.stride * 2)));
                            count = responseStream.Read(contents, pos, Math.Min(contents.Length - pos, 32768));
                            pos += count;
                        } while (count != 0);

                        if (pos != contents.Length)
                        {
                            entry.httpStatus = HttpStatusCode.PartialContent;
                            return null;
                        }

                        syn = ParityToSyndrome.Bytes2Syndrome(entry.stride, npar, contents);
                        for (int i = 0; i < npar; i++)
                            if (syn[0, i] != entry.syndrome[0, i])
                            {
                                entry.httpStatus = HttpStatusCode.Conflict;
                                return null;
                            }
                        entry.httpStatus = HttpStatusCode.OK;
                        return syn;
                    }
                }
            }
            catch (WebException ex)
            {
                if (ex.Status == WebExceptionStatus.ProtocolError)
                    entry.httpStatus = ((HttpWebResponse)ex.Response).StatusCode;
                else
                    entry.httpStatus = HttpStatusCode.BadRequest;
            }
			finally
			{
				currentReq = null;
			}
            return null;
		}
Exemple #4
0
        public void ContactDB(string server, string userAgent, string driveName, bool ctdb, bool fuzzy, CTDBMetadataSearch metadataSearch)
        {
            this.driveName = driveName;
            this.userAgent = userAgent + " (" + Environment.OSVersion.VersionString + ")" + (driveName != null ? " (" + driveName + ")" : "");
            this.urlbase   = "http://" + (server ?? defaultServer);
            this.total     = 0;

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(urlbase
                                                                   + "/lookup2.php"
                                                                   + "?version=3"
                                                                   + "&ctdb=" + (ctdb ? 1 : 0)
                                                                   + "&fuzzy=" + (fuzzy ? 1 : 0)
                                                                   + "&metadata=" + (metadataSearch == CTDBMetadataSearch.None ? "none" : metadataSearch == CTDBMetadataSearch.Fast ? "fast" : metadataSearch == CTDBMetadataSearch.Default ? "default" : "extensive")
                                                                   + "&toc=" + toc.ToString());

            req.Method                 = "GET";
            req.Proxy                  = proxy;
            req.UserAgent              = this.userAgent;
            req.Timeout                = connectTimeout;
            req.ReadWriteTimeout       = socketTimeout;
            req.AutomaticDecompression = DecompressionMethods.Deflate | DecompressionMethods.GZip;

            if (uploadHelper.onProgress != null)
            {
                uploadHelper.onProgress(this, new UploadProgressEventArgs(req.RequestUri.AbsoluteUri, 0));
            }

            this.subResult = null;
            this.entries   = new List <DBEntry>();
            this.metadata  = new List <CTDBResponseMeta>();
            currentReq     = req;
            try
            {
                using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
                {
                    this.QueryExceptionStatus  = WebExceptionStatus.ProtocolError;
                    this.QueryResponseStatus   = resp.StatusCode;
                    this.QueryExceptionMessage = resp.StatusDescription;
                    if (this.QueryResponseStatus == HttpStatusCode.OK)
                    {
                        //var serializer = new XmlSerializer(typeof(CTDBResponse));
                        var serializer = new Microsoft.Xml.Serialization.GeneratedAssembly.CTDBResponseSerializer();
                        this.total = 0;
                        using (Stream responseStream = resp.GetResponseStream())
                        {
                            CTDBResponse ctdbResp = serializer.Deserialize(responseStream) as CTDBResponse;
                            if (ctdbResp.entry != null)
                            {
                                foreach (var ctdbRespEntry in ctdbResp.entry)
                                {
                                    if (ctdbRespEntry.toc == null)
                                    {
                                        continue;
                                    }
                                    this.total += ctdbRespEntry.confidence;
                                    var entry = new DBEntry(ctdbRespEntry);
                                    entries.Add(entry);
                                }
                            }
                            if (ctdbResp.metadata != null && ctdbResp.metadata.Length != 0)
                            {
                                metadata.AddRange(ctdbResp.metadata);
                            }
                        }
                        if (entries.Count == 0)
                        {
                            this.QueryResponseStatus = HttpStatusCode.NotFound;
                        }
                        else
                        {
                            this.QueryExceptionStatus = WebExceptionStatus.Success;
                        }
                    }
                }
            }
            catch (WebException ex)
            {
                this.QueryExceptionStatus  = ex.Status;
                this.QueryExceptionMessage = ex.Message;
                if (this.QueryExceptionStatus == WebExceptionStatus.ProtocolError)
                {
                    this.QueryResponseStatus   = (ex.Response as HttpWebResponse).StatusCode;
                    this.QueryExceptionMessage = (ex.Response as HttpWebResponse).StatusDescription;
                }
            }
            catch (Exception ex)
            {
                this.QueryExceptionStatus  = WebExceptionStatus.UnknownError;
                this.QueryExceptionMessage = ex.Message;
            }
            finally
            {
                currentReq = null;
            }
        }
Exemple #5
0
        protected CTDBResponse DoSubmit(int confidence, int quality, string artist, string title, string barcode, bool upload, DBEntry confirm, int npar)
        {
            var  files = new List <UploadFile>();
            long maxId = 0;

            foreach (var e in this.entries)
            {
                maxId = Math.Max(maxId, e.id);
            }

            HttpWebRequest req = (HttpWebRequest)WebRequest.Create(urlbase + "/submit2.php");

            req.Proxy            = proxy;
            req.UserAgent        = this.userAgent;
            req.Timeout          = connectTimeout;
            req.ReadWriteTimeout = socketTimeout;
            NameValueCollection form = new NameValueCollection();
            int offset = 0;

            if (confirm != null)
            {
                offset = -confirm.offset;

#if DEBUG
                // Optional sanity check: should be done by server
                if (verify.AR.CTDBCRC(offset) != confirm.crc)
                {
                    throw new Exception("crc mismatch");
                }

                if (confirm.trackcrcs != null)
                {
                    bool crcEquals = true;
                    for (int i = 0; i < confirm.trackcrcs.Length; i++)
                    {
                        crcEquals &= verify.TrackCRC(i + 1, offset) == confirm.trackcrcs[i];
                    }
                    if (!crcEquals)
                    {
                        throw new Exception("track crc mismatch");
                    }
                }

                var  syn2   = verify.AR.GetSyndrome(confirm.Npar, 1, offset);
                bool equals = true;
                for (int i = 0; i < confirm.Npar; i++)
                {
                    equals &= confirm.syndrome[0, i] == syn2[0, i];
                }
                if (!equals)
                {
                    throw new Exception("syndrome mismatch");
                }
#endif
            }
            if (upload)
            {
                files.Add(new UploadFile(new MemoryStream(ParityToSyndrome.Syndrome2Bytes(verify.AR.GetSyndrome(npar, -1, offset))), "parityfile", "data.bin", "application/octet-stream"));
                form.Add("parityfile", "1");
            }
            form.Add("parity", Convert.ToBase64String(ParityToSyndrome.Syndrome2Parity(verify.AR.GetSyndrome(8, 1, offset))));
            form.Add("syndrome", Convert.ToBase64String(ParityToSyndrome.Syndrome2Bytes(verify.AR.GetSyndrome(npar, 1, offset))));
            if (confirm != null)
            {
                form.Add("confirmid", confirm.id.ToString());
            }
            form.Add("ctdb", "2");
            form.Add("npar", npar.ToString());
            form.Add("maxid", maxId.ToString());
            form.Add("toc", toc.ToString());
            form.Add("crc32", ((int)verify.AR.CTDBCRC(offset)).ToString());
            form.Add("trackcrcs", verify.GetTrackCRCs(offset));
            form.Add("confidence", confidence.ToString());
            form.Add("userid", GetUUID());
            form.Add("quality", quality.ToString());
            if (driveName != null && driveName != "")
            {
                form.Add("drivename", driveName);
            }
            if (barcode != null && barcode != "")
            {
                form.Add("barcode", barcode);
            }
            if (artist != null && artist != "")
            {
                form.Add("artist", artist);
            }
            if (title != null && title != "")
            {
                form.Add("title", title);
            }

            currentReq = req;
            try
            {
                using (HttpWebResponse resp = uploadHelper.Upload(req, files.ToArray(), form))
                {
                    if (resp.StatusCode == HttpStatusCode.OK)
                    {
                        using (Stream s = resp.GetResponseStream())
                        {
                            //var serializer = new XmlSerializer(typeof(CTDBResponse));
                            var serializer = new Microsoft.Xml.Serialization.GeneratedAssembly.CTDBResponseSerializer();
                            return(serializer.Deserialize(s) as CTDBResponse);
                        }
                    }
                    else
                    {
                        return(new CTDBResponse()
                        {
                            status = "database access error", message = resp.StatusCode.ToString()
                        });
                    }
                }
            }
            catch (WebException ex)
            {
                return(new CTDBResponse()
                {
                    status = "database access error", message = ex.Message ?? ex.Status.ToString()
                });
            }
            catch (Exception ex)
            {
                return(new CTDBResponse()
                {
                    status = "database access error", message = ex.Message
                });
            }
            finally
            {
                currentReq = null;
            }
        }
Exemple #6
0
        public ushort[,] FetchDB(DBEntry entry, int npar, ushort[,] syn)
        {
            string         url     = entry.hasParity[0] == '/' ? urlbase + entry.hasParity : entry.hasParity;
            HttpWebRequest req     = (HttpWebRequest)WebRequest.Create(url);
            int            prevLen = syn == null ? 0 : syn.GetLength(1) * entry.stride * 2;

            req.Method                 = "GET";
            req.Proxy                  = proxy;
            req.UserAgent              = this.userAgent;
            req.Timeout                = connectTimeout;
            req.ReadWriteTimeout       = socketTimeout;
            req.AutomaticDecompression = DecompressionMethods.None;
            req.AddRange(prevLen, npar * entry.stride * 2 - 1);

            currentReq = req;
            try
            {
                using (HttpWebResponse resp = (HttpWebResponse)req.GetResponse())
                {
                    if (resp.StatusCode != HttpStatusCode.OK && resp.StatusCode != HttpStatusCode.PartialContent)
                    {
                        entry.httpStatus = resp.StatusCode;
                        return(null);
                    }
                    if (resp.StatusCode == HttpStatusCode.OK && resp.ContentLength == entry.Npar * entry.stride * 2)
                    {
                        npar    = entry.Npar;
                        prevLen = 0;
                        syn     = null;
                    }
                    else if (resp.StatusCode != HttpStatusCode.PartialContent || (resp.ContentLength + prevLen) != npar * entry.stride * 2)
                    {
                        entry.httpStatus = HttpStatusCode.PartialContent;
                        return(null);
                    }

                    using (Stream responseStream = resp.GetResponseStream())
                    {
                        byte[] contents = syn == null ? null : ParityToSyndrome.Syndrome2Bytes(syn);
                        Array.Resize(ref contents, prevLen + (int)resp.ContentLength);
                        int pos = prevLen, count = 0;
                        do
                        {
                            if (uploadHelper.onProgress != null)
                            {
                                uploadHelper.onProgress(url, new UploadProgressEventArgs(req.RequestUri.AbsoluteUri, ((double)pos) / (entry.Npar * entry.stride * 2)));
                            }
                            count = responseStream.Read(contents, pos, Math.Min(contents.Length - pos, 32768));
                            pos  += count;
                        } while (count != 0);

                        if (pos != contents.Length)
                        {
                            entry.httpStatus = HttpStatusCode.PartialContent;
                            return(null);
                        }

                        syn = ParityToSyndrome.Bytes2Syndrome(entry.stride, npar, contents);
                        for (int i = 0; i < npar; i++)
                        {
                            if (syn[0, i] != entry.syndrome[0, i])
                            {
                                entry.httpStatus = HttpStatusCode.Conflict;
                                return(null);
                            }
                        }
                        entry.httpStatus = HttpStatusCode.OK;
                        return(syn);
                    }
                }
            }
            catch (WebException ex)
            {
                if (ex.Status == WebExceptionStatus.ProtocolError)
                {
                    entry.httpStatus = ((HttpWebResponse)ex.Response).StatusCode;
                }
                else
                {
                    entry.httpStatus = HttpStatusCode.BadRequest;
                }
            }
            finally
            {
                currentReq = null;
            }
            return(null);
        }