Esempio n. 1
0
        public ActionResult AddFile(int id = -1)
        {
            ViewBag.AlreadyExisting = false;
            var db = new OneDriveDbContext();

            if (User.IsInRole(nameof(Role.アップロード)))
            {
                var    manager = HttpContext.GetOwinContext().GetUserManager <ApplicationUserManager>();
                string name    = ViewBag.FileName = manager.FindByName(User.Identity.Name).Title;

                if (db.Files.Any(info => info.DocumentName == name))
                {
                    ViewBag.AlreadyExisting = true;
                }

                return(View());
            }

            if (!User.IsInRole(nameof(Role.管理)) || id == -1)
            {
                return(View("Error"));
            }

            var title = GetTitleById(id);

            ViewBag.id       = id;
            ViewBag.FileName = title;

            if (db.Files.Any(info => info.DocumentId == id))
            {
                ViewBag.AlreadyExisting = true;
            }

            return(View());
        }
Esempio n. 2
0
        public ActionResult ChangeAssosiationResult(ChangeAssosiationViewModel model)
        {
            var db          = new OneDriveDbContext();
            var userManager = HttpContext.GetOwinContext().GetUserManager <ApplicationUserManager>();

            if (model.CurrentId == -1)
            {
                if (db.Files.Any(x => x.DocumentName == model.Title) && userManager.Users.Any(x => x.Title == model.Title))
                {
                    if (model.NewId == -1 || !db.Files.Any(x => x.DocumentId == model.NewId))
                    {
                        db.Files.First(x => x.DocumentName == model.Title).DocumentId = model.NewId;
                        var user = userManager.Users.First(x => x.Title == model.Title);
                        user.Title = GetTitleById(model.NewId);
                        if (userManager.Update(user).Succeeded)
                        {
                            db.SaveChanges();
                            return(View(true));
                        }
                    }
                }
            }
            else if (db.Files.Any(x => x.DocumentId == model.CurrentId))
            {
                if (model.NewId == -1 || !db.Files.Any(x => x.DocumentId == model.NewId))
                {
                    db.Files.First(x => x.DocumentId == model.CurrentId).DocumentId = model.NewId;
                    db.SaveChanges();
                    return(View(true));
                }
            }
            return(View(false));
        }
Esempio n. 3
0
        public static async Task Delete(int accountNum, string fileId)
        {
            var refreshToken = new OneDriveDbContext().Accounts.First(x => x.Id == accountNum).RefleshToken;
            var token        = await GetAccessToken(refreshToken);

            await Delete(token, fileId);
        }
Esempio n. 4
0
        public static async Task <ShareInfo> CreateShareLink(int accountNum, string fileId)
        {
            var refreshToken = new OneDriveDbContext().Accounts.First(x => x.Id == accountNum).RefleshToken;
            var token        = await GetAccessToken(refreshToken);

            var shareinfo = await CreateShareLink(token, fileId);

            return(shareinfo);
        }
Esempio n. 5
0
        public async Task <ActionResult> ShowDocument(int id = -1, string title = "")
        {
            var  db = new OneDriveDbContext();
            File file;

            if (id != -1)
            {
                //権限がない
                if (User.IsInRole(nameof(Role.アップロード)))
                {
                    return(View("Error"));
                }

                file = db.Files.First(info => info.DocumentId == id);
            }
            else
            {
                if (title == "")
                {
                    var manager = HttpContext.GetOwinContext().GetUserManager <ApplicationUserManager>();
                    var name    = manager.FindByName(User.Identity.Name).Title;
                    //該当する資料が存在しない
                    if (!db.Files.Any(info => info.DocumentName == name))
                    {
                        return(View("Error"));
                    }

                    file = db.Files.First(info => info.DocumentName == name);
                }
                else
                {
                    //権限がない
                    if (User.IsInRole(nameof(Role.アップロード)))
                    {
                        return(View("Error"));
                    }

                    var manager = HttpContext.GetOwinContext().GetUserManager <ApplicationUserManager>();
                    //該当する資料が存在しない
                    if (!db.Files.Any(info => info.DocumentName == title))
                    {
                        return(View("Error"));
                    }

                    file = db.Files.First(info => info.DocumentName == title);
                }
            }

            file.DownloadCount++;
            db.SaveChanges();
            var shareInfo = await OneDriveService.CreateShareLink(file.MicrosoftAccountNum, file.OneDriveFileId);

            _tasks.Add(DeleteShareLinkTask(file.MicrosoftAccountNum, file.OneDriveFileId, shareInfo.PermissionId));
            _tasks = _tasks.Where(x => !x.IsCompleted || !x.IsCanceled || !x.IsFaulted).ToList(); //完了済みのものを取り除く
            return(Redirect(shareInfo.Url));
        }
Esempio n. 6
0
        public ActionResult ManageFiles(ManageMessageId?message)
        {
            ViewBag.StatusMessage =
                message == ManageMessageId.Success ? "成功しました"
                    : message == ManageMessageId.Error ? "エラーが発生しました"
                    : "";

            var db = new OneDriveDbContext();

            return(View(db.Files.ToArray()));
        }
Esempio n. 7
0
        public ActionResult UnregisteredContents()
        {
            var db    = new OneDriveDbContext();
            var files = from File file in db.Files.Where(file => file.DocumentId == -1) select file;
            var list  = new List <Content>();

            foreach (var file in files)
            {
                list.Add(new Content(file.DocumentName, -1, null, -1));
            }
            return(View(list));
        }
Esempio n. 8
0
        public ActionResult ChangeUsingMicrosoftAccount(int id)
        {
            var db = new OneDriveDbContext();

            if (db.Accounts.Any(account => account.Id == id))
            {
                SetConfiguration("UsingMicrosoftAccountNum", id.ToString());
            }
            else
            {
                return(View("Error"));
            }
            return(View());
        }
Esempio n. 9
0
        public async Task <ActionResult> DeleteDocument(int documentId = -1, string title = "")
        {
            var  db = new OneDriveDbContext();
            File file;

            if (User.IsInRole(nameof(Role.管理)))
            {
                if (title == "")
                {
                    if (documentId != -1 && !db.Files.Any(info => info.DocumentId == documentId))
                    {
                        return(View("Error"));
                    }
                    file = db.Files.First(info => info.DocumentId == documentId);
                }
                else
                {
                    if (!db.Files.Any(info => info.DocumentName == title))
                    {
                        return(View("Error"));
                    }
                    file = db.Files.First(info => info.DocumentName == title);
                }
            }
            else if (User.IsInRole(nameof(Role.アップロード)))
            {
                var manager = HttpContext.GetOwinContext().GetUserManager <ApplicationUserManager>();
                var name    = manager.FindByName(User.Identity.Name).Title;
                if (!db.Files.Any(info => info.DocumentName == name))
                {
                    return(View("Error"));
                }
                file = db.Files.First(info => info.DocumentName == name);
            }
            else
            {
                //権限がない
                return(View("Error"));
            }

            await OneDriveService.Delete(file.MicrosoftAccountNum, file.OneDriveFileId);

            db.Files.Remove(file);
            await db.SaveChangesAsync();

            return(View());
        }
Esempio n. 10
0
        public async Task <ActionResult> ManageMicrosoftAccounts()
        {
            var db    = new OneDriveDbContext();
            var model = new List <MicrosoftAccount>();

            foreach (var a in db.Accounts)
            {
                model.Add(new MicrosoftAccount
                {
                    Id        = a.Id,
                    Name      = a.Name,
                    FreeSpace = GetHumanReadableSize((await OneDriveService.GetOwnerInfo(a.RefleshToken)).FreeSpace),
                    Using     = GetConfiguration <int>("UsingMicrosoftAccountNum") == a.Id
                });
            }

            return(View(model));
        }
Esempio n. 11
0
        public ActionResult ChangeAssosiation(int id = -1, string title = "")
        {
            if (id == -1 && title == "")
            {
                return(View("Error"));
            }
            if (title == "")
            {
                title = GetTitleById(id);
            }

            var db    = new OneDriveDbContext();
            var model = new ChangeAssosiationViewModel {
                Title = title, CurrentId = id, NewId = id
            };

            return(db.Files.Any(x => id != -1 ? x.DocumentId == id : x.DocumentName == title) ? View(model) : View("Error"));
        }
Esempio n. 12
0
        public static async Task <string> Upload(int accountNum, string filename, Stream file)
        {
            var refreshToken = new OneDriveDbContext().Accounts.First(x => x.Id == accountNum).RefleshToken;
            var token        = await GetAccessToken(refreshToken);

            string fileId;

            if (file.Length < 100 * 1024 * 1024)
            {
                fileId = await Upload(token, filename, file);
            }
            else
            {
                fileId = await UploadLargeFile(token, filename, file);
            }

            return(fileId);
        }
Esempio n. 13
0
        public ActionResult DeleteMicrosoftAccount(int id)
        {
            if (GetConfiguration <int>("UsingMicrosoftAccountNum") == id)
            {
                return(View("Error"));
            }

            var db = new OneDriveDbContext();

            if (db.Accounts.Any(account => account.Id == id))
            {
                db.Files.RemoveRange(db.Files.Where(file => file.MicrosoftAccountNum == id));
                db.Accounts.Remove(db.Accounts.First(account => account.Id == id));
                db.SaveChanges();
            }
            else
            {
                return(View("Error"));
            }
            return(View());
        }
Esempio n. 14
0
            public Content(string title, int count, string url, int id)
            {
                Title = title;
                Count = count;
                Url   = url;
                Id    = id;

                var db = new OneDriveDbContext();

                //アップロード済みファイルとの関連付け
                if (db.Files.Any(file => file.DocumentId == -1 && file.DocumentName == title))
                {
                    db.Files.First(file => file.DocumentName == title).DocumentId = id;
                    db.SaveChanges();
                }

                if (count == -1 && db.Files.Any(x => x.DocumentId == id))
                {
                    var item = db.Files.First(x => x.DocumentId == id);
                    Uploaded      = item.OneDriveFileId != "";
                    DownloadCount = item.DownloadCount;
                }
            }
Esempio n. 15
0
        //
        // GET: /Manage/AddMicrosoftAccountCallback
        public async Task <ActionResult> AddMicrosoftAccountCallback(string code)
        {
            var refreshToken = await OneDriveService.GetRefreshToken(code);

            var info = await OneDriveService.GetOwnerInfo(refreshToken);

            var db = new OneDriveDbContext();

            if (db.Accounts.Any(x => x.OneDriveId == info.Id))
            {
                ViewBag.Success = false;
                return(View());
            }
            db.Accounts.Add(new Account
            {
                Name         = info.DisplayName,
                OneDriveId   = info.Id,
                RefleshToken = refreshToken
            });
            db.SaveChanges();

            ViewBag.Success = true;
            return(View());
        }
Esempio n. 16
0
        public async Task <ActionResult> Upload(int id = -1)
        {
            //許可された拡張子
            var allowedExtentions = new[]
            {
                ".pptx",
                ".ppt",
                ".pptm",
                ".ppsx",
                ".pps",
                ".ppsm",
                ".pdf",
                ".zip"
            };

            ViewBag.success = false;
            var db = new OneDriveDbContext();

            //ファイルが無い
            if (Request.Files.Count <= 0)
            {
                return(View("Error"));
            }
            var file = Request.Files[0];

            if (file?.FileName == null || file.ContentLength <= 0)
            {
                return(View("Error"));
            }

            //許可された拡張子ではない
            if (allowedExtentions.All(ext => Path.GetExtension(file.FileName).ToLower() != ext))
            {
                return(View("UploadFinished"));
            }

            //ファイル名は"UnixTime_元のファイル名"
            var fileName     = $"{GetUnixTime(DateTime.Now)}_{Path.GetFileName(file.FileName)}";
            var tempFileName = Path.GetTempFileName();

            file.SaveAs(tempFileName);
            var stream = new FileStream(tempFileName, FileMode.Open, FileAccess.Read, FileShare.None, 8, FileOptions.DeleteOnClose);

            try
            {
                var manager   = HttpContext.GetOwinContext().GetUserManager <ApplicationUserManager>();
                var accountId = ManageController.GetConfiguration <int>("UsingMicrosoftAccountNum");
                var fileId    = await OneDriveService.Upload(accountId, fileName, stream);

                if (ManageController.GetConfiguration <bool>("EnableAccountAutoChange"))
                {
                    var currentAccount = await OneDriveService.GetOwnerInfo(db.Accounts.Single(x => x.Id == accountId).RefleshToken);

                    var threshold = ManageController.GetConfiguration <int>("ChangeThreshold");
                    if ((double)currentAccount.FreeSpace / 1024 / 1024 < threshold)
                    {
                        var preload = db.Accounts.Select(x => OneDriveService.GetOwnerInfo(x.RefleshToken));
                        await Task.WhenAll(preload);

                        var nextAccount = preload.Select(x => x.Result).FirstOrDefault(x => (double)x.FreeSpace / 1024 / 1024 >= threshold);
                        if (nextAccount != null)
                        {
                            ManageController.SetConfiguration("UsingMicrosoftAccountNum", nextAccount.Id);
                        }
                    }
                }

                if (string.IsNullOrWhiteSpace(fileId))
                {
                    ViewBag.success = false;
                    return(View("UploadFinished"));
                }
                if (User.IsInRole(nameof(Role.管理)))
                {
                    //既に登録済みのファイルIDである
                    if (db.Files.Any(x => x.DocumentId == id))
                    {
                        return(View("Error"));
                    }
                    var wc = new WebClient {
                        Encoding = Encoding.UTF8
                    };
                    var str   = wc.DownloadString($"https://ipsj.ixsq.nii.ac.jp/ej/?action=repository_uri&item_id={id}");
                    var reg   = new Regex(@"<meta name=""citation_title"" content=""(?<title>.+?)""/>");
                    var title = reg.Match(str).Groups["title"].Value;
                    db.Files.Add(new File
                    {
                        DocumentId          = id,
                        DocumentName        = title,
                        MicrosoftAccountNum = accountId,
                        OneDriveFileId      = fileId
                    });
                }
                else if (User.IsInRole(nameof(Role.アップロード)))
                {
                    var name = manager.FindByName(User.Identity.Name).Title;
                    //既に登録済みのタイトルである
                    if (db.Files.Any(x => x.DocumentName == name))
                    {
                        return(View("Error"));
                    }
                    db.Files.Add(new File
                    {
                        DocumentId          = -1,
                        DocumentName        = name,
                        MicrosoftAccountNum = accountId,
                        OneDriveFileId      = fileId
                    });
                }
                else
                {
                    //権限がない
                    return(View("Error"));
                }
                await db.SaveChangesAsync();
            }
            catch (Exception)
            {
                return(View("Error"));
            }

            ViewBag.success = true;
            return(View("UploadFinished"));
        }
Esempio n. 17
0
        public ActionResult AddNewAccounts()
        {
            IEnumerable <MailMessage> messages;

            using (var client = new ImapClient(ConfigurationManager.AppSettings["MailServer"], 993,
                                               ConfigurationManager.AppSettings["AccountName"], ConfigurationManager.AppSettings["Password"],
                                               AuthMethod.Login, true))
            {
                var uids = client.Search(SearchCondition.Unseen());
                messages = client.GetMessages(uids);
            }

            var addedUsers        = new List <ApplicationUser>();
            var titleChangedUsers = new List <ApplicationUser>();

            foreach (var message in messages.Where(x => x.Subject.Contains("発表申込完了のお知らせ")))
            {
                var r = new Regex(@"1.整理番号:(?<id>\d+)");
                if (!r.IsMatch(message.Body))
                {
                    continue;
                }
                var id = r.Match(message.Body).Groups["id"].Value;

                r = new Regex(@"2.パスワード:(?<password>[a-zA-Z0-9]+)");
                if (!r.IsMatch(message.Body))
                {
                    continue;
                }
                var password = r.Match(message.Body).Groups["password"].Value;

                r = new Regex(@"3.講演題名:(?<title>.+?)------------------------------------------------------------", RegexOptions.Singleline);
                if (!r.IsMatch(message.Body))
                {
                    continue;
                }
                var title = r.Match(message.Body).Groups["title"].Value.Replace("\r", "").Replace("\n", "");

                var user = new ApplicationUser {
                    UserName = id, Title = title
                };
                var result = UserManager.Create(user, password);
                if (result.Succeeded)
                {
                    UserManager.AddToRole(user.Id, nameof(Role.アップロード));
                    addedUsers.Add(user);
                }
            }

            foreach (var message in messages.Where(x => x.Subject.Contains("担当研究会申込者更新連絡のお知らせ")))
            {
                var r = new Regex(@"1.整理番号:(?<id>\d+)");
                if (!r.IsMatch(message.Body))
                {
                    continue;
                }
                var id = r.Match(message.Body).Groups["id"].Value;

                r = new Regex(@"2.タイトル:(?<title>.+?)------------------------------------------------------------", RegexOptions.Singleline);
                if (!r.IsMatch(message.Body))
                {
                    continue;
                }
                var title = r.Match(message.Body).Groups["title"].Value.Replace("\r", "").Replace("\n", "");

                var user = UserManager.FindByName(id);
                if (user == null)
                {
                    continue;
                }

                var db = new OneDriveDbContext();
                //既にアップロード済みのファイルがある場合はタイトルを変更する
                if (db.Files.Any(x => x.DocumentName == user.Title))
                {
                    var file = db.Files.Single(x => x.DocumentName == user.Title);
                    file.DocumentName = title;
                    db.Files.AddOrUpdate(file);
                    db.SaveChanges();
                }

                user.Title = title;
                var result = UserManager.Update(user);
                if (result.Succeeded)
                {
                    titleChangedUsers.Add(user);
                }
            }

            ViewBag.Roles = UserManager.Roles;
            return(View((addedUsers, titleChangedUsers)));
        }