Esempio n. 1
0
        public async Task Recover(DeveloperUser User, App ThisApp, DeveloperDbContext _dbContext)
        {
            base.Recover(User, 1);
            var token = AppsContainer.AccessToken(ThisApp.AppId, ThisApp.AppSecret);

            var buckets = await ApiService.ViewMyBucketsAsync(await token());

            Buckets = buckets.Buckets;

            var grants = await Pylon.Services.ToAPIServer.ApiService.AllUserGrantedAsync(await token());

            Grants = grants.Grants;
        }
Esempio n. 2
0
        public async Task <CreateChannelViewModel> Init(string userId)
        {
            var token = await _appsContainer.AccessToken();

            var channel = await _channelService.CreateChannelAsync(token, $"Kahla User Channel for Id: {userId}");

            return(channel);
        }
Esempio n. 3
0
        public async Task <IActionResult> Me()
        {
            var user = await GetKahlaUser();

            await _signInManager.RefreshSignInAsync(user);

            user.IsMe = true;
            try
            {
                user = await _authService.OnlyUpdate(user);
            }
            catch (WebException e)
            {
                var accessToken = await _appsContainer.AccessToken();

                await _eventService.LogExceptionAsync(accessToken, e, HttpContext.Request.Path);
            }
            return(this.Protocol(new AiurValue <KahlaUser>(user.Build(_onlineJudger))
            {
                Code = ErrorType.Success,
                Message = "Successfully get your information."
            }));
        }
Esempio n. 4
0
        public async Task <IActionResult> CreateSite(CreateSiteViewModel model)
        {
            var user = await GetCurrentUserAsync();

            if (!ModelState.IsValid)
            {
                model.ModelStateValid = false;
                model.Recover(user);
                return(View(model));
            }
            var app = await _dbContext.Apps.FindAsync(model.AppId);

            if (app == null)
            {
                return(NotFound());
            }
            if (app.CreatorId != user.Id)
            {
                return(Unauthorized());
            }
            try
            {
                var token = await _appsContainer.AccessToken(app.AppId, app.AppSecret);

                await _sitesService.CreateNewSiteAsync(token, model.SiteName);

                return(RedirectToAction(nameof(AppsController.ViewApp), "Apps", new { id = app.AppId, JustHaveUpdated = true }));
            }
            catch (AiurUnexceptedResponse e)
            {
                ModelState.AddModelError(string.Empty, e.Response.Message);
                model.ModelStateValid = false;
                model.Recover(user);
                return(View(model));
            }
        }
Esempio n. 5
0
        public async Task <IActionResult> Phone(bool JustHaveUpdated)
        {
            var user = await GetCurrentUserAsync();

            var phone = await UserService.ViewPhoneNumberAsync(user.Id, await AppsContainer.AccessToken()());

            var model = new PhoneViewModel(user)
            {
                CurrentPhoneNumber   = phone.Value,
                PhoneNumberConfirmed = !string.IsNullOrEmpty(phone.Value),
                JustHaveUpdated      = JustHaveUpdated
            };

            return(View(model));
        }
Esempio n. 6
0
        public async Task <IActionResult> Email(bool JustHaveUpdated)
        {
            var user = await GetCurrentUserAsync();

            var emails = await UserService.ViewAllEmailsAsync(await AppsContainer.AccessToken()(), user.Id);

            var model = new EmailViewModel(user)
            {
                Emails       = emails.Items,
                PrimaryEmail = user.Email
            };

            model.JustHaveUpdated = JustHaveUpdated;
            return(View(model));
        }
Esempio n. 7
0
        public async Task <IActionResult> Create(IndexViewModel model)
        {
            var token = await _appsContainer.AccessToken();

            try
            {
                await _recordsService.CreateNewRecordAsync(token, model.NewRecordName, model.Url, new[] { "Anonymous" }, RecordType.Redirect, enabled : true);
            }
            catch (AiurUnexpectedResponse e) when(e.Code == ErrorType.NotEnoughResources)
            {
                ModelState.AddModelError(nameof(model.NewRecordName), $"Sorry but the key:'{model.NewRecordName}' already exists. Try another one.");
                return(View(nameof(Index), model));
            }
            return(View("Created", model));
        }
Esempio n. 8
0
        public async Task <IActionResult> UnBind()
        {
            var user = await GetCurrentUserAsync();

            var result = await UserService.SetPhoneNumberAsync(user.Id, await AppsContainer.AccessToken()(), string.Empty);

            if (result.Code == ErrorType.Success)
            {
                user.PhoneNumber = string.Empty;
                await _userManager.UpdateAsync(user);

                return(RedirectToAction(nameof(Phone)));
            }
            throw new InvalidOperationException();
        }
Esempio n. 9
0
        public async Task <IActionResult> InitIconUpload()
        {
            var accessToken = await _appsContainer.AccessToken();

            var siteName = _configuration["UserIconsSiteName"];
            var path     = DateTime.UtcNow.ToString("yyyy-MM-dd");
            var token    = await _tokenService.GetUploadTokenAsync(
                accessToken,
                siteName,
                "Upload",
                path);

            var address = new AiurUrl(_serviceLocation.Probe, $"/Files/UploadFile/{siteName}/{path}", new
            {
                pbtoken         = token,
                recursiveCreate = true
            });

            return(Json(new AiurValue <string>(address.ToString())
            {
                Code = ErrorType.Success,
                Message = $"Token is given. You can not upload your file to that address. And your will get your response as 'FilePath'."
            }));
        }
        public async Task FriendAcceptedEvent(string recieverId)
        {
            var token = AppsContainer.AccessToken();
            var user  = await _dbContext.Users.FindAsync(recieverId);

            var channel = user.CurrentChannel;
            var nevent  = new FriendAcceptedEvent
            {
                Type = EventType.FriendAcceptedEvent
            };

            if (channel != -1)
            {
                await _pushMessageService.PushMessageAsync(await token(), channel, _CammalSer(nevent), true);
            }
        }
Esempio n. 11
0
        public async Task <IActionResult> CreateApp(CreateAppViewModel model)
        {
            var _cuser = await GetCurrentUserAsync();

            if (!ModelState.IsValid)
            {
                model.ModelStateValid = false;
                model.Recover(_cuser, 1);
                return(View(model));
            }
            string iconPath = string.Empty;

            if (Request.Form.Files.Count == 0 || Request.Form.Files.First().Length < 1)
            {
                iconPath = Values.DeveloperServerAddress + "/images/appdefaulticon.png";
            }
            else
            {
                var    iconFile      = Request.Form.Files.First();
                string DirectoryPath = GetCurrentDirectory() + DirectorySeparatorChar + $@"Storage" + DirectorySeparatorChar;
                if (Exists(DirectoryPath) == false)
                {
                    CreateDirectory(DirectoryPath);
                }
                var NewFilePath = DirectoryPath + StringOperation.RandomString(10) + GetExtension(iconFile.FileName);
                var fileStream  = new FileStream(NewFilePath, FileMode.Create);
                await iconFile.CopyToAsync(fileStream);

                fileStream.Close();
                var fileAddress = await ApiService.UploadFile(await AppsContainer.AccessToken()(), Values.AppsIconBucketId, NewFilePath);

                iconPath = fileAddress.Path;
            }

            var _newApp = new App(_cuser.Id, model.AppName, model.AppDescription, model.AppCategory, model.AppPlatform)
            {
                CreaterId      = _cuser.Id,
                AppIconAddress = iconPath
            };

            _dbContext.Apps.Add(_newApp);
            await _dbContext.SaveChangesAsync();

            return(RedirectToAction(nameof(ViewApp), new { id = _newApp.AppId }));
        }
Esempio n. 12
0
        public async Task <IActionResult> Index(IndexViewModel model)
        {
            var cuser = await GetCurrentUserAsync();

            if (!ModelState.IsValid)
            {
                model.ModelStateValid = false;
                model.Recover(cuser);
                return(View(model));
            }
            cuser.NickName = model.NickName;
            cuser.Bio      = model.Bio;
            await UserService.ChangeProfileAsync(cuser.Id, await AppsContainer.AccessToken()(), cuser.NickName, string.Empty, cuser.Bio);

            await _userManager.UpdateAsync(cuser);

            return(RedirectToAction(nameof(Index), new { JustHaveUpdated = true }));
        }
Esempio n. 13
0
        public async Task <IActionResult> IntegratedTest()
        {
            var token = await _appsContainer.AccessToken();

            var result = await _channelService.CreateChannelAsync(token, "Test Channel");

            _cannonService.FireAsync <DebugMessageSender>(d =>
            {
                return(d.SendDebuggingMessages(token, result.ChannelId));
            });
            var model = new ChannelAddressModel
            {
                Id  = result.ChannelId,
                Key = result.ConnectKey
            };

            return(View("Test", model));
        }
Esempio n. 14
0
        public async Task <IActionResult> DissolveGroup([Required] string groupName)
        {
            var user = await GetKahlaUser();

            var group = await _ownerChecker.FindMyOwnedGroupAsync(groupName, user.Id);

            await group.ForEachUserAsync((eachUser, relation) => _pusher.DissolveEvent(eachUser, group.Id));

            _dbContext.GroupConversations.Remove(group);
            await _dbContext.SaveChangesAsync();

            var token = await _appsContainer.AccessToken();

            var siteName = _configuration["UserFilesSiteName"];
            await _foldersService.DeleteFolderAsync(token, siteName, $"conversation-{group.Id}");

            return(this.Protocol(ErrorType.Success, $"Successfully dissolved the group '{groupName}'!"));
        }
Esempio n. 15
0
        public async Task <IActionResult> Avatar(AvatarViewModel model)
        {
            var cuser = await GetCurrentUserAsync();

            if (!ModelState.IsValid)
            {
                model.ModelStateValid = false;
                model.Recover(cuser);
                return(View(model));
            }
            cuser.HeadImgUrl = await StorageService.SaveToOSS(Request.Form.Files.First(), Values.UsersIconBucketId, 365);

            await UserService.ChangeProfileAsync(cuser.Id, await AppsContainer.AccessToken()(), string.Empty, cuser.HeadImgUrl, string.Empty);

            await _userManager.UpdateAsync(cuser);

            return(RedirectToAction(nameof(Avatar), new { JustHaveUpdated = true }));
        }
Esempio n. 16
0
        public async Task <IActionResult> IntegratedTest()
        {
            var token  = AppsContainer.AccessToken();
            var result = await ChannelService.CreateChannelAsync(await token(), "Test Channel");

            await Task.Factory.StartNew(async() =>
            {
                await _debugger.SendDebuggingMessages(await token(), result.ChannelId);
            });

            var model = new ChannelAddressModel
            {
                Id  = result.ChannelId,
                Key = result.ConnectKey
            };

            return(View("Test", model));
        }
Esempio n. 17
0
        public async Task Recover(
            DeveloperUser User,
            App ThisApp,
            CoreApiService coreApiService,
            OSSApiService ossApiService,
            AppsContainer appsContainer)
        {
            base.Recover(User, 1);
            var token = await appsContainer.AccessToken(ThisApp.AppId, ThisApp.AppSecret);

            var buckets = await ossApiService.ViewMyBucketsAsync(token);

            Buckets = buckets.Buckets;

            var grants = await coreApiService.AllUserGrantedAsync(token);

            Grants = grants.Grants;
        }
Esempio n. 18
0
        public async Task <IActionResult> Index()
        {
            var cuser = await GetCurrentUserAsync();

            var allBuckets = new List <Bucket>();

            foreach (var app in cuser.MyApps)
            {
                var appInfo = await ApiService.ViewMyBucketsAsync(await AppsContainer.AccessToken(app.AppId, app.AppSecret)());

                allBuckets.AddRange(appInfo.Buckets);
            }
            var model = new IndexViewModel(cuser)
            {
                AllBuckets = allBuckets
            };

            return(View(model));
        }
        public async Task NewMessageEvent(string recieverId, int conversationId, string Content, KahlaUser sender)
        {
            var token = AppsContainer.AccessToken();
            var user  = await _dbContext.Users.FindAsync(recieverId);

            var channel = user.CurrentChannel;
            var nevent  = new NewMessageEvent
            {
                Type           = EventType.NewMessage,
                ConversationId = conversationId,
                Sender         = sender,
                Content        = Content
            };

            if (channel != -1)
            {
                await _pushMessageService.PushMessageAsync(await token(), channel, _CammalSer(nevent), true);
            }
        }
Esempio n. 20
0
        public async Task <IActionResult> ViewFiles(int id)//Bucket Id
        {
            var cuser = await GetCurrentUserAsync();

            var bucketInfo = await ApiService.ViewBucketDetailAsync(id);

            var app = await _dbContext.Apps.FindAsync(bucketInfo.BelongingAppId);

            var files = await ApiService.ViewAllFilesAsync(await AppsContainer.AccessToken(app.AppId, app.AppSecret)(), id);

            var model = new ViewFilesViewModel(cuser)
            {
                BucketId = files.BucketId,
                AllFiles = files.AllFiles,
                AppId    = app.AppId
            };

            return(View(model));
        }
Esempio n. 21
0
        public async Task <IActionResult> UpdateInfo(UpdateInfoAddressModel model)
        {
            var cuser = await GetKahlaUser();

            if (!string.IsNullOrEmpty(model.NickName))
            {
                cuser.NickName = model.NickName;
            }
            if (!string.IsNullOrEmpty(model.HeadImgUrl))
            {
                cuser.HeadImgUrl = model.HeadImgUrl;
            }
            cuser.Bio = model.Bio;
            await _userService.ChangeProfileAsync(cuser.Id, await _appsContainer.AccessToken(), cuser.NickName, cuser.HeadImgUrl, cuser.Bio);

            await _userManager.UpdateAsync(cuser);

            return(this.Protocal(ErrorType.Success, "Successfully set your personal info."));
        }
Esempio n. 22
0
        public async Task <IActionResult> UploadFile(UploadFileViewModel model)
        {
            var cuser = await GetCurrentUserAsync();

            if (!ModelState.IsValid)
            {
                model.Recover(cuser, 3);
                model.ModelStateValid = false;
                return(View(model));
            }
            var app = await _dbContext.Apps.FindAsync(model.AppId);

            string accessToken = await AppsContainer.AccessToken(app.AppId, app.AppSecret)();

            var file = Request.Form.Files.First();
            await StorageService.SaveToOSS(file, model.BucketId, model.AliveDays, SaveFileOptions.SourceName, accessToken);

            return(RedirectToAction(nameof(ViewFiles), new { id = model.BucketId }));
        }
Esempio n. 23
0
        public async Task <IActionResult> Upgrade()
        {
            var users = await _dbContext.Users.ToListAsync();

            await _appsContainer.AccessToken();

            foreach (var user in users)
            {
                try
                {
                    await _authService.OnlyUpdate(user);
                }
                catch (Exception e)
                {
                    Console.WriteLine(e.Message);
                    Console.WriteLine(e.StackTrace);
                }
            }
            return(Json(""));
        }
Esempio n. 24
0
        public async Task <IActionResult> DeleteBucket([FromForm] DeleteBucketViewModel model)
        {
            if (ModelState.IsValid)
            {
                var app = await _dbContext.Apps.FindAsync(model.AppId);

                var cuser = await GetCurrentUserAsync();

                var token  = AppsContainer.AccessToken(app.AppId, app.AppSecret);
                var bucket = await ApiService.ViewBucketDetailAsync(model.BucketId);

                if (bucket.BelongingAppId != app.AppId || app.CreaterId != cuser.Id)
                {
                    return(Unauthorized());
                }
                await ApiService.DeleteBucketAsync(await token(), model.BucketId);

                return(RedirectToAction(nameof(AppsController.ViewApp), "Apps", new { id = model.AppId }));
            }
            return(View(model));
        }
Esempio n. 25
0
        public async Task AllClean(FoldersService foldersService)
        {
            try
            {
                var deadline    = DateTime.UtcNow - TimeSpan.FromDays(100);
                var publicSite  = _configuration["UserFilesSiteName"];
                var accessToken = await _appsContainer.AccessToken();

                var rootFolders = await foldersService.ViewContentAsync(accessToken, publicSite, string.Empty);

                foreach (var conversation in rootFolders.Value.SubFolders)
                {
                    var folders = await foldersService.ViewContentAsync(accessToken, publicSite, conversation.FolderName);

                    foreach (var folder in folders.Value.SubFolders)
                    {
                        try
                        {
                            var parts = folder.FolderName.Split('-');
                            var time  = new DateTime(
                                Convert.ToInt32(parts[0]),
                                Convert.ToInt32(parts[1]),
                                Convert.ToInt32(parts[2]));
                            if (time < deadline)
                            {
                                await foldersService.DeleteFolderAsync(accessToken, publicSite, $"{conversation.FolderName}/{folder.FolderName}");
                            }
                        }
                        catch
                        {
                            await foldersService.DeleteFolderAsync(accessToken, publicSite, $"{conversation.FolderName}/{folder.FolderName}");
                        }
                    }
                }
            }
            catch (Exception e)
            {
                _logger.LogCritical(e.Message);
            }
        }
Esempio n. 26
0
 public async Task<IViewComponentResult> InvokeAsync(
         string aspFor,
         string siteName,
         string path,
         int sizeInMb,
         string defaultFile,
         string allowedExtensions)
 {
     var accessToken = ViewBag.AccessToken as string ?? await _appsContainer.AccessToken();
     var token = await _tokenService.GetUploadTokenAsync(accessToken, siteName, "Upload", path);
     var model = new AiurUploaderViewModel
     {
         Name = aspFor,
         PBToken = token,
         Path = path,
         SiteName = siteName,
         SizeInMB = sizeInMb,
         DefaultFile = defaultFile,
         AllowedExtensions = allowedExtensions
     };
     return View(model);
 }
Esempio n. 27
0
        public async Task PendingClose()
        {
            try
            {
                var buffer = new ArraySegment <byte>(new byte[4096 * 20]);
                while (true)
                {
                    await _ws.ReceiveAsync(buffer, CancellationToken.None);

                    if (_ws.State != WebSocketState.Open)
                    {
                        _dropped = true;
                        return;
                    }
                }
            }
            catch (Exception e)
            {
                var accessToken = _appsContainer.AccessToken();
                await _eventService.LogAsync(await accessToken, e.Message, e.StackTrace, EventLevel.Exception, "InPusher");
            }
        }
Esempio n. 28
0
        public async Task DeleteOnDisk(File file)
        {
            try
            {
                var haveDaemon = await _probeDbContext.Files.Where(f => f.Id != file.Id).AnyAsync(f => f.HardwareId == file.HardwareId);

                if (!haveDaemon)
                {
                    await _retryEngine.RunWithTry(taskFactory : _ =>
                    {
                        _storageProvider.DeleteToTrash(file.HardwareId);
                        return(Task.FromResult(0));
                    }, attempts : 10);
                }
            }
            catch (Exception e)
            {
                var token = await _appsContainer.AccessToken();

                await _eventService.LogExceptionAsync(token, e, "Deleter");
            }
        }
Esempio n. 29
0
        public async Task PendingClose()
        {
            try
            {
                var buffer = new ArraySegment <byte>(new byte[4096 * 20]);
                while (true)
                {
                    await _ws.ReceiveAsync(buffer, CancellationToken.None);

                    if (_ws.State != WebSocketState.Open)
                    {
                        _dropped = true;
                        return;
                    }
                }
            }
            catch (Exception e) when(!e.Message.StartsWith("The remote party closed the WebSocket connection"))
            {
                _dropped = true;
                var accessToken = _appsContainer.AccessToken();
                await _eventService.LogExceptionAsync(await accessToken, e, "InPusher");
            }
        }
Esempio n. 30
0
        public async Task <IActionResult> DissolveGroup([Required] string groupName)
        {
            var user = await GetKahlaUser();

            var group = await _ownerChecker.FindMyOwnedGroupAsync(groupName, user.Id);

            group.ForEachUser((eachUser, relation) =>
                              _cannonQueue.QueueWithDependency <KahlaPushService>(pusher =>
                                                                                  pusher.DissolveEvent(eachUser, group.Id)));

            _dbContext.GroupConversations.Remove(group);
            await _dbContext.SaveChangesAsync();

            var token = await _appsContainer.AccessToken();

            var siteName = _configuration["UserFilesSiteName"];

            if ((await _foldersService.ViewContentAsync(token, siteName, "/")).Value.SubFolders.Any(f => f.FolderName == $"conversation-{group.Id}"))
            {
                await _foldersService.DeleteFolderAsync(token, siteName, $"conversation-{group.Id}");
            }
            return(this.Protocol(ErrorType.Success, $"Successfully dissolved the group '{groupName}'!"));
        }