Exemplo n.º 1
0
        // 新增一个上传任务(一次请求上传一个文件)
        private async void btnAddUpload_Click(object sender, RoutedEventArgs e)
        {
            // 上传服务的地址
            Uri serverUri = new Uri("http://localhost:44914/api/Upload", UriKind.Absolute);

            StorageFile sourceFile;

            try
            {
                // 需要上传的文件
                sourceFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///Assets/hololens.jpg", UriKind.Absolute));
            }
            catch (Exception ex)
            {
                WriteLine(ex.ToString());
                return;
            }

            // 实例化 BackgroundUploader,并设置 http header
            BackgroundUploader backgroundUploader = new BackgroundUploader();

            backgroundUploader.SetRequestHeader("Filename", "hololens.jpg");

            // 任务成功后弹出指定的 toast 通知(类似的还有 SuccessTileNotification, FailureToastNotification, FailureTileNotification)
            backgroundUploader.SuccessToastNotification = GetToastNotification();

            // 创建一个后台上传任务,此任务包含一个上传文件
            UploadOperation upload = backgroundUploader.CreateUpload(serverUri, sourceFile);

            // 以流的方式创建一个后台上传任务
            // await backgroundUploader.CreateUploadFromStreamAsync(Uri uri, IInputStream sourceStream);

            // 处理并监视指定的后台上传任务
            await HandleUploadAsync(upload, true);
        }
Exemplo n.º 2
0
        private async Task <UploadOperation> synchronizePicture(Picture _picture, String _pathAlbum, int _index, TripSummary _summary)
        {
            StorageFile        _file;
            BackgroundUploader _uploader = new BackgroundUploader();
            UploadOperation    _upload   = null;

            String _request = API_FILES_PUT + "/sandbox/" + _pathAlbum + "/" + _picture.Name + _picture.Extension +
                              "?access_token=" + Token + "&overwrite=true";

            try
            {
                if (_summary.Sample)
                {
                    _file = await StorageFile.GetFileFromApplicationUriAsync(new Uri("ms-appx:///appdata/" + _summary.PathThumb + "/" + _summary.PicturesThumb[_index % 4]));
                }
                else
                {
                    _file = await StorageFile.GetFileFromPathAsync(_picture.GetPath());
                }
            }
            catch (FileNotFoundException)
            {
                return(null);
            }

            try
            {
                _upload = _uploader.CreateUpload(new Uri(_request), _file);
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.Message);
            }
            return(_upload);
        }
Exemplo n.º 3
0
        private async void UploadSingleFile(Uri uri, StorageFile file)
        {
            if (file == null)
            {
                rootPage.NotifyUser("No file selected.", NotifyType.ErrorMessage);
                return;
            }

            BasicProperties properties = await file.GetBasicPropertiesAsync();

            if (properties.Size > maxUploadFileSize)
            {
                rootPage.NotifyUser(String.Format(CultureInfo.CurrentCulture,
                                                  "Selected file exceeds max. upload file size ({0} MB).", maxUploadFileSize / (1024 * 1024)),
                                    NotifyType.ErrorMessage);
                return;
            }

            BackgroundUploader uploader = new BackgroundUploader();

            uploader.SetRequestHeader("Filename", file.Name);

            UploadOperation upload = uploader.CreateUpload(uri, file);

            Log(String.Format(CultureInfo.CurrentCulture, "Uploading {0} to {1}, {2}", file.Name, uri.AbsoluteUri,
                              upload.Guid));

            // Attach progress and completion handlers.
            await HandleUploadAsync(upload, true);
        }
        public override IHttpTask Upload(TaskConfiguration config)
        {
            if (String.IsNullOrWhiteSpace(config.LocalFilePath))
            {
                throw new ArgumentException("You must set the local file path when uploading");
            }

            if (!File.Exists(config.LocalFilePath))
            {
                throw new ArgumentException($"File '{config.LocalFilePath}' does not exist");
            }

            var task = new BackgroundUploader
            {
                Method     = config.HttpMethod,
                CostPolicy = config.UseMeteredConnection
                    ? BackgroundTransferCostPolicy.Default
                    : BackgroundTransferCostPolicy.UnrestrictedOnly
            };

            foreach (var header in config.Headers)
            {
                task.SetRequestHeader(header.Key, header.Value);
            }

            // seriously - this should not be async!
            var file      = StorageFile.GetFileFromPathAsync(config.LocalFilePath).AsTask().Result;
            var operation = task.CreateUpload(new Uri(config.Uri), file);
            var httpTask  = new UploadHttpTask(config, operation, false);

            this.Add(httpTask);

            return(httpTask);
        }
Exemplo n.º 5
0
        public async Task <DavItem> Upload(Uri url, StorageFile file)
        {
            if (!url.IsAbsoluteUri)
            {
                url = new Uri(_serverUrl, url);
            }

            BackgroundUploader uploader = new BackgroundUploader();

            uploader.CostPolicy = ExecutionContext.Instance.IsBackgroundTask
                ? BackgroundTransferCostPolicy.UnrestrictedOnly
                : BackgroundTransferCostPolicy.Always;
            uploader.Method = "PUT";
            var buffer = CryptographicBuffer.ConvertStringToBinary(_credential.UserName + ":" + _credential.Password, BinaryStringEncoding.Utf8);
            var token  = CryptographicBuffer.EncodeToBase64String(buffer);
            var value  = new HttpCredentialsHeaderValue("Basic", token);

            uploader.SetRequestHeader("Authorization", value.ToString());

            var upload = uploader.CreateUpload(url, file);
            Progress <UploadOperation> progressCallback = new Progress <UploadOperation>(async operation => await OnUploadProgressChanged(operation));
            var task  = upload.StartAsync().AsTask(progressCallback);
            var task2 = await task.ContinueWith(OnUploadCompleted);

            return(await task2);
        }
        public async Task UploadAsync(StorageFile file, int travelerId, Progress <UploadOperation> progressCallback, int reservationId, bool isPrivate)
        {
            var address     = isPrivate ? Addresses.UploadPrivateFileUri : Addresses.UploadPublicFileUri;
            Uri destination = new Uri(string.Format(address, reservationId));

            BackgroundUploader uploader = new BackgroundUploader();

            uploader.SetRequestHeader("Filename", file.Name);
            UploadOperation upload = uploader.CreateUpload(destination, file);

            UploadOperation result = await upload.StartAsync().AsTask();

            string fileUri = result.GetResponseInformation().Headers["Location"];
            await _data.CreateAzureStorageFileMetadata(fileUri, file.Name, reservationId, isPrivate, UserAuth.Instance.Traveler.TravelerId);
        }
Exemplo n.º 7
0
        public async Task UploadAsync(StorageFile sourceFile, int travelerId, int reservationId, bool isPrivate, int locationId)
        {
            var address        = isPrivate ? Addresses.UploadPrivateFileUri : Addresses.UploadPublicFileUri;
            Uri destinationUri = new Uri(string.Format(address, reservationId));

            BackgroundUploader uploader = new BackgroundUploader();

            uploader.SetRequestHeader("Filename", sourceFile.Name);
            UploadOperation upload = uploader.CreateUpload(destinationUri, sourceFile);
            await upload.StartAsync();

            var fileAddress = upload.GetResponseInformation().Headers["Location"];

            await _data.CreateAzureStorageFileMetadata(new Uri(fileAddress), sourceFile.Name, reservationId, isPrivate, travelerId, locationId);
        }
Exemplo n.º 8
0
        private async void StartUpload_Click(object sender, RoutedEventArgs e)
        {
            // By default 'serverAddressField' is disabled and URI validation is not required. When enabling the text
            // box validating the URI is required since it was received from an untrusted source (user input).
            // The URI is validated by calling Uri.TryCreate() that will return 'false' for strings that are not valid URIs.
            // Note that when enabling the text box users may provide URIs to machines on the intrAnet that require
            // the "Home or Work Networking" capability.
            Uri uri;

            if (!Uri.TryCreate(serverAddressField.Text.Trim(), UriKind.Absolute, out uri))
            {
                rootPage.NotifyUser("Invalid URI.", NotifyType.ErrorMessage);
                return;
            }

            FileOpenPicker picker = new FileOpenPicker();

            picker.FileTypeFilter.Add("*");
            StorageFile file = await picker.PickSingleFileAsync();

            if (file == null)
            {
                rootPage.NotifyUser("No file selected.", NotifyType.ErrorMessage);
                return;
            }

            BasicProperties properties = await file.GetBasicPropertiesAsync();

            if (properties.Size > maxUploadFileSize)
            {
                rootPage.NotifyUser(String.Format(CultureInfo.CurrentCulture,
                                                  "Selected file exceeds max. upload file size ({0} MB).", maxUploadFileSize / (1024 * 1024)),
                                    NotifyType.ErrorMessage);
                return;
            }

            BackgroundUploader uploader = new BackgroundUploader();

            uploader.SetRequestHeader("Filename", file.Name);

            UploadOperation upload = uploader.CreateUpload(uri, file);

            Log(String.Format(CultureInfo.CurrentCulture, "Uploading {0} to {1}, {2}", file.Name, uri.AbsoluteUri,
                              upload.Guid));

            // Attach progress and completion handlers.
            await HandleUploadAsync(upload, true);
        }
 /// <summary>
 /// Starts to upload the file as an asynchronous operation.
 /// </summary>
 /// <param name="sdkClient">The SDK client.</param>
 /// <param name="path">The path to the file.</param>
 /// <param name="file">The file.</param>
 /// <param name="progress">The progress.</param>
 public static async Task StartUploadFileAsync(this IDiskSdkClient sdkClient, string path, IStorageFile file, IProgress progress)
 {
     try
     {
         var uri      = new Uri(WebdavResources.ApiUrl + path);
         var uploader = new BackgroundUploader {
             Method = "PUT"
         };
         uploader.SetRequestHeader("Authorization", "OAuth " + sdkClient.AccessToken);
         uploader.SetRequestHeader("X-Yandex-SDK-Version", "winui, 1.0");
         var upload = uploader.CreateUpload(uri, file);
         await HandleUploadAsync(upload, progress, true);
     }
     catch (Exception ex)
     {
         throw HttpUtilities.ProcessException(ex);
     }
 }
Exemplo n.º 10
0
        private async void StartUpload_Click(object sender, RoutedEventArgs e)
        {
            // By default 'serverAddressField' is disabled and URI validation is not required. When enabling the text
            // box validating the URI is required since it was received from an untrusted source (user input).
            // The URI is validated by calling Uri.TryCreate() that will return 'false' for strings that are not valid URIs.
            // Note that when enabling the text box users may provide URIs to machines on the intrAnet that require
            // the "Home or Work Networking" capability.
            Uri uri;

            if (!Uri.TryCreate(serverAddressField.Text.Trim(), UriKind.Absolute, out uri))
            {
                rootPage.NotifyUser("Invalid URI.", NotifyType.ErrorMessage);
                return;
            }

            // Verify that we are currently not snapped, or that we can unsnap to open the picker.
            if (ApplicationView.Value == ApplicationViewState.Snapped && !ApplicationView.TryUnsnap())
            {
                rootPage.NotifyUser("File picker cannot be opened in snapped mode. Please unsnap first.", NotifyType.ErrorMessage);
                return;
            }

            FileOpenPicker picker = new FileOpenPicker();

            picker.FileTypeFilter.Add("*");
            StorageFile file = await picker.PickSingleFileAsync();

            if (file == null)
            {
                rootPage.NotifyUser("No file selected.", NotifyType.ErrorMessage);
                return;
            }

            BackgroundUploader uploader = new BackgroundUploader();

            uploader.SetRequestHeader("Filename", file.Name);

            UploadOperation upload = uploader.CreateUpload(uri, file);

            Log(String.Format("Uploading {0} to {1}, {2}", file.Name, uri.AbsoluteUri, upload.Guid));

            // Attach progress and completion handlers.
            await HandleUploadAsync(upload, true);
        }
Exemplo n.º 11
0
        private async Task UploadSingleFile(StorageFile file, CpuArchitecture fileType)
        {
            var uri = new Uri(Constants.PackageUploadServerUrl);

            var uploader = new BackgroundUploader();

            uploader.SetRequestHeader("Filename", file.Name);
            uploader.SetRequestHeader("Guid", _dataContext.AppDetail.AppSpecification.Guid.ToString());
            uploader.SetRequestHeader("AppName", fileType.ToString());


            var upload = uploader.CreateUpload(uri, file);

            //Log(String.Format(CultureInfo.CurrentCulture, "Uploading {0} to {1}, {2}", file.Name, uri.AbsoluteUri,
            //    upload.Guid));

            // Attach progress and completion handlers.
            await HandleUploadAsync(upload, true);
        }
Exemplo n.º 12
0
        private async void OnGetUploadLinkCompleted(LiveOperationResult result)
        {
            if (result.Error != null)
            {
                this.taskCompletionSource.SetException(result.Error);
                return;
            }

            var uploadUrl = new Uri(result.RawResult, UriKind.Absolute);

            // NOTE: the GetUploadLinkOperation will return a uri with the overwite, suppress_response_codes,
            // and suppress_redirect query parameters set.
            Debug.Assert(uploadUrl.Query != null);
            Debug.Assert(uploadUrl.Query.Contains(QueryParameters.Overwrite));
            Debug.Assert(uploadUrl.Query.Contains(QueryParameters.SuppressRedirects));
            Debug.Assert(uploadUrl.Query.Contains(QueryParameters.SuppressResponseCodes));

            var uploader = new BackgroundUploader();

            uploader.Group = LiveConnectClient.LiveSDKUploadGroup;
            if (this.LiveClient.Session != null)
            {
                uploader.SetRequestHeader(
                    ApiOperation.AuthorizationHeader,
                    AuthConstants.BearerTokenType + " " + this.LiveClient.Session.AccessToken);
            }
            uploader.SetRequestHeader(ApiOperation.LibraryHeader, Platform.GetLibraryHeaderValue());
            uploader.Method = HttpMethods.Put;

            UploadOperation uploadOperation;

            if (this.InputStream != null)
            {
                uploadOperation = await uploader.CreateUploadFromStreamAsync(uploadUrl, this.InputStream);
            }
            else
            {
                uploadOperation = uploader.CreateUpload(uploadUrl, this.InputFile);
            }

            this.taskCompletionSource.SetResult(new LiveUploadOperation(uploadOperation));
        }
 /// <summary>
 /// This will upload the file and give the progress in % and bytes.
 /// </summary>
 /// <param name="strURL"></param>
 /// <param name="headers"></param>
 public static async void uploadFile(string strURL, StorageFile file)
 {
     try
     {
         Uri uri = new Uri(strURL);
         cancellationToken = new CancellationTokenSource();
         BackgroundUploader uploader = new BackgroundUploader();
         if (HelperMethods.dictHeader != null && HelperMethods.dictHeader.Count() > 0)
         {
             foreach (var items in HelperMethods.dictHeader)
             {
                 uploader.SetRequestHeader(items.Key, items.Value);
             }
         }
         UploadOperation upload = uploader.CreateUpload(uri, file);
         HandleUploadAsync(upload, true);
     }
     catch (Exception ex)
     {
         System.Diagnostics.Debug.WriteLine("Exception Occur uploadFile -- TSGServiceManager: " + ex.ToString());
     }
 }
Exemplo n.º 14
0
        protected override async Task <HttpTransfer> CreateUpload(HttpTransferRequest request)
        {
            var task = new BackgroundUploader
            {
                Method     = request.HttpMethod.Method,
                CostPolicy = request.UseMeteredConnection
                    ? BackgroundTransferCostPolicy.Default
                    : BackgroundTransferCostPolicy.UnrestrictedOnly
            };

            foreach (var header in request.Headers)
            {
                task.SetRequestHeader(header.Key, header.Value);
            }

            var winFile = await StorageFile.GetFileFromPathAsync(request.LocalFile.FullName).AsTask();

            var operation = task.CreateUpload(new Uri(request.Uri), winFile);
            await operation.StartAsync();

            return(operation.FromNative());
        }
        private async void UploadMedia(object parameter)
        {
            if (SelectedMediaItem == null)
            {
                var msg = new Windows.UI.Popups.MessageDialog(Accessories.resourceLoader.GetString("SelectMediaFileForUpload"));
                await msg.ShowAsync();

                return;
            }

            var file = await _mediaTempFolder.GetFileAsync(this.SelectedMediaItem.Name);

            this.Idle = false;
            BackgroundUploader uploader = new BackgroundUploader();
            UploadOperation    upload   = uploader.CreateUpload(new Uri("ServerUri"), file);

            Progress <UploadOperation> progressCallback = new Progress <UploadOperation>(UploadProgress);
            await upload.StartAsync().AsTask(cts.Token, progressCallback);

            ResponseInformation response = upload.GetResponseInformation();

            this.Idle = true;
        }
Exemplo n.º 16
0
        public List <UploadOperation> CreateUpload(DavItem item, List <StorageFile> files)
        {
            List <UploadOperation> result   = new List <UploadOperation>();
            BackgroundUploader     uploader = new BackgroundUploader();

            uploader.Method = "PUT";
            var buffer = CryptographicBuffer.ConvertStringToBinary(Configuration.UserName + ":" + Configuration.Password, BinaryStringEncoding.Utf8);
            var token  = CryptographicBuffer.EncodeToBase64String(buffer);
            var value  = new HttpCredentialsHeaderValue("Basic", token);

            uploader.SetRequestHeader("Authorization", value.ToString());
            foreach (var storageFile in files)
            {
                var uri = new Uri(item.EntityId.TrimEnd('/'), UriKind.RelativeOrAbsolute);
                uri = new Uri(uri + "/" + storageFile.Name, UriKind.RelativeOrAbsolute);
                if (!uri.IsAbsoluteUri)
                {
                    uri = CreateItemUri(uri);
                }
                UploadOperation upload = uploader.CreateUpload(uri, storageFile);
                result.Add(upload);
            }
            return(result);
        }
Exemplo n.º 17
0
        public async void UploadSingleVoice(StorageFile File, string threadId)
        {
            ThreadId = threadId;
            UploadId = GenerateUploadId();
            GUID     = Guid.NewGuid().ToString();
            WaveForm.Clear();
            //try
            //{
            //    var deteils = await File.Properties.GetMusicPropertiesAsync();
            //    var count = deteils.Duration.TotalMilliseconds/* * 100*/;
            //    for (int i = 0; i < count; i++)
            //        WaveForm.Add($"0.{GetRnd()}");
            //}
            //catch { }
            InstaDirectInboxItem directItem = new InstaDirectInboxItem
            {
                ItemType   = InstaDirectThreadItemType.VoiceMedia,
                VoiceMedia = new InstaVoiceMedia
                {
                    Media = new InstaVoice
                    {
                        Audio = new InstaAudio
                        {
                            AudioSource  = File.Path,
                            WaveformData = new float[] { }
                        }
                    }
                },
                UserId      = InstaApi.GetLoggedUser().LoggedInUser.Pk,
                TimeStamp   = DateTime.UtcNow,
                SendingType = InstagramApiSharp.Enums.InstaDirectInboxItemSendingType.Pending,
                ItemId      = GUID
            };

            DirectItem = directItem;
            ThreadView.Current?.ThreadVM.Items.Add(directItem);



            var hashCode   = Path.GetFileName(File.Path ?? $"C:\\{13.GenerateRandomStringStatic()}.jpg").GetHashCode();
            var entityName = $"{UploadId}_0_{hashCode}";
            var instaUri   = GetMediaUploadUri(UploadId, hashCode);

            var device = InstaApi.GetCurrentDevice();
            var httpRequestProcessor = InstaApi.HttpRequestProcessor;

            BackgroundUploader BGU = new BackgroundUploader();

            var cookies    = httpRequestProcessor.HttpHandler.CookieContainer.GetCookies(httpRequestProcessor.Client.BaseAddress);
            var strCookies = string.Empty;

            foreach (Cookie cook in cookies)
            {
                strCookies += $"{cook.Name}={cook.Value}; ";
            }
            // header haye asli in ha hastan faghat
            BGU.SetRequestHeader("Cookie", strCookies);
            var r = InstaApi.HttpHelper.GetDefaultRequest(HttpMethod.Post, instaUri, device);

            foreach (var item in r.Headers)
            {
                BGU.SetRequestHeader(item.Key, string.Join(" ", item.Value));
            }


            var photoUploadParamsObj = new JObject
            {
                { "xsharing_user_ids", "[]" },
                { "is_direct_voice", "1" },
                { "upload_media_duration_ms", "0" },
                { "upload_id", UploadId },
                { "retry_context", GetRetryContext() },
                { "media_type", "11" }
            };
            var photoUploadParams = JsonConvert.SerializeObject(photoUploadParamsObj);
            var openedFile        = await File.OpenAsync(FileAccessMode.Read);

            BGU.SetRequestHeader("X-Entity-Type", "audio/mp4");
            BGU.SetRequestHeader("Offset", "0");
            BGU.SetRequestHeader("X-Instagram-Rupload-Params", photoUploadParams);
            BGU.SetRequestHeader("X-Entity-Name", entityName);
            BGU.SetRequestHeader("X-Entity-Length", openedFile.AsStream().Length.ToString());
            BGU.SetRequestHeader("X_FB_VIDEO_WATERFALL_ID", ExtensionHelper.GetThreadToken());
            BGU.SetRequestHeader("Content-Transfer-Encoding", "binary");
            BGU.SetRequestHeader("Content-Type", "application/octet-stream");

            Debug.WriteLine("----------------------------------------Start upload----------------------------------");

            //var uploadX = await BGU.CreateUploadAsync(instaUri, parts, "", UploadId);
            var upload = BGU.CreateUpload(instaUri, File);

            upload.Priority = BackgroundTransferPriority.High;
            await HandleUploadAsync(upload, true);
        }
Exemplo n.º 18
0
        public async void UploadSinglePhoto(StorageFile File, string threadId, string recipient,
                                            InstaInboxMedia mediaShare, InstaDirectInboxThread thread, InstaDirectInboxItem inboxItem)
        {
            Thread     = thread;
            MediaShare = mediaShare;
            UploadId   = GenerateUploadId();
            ThreadId   = threadId;
            Recipient  = recipient;
            Item       = inboxItem;
            var photoHashCode   = Path.GetFileName(File.Path ?? $"C:\\{13.GenerateRandomStringStatic()}.jpg").GetHashCode();
            var photoEntityName = $"{UploadId}_0_{photoHashCode}";
            var instaUri        = GetUploadPhotoUri(UploadId, photoHashCode);

            var device = InstaApi.GetCurrentDevice();
            var httpRequestProcessor = InstaApi.HttpRequestProcessor;

            BackgroundUploader BGU = new BackgroundUploader();

            var cookies    = httpRequestProcessor.HttpHandler.CookieContainer.GetCookies(httpRequestProcessor.Client.BaseAddress);
            var strCookies = string.Empty;

            foreach (Cookie cook in cookies)
            {
                strCookies += $"{cook.Name}={cook.Value}; ";
            }
            // header haye asli in ha hastan faghat
            BGU.SetRequestHeader("Cookie", strCookies);
            var r = InstaApi.HttpHelper.GetDefaultRequest(HttpMethod.Post, instaUri, device);

            foreach (var item in r.Headers)
            {
                BGU.SetRequestHeader(item.Key, string.Join(" ", item.Value));
            }

            //{
            //  "upload_id": "1595581225629",
            //  "media_type": "1",
            //  "retry_context": "{\"num_reupload\":0,\"num_step_auto_retry\":0,\"num_step_manual_retry\":0}",
            //  "image_compression": "{\"lib_name\":\"moz\",\"lib_version\":\"3.1.m\",\"quality\":\"0\"}",
            //  "xsharing_user_ids": "[\"1647718432\",\"1581245356\"]"
            //}
            var photoUploadParamsObj = new JObject
            {
                { "upload_id", UploadId },
                { "media_type", "1" },
                { "retry_context", GetRetryContext() },
                { "image_compression", "{\"lib_name\":\"moz\",\"lib_version\":\"3.1.m\",\"quality\":\"0\"}" },
                { "xsharing_user_ids", $"[{recipient ?? string.Empty}]" },
            };
            var  photoUploadParams = JsonConvert.SerializeObject(photoUploadParamsObj);
            long fileLength        = 0;

            using (var openedFile = await File.OpenAsync(FileAccessMode.Read))
                fileLength = openedFile.AsStream().Length;

            BGU.SetRequestHeader("X_FB_PHOTO_WATERFALL_ID", Guid.NewGuid().ToString());
            BGU.SetRequestHeader("X-Entity-Length", fileLength.ToString());
            BGU.SetRequestHeader("X-Entity-Name", photoEntityName);
            BGU.SetRequestHeader("X-Instagram-Rupload-Params", photoUploadParams);
            BGU.SetRequestHeader("X-Entity-Type", "image/jpeg");
            BGU.SetRequestHeader("Offset", "0");
            BGU.SetRequestHeader("Content-Transfer-Encoding", "binary");
            BGU.SetRequestHeader("Content-Type", "application/octet-stream");

            // hatman bayad noe file ro moshakhas koni, mese in zirie> oun PHOTO mishe name
            // requestContent.Add(imageContent, "photo", $"pending_media_{ApiRequestMessage.GenerateUploadId()}.jpg");
            // vase video nemikhad esmi bezari!

            //BackgroundTransferContentPart filePart = new BackgroundTransferContentPart(/*"photo"*/);
            //filePart.SetFile(File);
            //// chon binary hast:
            //filePart.SetHeader("Content-Transfer-Encoding", "binary");
            //filePart.SetHeader("Content-Type", "application/octet-stream");

            //var parts = new List<BackgroundTransferContentPart>
            //{
            //    filePart
            //};
            Debug.WriteLine("----------------------------------------Start upload----------------------------------");

            //var uploadX = await BGU.CreateUploadAsync(instaUri, parts, "", UploadId);
            var upload = BGU.CreateUpload(instaUri, File);

            upload.Priority = BackgroundTransferPriority.High;
            await HandleUploadAsync(upload, true);
        }
Exemplo n.º 19
0
        public async void UploadFile(StorageUploadItem uploadItem)
        {
            MainPage.Current?.ShowMediaUploadingUc();
            UploadId            = GenerateUploadId(true);
            uploadItem.UploadId = UploadId;
            UploadItem          = uploadItem;
            try
            {
                var cacheFolder = await SessionHelper.LocalFolder.GetFolderAsync("Cache");

                NotifyFile = await cacheFolder.CreateFileAsync(15.GenerateRandomStringStatic() + ".jpg");

                NotifyFile = await UploadItem.ImageToUpload.CopyAsync(cacheFolder);
            }
            catch { }
            var hashCode    = Path.GetFileName($"C:\\{13.GenerateRandomStringStatic()}.jpg").GetHashCode();
            var storyHashId = GenerateStoryHashId();
            var storyHash   = InstagramApiSharp.Helpers.CryptoHelper.CalculateHash(InstaApi.GetApiVersionInfo().SignatureKey, storyHashId).Substring(0, "763975004617a2a82570956fc58340b8".Length);

            var entityName           = UploadItem.IsStory ? $"{storyHash}-0-{storyHashId}" : $"{UploadId}_0_{hashCode}";
            var instaUri             = UploadItem.IsVideo ? (UploadItem.IsStory ? GetUploadVideoStoryUri(entityName) : GetUploadVideoUri(UploadId, hashCode)) : GetUploadPhotoUri(UploadId, hashCode);
            var device               = InstaApi.GetCurrentDevice();
            var httpRequestProcessor = InstaApi.HttpRequestProcessor;

            BackgroundUploader BGU = new BackgroundUploader();

            var cookies    = httpRequestProcessor.HttpHandler.CookieContainer.GetCookies(httpRequestProcessor.Client.BaseAddress);
            var strCookies = string.Empty;

            foreach (Cookie cook in cookies)
            {
                strCookies += $"{cook.Name}={cook.Value}; ";
            }
            // header haye asli in ha hastan faghat
            BGU.SetRequestHeader("Cookie", strCookies);
            var r = InstaApi.HttpHelper.GetDefaultRequest(HttpMethod.Post, instaUri, device);

            foreach (var item in r.Headers)
            {
                BGU.SetRequestHeader(item.Key, string.Join(" ", item.Value));
            }


            JObject uploadParamsObj = new JObject
            {
                { "upload_id", UploadId },
                { "media_type", "1" },
                { "retry_context", GetRetryContext() },
                { "image_compression", "{\"lib_name\":\"moz\",\"lib_version\":\"3.1.m\",\"quality\":\"95\"}" },
            };

            if (UploadItem.IsVideo)
            {
                uploadParamsObj = new JObject
                {
                    { "upload_media_height", UploadItem.PixelHeight },
                    { "upload_media_width", UploadItem.PixelWidth },
                    { "upload_media_duration_ms", UploadItem.Duration.TotalMilliseconds },
                    { "upload_id", UploadId },
                    { "retry_context", GetRetryContext() },
                    { "media_type", "2" },
                    { "xsharing_user_ids", "[]" },
                    { "extract_cover_frame", "1" }
                };

                if (UploadItem.IsStory)
                {
                    uploadParamsObj.Add("for_album", "1");
                }
            }
            if (UploadItem.IsAlbum)
            {
                uploadParamsObj.Add("is_sidecar", "1");
            }
            var uploadParams = JsonConvert.SerializeObject(uploadParamsObj);
            var fileBytes    = "";

            try
            {
                StorageFile file = UploadItem.IsVideo ? UploadItem.VideoToUpload : UploadItem.ImageToUpload;
                using (var openedFile = await file.OpenAsync(FileAccessMode.Read))
                {
                    fileBytes = openedFile.AsStream().Length.ToString();
                    await Task.Delay(250);
                }
            }
            catch { }
            BGU.SetRequestHeader("X-Entity-Type", UploadItem.IsVideo ? "video/mp4" : "image/jpeg");
            if (UploadItem.IsStory)
            {
                BGU.SetRequestHeader("Segment-Start-Offset", "0");
                BGU.SetRequestHeader("Segment-Type", "3");
            }
            BGU.SetRequestHeader("Offset", "0");
            BGU.SetRequestHeader("X-Instagram-Rupload-Params", uploadParams);
            BGU.SetRequestHeader("X-Entity-Name", entityName);
            BGU.SetRequestHeader("X-Entity-Length", fileBytes);
            BGU.SetRequestHeader($"X_FB_{(UploadItem.IsVideo ? "VIDEO" : "PHOTO")}_WATERFALL_ID", UploadItem.IsStory ? UploadId : Guid.NewGuid().ToString());
            BGU.SetRequestHeader("Content-Transfer-Encoding", "binary");
            BGU.SetRequestHeader("Content-Type", "application/octet-stream");
            Debug.WriteLine("----------------------------------------Start upload----------------------------------");

            var upload = BGU.CreateUpload(instaUri, UploadItem.IsVideo ? UploadItem.VideoToUpload : UploadItem.ImageToUpload);

            upload.Priority = BackgroundTransferPriority.Default;
            await HandleUploadAsync(upload, true);
        }
Exemplo n.º 20
0
        private async void upload()
        {
            if (EnsureUnsnapped())
            {
                var            ignored1   = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { loading.IsIndeterminate = true; });
                FileOpenPicker openPicker = new FileOpenPicker();
                openPicker.ViewMode = PickerViewMode.List;
                openPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
                if (Params.Filters[0] == "*.*")
                {
                    openPicker.FileTypeFilter.Add("*");
                }
                else
                {
                    foreach (string s in Params.Filters)
                    {
                        if (s.Contains(";"))
                        {
                            foreach (string s1 in s.Split(new char[] { ';' }))
                            {
                                openPicker.FileTypeFilter.Add(s1.Substring(1).Trim());
                            }
                        }
                        else
                        {
                            openPicker.FileTypeFilter.Add(s.Substring(1).Trim());
                        }
                    }
                }

                var files = await openPicker.PickMultipleFilesAsync();

                if (files != null && files.Count > 0)
                {
                    try
                    {
                        List <string> filenames = new List <string>();
                        foreach (StorageFile file in files)
                        {
                            Uri uri = new Uri(HAPSettings.CurrentSite.Address, "./api/myfiles-upload/" + (fileGridView.SelectedItem == null ? path : ((JSONFile)fileGridView.SelectedItem).Path).Replace('\\', '/'));
                            BackgroundUploader uploader = new BackgroundUploader();
                            uploader.SetRequestHeader("X_FILENAME", file.Name);
                            filenames.Add(file.Name);
                            uploader.Method = "POST";
                            uploader.SetRequestHeader("Cookie", string.Format("{0}={1}; token={2}", HAPSettings.CurrentToken[2], HAPSettings.CurrentToken[1], HAPSettings.CurrentToken[0]));
                            UploadOperation upload = uploader.CreateUpload(uri, file);

                            // Attach progress and completion handlers.
                            HandleUploadAsync(upload, true);
                        }
                        MessageDialog mes = new MessageDialog("The upload of " + string.Join(", ", filenames.ToArray()) + " has started, you will get notified when it's done", "Uploading");
                        mes.Commands.Add(new UICommand("OK"));
                        mes.DefaultCommandIndex = 0;
                        mes.ShowAsync();
                        var ignored3 = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { loading.IsIndeterminate = false; });
                    }
                    catch (Exception ex)
                    {
                        MessageDialog mes = new MessageDialog(ex.ToString(), "Error");
                        mes.Commands.Add(new UICommand("OK"));
                        mes.DefaultCommandIndex = 0;
                        mes.ShowAsync();
                        var ignored3 = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { loading.IsIndeterminate = false; });
                    }
                }
                else
                {
                    var ignored2 = Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { pro.Visibility = Windows.UI.Xaml.Visibility.Collapsed; pro.Value = 100.0; loading.IsIndeterminate = false; });
                }
            }
        }
Exemplo n.º 21
0
        public async void UploadSinglePhoto(StorageFile File, string caption)
        {
            Caption = caption;

            if (!string.IsNullOrEmpty(Caption))
            {
                Caption = Caption.Replace("\r", "\n");
            }

            UploadId = GenerateUploadId();
            try
            {
                var cacheFolder = await SessionHelper.LocalFolder.GetFolderAsync("Cache");

                NotifyFile = await cacheFolder.CreateFileAsync(15.GenerateRandomStringStatic() + ".jpg");

                NotifyFile = await File.CopyAsync(cacheFolder);
            }
            catch { }
            var photoHashCode   = Path.GetFileName(File.Path ?? $"C:\\{13.GenerateRandomStringStatic()}.jpg").GetHashCode();
            var photoEntityName = $"{UploadId}_0_{photoHashCode}";
            var instaUri        = GetUploadPhotoUri(UploadId, photoHashCode);

            var device = InstaApi.GetCurrentDevice();
            var httpRequestProcessor = InstaApi.HttpRequestProcessor;

            BackgroundUploader BGU = new BackgroundUploader();

            var cookies    = httpRequestProcessor.HttpHandler.CookieContainer.GetCookies(httpRequestProcessor.Client.BaseAddress);
            var strCookies = string.Empty;

            foreach (Cookie cook in cookies)
            {
                strCookies += $"{cook.Name}={cook.Value}; ";
            }
            // header haye asli in ha hastan faghat
            BGU.SetRequestHeader("Cookie", strCookies);
            var r = InstaApi.HttpHelper.GetDefaultRequest(HttpMethod.Post, instaUri, device);

            foreach (var item in r.Headers)
            {
                BGU.SetRequestHeader(item.Key, string.Join(" ", item.Value));
            }


            var photoUploadParamsObj = new JObject
            {
                { "upload_id", UploadId },
                { "media_type", "1" },
                { "retry_context", GetRetryContext() },
                { "image_compression", "{\"lib_name\":\"moz\",\"lib_version\":\"3.1.m\",\"quality\":\"95\"}" },
            };
            var photoUploadParams = JsonConvert.SerializeObject(photoUploadParamsObj);
            var openedFile        = await File.OpenAsync(FileAccessMode.Read);

            BGU.SetRequestHeader("X-Entity-Type", "image/jpeg");
            BGU.SetRequestHeader("Offset", "0");
            BGU.SetRequestHeader("X-Instagram-Rupload-Params", photoUploadParams);
            BGU.SetRequestHeader("X-Entity-Name", photoEntityName);
            BGU.SetRequestHeader("X-Entity-Length", openedFile.AsStream().Length.ToString());
            BGU.SetRequestHeader("X_FB_PHOTO_WATERFALL_ID", Guid.NewGuid().ToString());
            BGU.SetRequestHeader("Content-Transfer-Encoding", "binary");
            BGU.SetRequestHeader("Content-Type", "application/octet-stream");

            Debug.WriteLine("----------------------------------------Start upload----------------------------------");

            //var uploadX = await BGU.CreateUploadAsync(instaUri, parts, "", UploadId);
            var upload = BGU.CreateUpload(instaUri, File);

            upload.Priority = BackgroundTransferPriority.High;
            await HandleUploadAsync(upload, true);
        }
Exemplo n.º 22
0
        public async void UploadFile(StorageUploadItem uploadItem)
        {
            MainPage.Current?.ShowMediaUploadingUc();
            UploadId            = GenerateUploadId(true);
            uploadItem.UploadId = UploadId;
            UploadItem          = uploadItem;
            try
            {
                var cacheFolder = await SessionHelper.LocalFolder.GetFolderAsync("Cache");

                NotifyFile = await cacheFolder.CreateFileAsync(15.GenerateRandomStringStatic() + ".jpg");

                NotifyFile = await UploadItem.ImageToUpload.CopyAsync(cacheFolder);
            }
            catch { }
            //763975004617a2a82570956fc58340b8-0-752599
            // 17538305748504876_0_567406570
            var hashCode    = Path.GetFileName($"C:\\{13.GenerateRandomStringStatic()}.jpg").GetHashCode();
            var storyHashId = GenerateStoryHashId();
            var storyHash   = InstagramApiSharp.Helpers.CryptoHelper.CalculateHash(InstaApi.GetApiVersionInfo().SignatureKey, storyHashId).Substring(0, "763975004617a2a82570956fc58340b8".Length);

            var entityName           = UploadItem.IsStory ? $"{storyHash}-0-{storyHashId}" : $"{UploadId}_0_{hashCode}";
            var instaUri             = UploadItem.IsVideo ? (UploadItem.IsStory ? GetUploadVideoStoryUri(entityName) : GetUploadVideoUri(UploadId, hashCode)) : GetUploadPhotoUri(UploadId, hashCode);
            var device               = InstaApi.GetCurrentDevice();
            var httpRequestProcessor = InstaApi.HttpRequestProcessor;

            BackgroundUploader BGU = new BackgroundUploader();

            var cookies    = httpRequestProcessor.HttpHandler.CookieContainer.GetCookies(httpRequestProcessor.Client.BaseAddress);
            var strCookies = string.Empty;

            foreach (Cookie cook in cookies)
            {
                strCookies += $"{cook.Name}={cook.Value}; ";
            }
            // header haye asli in ha hastan faghat
            BGU.SetRequestHeader("Cookie", strCookies);
            var r = InstaApi.HttpHelper.GetDefaultRequest(HttpMethod.Post, instaUri, device);

            foreach (var item in r.Headers)
            {
                BGU.SetRequestHeader(item.Key, string.Join(" ", item.Value));
            }


            JObject uploadParamsObj = new JObject
            {
                { "upload_id", UploadId },
                { "media_type", "1" },
                { "retry_context", GetRetryContext() },
                { "image_compression", "{\"lib_name\":\"moz\",\"lib_version\":\"3.1.m\",\"quality\":\"95\"}" },
            };

            if (UploadItem.IsVideo)
            {
                uploadParamsObj = new JObject
                {
                    { "upload_media_height", UploadItem.PixelHeight },
                    { "upload_media_width", UploadItem.PixelWidth },
                    { "upload_media_duration_ms", UploadItem.Duration.TotalMilliseconds },
                    { "upload_id", UploadId },
                    { "retry_context", GetRetryContext() },
                    { "media_type", "2" },
                    { "xsharing_user_ids", "[]" },
                    { "extract_cover_frame", "1" }
                };

                if (UploadItem.IsStory)
                {
                    uploadParamsObj.Add("for_album", "1");
                }
            }
            if (UploadItem.IsAlbum)
            {
                uploadParamsObj.Add("is_sidecar", "1");
            }
            var uploadParams = JsonConvert.SerializeObject(uploadParamsObj);
            var fileBytes    = "";

            //if (UploadItem.IsVideo)
            {
                try
                {
                    StorageFile file = UploadItem.IsVideo ? UploadItem.VideoToUpload : UploadItem.ImageToUpload;
                    using (var openedFile = await file.OpenAsync(FileAccessMode.Read))
                    {
                        fileBytes = openedFile.AsStream().Length.ToString();
                        await Task.Delay(250);
                    }
                }
                catch { }
            }
            BGU.SetRequestHeader("X-Entity-Type", UploadItem.IsVideo ? "video/mp4" : "image/jpeg");
            if (UploadItem.IsStory)
            {
                //GET /rupload_igvideo/763975004617a2a82570956fc58340b8-0-752599 HTTP/1.1
                //X-Instagram-Rupload-Params: {"upload_media_height":"1196","extract_cover_frame":"1","xsharing_user_ids":"[\"11292195227\",\"1647718432\",\"8651542203\"]","upload_media_width":"720","upload_media_duration_ms":"5433","upload_id":"173258081688145","for_album":"1","retry_context":"{\"num_reupload\":0,\"num_step_auto_retry\":0,\"num_step_manual_retry\":0}","media_type":"2"}
                //Segment-Start-Offset: 0
                //X_FB_VIDEO_WATERFALL_ID: 173258081688145
                //Segment-Type: 3
                //X-IG-Connection-Type: WIFI
                //X-IG-Capabilities: 3brTvwM=
                //X-IG-App-ID: 567067343352427
                //User-Agent: Instagram 130.0.0.31.121 Android (26/8.0.0; 480dpi; 1080x1794; HUAWEI/HONOR; PRA-LA1; HWPRA-H; hi6250; en_US; 200396014)
                //Accept-Language: en-US
                //Cookie: urlgen={\"178.131.93.78\": 50810}:1jSIQm:SiXtqscCrX4FarygVtZ9rUSk1FE; ig_direct_region_hint=ATN; ds_user=rmt4006; igfl=rmt4006; ds_user_id=5318277344; mid=XkwRBQABAAEFAQ-YHBcUNU_oAnq-; shbts=1587579994.6701467; sessionid=5318277344%3AYpsEMoOF3jdznX%3A26; csrftoken=H5ZBkafSXpZB06QEZC7hVX3IdDYKscjQ; shbid=8693; rur=FRC; is_starred_enabled=yes
                //X-MID: XkwRBQABAAEFAQ-YHBcUNU_oAnq-
                //Accept-Encoding: gzip, deflate
                //Host: i.instagram.com
                //X-FB-HTTP-Engine: Liger
                //Connection: keep-alive
                BGU.SetRequestHeader("Segment-Start-Offset", "0");
                BGU.SetRequestHeader("Segment-Type", "3");
            }
            BGU.SetRequestHeader("Offset", "0");
            BGU.SetRequestHeader("X-Instagram-Rupload-Params", uploadParams);
            BGU.SetRequestHeader("X-Entity-Name", entityName);
            BGU.SetRequestHeader("X-Entity-Length", fileBytes);
            BGU.SetRequestHeader($"X_FB_{(UploadItem.IsVideo ? "VIDEO" : "PHOTO")}_WATERFALL_ID", UploadItem.IsStory ? UploadId : Guid.NewGuid().ToString());
            BGU.SetRequestHeader("Content-Transfer-Encoding", "binary");
            BGU.SetRequestHeader("Content-Type", "application/octet-stream");
            Debug.WriteLine("----------------------------------------Start upload----------------------------------");

            var upload = BGU.CreateUpload(instaUri, UploadItem.IsVideo ? UploadItem.VideoToUpload : UploadItem.ImageToUpload);

            upload.Priority = BackgroundTransferPriority.Default;
            await HandleUploadAsync(upload, true);
        }