Example #1
0
        StorageUploadItem GetUploadItem()
        {
            if (FileToUpload == null && ThumbnailFile == null)
            {
                return(null);
            }
            VideoEncodingQuality quality;

            if (QualityCombo.SelectedItem != null)
            {
                quality = (VideoEncodingQuality)Enum.Parse(typeof(VideoEncodingQuality), ((ComboBoxItem)QualityCombo.SelectedItem).Content.ToString());
            }
            else
            {
                quality = VideoEncodingQuality.Auto;
            }
            var upItem = new StorageUploadItem
            {
                VideoEncodingQuality = quality,
                //VideoToUpload = FileToUpload,
                //ImageToUpload = ThumbnailFile ?? FileToUpload,
                PixelHeight = (uint)Editor.ScaledSize.Height /*BitmapDecoder.PixelHeight*/,
                PixelWidth  = (uint)Editor.ScaledSize.Width /* BitmapDecoder.PixelWidth*/,
                StartTime   = TimeSpan.FromSeconds(TrimControl.RangeMin),
                EndTime     = TimeSpan.FromSeconds(TrimControl.RangeMax),
                //AudioMuted = ToggleMuteAudio.IsChecked ?? false,
                Rect    = Editor.ScaledCropRect,
                IsStory = true
            };

            upItem.ThisIsVideo(IsVideo);
            if (IsVideo)
            {
                upItem.VideoToUpload = FileToUpload;
                upItem.ImageToUpload = ThumbnailFile;
            }
            else
            {
                upItem.VideoToUpload = null;
                upItem.ImageToUpload = FileToUpload;
            }
            try
            {
                if (IsVideo)
                {
                    var start = TimeSpan.FromSeconds(TrimControl.RangeMin);
                    var end   = TimeSpan.FromSeconds(TrimControl.RangeMax);

                    upItem.StartTime = start;
                    upItem.EndTime   = end;
                }
            }
            catch (Exception ex)
            {
                ex.PrintException("GetUploadItemAsync");
            }
            return(upItem);
        }
Example #2
0
        async Task <StorageUploadItem> ConvertVideoAsync(StorageUploadItem uploadItem)
        {
            try
            {
                var MediaProfile = MediaEncodingProfile.CreateMp4(uploadItem.VideoEncodingQuality);
                var outputFile   = await GenerateRandomOutputFile();

                if (uploadItem != null && outputFile != null)
                {
                    var inputFile = uploadItem.VideoToUpload;

                    //MediaProfile = await MediaEncodingProfile.CreateFromFileAsync(inputFile);
                    Transcoder.TrimStartTime = uploadItem.StartTime;
                    Transcoder.TrimStopTime  = uploadItem.EndTime;

                    MediaProfile.Video.Height = (uint)uploadItem.Size.Height;
                    MediaProfile.Video.Width  = (uint)uploadItem.Size.Width;


                    var transform = new VideoTransformEffectDefinition
                    {
                        Rotation      = MediaRotation.None,
                        OutputSize    = uploadItem.Size,
                        Mirror        = MediaMirroringOptions.None,
                        CropRectangle = uploadItem.Rect
                    };

                    Transcoder.AddVideoEffect(transform.ActivatableClassId, true, transform.Properties);

                    var preparedTranscodeResult = await Transcoder
                                                  .PrepareFileTranscodeAsync(inputFile,
                                                                             outputFile,
                                                                             //.PrepareMediaStreamSourceTranscodeAsync(Mss,
                                                                             //await outputFile.OpenAsync(FileAccessMode.ReadWrite),
                                                                             MediaProfile);

                    if (preparedTranscodeResult.CanTranscode)
                    {
                        var progress = new Progress <double>(ConvertProgress);
                        await preparedTranscodeResult.TranscodeAsync().AsTask(new CancellationTokenSource().Token, progress);

                        ConvertComplete(outputFile);
                        uploadItem.VideoToUpload = outputFile;
                        return(uploadItem);
                    }
                    else
                    {
                        preparedTranscodeResult.FailureReason.ToString().ShowMsg();
                    }
                }
            }
            catch (Exception ex) { ex.PrintException().ShowMsg("ConvertVideo"); }
            return(uploadItem);
        }
Example #3
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);
        }
Example #4
0
        async Task <StorageUploadItem> ConvertVideoAsync(StorageUploadItem uploadItem)
        {
            try
            {
                var mediaProfile = MediaEncodingProfile.CreateMp4(uploadItem.VideoEncodingQuality);
                var outputFile   = await GenerateRandomOutputFile();

                if (uploadItem != null && outputFile != null)
                {
                    var inputFile = uploadItem.VideoToUpload;

                    var fileProfile = await GetEncodingProfileFromFileAsync(inputFile);

                    if (fileProfile != null)
                    {
                        mediaProfile.Video.Bitrate = fileProfile.Video.Bitrate;
                        if (mediaProfile.Audio != null)
                        {
                            mediaProfile.Audio.Bitrate       = fileProfile.Audio.Bitrate;
                            mediaProfile.Audio.BitsPerSample = fileProfile.Audio.BitsPerSample;
                            mediaProfile.Audio.ChannelCount  = fileProfile.Audio.ChannelCount;
                            mediaProfile.Audio.SampleRate    = fileProfile.Audio.SampleRate;
                        }
                        "Media profile copied from original video".PrintDebug();
                    }
                    //MediaProfile = await MediaEncodingProfile.CreateFromFileAsync(inputFile);
                    Transcoder.TrimStartTime = uploadItem.StartTime;
                    Transcoder.TrimStopTime  = uploadItem.EndTime;

                    mediaProfile.Video.Height = (uint)uploadItem.Size.Height;
                    mediaProfile.Video.Width  = (uint)uploadItem.Size.Width;


                    var transform = new VideoTransformEffectDefinition
                    {
                        Rotation      = MediaRotation.None,
                        OutputSize    = uploadItem.Size,
                        Mirror        = MediaMirroringOptions.None,
                        CropRectangle = uploadItem.Rect
                    };

                    Transcoder.AddVideoEffect(transform.ActivatableClassId, true, transform.Properties);

                    var preparedTranscodeResult = await Transcoder
                                                  .PrepareFileTranscodeAsync(inputFile,
                                                                             outputFile,
                                                                             mediaProfile);

                    if (preparedTranscodeResult.CanTranscode)
                    {
                        var progress = new Progress <double>(ConvertProgress);
                        await preparedTranscodeResult.TranscodeAsync().AsTask(new CancellationTokenSource().Token, progress);

                        ConvertComplete(outputFile);
                        uploadItem.VideoToUpload = outputFile;
                        return(uploadItem);
                    }
                    else
                    {
                        preparedTranscodeResult.FailureReason.ToString().ShowMsg();
                    }
                }
            }
            catch (Exception ex) { ex.PrintException().ShowMsg("ConvertVideo"); }
            return(uploadItem);
        }
Example #5
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);
        }