Пример #1
0
        public async Task<string> GetFile(FileLocation fileLocation) {
            logger.debug("Getting file {0}", fileLocation);
            if(fileLocation.Constructor == Constructor.fileLocation) {
                FileLocationConstructor location = (FileLocationConstructor) fileLocation;
                string filePath = FileLocationToCachePath(location);
                using(IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication()) {
                    if(!storage.DirectoryExists("cache")) {
                        storage.CreateDirectory("cache");
                    }

                    if(storage.FileExists(filePath)) {
                        logger.debug("Getting file {0} from cache", filePath);
                        return filePath;
                    }

                    TLApi api = await session.GetFileSession(location.dc_id);
                    logger.debug("Got file session for dc {0}", location.dc_id);

                    Upload_fileConstructor file = (Upload_fileConstructor) await api.upload_getFile(TL.inputFileLocation(location.volume_id, location.local_id, location.secret), 0, int.MaxValue);

                    logger.debug("File constructor found");

                    using (Stream fileStream = new IsolatedStorageFileStream(filePath, FileMode.OpenOrCreate,
                                                                          FileAccess.Write, storage)) {
                        await fileStream.WriteAsync(file.bytes, 0, file.bytes.Length);
                    }

                    logger.debug("File saved successfully");
                    return filePath;
                }
            } else {
                throw new MTProtoFileUnavailableException();
            }
        }
			public async void downloadFileAsync(string url, IsolatedStorageFileStream filestream) {
				SynchronizationContext ctx = SynchronizationContext.Current;
				HttpWebRequest request = (HttpWebRequest)WebRequest.CreateHttp(new Uri(url));
				request.Method = "GET";

				Logger.log("DownloadRequestHandler", "Downloading " + url + " asynchronously...");

				request.BeginGetResponse(async callbackResult => {
					try {
						HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(callbackResult);
						Logger.log("DownloadRequestHandler", "Status: " + (int)response.StatusCode + " " + response.StatusDescription);
						if (response.Headers["Content-Length"] != null) {
							Logger.log("DownloadRequestHandler", "Content length: " + response.Headers["Content-Length"]);
						} else {
							Logger.log("DownloadRequestHandler", "Content length: unknown");
						}

						Stream responseStream = response.GetResponseStream();
						BinaryReader br = new BinaryReader(responseStream);
						int responseBufferSize = 4096;
						int responseBytesRead = 0;
						int responseTotalBytesRead = 0;
						byte[] responseBuffer = new byte[responseBufferSize];

						while ((responseBytesRead = br.Read(responseBuffer, 0, responseBuffer.Length)) > 0) {
							responseTotalBytesRead += responseBytesRead;
							await filestream.WriteAsync(responseBuffer, 0, responseBuffer.Length);
						}
						filestream.Close();

						Logger.log("DownloadRequestHandler", "Wrote " + responseTotalBytesRead + " bytes");

						DownloadFileEventArgs args = new DownloadFileEventArgs();
						args.file = filestream.Name;
						args.size = responseTotalBytesRead;

						ctx.Post(result => {
							DownloadFile df = (DownloadFile)callbackResult.AsyncState;
							df.OnComplete((DownloadFileEventArgs)result);
						}, args);

					} catch (WebException ex) {
						// check if we have an expired or self-signed cert
						if (ex.Status == WebExceptionStatus.UnknownError) {
							if (ex.Response.Headers.Count == 0) {
								Logger.log("DownloadRequestHandler", "Invalid SSL certificate, returning a 400 Bad Request");
								throw new Exception("Download Handler Exception: Invalid SSL certificate, returning a 400 Bad Request");
							} else {
								Logger.log("DownloadRequestHandler", "File not found, returning a 404");
								throw new Exception("Download Handler Exception: File not found, returning a 404");
							}
						} else {
							Logger.log("DownloadRequestHandler", "400 Bad Request");
							Logger.log("DownloadRequestHandler", ex.Status.ToString());
							throw;
						}
					}
				}, this);
			}