Example #1
0
        public async Task NewEmails(string id)
        {
            // 获取所有待更新的key
            var group = LiteDb.SingleOrDefault <Group>(g => g._id == id);

            if (group == null)
            {
                await ResponseErrorAsync($"未通过{id}找到组");

                return;
            }
            // 根据key来进行实例化
            if (group.groupType == "send")
            {
                var emailInfos = Body.ToObject <List <SendBox> >();
                emailInfos.ForEach(e => e.groupId = id);
                LiteDb.Database.GetCollection <SendBox>().InsertBulk(emailInfos);
                await ResponseSuccessAsync(emailInfos);
            }
            else
            {
                var emailInfos = Body.ToObject <List <ReceiveBox> >();
                emailInfos.ForEach(e => e.groupId = id);
                LiteDb.Database.GetCollection <ReceiveBox>().InsertBulk(emailInfos);
                await ResponseSuccessAsync(emailInfos);
            }
        }
        /// <summary>
        /// Creates a new RhinoTestCaseCollection under context.
        /// </summary>
        /// <param name="authentication">Authentication object by which to create RhinoTestCaseCollection.</param>
        /// <param name="data">RhinoTestCaseCollection data to create.</param>
        /// <returns>The <see cref="RhinoTestCaseCollection.Id"/> of the newly created entity.</returns>
        public string Post(Authentication authentication, RhinoTestCaseCollection data)
        {
            // validate
            CreateCollection(authentication);

            // get collection
            var collection = LiteDb.GetCollection <RhinoTestCaseCollection>(name: Collection);

            // insert
            collection.Insert(entity: data);

            // exit conditions
            if (data.Configurations == null || data.Configurations.Count == 0)
            {
                return($"{data.Id}");
            }

            // cascade
            foreach (var configuration in data.Configurations)
            {
                ApplyToConfiguration(authentication, configuration, collection: data);
            }

            // response
            return($"{data.Id}");
        }
        public void Test(Authentication authentication)
        {
            // ensure
            CreateCollection(authentication);

            // get environment
            var collection            = LiteDb.GetCollection <RhinoEnvironmentModel>(name: Collection);
            var environmentCollection = Get(name: Collection, collection);

            // not found
            if (environmentCollection.StatusCode == HttpStatusCode.NotFound)
            {
                var onEnvironment = new RhinoEnvironmentModel
                {
                    Environment = new ConcurrentDictionary <string, object>(),
                    Name        = Collection
                };

                collection.Insert(onEnvironment);
            }

            if (1 + 1 == 2)
            {
                var a = Get(name: Collection, collection);
            }
        }
        public (HttpStatusCode StatusCode, RhinoEnvironmentModel Model) Get(Authentication authentication)
        {
            try
            {
                // ensure
                CreateCollection(authentication);

                // get environment
                var collection            = LiteDb.GetCollection <RhinoEnvironmentModel>(name: Collection);
                var environmentCollection = Get(name: Collection, collection);

                // not found
                if (environmentCollection.StatusCode == HttpStatusCode.NotFound)
                {
                    var onEnvironment = new RhinoEnvironmentModel
                    {
                        Environment = new ConcurrentDictionary <string, object>(),
                        Name        = Collection
                    };

                    return(HttpStatusCode.OK, onEnvironment);
                }

                // append
                var entity = Get(name: Collection, collection).Environment;

                // save
                return(HttpStatusCode.OK, entity);
            }
            catch (Exception e) when(e != null)
            {
                return(HttpStatusCode.InternalServerError, new RhinoEnvironmentModel());
            }
        }
Example #5
0
        public async Task UserInfo([QueryField] string token)
        {
            // 用 token 获取用户信息
            UserConfig uConfig  = IoC.Get <UserConfig>();
            JwtToken   jwtToken = new JwtToken(uConfig.TokenSecret, token);

            if (jwtToken.TokenValidState != TokenValidState.Valid)
            {
                await ResponseErrorAsync("token无效");

                return;
            }


            // 返回用户信息
            var user = LiteDb.Query <User>().Where(u => u.userId == jwtToken.UserId).FirstOrDefault();

            if (user == null)
            {
                await ResponseErrorAsync("未找到用户!");

                return;
            }

            if (string.IsNullOrEmpty(user.avatar))
            {
                user.avatar = uConfig.DefaultAvatar;
            }

            await ResponseSuccessAsync(user);
        }
        public HttpStatusCode Sync(Authentication authentication)
        {
            try
            {
                // ensure
                CreateCollection(authentication);

                // get environment
                var collection            = LiteDb.GetCollection <RhinoEnvironmentModel>(name: Collection);
                var environmentCollection = Get(name: Collection, collection);

                // not found
                if (environmentCollection.StatusCode == HttpStatusCode.NotFound)
                {
                    return(HttpStatusCode.NotFound);
                }

                // get
                var entity = Get(name: Collection, collection).Environment;
                entity.Environment ??= new ConcurrentDictionary <string, object>();

                // sync
                foreach (var item in entity.Environment)
                {
                    AutomationEnvironment.SessionParams[item.Key] = item.Value;
                }

                // save
                return(HttpStatusCode.OK);
            }
            catch (Exception e) when(e != null)
            {
                return(HttpStatusCode.InternalServerError);
            }
        }
Example #7
0
        public async Task NewEmail(string id)
        {
            // 根据id获取组
            var group = LiteDb.SingleOrDefault <Group>(g => g._id == id);

            if (group == null)
            {
                await ResponseErrorAsync($"未通过{id}找到组");

                return;
            }
            // 根据key来进行实例化
            EmailInfo res;

            if (group.groupType == "send")
            {
                var emailInfo = Body.ToObject <SendBox>();
                res = LiteDb.Upsert2(g => g.email == emailInfo.email, emailInfo);
            }
            else
            {
                var emailInfo = Body.ToObject <ReceiveBox>();
                res = LiteDb.Upsert2(g => g.email == emailInfo.email, emailInfo);
            }

            await ResponseSuccessAsync(res);
        }
Example #8
0
        public async Task DeleteGroup()
        {
            List <string> ids = Body["groupIds"].ToObject <List <string> >();

            LiteDb.DeleteMany <Group>(g => ids.Contains(g._id));
            await ResponseSuccessAsync(ids);
        }
        public async Task GetAllSuccessRate()
        {
            // 找到当前的用户名
            var userId = Token.UserId;
            // 获取用户发送的历史组
            var historyGroups = LiteDb.Fetch <HistoryGroup>(g => g.userId == userId).ToList();

            if (historyGroups.Count < 1)
            {
                // 返回1
                await ResponseSuccessAsync(1);

                return;
            }
            ;


            // 查找历史组下面的所有的发件
            var sendItems = LiteDb.Fetch <SendItem>(Query.In(Fields.historyId, new BsonArray(historyGroups.ConvertAll(hg => new BsonValue(hg._id)))));

            if (sendItems.Count < 1)
            {
                // 返回1
                await ResponseSuccessAsync(1);

                return;
            }

            // 计算比例
            var successItems = sendItems.FindAll(item => item.isSent);

            await ResponseSuccessAsync(successItems.Count * 1.0 / sendItems.Count);
        }
        public async Task GetSendItems(string historyId)
        {
            var results = LiteDb.Fetch <SendItem>(s => s.historyId == historyId);

            // 获取状态
            await ResponseSuccessAsync(results);
        }
Example #11
0
        /// <summary>
        /// PUT a new Rhino.Api.Contracts.Configuration.RhinoConfiguration into this domain collection.
        /// </summary>
        /// <param name="authentication">Authentication object by which to access the collection.</param>
        /// <param name="id">Rhino.Api.Contracts.Configuration.RhinoConfiguration.Id to PUT.</param>
        /// <param name="data">The Rhino.Api.Contracts.Configuration.RhinoConfiguration to PUT.</param>
        /// <returns>Status code and configuration (if any).</returns>
        public (HttpStatusCode statusCode, RhinoConfiguration data) Put(Authentication authentication, string id, RhinoConfiguration data)
        {
            // validate
            CreateCollection(authentication);

            // get collection
            var collection = LiteDb.GetCollection <RhinoConfiguration>(name: Collection);

            // get configuration
            var(statusCode, configuration) = Get(id, collection);

            // not found
            if (statusCode == HttpStatusCode.NotFound)
            {
                return(statusCode, configuration);
            }

            // update
            data.Id             = configuration.Id;
            data.Authentication = authentication;
            collection.Update(entity: data);

            // results
            return(HttpStatusCode.OK, data);
        }
        /// <summary>
        /// Creates a new RhinoPageModelCollection under context.
        /// </summary>
        /// <param name="authentication">Authentication object by which to create RhinoPageModelCollection.</param>
        /// <param name="data">RhinoPageModelCollection data to create.</param>
        /// <returns>The <see cref="RhinoPageModelCollection.Id"/> of the newly created entity.</returns>
        public string Post(Authentication authentication, RhinoPageModelCollection data)
        {
            // validate
            CreateCollection(authentication);

            // get collection
            var collection = LiteDb.GetCollection <RhinoPageModelCollection>(name: Collection);

            // get models
            var namesToExclude = collection.FindAll().SelectMany(i => i.Models).Select(i => i.Name);

            data.Models = data.Models.Where(i => !namesToExclude.Contains(i.Name)).ToList();

            // insert
            if (data.Models.Count == 0)
            {
                return(string.Empty);
            }
            collection.Insert(entity: data);

            // exit conditions
            if (data.Configurations == null || data.Configurations.Count == 0)
            {
                return($"{data.Id}");
            }

            // cascade
            foreach (var configuration in data.Configurations)
            {
                ApplyToConfiguration(authentication, configuration, collection: data);
            }

            // response
            return($"{data.Id}");
        }
        public async Task GetTemplates(string id)
        {
            // 获取用户名
            var result = LiteDb.SingleOrDefault <Template>(t => t.userId == Token.UserId && t._id == id);

            await ResponseSuccessAsync(result);
        }
        public async Task GetTemplates()
        {
            // 获取用户名
            List <Template> results = LiteDb.Fetch <Template>(t => t.userId == Token.UserId);

            await ResponseSuccessAsync(results);
        }
Example #15
0
        public async Task GetEmails(string id)
        {
            var group = LiteDb.SingleOrDefault <Group>(g => g._id == id);

            if (group == null)
            {
                await ResponseErrorAsync($"未通过{id}找到组");

                return;
            }

            List <EmailInfo> results = new List <EmailInfo>();

            if (group.groupType == "send")
            {
                var emails = LiteDb.Fetch <SendBox>(e => e.groupId == id).ToList();
                results.AddRange(emails);
            }
            else
            {
                var emails = LiteDb.Fetch <ReceiveBox>(e => e.groupId == id).ToList();
                results.AddRange(emails);
            }

            await ResponseSuccessAsync(results);
        }
Example #16
0
        public async Task DeleteEmail(string id)
        {
            // 获取所有待更新的key
            LiteDb.Delete <SendBox>(id);
            LiteDb.Delete <ReceiveBox>(id);

            await ResponseSuccessAsync("success");
        }
        /// <summary>
        /// 生成之后的操作
        /// </summary>
        /// <param name="sendItems"></param>
        /// <param name="receiveBoxes"></param>
        protected override void PreviewItemCreated(List <SendItem> sendItems, List <ReceiveBox> receiveBoxes)
        {
            // 生成发送的组
            // 获取发件箱

            // 判断数据中是否有发件人
            var            senderIds = new List <string>();
            List <SendBox> senders   = null;

            if (senderIds.Count > 0)
            {
                // 使用选择发件人发件
                senders = LiteDb.Fetch <SendBox>(sd => senderIds.Contains(sd._id));
            }
            else
            {
                senders = LiteDb.Database.GetCollection <SendBox>().FindAll().ToList();
            }

            // 添加历史
            HistoryGroup historyGroup = new HistoryGroup()
            {
                userId       = _userId,
                createDate   = DateTime.Now,
                subject      = Subject,
                data         = JsonConvert.SerializeObject(Data),
                receiverIds  = receiveBoxes.ConvertAll(rec => rec._id),
                templateId   = Template._id,
                templateName = Template.name,
                senderIds    = senders.ConvertAll(s => s._id),
                sendStatus   = SendStatus.Sending,
            };

            LiteDb.Database.GetCollection <HistoryGroup>().Insert(historyGroup);

            // 反回发件信息
            _info.historyId = historyGroup._id;

            // 如果选择发件人,默认从数据中读取发件人,所以选择的发件人数量为0
            if (Receivers == null || Receivers.Count < 1)
            {
                _info.selectedReceiverCount = 0;
            }
            else
            {
                _info.selectedReceiverCount = receiveBoxes.Count;
            }

            _info.dataReceiverCount    = Data.Count;
            _info.acctualReceiverCount = sendItems.Count;
            _info.ok          = true;
            _info.senderCount = senders.Count;

            // 将所有的待发信息添加到数据库
            sendItems.ForEach(item => item.historyId = historyGroup._id);
            LiteDb.Database.GetCollection <SendItem>().InsertBulk(sendItems);
        }
Example #18
0
        public async Task UpdateGroup(string id)
        {
            // 获取所有待更新的key
            List <string> keys  = (Body as JObject).Properties().ToList().ConvertAll(p => p.Name);
            Group         group = Body.ToObject <Group>();
            var           res   = LiteDb.Upsert2(g => g._id == id, group, new Database.Definitions.UpdateOptions(keys));

            await ResponseSuccessAsync(res);
        }
        public async Task UploadTemplate()
        {
            // 获取用户名
            var template = Body.ToObject <Template>();

            template.userId     = Token.UserId;
            template.createDate = DateTime.Now;

            LiteDb.Insert(template);
            await ResponseSuccessAsync(template);
        }
        /// <summary>
        /// Gets a single RhinoTestCaseCollection from context.
        /// </summary>
        /// <param name="authentication">Authentication object by which to get RhinoTestCaseCollection.</param>
        /// <param name="id"><see cref="RhinoTestCaseCollection.Id"/> by which to find this RhinoTestCaseCollection.</param>
        /// <returns>A RhinoTestCaseCollection instance.</returns>
        public (HttpStatusCode statusCode, RhinoTestCaseCollection data) Get(Authentication authentication, string id)
        {
            // validate
            CreateCollection(authentication);

            // get collection
            var collection = LiteDb.GetCollection <RhinoTestCaseCollection>(name: Collection);

            // get configuration
            return(Get(id, collection));
        }
        public async Task GetHistory(string historyId)
        {
            var history = LiteDb.SingleById <HistoryGroup>(historyId);

            // 获取成功的数量
            history.successCount = LiteDb.Fetch <SendItem>(s => s.historyId == history._id && s.isSent).Count;


            // 获取状态
            await ResponseSuccessAsync(history);
        }
        public async Task DeleteHistoryGroup(string historyId)
        {
            // 删除发送记录
            LiteDb.DeleteMany <SendItem>(item => item.historyId == historyId);

            // 删除组
            LiteDb.Delete <HistoryGroup>(historyId);

            // 获取状态
            await ResponseSuccessAsync(true);
        }
Example #23
0
        /// <summary>
        /// DELETE all configurations from this domain state.
        /// </summary>
        /// <param name="authentication">Authentication object by which to access the collection.</param>
        /// <returns>Status code.</returns>
        public HttpStatusCode Delete(Authentication authentication)
        {
            // validate
            CreateCollection(authentication);

            // get collection > configuration
            var collection = LiteDb.GetCollection <RhinoConfiguration>(name: Collection);

            // delete
            collection.DeleteAll();
            return(HttpStatusCode.NoContent);
        }
Example #24
0
        public async Task UserLogin()
        {
            // 读取jsonData
            var body = JObject.Parse(await HttpContext.GetRequestBodyAsStringAsync());

            string userId   = body.SelectToken(Fields.userName).ValueOrDefault(string.Empty);
            string password = body.SelectToken(Fields.password).ValueOrDefault(string.Empty); // 由于是客户端,不加密

            // 判断数据正确性
            if (string.IsNullOrEmpty(userId))
            {
                await ResponseErrorAsync("用户名为空");
            }

            if (string.IsNullOrEmpty(password))
            {
                await ResponseErrorAsync("密码为空");

                return;
            }

            // 获取数据库
            var user = LiteDb.Query <User>().Where(u => u.userId == userId).FirstOrDefault();

            if (user == null)
            {
                // 新建用户
                LiteDb.Insert(new User()
                {
                    userId     = userId,
                    password   = password,
                    createDate = DateTime.Now
                });

                // 新建用户后,同时给用户建立默认配置
                LiteDb.Insert(Setting.DefaultSetting(userId));
            }
            else
            {
                // 判断密码正确性
                if (user.password != password)
                {
                    await ResponseErrorAsync("密码错误");

                    return;
                }
            }

            UserConfig uConfig  = IoC.Get <UserConfig>();
            JwtToken   jwtToken = new JwtToken(uConfig.TokenSecret, userId, JwtToken.DefaultExp());

            await ResponseSuccessAsync(new JObject(new JProperty(Fields.token, jwtToken.Token)));
        }
Example #25
0
        public async Task GetGroups([QueryField] string groupType)
        {
            if (string.IsNullOrEmpty(groupType))
            {
                await ResponseErrorAsync("请传递组的类型:[send,receive]");
            }
            ;

            var results = LiteDb.Fetch <Group>(g => g.groupType == groupType).ToList();

            await ResponseSuccessAsync(results);
        }
        /// <summary>
        /// Gets all RhinoTestCaseCollection under context.
        /// </summary>
        /// <param name="authentication">Authentication object by which to get RhinoTestCaseCollection.</param>
        /// <returns>A collection of RhinoTestCaseCollection.</returns>
        public (HttpStatusCode statusCode, IEnumerable <RhinoTestCaseCollection> data) Get(Authentication authentication)
        {
            // validate
            CreateCollection(authentication);

            // get collection
            var collection = LiteDb.GetCollection <RhinoTestCaseCollection>(name: Collection);

            collection.EnsureIndex(i => i.Id);

            // get configuration
            return(HttpStatusCode.OK, collection.FindAll());
        }
        public async Task DeleteTemplates(string id)
        {
            var deleteResult = LiteDb.Delete <Template>(id);

            if (deleteResult)
            {
                await ResponseSuccessAsync(deleteResult);
            }
            else
            {
                await ResponseErrorAsync("删除失败");
            }
        }
Example #28
0
        /// <summary>
        /// GET all configuration in this domain collection.
        /// </summary>
        /// <param name="authentication">Authentication object by which to access the collection.</param>
        /// <returns>Collection of Rhino.Api.Contracts.Configuration.RhinoConfiguration.</returns>
        public IEnumerable <RhinoConfiguration> Get(Authentication authentication)
        {
            // validate
            CreateCollection(authentication);

            // get collection
            var collection = LiteDb.GetCollection <RhinoConfiguration>(name: Collection);

            collection.EnsureIndex(i => i.Id);

            // get configuration
            return(collection.FindAll());
        }
        public async Task GetHistories()
        {
            var histories = LiteDb.Fetch <HistoryGroup>(h => h.userId == Token.UserId).OrderByDescending(item => item._id);

            foreach (HistoryGroup history in histories)
            {
                // 获取成功的数量
                history.successCount = LiteDb.Fetch <SendItem>(s => s.historyId == history._id && s.isSent).Count;
            }

            // 获取状态
            await ResponseSuccessAsync(histories);
        }
        public async Task UpsertTemplate(string id)
        {
            // 获取用户名
            var template = Body.ToObject <Template>();

            template._id        = id;
            template.userId     = Token.UserId;
            template.createDate = DateTime.Now;

            LiteDb.Upsert(template);

            // 返回结果
            await ResponseSuccessAsync(template);
        }