コード例 #1
0
ファイル: Quicktest.cs プロジェクト: blmrbemery/Blink-XT2
        /// <summary>
        /// Demo implementation to show which data the api calls are requiering and how the api calls are made.
        /// </summary>
        /// <param name="form">Reference to the 'form1' instance.</param>
        /// <param name="baseData">The data recieved while the login/authentification were made.</param>
        /// <returns></returns>
        public void Test(Form1 form, BaseData baseData)
        {
            var uweR70_Get     = new UweR70_Get();
            var uweR70_GetData = new UweR70_GetData();
            var uweR70_PostCallWithEmptyBody    = new UweR70_PostCallWithEmptyBody();
            var uweR70_PostCallWithNonEmptyBody = new UweR70_PostCallWithNonEmptyBody();

            var networkObject = baseData.Networks[0];

            /*
             * var cameraList = baseData.Networks[0].Cameras.Where(x => x.Name.Equals("Garage", StringComparison.InvariantCultureIgnoreCase)).ToList();
             * if (cameraList == null || cameraList.Count != 1)
             * {
             *  throw new Exception("'Quicktest.cs', 'TestAsync(...)': Something went wrong!");
             * }
             * var cameraObject = cameraList[0];
             */
            var cameraObject = baseData.Networks[0].Cameras[1];

            var minData = new MinimumData
            {
                AuthToken  = baseData.AuthToken,
                RegionTier = baseData.RegionTier,
                NetworkId  = networkObject.Id,
                CameraId   = cameraObject.Id
            };


            /*
             * var videoLiveViewBody = new VideoLiveViewBody
             * {
             *   id = minData.CameraId,
             *   network = minData.NetworkId,
             *   type = 4
             * };
             * try
             * {
             *  var liveVideoResponse = new UweR70_PostCallWithNonEmptyBody().LiveView(minData, videoLiveViewBody).Result;
             *
             *  // liveVideoResponse.server = "immis://18.196.123.157:443/jb2dzOlaeVLqLO5C__IMDS_811177681?client_id=146"
             *  // iMMis != iMis, but found olny this ...
             *  //http://help.imis.com/sdk/index.htm#!exampleusingc2.htm
             *
             *  var dummy = 1;
             * }
             * catch (Exception ex)
             * {
             *  var errorMessage = ex.Message;
             *  if (ex.InnerException != null && !string.IsNullOrEmpty(ex.InnerException.Message))
             *  {
             *      errorMessage = ex.InnerException.Message;
             *  }
             *  var xx = errorMessage;
             * }
             */



            /*
             * var network = uweR70_Get.BatteryUssageAsync(baseData).Result;
             * var changedMedia = uweR70_Get.ChangedMediaAsync(baseData, 0).Result;
             * var cameraStatus = uweR70_Get.CameraStatusAsync(minData).Result;
             * var signalStrength = uweR70_Get.SignalStrengthAsync(minData).Result;
             * var homescreenV3 = uweR70_Get.HomescreenV3Async(baseData).Result;
             * var quickRegionInfo = uweR70_Get.QuickRegionInfoAsync(baseData).Result;
             * var syncModules = uweR70_Get.SyncModulesAsync(minData).Result;
             * var regions = uweR70_Get.GetRegionsAsync(baseData, "US").Result;
             *
             * var events = uweR70_Get.EventsAsync(minData).Result;
             * var typeList = new[] { "first_boot", "battery", "armed", "disarmed", "scheduled_arm", "scheduled_disarm", "heartbeat", "sm_offline" };
             * var blinkEvents = events._event;
             * var count = blinkEvents.Length;
             * for (int i = 0; i < typeList.Length; i++)
             * {
             *  blinkEvents = blinkEvents.Where(x => !x.type.Equals(typeList[i], StringComparison.InvariantCultureIgnoreCase)).ToArray();
             *  count = blinkEvents.Length;
             * }
             *
             *
             * var thumbnailImage = uweR70_GetData.ThumbnailImageAsync(minData, "<enter valid data here>").Result;
             * var video = uweR70_GetData.VideoAsync(baseData, "<enter valid data here>").Result;
             *
             *
             * var commandArm = uweR70_PostCallWithEmptyBody.CommandArmDisarmAsync(minData, UweR70_PostCallWithEmptyBody.ArmDisarm.arm).Result;
             * var commandDisarm = uweR70_PostCallWithEmptyBody.CommandArmDisarmAsync(minData, UweR70_PostCallWithEmptyBody.ArmDisarm.disarm).Result;
             * var commandMotionDetectionEnable = uweR70_PostCallWithEmptyBody.CommandMotionDetectionAsync(minData, UweR70_PostCallWithEmptyBody.MotionDetection.enable).Result;
             * var commandMotionDetectionDisable = uweR70_PostCallWithEmptyBody.CommandMotionDetectionAsync(minData, UweR70_PostCallWithEmptyBody.MotionDetection.disable).Result;
             * var commandClip = uweR70_PostCallWithEmptyBody.CommandClipAsync(minData).Result;
             * var commandThumbnail = uweR70_PostCallWithEmptyBody.CommandThumbnailAsync(minData).Result;
             *
             * var login = uweR70_PostCallWithNonEmptyBody.LoginAsync(baseData, new LoginBody
             * {
             *  email = "<your blink email address>",
             *  password = "******"
             * }).Result;
             *
             * var mediaIdLIstBody = new MediaIdListBody
             * {
             *  media_list = new List<long>(new long[] { 12345678, 23456789 })  // Example values
             * };
             * var test = uweR70_PostCallWithNonEmptyBody.DeleteMediaCall(baseData, mediaIdLIstBody);
             */
        }
コード例 #2
0
        public BaseData Start(Form1 form, string email, string password, string saveDirectory, bool isGerman, MediaIdListBody mediaIdListBody)
        {
            try
            {
                form.SetP0TxtBoxInfoText("Started.");
                form.SetP0TxtBoxInfoText(string.Empty);

                var common         = new Common();
                var uweR70_Get     = new UweR70_Get();
                var uweR70_GetData = new UweR70_GetData();
                var uweR70_PostCallWithNonEmptyBody = new UweR70_PostCallWithNonEmptyBody();

                var storeIt = new StoreIt();

                var baseData = new BaseData
                {
                    Email     = email,
                    LoginTier = isGerman ? "prde" : "prod",
                    Networks  = new List <BaseData.Network>()
                };

                Blink.BatteryUsage batteryUssage = null;

                var alreadyStoredAuthTokens = storeIt.ReadAuthToken();
                var alreadyStoredMainData   = storeIt.ReadMainData();
                var oldAuthTokenWorked      = false;
                if (alreadyStoredAuthTokens != null && alreadyStoredAuthTokens.Count != 0 && alreadyStoredMainData != null)
                {
                    try
                    {
                        baseData.RegionTier        = alreadyStoredMainData.RegionTier;
                        baseData.RegionDescription = alreadyStoredMainData.RegionDescription;
                        baseData.AuthToken         = alreadyStoredAuthTokens[alreadyStoredAuthTokens.Count - 1].Token;
                        baseData.AccountId         = alreadyStoredMainData.AccountId;
                        baseData.ClientId          = alreadyStoredMainData.ClientId;

                        batteryUssage = uweR70_Get.BatteryUssageAsync(baseData).Result;

                        oldAuthTokenWorked = true;
                    }
                    catch {}
                }
                if (!oldAuthTokenWorked)
                {
                    // Authentification api call
                    var login = uweR70_PostCallWithNonEmptyBody.LoginAsync(baseData, new LoginBody
                    {
                        email    = email,
                        password = password
                    }).Result;

                    baseData.RegionTier        = login.region.tier;
                    baseData.RegionDescription = login.region.description;
                    baseData.AuthToken         = login.authtoken.authtoken;
                    baseData.AccountId         = login.account.id;
                    baseData.ClientId          = login.client.id;

                    batteryUssage = uweR70_Get.BatteryUssageAsync(baseData).Result;
                    storeIt.StoreData(baseData, batteryUssage);
                }

                for (var i = 0; i < batteryUssage.networks.Length; i++)
                {
                    baseData.Networks.Add(new BaseData.Network
                    {
                        Id      = batteryUssage.networks[i].network_id,
                        Name    = batteryUssage.networks[i].name,
                        Cameras = new List <BaseData.Camera>()
                    });

                    var minData = new MinimumData
                    {
                        AuthToken  = baseData.AuthToken,
                        RegionTier = baseData.RegionTier,
                        NetworkId  = baseData.Networks[i].Id
                    };

                    form.SetP0TxtBoxInfoText($"Network id >{baseData.Networks[i].Id}<");
                    form.SetP0TxtBoxInfoText($"Network name >{baseData.Networks[i].Name}<");
                    form.SetP0TxtBoxInfoText($"camera count >{batteryUssage.networks[i].cameras.Length}<");

                    for (var n = 0; n < batteryUssage.networks[i].cameras.Length; n++)
                    {
                        form.SetP0TxtBoxInfoText(string.Empty);
                        form.SetP0TxtBoxInfoText($"camera #{n + 1:D2}");

                        baseData.Networks[i].Cameras.Add(new BaseData.Camera
                        {
                            Id    = batteryUssage.networks[i].cameras[n].id,
                            Name  = batteryUssage.networks[i].cameras[n].name,
                            Media = new BaseData.Media()
                        });

                        minData.CameraId = baseData.Networks[i].Cameras[n].Id;

                        form.SetP0TxtBoxInfoText($"camera id >{baseData.Networks[i].Cameras[n].Id}<");
                        form.SetP0TxtBoxInfoText($"camera name >{baseData.Networks[i].Cameras[n].Name}<");

                        var cameraStatus = uweR70_Get.CameraStatusAsync(minData).Result;

                        var cameraThumbnail = cameraStatus.camera_status.thumbnail;

                        var networkNameAndId = common.CombineNameAndId(baseData.Networks[i].Name, baseData.Networks[i].Id);
                        var cameraNameAndId  = common.CombineNameAndId(batteryUssage.networks[i].cameras[n].name, batteryUssage.networks[i].cameras[n].id);
                        var storagePath      = GetStoragePath(saveDirectory, networkNameAndId, cameraNameAndId);
                        if (string.IsNullOrEmpty(baseData.StoragePathNetwork))
                        {   /* Both folligng directories where created while  "GetStoragePath(...)" worked out!
                             * because the there combined path contains all parts of the following two combined directories.
                             */
                            baseData.StoragePathNetwork = Path.Combine(saveDirectory, $"{Config.StoragePartBase}\\{networkNameAndId}");
                            baseData.StoragePathMain    = $"{baseData.StoragePathNetwork}\\{Config.StoragePartMain}";
                        }
                        var cameraThumbnailFileName        = GetAdjustedCameraThumbnailFileName(Path.GetFileName(cameraThumbnail));
                        var cameraThumbnailPathAndFileName = $"{storagePath}\\{cameraThumbnailFileName}";
                        baseData.Networks[i].Cameras[n].Media.PathAndFileNameThumbnail = cameraThumbnailPathAndFileName;
                        baseData.Networks[i].Cameras[n].Media.PathAndFileNameVideos    = new List <string>();
                        if (!File.Exists(cameraThumbnailPathAndFileName))
                        {
                            var cameraThumbnailByteArray = uweR70_GetData.ThumbnailImageAsync(minData, cameraThumbnail).Result;
                            File.WriteAllBytes(cameraThumbnailPathAndFileName, cameraThumbnailByteArray);
                        }
                    }
                }

                var timestampFormatter = common.GetTimestampFormatter();

                var pageCounter = 0;
                var aborted     = false;
                form.SetP0TxtBoxInfoText(string.Empty);
                form.SetP0TxtBoxInfoText($"Try to download videos.");
                do
                {
                    pageCounter++;

                    var changedMedia = uweR70_Get.ChangedMediaAsync(baseData, pageCounter).Result;
                    if (changedMedia.media == null || changedMedia.media.Length == 0)
                    {
                        break;
                    }

                    form.SetP0TxtBoxInfoText(string.Empty);
                    form.SetP0TxtBoxInfoText($"Page #{pageCounter} contains {changedMedia.media.Length} videos.");

                    var counterMarkedAsDeleted         = 0;
                    var counterAlreadyBeforeDownloaded = 0;
                    var counterDownloaded = 0;

                    form.SetP0TxtBoxInfoText($"\tMarked as deleted #{counterMarkedAsDeleted}.");
                    form.SetP0TxtBoxInfoText($"\tAlready before downloaded #{counterAlreadyBeforeDownloaded}.");
                    form.SetP0TxtBoxInfoText($"\tDownloaded #{counterDownloaded}.");

                    for (var i = 0; i < changedMedia.media.Length; i++)
                    {
                        if (changedMedia.media[i].deleted)
                        {
                            counterMarkedAsDeleted++;
                            AdjustInfo(form, common, $"\tMarked as deleted #{counterMarkedAsDeleted - 1}.", $"\tMarked as deleted #{counterMarkedAsDeleted}.");

                            if (counterMarkedAsDeleted == MagicNumberVideosPerPage)
                            {
                                form.SetP0TxtBoxInfoText($"Download aborted becasue current page cantains {MagicNumberVideosPerPage} as deleted marked videos!");
                                aborted = true;
                                break;
                            }
                            continue;
                        }

                        var networkObject = baseData.Networks.Where(x => x.Id == changedMedia.media[i].network_id).ToList();
                        if (networkObject == null || networkObject.Count() != 1)
                        {
                            // Should never be true!
                            continue;
                        }
                        var cameraObject = networkObject[0].Cameras.Where(x => x.Id == changedMedia.media[i].device_id).ToList();
                        if (cameraObject == null || cameraObject.Count() != 1)
                        {
                            // Should never be true!
                            continue;
                        }

                        // Method called and not just path combined because called method creates directory if it does not exist.
                        var networkNameAndId     = common.CombineNameAndId(changedMedia.media[i].network_name, changedMedia.media[i].network_id);
                        var cameraNameAndId      = common.CombineNameAndId(changedMedia.media[i].device_name, changedMedia.media[i].device_id);
                        var storagePath          = GetStoragePath(saveDirectory, networkNameAndId, cameraNameAndId);
                        var videoFileName        = changedMedia.media[i].created_at.ToString(timestampFormatter) + ".mp4";
                        var videoPathAndFileName = $"{storagePath}\\{videoFileName}";
                        cameraObject[0].Media.PathAndFileNameVideos.Add(videoPathAndFileName);
                        if (!File.Exists(videoPathAndFileName))
                        {
                            var videoByteArray = uweR70_GetData.VideoAsync(baseData, changedMedia.media[i].media).Result;
                            mediaIdListBody.media_list.Add(changedMedia.media[i].id);
                            File.WriteAllBytes(videoPathAndFileName, videoByteArray);
                            counterDownloaded++;
                            AdjustInfo(form, common, $"\tDownloaded #{counterDownloaded - 1}.", $"\tDownloaded #{counterDownloaded}.");
                        }
                        else
                        {
                            counterAlreadyBeforeDownloaded++;
                            AdjustInfo(form, common, $"\tAlready before downloaded #{counterAlreadyBeforeDownloaded - 1}.", $"\tAlready before downloaded #{counterAlreadyBeforeDownloaded}.");
                        }
                    }
                } while (!aborted);

                form.SetP0TxtBoxInfoText(string.Empty);
                form.SetP0TxtBoxInfoText("Done!");
                return(baseData);
            }
            catch (Exception ex)
            {
                form.SetP0TxtBoxInfoText(string.Empty);
                form.SetP0TxtBoxInfoText($"### ERROR ###");
                var errorMessage = ex.Message;
                if (ex.InnerException != null && !string.IsNullOrEmpty(ex.InnerException.Message))
                {
                    errorMessage = ex.InnerException.Message;
                }
                form.SetP0TxtBoxInfoText($"\t{errorMessage}");
                return(null);
            }
        }