Exemple #1
0
        private void ClientDecoded(ActiveClientEventArgs args)
        {
            var ctx = new ProtocolContext();

            ctx.ProtocolDatas.Add((ProtocolData)args.ProtocolData);
            ctx.SaveChanges();
        }
Exemple #2
0
        private void showNotifyIconMenu(ProtocolContext ctx)
        {
            int index;
            var saveDev = findItemFromSameDevice(ctx, out index);

            if (saveDev != null)
            {
                notifyIcon.ContextMenuStrip.Items.RemoveAt(index + 1);
                notifyIcon.ContextMenuStrip.Items.Remove(saveDev);
            }


            ToolStripItem itemFound = findItemFromSameCtx(ctx);

            if (itemFound == null)
            {
                var item = new ToolStripMenuItem();
                item.Text    = getOverallProgressText(ctx);
                item.Tag     = ctx;
                item.Enabled = false;
                deviceStipItems.Add(ctx, item);


                var item2 = new ToolStripMenuItem();
                item2.Text    = getSingleFileText(ctx);
                item2.Enabled = false;


                notifyIcon.ContextMenuStrip.Items.Insert(2, item);
                notifyIcon.ContextMenuStrip.Items.Insert(3, item2);
                //notifyIcon.ShowBalloonTip(3000, Resources.ProductName, string.Format(Resources.BallonText_Transferring, ctx.device_name, ctx.total_count), ToolTipIcon.Info);
            }
        }
        public void testFileStart_has_dup()
        {
            fac.Setup(x => x.CreateTempFile()).Returns(tempFile.Object).Verifiable();

            var fileUtil = new Mock <IFileUtility>();

            fileUtil.Setup(x => x.HasDuplicateFile(It.IsAny <FileContext>(), It.IsAny <string>())).Returns(true);
            var    state    = new TransmitInitState(fileUtil.Object);
            var    ctx      = new ProtocolContext(fac.Object, storage.Object, state);
            string sentData = "";

            ctx.SendFunc = (x) => { sentData = x; };

            var cmd = new TextCommand
            {
                action         = "file-start",
                file_name      = "name",
                file_size      = 1234,
                type           = "audio",
                folder         = "/sto/pp",
                datetime       = DateTime.Now,
                total_count    = 1000,
                backuped_count = 333,
            };

            ctx.handleFileStartCmd(cmd);

            Assert.IsTrue(ctx.GetState() is TransmitInitState);
            Assert.IsNull(ctx.fileCtx);

            var o = JsonConvert.DeserializeObject <TextCommand>(sentData);

            Assert.AreEqual("file-exist", o.action);
            Assert.AreEqual("name", o.file_name);
        }
        public InfiniteStorageWebSocketService()
        {
            if (!Directory.Exists(MyFileFolder.Temp))
            {
                Directory.CreateDirectory(MyFileFolder.Temp);
                var dir = new DirectoryInfo(MyFileFolder.Temp);
                dir.Attributes = FileAttributes.Hidden | dir.Attributes;
            }

            var storage = new PendingFileStorage();

            var ctx = new ProtocolContext(new TempFileFactory(MyFileFolder.Temp), storage, new UnconnectedState())
            {
                SendFunc = this.Send,
                StopFunc = this.Stop,
                PingFunc = this.Ping
            };

            ctx.OnConnectAccepted   += DeviceAccepted;
            ctx.OnPairingRequired   += PairingRequesting;
            ctx.OnTotalCountUpdated += TotalCountUpdated;
            ctx.OnFileReceiving     += FileReceiving;
            ctx.OnFileReceived      += FileReceived;
            ctx.OnFileEnding        += FileEnding;

            handler = new ProtocolHanlder(ctx);
        }
Exemple #5
0
        public void unconnected_connect_conntected()
        {
            var connectMsg = new TextCommand {
                action = "connect", device_name = "dev", device_id = "guid1"
            };

            var tempFactory    = new Mock <ITempFileFactory>();
            var fileStorage    = new Mock <IFileStorage>();
            var connectHandler = new Mock <IConnectMsgHandler>();
            var retState       = new Mock <AbstractProtocolState>();


            var initState = new UnconnectedState();

            initState.handler = connectHandler.Object;
            var ctx = new ProtocolContext(tempFactory.Object, storage.Object, initState);

            connectHandler.Setup(x => x.HandleConnectMsg(connectMsg, It.IsAny <ProtocolContext>())).Callback(() => { ctx.SetState(retState.Object); }).Verifiable();

            ctx.handleConnectCmd(connectMsg);

            connectHandler.VerifyAll();
            Assert.AreEqual(retState.Object, ctx.GetState());
            Assert.AreEqual("dev", ctx.device_name);
            Assert.AreEqual("guid1", ctx.device_id);
        }
        public void testDisapprove()
        {
            var state = new WaitForApproveState();
            var ctx   = new ProtocolContext(null, null, state)
            {
                device_id = "dd", device_name = "na"
            };

            string sentData = null;

            ctx.SendFunc = (t) => { sentData = t; };

            CloseStatusCode code   = CloseStatusCode.NORMAL;
            string          reason = null;

            ctx.StopFunc = (code1, reason1) => { code = code1; reason = reason1; };

            state.handleDisapprove(ctx);

            var o = JObject.Parse(sentData);

            Assert.AreEqual("denied", o["action"]);
            Assert.AreEqual("user rejected", o["reason"]);

            Assert.IsTrue(ctx.GetState() is UnconnectedState);
            Assert.AreEqual(CloseStatusCode.POLICY_VIOLATION, code);
            Assert.AreEqual("User rejected", reason);
        }
Exemple #7
0
        public void replyAcceptMsgData_HaveExistingData()
        {
            fileStorage.Setup(x => x.setDeviceName("dev123")).Verifiable();
            string sentTxt = null;

            ctx.SendFunc = (txt) => sentTxt = txt;

            ProtocolContext evtCtx = null;

            ctx.OnConnectAccepted += (sr, ev) => { evtCtx = ev.ctx; };

            ctx.device_name = "dev";

            var util = new Mock <IConnectMsgHandlerUtil>();

            util.Setup(x => x.GetClientInfo("id1")).Returns(new Device
            {
                device_id   = "id1",
                device_name = "dev",
                folder_name = "dev123"
            });
            util.Setup(x => x.GetServerId()).Returns("server_id1");
            util.Setup(x => x.GetPhotoFolder()).Returns(@"c:\folder1\");
            util.Setup(x => x.GetFreeSpace(@"c:\folder1\")).Returns(102410241024L);
            util.Setup(x => x.GetDeviceSummary("id1")).Returns(
                new DeviceSummary
            {
                photo_count  = 100,
                video_count  = 200,
                audio_count  = 300,
                backup_range = new TimeRange(
                    new DateTime(2012, 1, 2, 0, 0, 0, DateTimeKind.Utc).ToLocalTime(),
                    new DateTime(2012, 1, 3, 0, 0, 0, DateTimeKind.Utc))
            }).Verifiable();

            var hdl = new ConnectMsgHandler();

            hdl.Util = util.Object;
            hdl.HandleConnectMsg(new TextCommand {
                action = "connect", device_name = "dev", device_id = "id1", transfer_count = 111
            }, ctx);

            JObject o = JObject.Parse(sentTxt);

            Assert.AreEqual("accept", o["action"]);
            Assert.AreEqual("server_id1", o["server_id"]);
            Assert.AreEqual(@"c:\folder1\", o["backup_folder"]);
            Assert.AreEqual(102410241024L, o["backup_folder_free_space"]);
            Assert.AreEqual(100, o["photo_count"]);
            Assert.AreEqual(200, o["video_count"]);
            Assert.AreEqual(300, o["audio_count"]);
            Assert.AreEqual(new DateTime(2012, 1, 2, 0, 0, 0, DateTimeKind.Utc), o["backup_startdate"].Value <DateTime>());
            Assert.AreEqual(new DateTime(2012, 1, 3, 0, 0, 0, DateTimeKind.Utc), o["backup_enddate"]);


            Assert.AreEqual(ctx, evtCtx);
            Assert.IsTrue(ctx.GetState() is TransmitInitState);

            fileStorage.VerifyAll();
        }
        public void testFileStart_no_dup()
        {
            fac.Setup(x => x.CreateTempFile()).Returns(tempFile.Object).Verifiable();

            var    fileUtil = new Mock <IFileUtility>();
            var    state    = new TransmitInitState(fileUtil.Object);
            var    ctx      = new ProtocolContext(fac.Object, storage.Object, state);
            string sentData = "";

            ctx.SendFunc = (x) => { sentData = x; };

            var cmd = new TextCommand
            {
                action         = "file-start",
                file_name      = "name",
                file_size      = 1234,
                type           = "audio",
                folder         = "/sto/pp",
                datetime       = DateTime.Now,
                total_count    = 1000,
                backuped_count = 333,
            };

            ctx.handleFileStartCmd(cmd);

            Assert.AreEqual(cmd.file_name, ctx.fileCtx.file_name);
            Assert.AreEqual(cmd.file_size, ctx.fileCtx.file_size);
            Assert.AreEqual(FileAssetType.audio, ctx.fileCtx.type);
            Assert.AreEqual(cmd.folder, ctx.fileCtx.folder);
            Assert.AreEqual(cmd.datetime, ctx.fileCtx.datetime);
            Assert.AreEqual(cmd.total_count, ctx.total_count);
            Assert.AreEqual(cmd.backuped_count, ctx.backup_count);

            Assert.IsTrue(ctx.GetState() is TransmitStartedState);
        }
Exemple #9
0
        public void firstConnect__replyWaitForPairing()
        {
            string sentTxt = null;

            ctx.SendFunc = (txt) => sentTxt = txt;

            ProtocolContext evtCtx = null;

            ctx.OnPairingRequired += (sr, ev) => { evtCtx = ev.ctx; };

            var util = new Mock <IConnectMsgHandlerUtil>();

            util.Setup(x => x.GetClientInfo("id1")).Returns(null as Device);

            var hdl = new ConnectMsgHandler();

            hdl.Util = util.Object;
            hdl.HandleConnectMsg(new TextCommand {
                action = "connect", device_name = "dev", device_id = "id1", transfer_count = 111
            }, ctx);


            Assert.IsFalse(string.IsNullOrEmpty(sentTxt));
            var o = JObject.Parse(sentTxt);

            Assert.AreEqual("wait-for-pair", o["action"]);

            Assert.AreEqual(evtCtx, ctx);
            Assert.IsTrue(ctx.GetState() is WaitForApproveState);
        }
Exemple #10
0
        public override void handleConnectCmd(ProtocolContext ctx, TextCommand cmd)
        {
            ctx.device_id   = cmd.device_id;
            ctx.device_name = cmd.device_name;

            handler.HandleConnectMsg(cmd, ctx);
        }
Exemple #11
0
 public PairingRequestDialog(ProtocolContext ctx)
 {
     this.ctx = ctx;
     InitializeComponent();
     Text         = Resources.ProductName;
     Icon         = Resources.ProductIcon;
     DialogResult = System.Windows.Forms.DialogResult.Cancel;
 }
        public void Create_Should_UseVirgilService_AccordingToAppToken()
        {
            var contextVirgil = ProtocolContext.Create(
                appToken: "AT.SOMETOKEN",
                servicePublicKey: this.servicePublicKey,
                appSecretKey: this.clientSecretKey);

            Assert.Equal(this.virgilServiceUrl, ((HttpClientBase)contextVirgil.Client).BaseUri.AbsoluteUri);
        }
Exemple #13
0
        public void setup()
        {
            var factory = new Mock <ITempFileFactory>();
            var state   = new Mock <AbstractProtocolState>();

            fileStorage = new Mock <IFileStorage>();

            ctx = new ProtocolContext(factory.Object, fileStorage.Object, state.Object);
        }
        private ProtocolContext InitContext(string applicationToken, string servicePubKey, string clientPrivKey, string serviceSubdomain)
        {
            var serializer = new HttpBodySerializer();
            var serviceUrl = ServiceUrl.ProvideByToken(applicationToken).Replace("api", serviceSubdomain);
            var client     = new PheHttpClient(serializer, applicationToken, serviceUrl);
            var context    = new ProtocolContext(applicationToken, client, servicePubKey, clientPrivKey);

            return(context);
        }
Exemple #15
0
        private static string getSingleFileText(ProtocolContext ctx)
        {
            if (ctx.NoMoreToTransfer())
            {
                return(Resources.MenuItem_BackupComplete);
            }

            return(ctx.temp_file != null?
                   string.Format("  - {0} : {1}%", ctx.fileCtx.file_name, 100 *ctx.temp_file.BytesWritten / ctx.fileCtx.file_size) :
                       Resources.MenuItem_Preparing);
        }
Exemple #16
0
        public void call_state_handle_upcate_count()
        {
            var state = new Mock <AbstractProtocolState>();
            var ctx   = new ProtocolContext(null, null, state.Object);

            state.Setup(x => x.handleUpdateCountCmd(ctx, It.Is <TextCommand>(t => t.action == "update-count" && t.transfer_count == 1000))).Verifiable();


            ctx.handleUpdateCountCmd(new TextCommand {
                action = "update-count", transfer_count = 1000
            });
        }
        public void Create_Should_RaiseException_IfTokenDoesnHaveCorrectPrefix()
        {
            var ex = Record.Exception(() =>
            {
                ProtocolContext.Create(
                    appToken: "OO.SOMETOKEN",
                    servicePublicKey: this.servicePublicKey,
                    appSecretKey: this.clientSecretKey);
            });

            Assert.IsType <ServiceClientException>(ex);
        }
Exemple #18
0
        private void updateNotifyIconMenu(ProtocolContext ctx)
        {
            ToolStripItem itemFound = findItemFromSameCtx(ctx);

            if (itemFound != null)
            {
                itemFound.Text = getOverallProgressText(ctx);

                var nextIdx = notifyIcon.ContextMenuStrip.Items.IndexOf(itemFound) + 1;

                notifyIcon.ContextMenuStrip.Items[nextIdx].Text = getSingleFileText(ctx);
            }
        }
Exemple #19
0
        protected override void OnStartup(StartupEventArgs e)
        {
            AppDomain.CurrentDomain.UnhandledException += UnhandledExceptionHandler;
            Current.DispatcherUnhandledException       += AppUnhandleExceptionHandler;
            var ctx       = new ProtocolContext();
            var protocols = new List <IProtocol>();

            protocols.AddRange(ctx.Protocols.Include("ProtocolStructures")
                               .Include("ProtocolCommands.CommandDatas")
                               .Include("Firmwares")
                               .ToList());
            EncodingManager.LoadEncoder(protocols);
        }
Exemple #20
0
        public static void CloseOpenedWindow(ProtocolContext ctx)
        {
            List <BackToPhoneDialog> opendDialogs;

            lock (cs)
            {
                opendDialogs = OpenDialogs.Where(x => x.Ctx == ctx).ToList();
            }

            foreach (var dialog in opendDialogs)
            {
                SynchronizationContextHelper.SendMainSyncContext(() => { dialog.Close(); });
            }
        }
        [Fact] // HTC-10
        public void Create_Should_RaiseExceptionIfUpdateTokenVersionIsIncorect()
        {
            // if update token version != current version + 1, then raise exception.
            var ex = Record.Exception(() =>
            {
                ProtocolContext.Create(
                    appToken: this.appToken,
                    servicePublicKey: this.servicePublicKey,
                    appSecretKey: this.clientSecretKey,
                    updateToken: this.updateTokenV3);
            });

            Assert.IsType <WrongVersionException>(ex);
        }
        [Fact] // HTC-8
        public void Create_Should_SetKeysVersionToCurrentVersion()
        {
            // if there is no updateToken, then
            // 1)current version is set up from keys' version
            // 2)context has only one pair of keys
            var contextWithUpdateToken = ProtocolContext.Create(
                appToken: this.appToken,
                servicePublicKey: this.servicePublicKey2,
                appSecretKey: this.clientSecretKey2);

            Assert.Equal <uint>(2, contextWithUpdateToken.CurrentVersion);
            Assert.True(contextWithUpdateToken.PheClients.Count == 1);
            Assert.Equal <uint>(2, contextWithUpdateToken.PheClients.Keys.First <uint>());
        }
        public void no_type_error()
        {
            var state = new TransmitInitState();
            var ctx   = new ProtocolContext(fac.Object, storage.Object, state);
            var cmd   = new TextCommand
            {
                action    = "file-start",
                file_name = "name",
                file_size = 1234,
                folder    = "/sto/pp",
                datetime  = DateTime.Now
            };

            ctx.handleFileStartCmd(cmd);
        }
        [Fact] // HTC-9
        public void Create_Should_RotateKeysIfUpdateTokenIsBigger()
        {
            // if update token version == current version + 1, then
            // 1)new keys are calculated
            // 2)current vesion == updateToken version
            // 3)context keeps keys for previous and current versions
            var contextWithUpdateToken = ProtocolContext.Create(
                appToken: this.appToken,
                servicePublicKey: this.servicePublicKey,
                appSecretKey: this.clientSecretKey,
                updateToken: this.updateTokenV2);

            Assert.Equal <uint>(2, contextWithUpdateToken.CurrentVersion);
            Assert.Equal(2, contextWithUpdateToken.PheClients.Count);
            Assert.Equal <uint>(2, contextWithUpdateToken.PheClients.Keys.Last <uint>());
        }
Exemple #25
0
        public void setup()
        {
            fac     = new Mock <ITempFileFactory>();
            temp    = new Mock <ITempFile>();
            storage = new Mock <IFileStorage>();
            util    = new Mock <ITransmitStateUtility>();

            ctx = new ProtocolContext(fac.Object, storage.Object, null)
            {
                device_id = "dev_id",
                fileCtx   = new FileContext()
                {
                    file_name = "n", file_size = 1000, folder = "f", datetime = DateTime.Now, type = FileAssetType.image
                },
                temp_file = temp.Object
            };
        }
        public void testApprove()
        {
            var util = new Mock <IConnectMsgHandlerUtil>();

            util.Setup(x => x.GetServerId()).Returns("server_id1").Verifiable();
            util.Setup(x => x.GetPhotoFolder()).Returns(@"c:\folder1\").Verifiable();
            util.Setup(x => x.GetFreeSpace(It.IsAny <string>())).Returns(123456).Verifiable();
            util.Setup(x => x.GetUniqueDeviceFolder("na")).Returns("ggyyUnique_dev_name").Verifiable();
            util.Setup(x => x.Save(It.Is <Device>(
                                       (d) =>
                                       d.device_id == "dd" &&
                                       d.device_name == "na" &&
                                       d.folder_name == "ggyyUnique_dev_name"
                                       ))).Callback <Device>((dev) => { }).Verifiable();

            var storage = new Mock <IFileStorage>();

            storage.Setup(x => x.setDeviceName("ggyyUnique_dev_name")).Verifiable();

            var state = new WaitForApproveState();
            var ctx   = new ProtocolContext(null, storage.Object, state)
            {
                device_id = "dd", device_name = "na"
            };

            string sentData = null;

            ctx.SendFunc = (t) => { sentData = t; };

            state.Util = util.Object;
            state.handleApprove(ctx);

            var o = JObject.Parse(sentData);

            Assert.AreEqual("accept", o["action"]);
            Assert.AreEqual("server_id1", o["server_id"]);
            Assert.AreEqual(@"c:\folder1\", o["backup_folder"]);
            Assert.AreEqual(123456L, o["backup_folder_free_space"]);

            Assert.IsTrue(ctx.GetState() is TransmitInitState);
            Assert.AreEqual("ggyyUnique_dev_name", ctx.device_folder_name);

            storage.VerifyAll();
            util.VerifyAll();
        }
Exemple #27
0
        private ToolStripItem findItemFromSameCtx(ProtocolContext targetCtx)
        {
            ToolStripItem itemFound = null;

            foreach (var it in notifyIcon.ContextMenuStrip.Items)
            {
                var stripItem = it as ToolStripItem;
                if (stripItem != null && stripItem.Tag is ProtocolContext)
                {
                    var ctx = stripItem.Tag as ProtocolContext;

                    if (ctx == targetCtx)
                    {
                        itemFound = stripItem;
                        break;
                    }
                }
            }
            return(itemFound);
        }
        public void ctx_counts_are_updated_by_update_count_msg()         // because update-count is deprecated
        {
            var state = new TransmitInitState();
            var ctx   = new ProtocolContext(fac.Object, storage.Object, state);

            ctx.total_count = 1000;

            var cmd = new TextCommand
            {
                action         = "update-count",
                transfer_count = 3322,
                backuped_count = 1000,
            };

            ctx.handleUpdateCountCmd(cmd);

            Assert.AreEqual(cmd.transfer_count, ctx.total_count);
            Assert.AreEqual(cmd.backuped_count, ctx.backup_count);
            Assert.AreEqual(state, ctx.GetState());
        }
Exemple #29
0
        private ToolStripItem findItemFromSameDevice(ProtocolContext targetCtx, out int index)
        {
            index = -1;
            ToolStripItem itemFound = null;

            //foreach (var it in notifyIcon.ContextMenuStrip.Items)
            for (int i = 0; i < notifyIcon.ContextMenuStrip.Items.Count; i++)
            {
                var stripItem = notifyIcon.ContextMenuStrip.Items[i] as ToolStripItem;
                if (stripItem != null && stripItem.Tag is ProtocolContext)
                {
                    var ctx = stripItem.Tag as ProtocolContext;

                    if (ctx.device_id == targetCtx.device_id)
                    {
                        itemFound = stripItem;
                        index     = i;
                        break;
                    }
                }
            }
            return(itemFound);
        }
Exemple #30
0
        public async Task Should_EnrollNewRecord_When_PasswordSpecified()
        {
            var context = ProtocolContext.Create(
                appId: "e60e6d91b0e3480b816f306337e96aaa",
                accessToken: "-rTsFFkAOGf6am4bEF_aAdoHt2kOGy78",
                serverPublicKey: "PK.1.BJ2+TUK/WVTfuYjgKj0KOVH4nKUqdBihqhH/EN1fyggwATu4gzGMC0P35jBDZnSTEFdm2zmC4qndyI5MKBvFjX8=",
                clientSecretKey: "SK.1.W7FVp+LhG/ton7P+wKu0ndIPECY5+mTzX7iWaW9+sXA="
                );

            var protocol = new Protocol(context);

            var record = await protocol.EnrollAsync("passw0rd");

            await Task.Delay(2000);

            var verifyResult = await protocol.VerifyAsync(record, "passw0rd");

            var context1 = ProtocolContext.Create(
                appId: "e60e6d91b0e3480b816f306337e96aaa",
                accessToken: "-rTsFFkAOGf6am4bEF_aAdoHt2kOGy78",
                serverPublicKey: "PK.1.BJ2+TUK/WVTfuYjgKj0KOVH4nKUqdBihqhH/EN1fyggwATu4gzGMC0P35jBDZnSTEFdm2zmC4qndyI5MKBvFjX8=",
                clientSecretKey: "SK.1.W7FVp+LhG/ton7P+wKu0ndIPECY5+mTzX7iWaW9+sXA=",
                updateTokens: new[] {
                "UT.2.MEQEIGw7O3Hm/9rSUBrShEFKiQQk8yi39TnGS7dpUP9/8aQiBCBhp5NxCylYeCpJq/hjK2SuTiA9Pl8zD8BZUDau6B72Ag=="
            }
                );

            var protocol1 = new Protocol(context1);

            var record1 = protocol1.Update(record);

            await Task.Delay(2000);

            var verifyResult1 = await protocol1.VerifyAsync(record1, "passw0rd");

            Assert.True(verifyResult.IsSuccess);
        }