Beispiel #1
0
        public void MarkAttempt(AttemptResult result)
        {
            if (result == AttemptResult.Exception || result == AttemptResult.Timeout)
            {
                result = AttemptResult.Failure;
            }

            var easeAdjustment = result switch {
                AttemptResult.Failure => - 0.4f,
                AttemptResult.Hard => - 0.1f,
                AttemptResult.Easy => 0.1f,
                _ => 0.0f,
            };

            // Adjust the ease down, but not below the minimum value of 1.3
            Ease = Math.Max(1.3f, Ease - easeAdjustment);

            // Adjust the interval
            // TODO: incorporate relearning or implement another algorithm
            var oldInterval = Interval;

            Interval = result switch {
                AttemptResult.Failure => TimeSpan.FromMinutes(10),
                AttemptResult.Hard => oldInterval * 1.2,
                _ => (oldInterval > TimeSpan.FromHours(1.0f)) switch {
                    true => TimeSpan.FromDays(1.0f),
                    false => oldInterval * Ease,
                }
            };

            // Now we need to set the due date for the card
            DueAt = DueAt + Interval;
        }
        public IAttemptResult <int> AddVideo(STypes::Video video)
        {
            //既にデータベースに存在する場合は再利用
            if (this.Exists(video.NiconicoId))
            {
                IAttemptResult <STypes::Video> vResult = this.GetVideo(video.NiconicoId);

                if (!vResult.IsSucceeded || vResult.Data is null)
                {
                    return(AttemptResult <int> .Fail(vResult.Message));
                }


                //動画情報が存在する場合は更新
                if (string.IsNullOrEmpty(video.Title))
                {
                    return(AttemptResult <int> .Succeeded(vResult.Data.Id));
                }

                video.Id = vResult.Data.Id;

                IAttemptResult uResult = this.UpdateInternal(video);

                if (uResult.IsSucceeded)
                {
                    this._logger.Log($"動画を上書きモードで追加しました。(niconicoID:{video.NiconicoId})");
                }

                return(uResult.IsSucceeded switch
                {
                    true => AttemptResult <int> .Succeeded(vResult.Data.Id),
                    _ => AttemptResult <int> .Fail(uResult.Message)
                });
Beispiel #3
0
        public AttemptResult Rename(string new_name, bool overwrite, long milliseconds = StreamSystem.DEFAULT_WAIT)
        {
            new_name = Filename.CleanFilename(new_name);

            AttemptResult result = GetStreamSystem().Rename(
                GetPath(),
                new_name,
                overwrite,
                milliseconds
                );

            if (result.IsDesired())
            {
                if (RenameInternal(new_name))
                {
                    name = new_name;
                }
                else
                {
                    this.OrphanHoldable();
                }
            }

            return(result);
        }
        public CurrentTopicTestResultsModel(int topicId, ILmsService lmsService)
        {
            User  currenUser = lmsService.FindService <IUserService>().GetCurrentUser();
            Topic topic      = lmsService.FindService <ICurriculumService>().GetTopic(topicId);

            if (currenUser != null & topic != null)
            {
                IEnumerable <AttemptResult> attemptResults = lmsService.FindService <ITestingService>().GetResults(currenUser, topic);
                if (attemptResults != null & attemptResults.Count() >= 1)
                {
                    _Attempt = attemptResults.Last();
                    if (_Attempt != null)
                    {
                        _UserAnswers = lmsService.FindService <ITestingService>().GetAnswers(_Attempt);
                        if (_UserAnswers != null)
                        {
                            _NoData = false;
                        }
                        else
                        {
                            _NoData = true;
                        }
                    }
                }
                else
                {
                    _NoData = true;
                }
            }
            else
            {
                _NoData = true;
            }
        }
Beispiel #5
0
 /// <summary>
 /// constructor that get all information from Testing System
 /// </summary>
 /// <param name="attemptId">id of attempt to show</param>
 /// <param name="attList">list of attempts from Session Context</param>
 /// <param name="lmsService">ILmsService for conection to Testing System</param>
 public TopicTestResultsModel(long attemptId, IEnumerable <AttemptResult> attList, ILmsService lmsService)
 {
     if (attemptId != -1)
     {
         Attempt = attList.First(c => c.AttemptId == attemptId);
         if (Attempt != null)
         {
             UserAnswers = lmsService.FindService <ITestingService>().GetAnswers(Attempt);
             if (UserAnswers != null)
             {
                 _NoData = false;
             }
             else
             {
                 _NoData = true;
             }
         }
         else
         {
             _NoData = true;
         }
     }
     else
     {
         _NoData = true;
     }
 }
Beispiel #6
0
        public virtual AttemptResult CopyDirectoryForeign(string src_path, StreamSystem dst, string dst_path, bool overwrite, long milliseconds = StreamSystem.DEFAULT_WAIT)
        {
            if (dst.CreateDirectory(dst_path, milliseconds).IsDesired())
            {
                AttemptResult result = AttemptResult.Succeeded;

                result = GetStreamNames(src_path).Apply(result,
                                                        (r, n) => r.GetAbsorbed(
                                                            CopyStreamForeign(
                                                                Filename.ForwardCombine(src_path, n),
                                                                dst,
                                                                Filename.ForwardCombine(dst_path, n),
                                                                overwrite,
                                                                milliseconds
                                                                )
                                                            )
                                                        );

                result = GetDirectoryNames(src_path).Apply(result,
                                                           (r, n) => r.GetAbsorbed(
                                                               CopyDirectoryForeign(
                                                                   Filename.ForwardCombine(src_path, n),
                                                                   dst,
                                                                   Filename.ForwardCombine(dst_path, n),
                                                                   overwrite,
                                                                   milliseconds
                                                                   )
                                                               )
                                                           );

                return(result);
            }

            return(AttemptResult.Failed);
        }
        public async Task <IAttemptResult <IListVideoInfo> > GetVideoListInfoAsync(string id, CancellationToken?ct = null)
        {
            IListVideoInfo video = this._videoInfoContainer.GetVideo(id);

            bool registerOnlyID = this._settingHandler.GetBoolSetting(SettingsEnum.StoreOnlyNiconicoID);

            if (registerOnlyID)
            {
                return(AttemptResult <IListVideoInfo> .Succeeded(video));
            }



            this._messageHandler.AppendMessage($"{id}の取得を開始します。");

            IAttemptResult <IListVideoInfo> result = await this._wacthPagehandler.TryGetVideoInfoAsync(id);

            if (!result.IsSucceeded || result.Data is null)
            {
                this._messageHandler.AppendMessage($"{id}の取得に失敗しました。(詳細:{result.Message})");
                return(AttemptResult <IListVideoInfo> .Fail($"{id}の取得に失敗しました。(詳細:{result.Message})"));
            }
            else
            {
                this._messageHandler.AppendMessage($"{id}の取得に成功しました。");
                video.SetNewData(result.Data);
            }

            return(AttemptResult <IListVideoInfo> .Succeeded(video));
        }
Beispiel #8
0
        public void UpdateUserAverage()
        {
            tests = UserManagementTests.Update();
            var user = new User {
                Username = "******", Email = "*****@*****.**", Password = "******"
            };

            this.tests.Storage.CreateUser(user);

            var attemptResult = new AttemptResult
            {
                AttemptId        = 1,
                AttemptStatus    = AttemptStatus.Completed,
                CompletionStatus = CompletionStatus.Completed,
                FinishTime       = DateTime.Now,
                StartTime        = DateTime.Now,
                Score            = new Score(0, 50, 45, 0.9F),
                SuccessStatus    = SuccessStatus.Passed,
                TopicType        = TopicTypeEnum.Test,
                User             = this.tests.Storage.GetUser(user.Username)
            };

            this.tests.Storage.UpdateUserAverage(attemptResult);

            var testUser = this.tests.Storage.GetUser(user.Username);

            Assert.IsTrue(testUser.TestsTotal == 1);
            Assert.IsTrue(testUser.TestsSum == 90);

            this.tests.Storage.DeleteUser(u => u.Username == "name1");
        }
Beispiel #9
0
        public IAttemptResult WireVideoToPlaylist(int videoID, int playlistID)
        {
            IAttemptResult <STypes::Video> vResult = this._videoStoreHandler.GetVideo(videoID);

            if (!vResult.IsSucceeded || vResult.Data is null)
            {
                return(AttemptResult.Fail("追加する動画はDBに保存されていません。"));
            }

            STypes::Video video = vResult.Data;

            video.PlaylistIds.AddUnique(playlistID);
            this._videoStoreHandler.Update(video);

            IAttemptResult result = this._playlistStoreHandler.WireVideo(video, playlistID);

            ITreePlaylistInfo playlistInfo = this._playlistInfoContainer.GetPlaylist(playlistID);
            IListVideoInfo    videoInfo    = this._videoInfoContainer.GetVideo(video.NiconicoId);

            if (!playlistInfo.Videos.Any(v => v.Id.Value == videoID))
            {
                playlistInfo.Videos.Add(videoInfo);
            }

            return(result);
        }
Beispiel #10
0
        /// <summary>
        /// 子プレイリストを辿って削除する
        /// </summary>
        /// <param name="parentId"></param>
        private IAttemptResult RemoveChildPlaylist(STypes::Playlist self)
        {
            if (self.IsConcretePlaylist)
            {
                return(AttemptResult.Succeeded());
            }

            IAttemptResult <List <STypes::Playlist> > cResult = this.GetChildPlaylists(self.Id);

            if (!cResult.IsSucceeded || cResult.Data is null)
            {
                return(AttemptResult.Fail("子プレイリストの取得に失敗しました。"));
            }

            foreach (var childPlaylist in cResult.Data)
            {
                IAttemptResult crResult = this.RemoveChildPlaylist(childPlaylist);
                if (!crResult.IsSucceeded)
                {
                    return(AttemptResult.Fail("子孫プレイリストの削除に失敗しました。"));
                }

                IAttemptResult dResul = this.DeletePlaylist(childPlaylist.Id);
                if (!dResul.IsSucceeded)
                {
                    return(AttemptResult.Fail("子プレイリストの削除に失敗しました。"));
                }

                this.logger.Log($"{self.Id}の子プレイリストを削除しました。");
            }

            return(AttemptResult.Succeeded());
        }
        public override IAttemptResult Initialize()
        {
            string        appData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
            List <string> packages;

            try
            {
                packages = this._directoryIO.GetDirectorys(Path.Combine(appData, "Packages"), "Mozilla.Firefox*");
            }
            catch (Exception e)
            {
                this._logger.Error("Microsoft Store版Firefoxアプリフォルダーの取得に失敗しました。", e);
                return(AttemptResult.Fail("Microsoft Store版Firefoxアプリフォルダーの取得に失敗しました。"));
            }

            if (packages.Count == 0)
            {
                return(AttemptResult.Fail("プロファイルの取得に失敗しました。"));
            }

            string profileRoot = Path.Combine(packages[0], @"LocalCache\Roaming\Mozilla\Firefox\Profiles");

            if (this._directoryIO.Exists(profileRoot))
            {
                this.profileFolder = profileRoot;
                this.isInitialized = true;
                return(AttemptResult.Succeeded());
            }
            else
            {
                return(AttemptResult.Fail("プロファイルフォルダーが存在しません、"));
            }
        }
Beispiel #12
0
        public IAttemptResult UnWireVideo(int videoId, int playlistId)
        {
            if (!this.Exists(playlistId))
            {
                return(AttemptResult.Fail("指定したプレイリストが存在しません。"));
            }

            IAttemptResult <STypes::Playlist> pResult = this.GetPlaylist(playlistId);

            if (!pResult.IsSucceeded || pResult.Data is null)
            {
                return(AttemptResult.Fail("プレイリストの取得に失敗しました。"));
            }

            STypes::Playlist playlist = pResult.Data;

            playlist.Videos.RemoveAll(v => v.Id == videoId);
            playlist.CustomVideoSequence.RemoveAll(v => v == videoId);

            var uResult = this.databaseInstance.Update(playlist, STypes::Playlist.TableName);

            if (!uResult.IsSucceeded)
            {
                return(AttemptResult.Fail($"動画の削除に失敗しました。(詳細:{uResult.ExceptionMessage})"));
            }

            this.logger.Log($"{playlist.PlaylistName}からの動画({videoId})を削除しました。");

            return(AttemptResult.Succeeded());
        }
Beispiel #13
0
        public IAttemptResult MoveVideoToPrev(int playlistID, int videoIndex)
        {
            if (!this.Exists(playlistID))
            {
                return new AttemptResult()
                       {
                           Message = $"指定されたプレイリストは存在しません。(id={playlistID})"
                       }
            }
            ;

            IAttemptResult <STypes::Playlist> pResult = this.GetPlaylist(playlistID);

            if (!pResult.IsSucceeded || pResult.Data is null)
            {
                return(AttemptResult.Fail("プレイリストの取得に失敗しました。"));
            }

            STypes::Playlist playlist = pResult.Data;

            if (playlist.Videos.Count < videoIndex + 1)
            {
                return new AttemptResult()
                       {
                           Message = $"指定されたインデックスは範囲外です。(index={videoIndex}, actual={playlist.Videos.Count})"
                       }
            }
            ;

            if (videoIndex == 0)
            {
                return new AttemptResult()
                       {
                           Message = $"指定されたインデックスは最初の動画です。(index={videoIndex})"
                       }
            }
            ;

            try
            {
                playlist.CustomVideoSequence.InsertIntoPrev(videoIndex);
            }
            catch (Exception e)
            {
                return(new AttemptResult()
                {
                    Message = $"挿入操作に失敗しました。", Exception = e
                });
            }

            playlist.SortType = STypes.VideoSortType.Custom;

            this.Update(playlist);

            this.logger.Log($"{playlistID}の{videoIndex + 1}番目の動画を一つ後ろに挿入しました。");
            return(new AttemptResult()
            {
                IsSucceeded = true
            });
        }
Beispiel #14
0
        public IAttemptResult <STypes::Playlist> GetPlaylist(Expression <Func <STypes::Playlist, bool> > predicate)
        {
            IAttemptResult <STypes::Playlist> result = this.databaseInstance.GetRecord <STypes::Playlist>(STypes::Playlist.TableName, predicate);

            if (!result.IsSucceeded || result.Data is null)
            {
                if (result.Exception is not null)
                {
                    this.logger.Error("プレイリストの取得に失敗しました。", result.Exception);
                }
                else
                {
                    this.logger.Error("プレイリストの取得に失敗しました。");
                }

                return(AttemptResult <STypes::Playlist> .Fail("プレイリストの取得に失敗しました。"));
            }


            if (result.Data.Videos.Count > 0 && result.Data.CustomVideoSequence.Count != result.Data.Videos.Count)
            {
                var ids = result.Data.Videos.Select(v => v.Id).Where(id => !result.Data.CustomVideoSequence.Contains(id));
                result.Data.CustomVideoSequence.AddRange(ids);
            }

            this.logger.Log($"プレイリスト(name:{result.Data.PlaylistName}, ID:{result.Data.Id})を取得しました。");
            return(AttemptResult <STypes::Playlist> .Succeeded(result.Data));
        }
Beispiel #15
0
        private async Task <IAttemptResult> EncodeVideosAsync(IWatchSession session, IDownloadContext context, IDownloadSettings settings, Action <string> onMessage, IEnumerable <string> segmentFilePaths, CancellationToken token)
        {
            var encodeSetting = new EncodeSettings()
            {
                FilePath           = context.FileName,
                CommandFormat      = settings.CommandFormat,
                TsFilePaths        = segmentFilePaths,
                IsOverwriteEnable  = settings.Overwrite,
                IsOverrideDTEnable = settings.OverrideVideoFileDateToUploadedDT,
                UploadedOn         = session.Video !.DmcInfo.UploadedOn,
                IsNoEncodeEnable   = settings.SaveWithoutEncode,
            };

            try
            {
                await this._encorder.EncodeAsync(encodeSetting, onMessage, token);
            }
            catch (Exception e)
            {
                this._logger.Error($"ファイルの変換中にエラーが発生しました。({this.context!.GetLogContent()})", e);
                onMessage("動画の変換中にエラー発生");
                return(AttemptResult.Fail($"ファイルの変換中にエラーが発生しました。(詳細: {e.Message})"));
            }

            return(AttemptResult.Succeeded());
        }
Beispiel #16
0
        /// <summary>
        /// constructor that get all information from Testing System
        /// </summary>
        /// <param name="attemptId">id of attempt to show</param>
        /// <param name="attList">list of attempts from Session Context</param>
        /// <param name="lmsService">ILmsService for conection to Testing System</param>
        public TopicTestResultsModel(long attemptId, IEnumerable <AttemptResult> attList, int groupId, ILmsService lmsService)
        {
            if (attemptId != -1)
            {
                this.group = lmsService.FindService <IUserService>().GetGroup(groupId);
                // hotfix: added checking of Course id
                this.attempt =
                    attList.FirstOrDefault(
                        c =>
                        c.AttemptId == attemptId && c.CurriculumChapterTopic.Topic.TestCourseRef == c.IudicoCourseRef);
                if (this.attempt != null)
                {
                    this.userAnswers = lmsService.FindService <ITestingService>().GetAnswers(this.attempt);
                    this.courseInfo  =
                        lmsService.FindService <ICourseService>().GetCourseInfo(this.attempt.IudicoCourseRef);

                    this.hasNoData = this.userAnswers == null;
                }
                else
                {
                    this.hasNoData = true;
                }
            }
            else
            {
                this.hasNoData = true;
            }
        }
Beispiel #17
0
        static public AttemptResult Attempt(AttemptProcess process, long milliseconds)
        {
            if (milliseconds > 0)
            {
                Timer timer = new Timer(milliseconds).StartAndGet();

                do
                {
                    AttemptResult result = process();
                    if (result.IsComplete())
                    {
                        return(result);
                    }

                    if (timer.GetTimeLeftInMilliseconds() > 50)
                    {
                        Thread.Sleep(1);
                    }
                }while (timer.IsTimeUnder());

                return(AttemptResult.Tried);
            }

            return(process());
        }
Beispiel #18
0
        public IAttemptResult MoveVideoToForward(int videoIndex, int playlistID)
        {
            IAttemptResult <ITreePlaylistInfo> result = this.GetPlaylist(playlistID);

            if (!result.IsSucceeded || result.Data is null)
            {
                return(AttemptResult.Fail(result.Message));
            }

            ITreePlaylistInfo playlist = result.Data;

            playlist.VideoSortType = STypes::VideoSortType.Custom;

            if (videoIndex == playlist.Videos.Count - 1)
            {
                return(AttemptResult.Fail("指定された動画は最後に存在するため前に移動できません。"));
            }

            try
            {
                playlist.Videos.InsertIntoForward(videoIndex);
            }
            catch (Exception e)
            {
                this._logger.Error($"動画の並び替え操作に失敗しました。({nameof(this.MoveVideoToForward)})", e);
                return(AttemptResult.Fail($"動画の並び替え操作に失敗しました。(詳細:{e.Message})", e));
            }

            return(this.Update(playlist));
        }
Beispiel #19
0
        /// <summary>
        /// Manages parsing of fields got from DataTable to return results of attempts.
        /// </summary>
        /// <param name="dataRows"><see cref="IEnumerable{T}"/> collection of <see cref="DataRow"/> containing results from <see cref="LearningStore"/></param>
        /// <param name="conditions"><see cref="List{T}"/> of <see cref="QueryCondition"/> objects needed to parse results properly.</param>
        /// <returns><see cref="IEnumerable{T}"/> collection of <see cref="AttemptResult"/> objects parsed from given <paramref name="dataRows"/>.</returns>
        protected IEnumerable <AttemptResult> ParseAttemptResults(
            IEnumerable <DataRow> dataRows, List <QueryCondition> conditions)
        {
            var queryColumns = AllAttemptsColumns.Except(conditions.Select(cond => cond.ColumnName)).ToList();

            foreach (var dataRow in dataRows)
            {
                var attemptResult = new AttemptResult();

                try
                {
                    foreach (var condition in conditions)
                    {
                        this.ParseAttemptResultField(condition.Value, condition.ColumnName, ref attemptResult);
                    }
                    foreach (var queryColumn in queryColumns)
                    {
                        this.ParseAttemptResultField(dataRow[queryColumn], queryColumn, ref attemptResult);
                    }
                }
                catch (NoNullAllowedException)
                {
                    // skip not actual attempt results
                    continue;
                }

                yield return(attemptResult);
            }
        }
Beispiel #20
0
        public async Task <IAttemptResult <string> > BuildRequestAsync(IDmcInfo dmcInfo, ICommentFetchOption option, string key)
        {
            IAttemptResult <List <Request::RequestRoot> > result;

            try
            {
                result = await this.BuildRequestAsyncInternal(dmcInfo, option, key);
            }
            catch (Exception ex)
            {
                this._logger.Error("リクエストの構築中にエラーが発生しました。", ex);
                return(AttemptResult <string> .Fail($"リクエストの構築中にエラーが発生しました。(詳細:{ex.Message})"));
            }

            if (!result.IsSucceeded || result.Data is null)
            {
                return(AttemptResult <string> .Fail(result.Message));
            }

            string json;

            try
            {
                json = JsonParser.Serialize(result.Data);
            }
            catch (Exception ex)
            {
                this._logger.Error("リクエストのシリアライズ中にエラーが発生しました。", ex);
                return(AttemptResult <string> .Fail($"リクエストのシリアライズ中にエラーが発生しました。(詳細:{ex.Message})"));
            }

            return(AttemptResult <string> .Succeeded(json));
        }
        /// <summary>
        /// コメントをダウンロードする
        /// </summary>
        private async Task <IAttemptResult> TryDownloadCommentAsync(IDownloadSettings settings, IWatchSession session, Action <string> onMessage, IDownloadContext context, CancellationToken token)
        {
            Cdl::ICommentDownloader?      v1 = null;
            V2Comment::ICommentDownloader?v2 = null;

            if (settings.EnableExperimentalCommentSafetySystem)
            {
                v2 = DIFactory.Provider.GetRequiredService <V2Comment::ICommentDownloader>();
            }
            else
            {
                v1 = DIFactory.Provider.GetRequiredService <Cdl::ICommentDownloader>();
            }

            IAttemptResult result;

            try
            {
                result = v2 is null ? await v1 !.DownloadComment(session, settings, onMessage, context, token) : await v2.DownloadCommentAsync(session.Video !.DmcInfo, settings, context, token);
            }
            catch (Exception e)
            {
                this.logger.Error("コメントのダウンロードに失敗しました。", e);
                return(AttemptResult.Fail($"コメントのダウンロードに失敗しました。({e.Message})"));
            }

            return(result);
        }
        public CurrentTopicTestResultsModel(int curriculumChapterTopicId, TopicTypeEnum topicType, int groupId, ILmsService lmsService)
        {
            this.group = lmsService.FindService <IUserService>().GetGroup(groupId);
            var currenUser             = lmsService.FindService <IUserService>().GetCurrentUser();
            var curriculumChapterTopic = lmsService.FindService <ICurriculumService>().GetCurriculumChapterTopicById(curriculumChapterTopicId);

            if (currenUser != null & curriculumChapterTopic != null)
            {
                var attemptResults = lmsService.FindService <ITestingService>().GetResults(currenUser, curriculumChapterTopic, topicType).ToList();
                if (attemptResults.Any())
                {
                    // hotfix: added checking of Course id
                    this.attempt =
                        attemptResults.FirstOrDefault(x => x.CurriculumChapterTopic.Topic.TestCourseRef == x.IudicoCourseRef);
                    if (this.attempt != null)
                    {
                        this.courseInfo =
                            lmsService.FindService <ICourseService>().GetCourseInfo(this.attempt.IudicoCourseRef);
                        this.userAnswers = lmsService.FindService <ITestingService>().GetAnswers(this.attempt);

                        this.hasNoData = this.userAnswers == null;
                    }
                }
                else
                {
                    this.hasNoData = true;
                }
            }
            else
            {
                this.hasNoData = true;
            }
        }
Beispiel #23
0
        /// <summary>
        /// プレイリストを作成する
        /// </summary>
        /// <param name="videos"></param>
        /// <param name="directoryPath"></param>
        /// <param name="type"></param>
        /// <returns></returns>
        public IAttemptResult <int> TryCreatePlaylist(IEnumerable <Playlist::IListVideoInfo> videos, PlaylistType type)
        {
            if (this._current.SelectedPlaylist.Value is null)
            {
                return(AttemptResult <int> .Fail("プレイリストが選択されていません。"));
            }

            string playlistName  = this._current.SelectedPlaylist.Value.Name.Value;
            string directoryPath = this._current.PlaylistFolderPath;

            videos = videos.Where(v => v.IsDownloaded.Value);
            if (!videos.Any())
            {
                return(AttemptResult <int> .Fail("ダウンロードされた動画がありません。"));
            }

            int           allVideos  = videos.Count();
            List <string> videosPath = new();
            string        data;

            try
            {
                videosPath = videos.Select(v => v.FileName.Value).Where(p => this._fileIO.Exists(p)).ToList();
                data       = this._fileFactory.GetPlaylist(videosPath, playlistName, type);
            }
            catch (Exception e)
            {
                this._logger.Error("プレイリストの作成に失敗しました。", e);
                return(AttemptResult <int> .Fail("プレイリストの作成に失敗しました。"));
            }

            if (!this._directoryIO.Exists(directoryPath))
            {
                try
                {
                    this._directoryIO.Create(directoryPath);
                }
                catch (Exception e)
                {
                    this._logger.Error("ディレクトリーの作成に失敗しました。", e);
                    return(AttemptResult <int> .Fail("ディレクトリーの作成に失敗しました。"));
                }
            }

            try
            {
                this._fileIO.Write(Path.Combine(directoryPath, $"playlist.{this.GetExt(type)}"), data, encoding: this.GetEncording(type));
            }
            catch (Exception e)
            {
                this._logger.Error("プレイリストへの書き込みに失敗しました。", e);
                return(AttemptResult <int> .Fail("プレイリストへの書き込みに失敗しました。"));
            }

            return(new AttemptResult <int>()
            {
                IsSucceeded = true, Data = allVideos - videosPath.Count
            });
        }
Beispiel #24
0
        static public AttemptResult AttemptReadObject <T>(this StreamSystem item, string path, out T obj, long milliseconds = StreamSystem.DEFAULT_WAIT)
        {
            object        general_obj;
            AttemptResult result = item.AttemptReadObject(path, out general_obj, milliseconds);

            obj = general_obj.Convert <T>();
            return(result);
        }
Beispiel #25
0
 public ReportAttemptInput(AttemptResult result, string resultText, float timeBeforeResponding, int cardId, string?clientMutationId)
 {
     Result               = result;
     ResultText           = resultText;
     TimeBeforeResponding = timeBeforeResponding;
     CardId               = cardId;
     ClientMutationId     = clientMutationId;
 }
Beispiel #26
0
        public IEnumerable <AttemptResult> GetAllAttempts()
        {
            List <AttemptResult> result = new List <AttemptResult>();
            LearningStoreJob     job    = LStore.CreateJob();

            RequestAllAttempts(job);
            DataTable dataTable = job.Execute <DataTable>();

            foreach (DataRow dataRow in dataTable.AsEnumerable())
            {
                AttemptItemIdentifier attemptItemId;
                LStoreHelper.CastNonNull(dataRow[Schema.AllAttemptsResults.AttemptId], out attemptItemId);
                long attemptId = attemptItemId.GetKey();

                String userKey;
                LStoreHelper.CastNonNull(dataRow[Schema.AllAttemptsResults.UserItemKey], out userKey);
                User user = UserService.GetUsers().Single(curr => curr.Id.ToString() == userKey);
                if (user == null)
                {
                    throw new NoNullAllowedException("Error while getting user with id = " + userKey);
                }

                Int32 topicId;
                LStoreHelper.CastNonNull(dataRow[Schema.AllAttemptsResults.ThemeId], out topicId);
                Topic topic = DisciplineService.GetTopic(topicId);
                if (topic == null)
                {
                    throw new NoNullAllowedException("Error while getting topic with id = " + topicId);
                }

                Microsoft.LearningComponents.CompletionStatus completionStatus;
                LStoreHelper.CastNonNull(dataRow[Schema.AllAttemptsResults.CompletionStatus], out completionStatus);
                IUDICO.Common.Models.Shared.Statistics.CompletionStatus iudicoCompletionStatus = (IUDICO.Common.Models.Shared.Statistics.CompletionStatus)completionStatus;

                Microsoft.LearningComponents.AttemptStatus attemptStatus;
                LStoreHelper.CastNonNull(dataRow[Schema.AllAttemptsResults.AttemptStatus], out attemptStatus);
                IUDICO.Common.Models.Shared.Statistics.AttemptStatus iudicoAttemptStatus = (IUDICO.Common.Models.Shared.Statistics.AttemptStatus)attemptStatus;

                Microsoft.LearningComponents.SuccessStatus successStatus;
                LStoreHelper.CastNonNull(dataRow[Schema.AllAttemptsResults.SuccessStatus], out successStatus);
                IUDICO.Common.Models.Shared.Statistics.SuccessStatus iudicoSuccessStatus = (IUDICO.Common.Models.Shared.Statistics.SuccessStatus)successStatus;

                DateTime?startTime;
                LStoreHelper.Cast(dataRow[Schema.AllAttemptsResults.StartedTimestamp], out startTime);

                DateTime?finishTime;
                LStoreHelper.Cast(dataRow[Schema.AllAttemptsResults.FinishedTimestamp], out finishTime);


                float?scaledScore;
                LStoreHelper.Cast <float>(dataRow[Schema.AllAttemptsResults.Score], out scaledScore);

                // Create AttemptResult object
                AttemptResult attemptResult = new AttemptResult(attemptId, user, topic, iudicoCompletionStatus, iudicoAttemptStatus, iudicoSuccessStatus, startTime, finishTime, scaledScore);
                result.Add(attemptResult);
            }
            return(result);
        }
Beispiel #27
0
        /// <summary>
        /// Thread要求を構築する
        /// </summary>
        /// <param name="threadInfo"></param>
        /// <param name="dmcInfo"></param>
        /// <param name="option"></param>
        /// <returns></returns>
        private async Task <IAttemptResult <Request::Thread> > GetThreadAsync(IThread threadInfo, IDmcInfo dmcInfo, ICommentFetchOption option)
        {
            var thread = new Request::Thread()
            {
                ThreadNo   = threadInfo.ID.ToString(),
                UserID     = dmcInfo.UserId,
                Fork       = threadInfo.Fork,
                Language   = 0,
                WithGlobal = 1,
                Scores     = 1,
                Nicoru     = 3,
                Force184   = threadInfo.Is184Forced ? "1" : null,
            };

            //投コメを判定
            if (threadInfo.IsOwnerThread)
            {
                thread.ResFrom = -1000;
                thread.Version = "20061206";
            }
            else
            {
                thread.Version = "20090904";
            }

            //Force184?
            if (threadInfo.Is184Forced)
            {
                thread.Force184 = "1";
            }


            //公式動画を判別
            if (threadInfo.IsThreadkeyRequired)
            {
                thread.ThreadKey = threadInfo.Threadkey;
            }
            else
            {
                thread.UserKey = dmcInfo.Userkey;
            }

            //過去ログ
            if (option.DownloadLog)
            {
                IAttemptResult <WayBackKey> wResult = await this._officialCommentHandler.GetWayBackKeyAsync(threadInfo.ID.ToString());

                if (!wResult.IsSucceeded || wResult.Data is null)
                {
                    return(AttemptResult <Request::Thread> .Fail(wResult.Message));
                }

                thread.When       = option.When;
                thread.WayBackKey = wResult.Data.Key;
            }

            return(AttemptResult <Request::Thread> .Succeeded(thread));
        }
Beispiel #28
0
        static public bool IsIncomplete(this AttemptResult item)
        {
            if (item == AttemptResult.Tried)
            {
                return(true);
            }

            return(false);
        }
Beispiel #29
0
        static public bool IsComplete(this AttemptResult item)
        {
            if (item.IsIncomplete() == false)
            {
                return(true);
            }

            return(false);
        }
Beispiel #30
0
        static public AttemptResult GetAbsorbed(this AttemptResult item, AttemptResult to_absorb)
        {
            if (to_absorb.GetSeverity() > item.GetSeverity())
            {
                return(to_absorb);
            }

            return(item);
        }
Beispiel #31
0
 public AnswerResult(long activityAttempId, long activityPackageId, string activityTitle, long? interactionId, CompletionStatus completionStatus, SuccessStatus? successStatus, AttemptResult attempResult, object learnerResponse, string correctResponse, InteractionType? learnerResponseType, float? minScore, float? maxScore, float? rawScore, float? scaledScore, string primaryResourceFromManifest)
 {
    this.ActivityAttemptId = activityAttempId;
    this.ActivityPackageId = activityPackageId;
    this.ActivityTitle = activityTitle;
    this.InteractionId = interactionId;
    this.CompletionStatus = completionStatus;
    this.SuccessStatus = successStatus;
    this.AttemptResult = attempResult;
    this.LearnerResponse = learnerResponse;
    this.CorrectResponse = correctResponse;
    this.LearnerResponseType = learnerResponseType;
    this.MinScore = minScore;
    this.MaxScore = maxScore;
    this.RawScore = rawScore;
    this.ScaledScore = scaledScore;
    this.PrimaryResourceFromManifest = primaryResourceFromManifest;
 }