コード例 #1
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"));
        }
コード例 #2
0
        private static async Task DeleteShareLinkTask(int accountNum, string fileId, string permissionId)
        {
            await Task.Delay(TimeSpan.FromMinutes(ManageController.GetConfiguration <int>("LinkEnableDuration")));

            await OneDriveService.DeleteShareLink(accountNum, fileId, permissionId);
        }
コード例 #3
0
        public ActionResult Contents(int id = -1)
        {
            if (id == -1)
            {
                id = 4088;           //IOTトップ
            }
            //キャッシュを利用する
            if (Cache.ContainsKey(id) && DateTime.Now - Cache[id].CachedAt <= TimeSpan.FromMinutes(ManageController.GetConfiguration <int>("CacheDuration")))
            {
                Debug.WriteLine("キャッシュ利用");
                return(View(Cache[id].Contents));
            }

            var url = $"https://ipsj.ixsq.nii.ac.jp/ej/?action=repository_opensearch&index_id={id}&count=100&order=7";
            var wc  = new WebClient {
                Encoding = Encoding.UTF8
            };
            var str       = wc.DownloadString(url);
            var regFolder = new Regex(
                @"<td class=""pl10 pt10 vat"" width=""100%""><span><a href=""(?<url>https://ipsj\.ixsq\.nii\.ac\.jp/ej/\?action=repository_opensearch&amp;index_id=(?<indexId>\d+)&amp;count=100&amp;order=7&amp;pn=1)"">(?<title>.+)</a><wbr /><span class=""text_color"">&nbsp;\[(?<count>\d+)件</span><span class=""text_color"">\]&nbsp;</span></span></td>");
            var results  = regFolder.Matches(str);
            var contents = (from Match result in results select new Content(result.Groups["title"].Value, int.Parse(result.Groups["count"].Value), result.Groups["url"].Value, int.Parse(result.Groups["indexId"].Value)));

            if (!contents.Any()) //フォルダが一つも無い→コンテンツ
            {
                var regContents = new Regex(
                    @"<div class=""item_title pl55"">\s+<a href=""(?<url>https://ipsj\.ixsq\.nii\.ac\.jp/ej/\?action=repository_uri&item_id=(?<itemId>\d+))"">\s+(?<title>.+)\s+</a>\s+</div>");
                results = regContents.Matches(str);

                contents = from Match result in results select new Content(result.Groups["title"].Value, -1, result.Groups["url"].Value, int.Parse(result.Groups["itemId"].Value));
            }

            //キャッシュに登録
            if (Cache.ContainsKey(id))
            {
                Cache.Remove(id);
            }
            Debug.WriteLine("キャッシュ登録");
            Cache.Add(id, new ContentsCache()
            {
                CachedAt = DateTime.Now, Contents = contents
            });
            return(View(contents));
        }