示例#1
0
    public void Add(Piece piece, List<Piece> same)
    {
        //Debug.LogWarning ("History Add");
        //string kanji = piece.Kanji;
        //Vector2 pos = piece.Tile;

        if (max > 0)
            return;

        bool isFirst = piece.Owner.IsFirst;

        string addition = "";

        if (same != null) {
            if(same.Count == 1) {
                if(same[0].Tile.x < piece.Tile.x) {
                    addition += isFirst ? "左" : "右";
                }
                if(same[0].Tile.x > piece.Tile.x) {
                    addition += !isFirst ? "左" : "右";
                }
            }
        }

        HistoryInfo info = new HistoryInfo (index++, piece, addition);
        //HistoryInfo info = new HistoryInfo (index++, kanji, pos, isFirst, addition);
        moves.Add (info);
    }
示例#2
0
        internal static List <string> GetSuggestion(Runspace runspace)
        {
            if (!(runspace is LocalRunspace localRunspace))
            {
                return(new List <string>());
            }

            // Get the last value of $?
            bool questionMarkVariableValue = localRunspace.ExecutionContext.QuestionMarkVariableValue;

            // Get the last history item
            History history = localRunspace.History;

            HistoryInfo[] entries = history.GetEntries(-1, 1, true);

            if (entries.Length == 0)
            {
                return(new List <string>());
            }

            HistoryInfo lastHistory = entries[0];

            // Get the last error
            ArrayList errorList = (ArrayList)localRunspace.GetExecutionContext.DollarErrorVariable;
            object    lastError = null;

            if (errorList.Count > 0)
            {
                lastError = errorList[0] as Exception;
                ErrorRecord lastErrorRecord = null;

                // The error was an actual ErrorRecord
                if (lastError == null)
                {
                    lastErrorRecord = errorList[0] as ErrorRecord;
                }
                else if (lastError is RuntimeException)
                {
                    lastErrorRecord = ((RuntimeException)lastError).ErrorRecord;
                }

                // If we got information about the error invocation,
                // we can be more careful with the errors we pass along
                if ((lastErrorRecord != null) && (lastErrorRecord.InvocationInfo != null))
                {
                    if (lastErrorRecord.InvocationInfo.HistoryId == lastHistory.Id)
                    {
                        lastError = lastErrorRecord;
                    }
                    else
                    {
                        lastError = null;
                    }
                }
            }

            Runspace oldDefault     = null;
            bool     changedDefault = false;

            if (Runspace.DefaultRunspace != runspace)
            {
                oldDefault               = Runspace.DefaultRunspace;
                changedDefault           = true;
                Runspace.DefaultRunspace = runspace;
            }

            List <string> suggestions = null;

            try
            {
                suggestions = GetSuggestion(lastHistory, lastError, errorList);
            }
            finally
            {
                if (changedDefault)
                {
                    Runspace.DefaultRunspace = oldDefault;
                }
            }

            // Restore $?
            localRunspace.ExecutionContext.QuestionMarkVariableValue = questionMarkVariableValue;
            return(suggestions);
        }
示例#3
0
        internal static ArrayList GetSuggestion(HistoryInfo lastHistory, Object lastError, ArrayList errorList)
        {
            ArrayList returnSuggestions = new ArrayList();

            PSModuleInfo invocationModule = new PSModuleInfo(true);

            invocationModule.SessionState.PSVariable.Set("lastHistory", lastHistory);
            invocationModule.SessionState.PSVariable.Set("lastError", lastError);

            int initialErrorCount = 0;

            // Go through all of the suggestions
            foreach (Hashtable suggestion in s_suggestions)
            {
                initialErrorCount = errorList.Count;

                // Make sure the rule is enabled
                if (!LanguagePrimitives.IsTrue(suggestion["Enabled"]))
                {
                    continue;
                }

                SuggestionMatchType matchType = (SuggestionMatchType)LanguagePrimitives.ConvertTo(
                    suggestion["MatchType"],
                    typeof(SuggestionMatchType),
                    CultureInfo.InvariantCulture);

                // If this is a dynamic match, evaluate the ScriptBlock
                if (matchType == SuggestionMatchType.Dynamic)
                {
                    object result = null;

                    ScriptBlock evaluator = suggestion["Rule"] as ScriptBlock;
                    if (evaluator == null)
                    {
                        suggestion["Enabled"] = false;

                        throw new ArgumentException(
                                  SuggestionStrings.RuleMustBeScriptBlock, "Rule");
                    }

                    try
                    {
                        result = invocationModule.Invoke(evaluator, null);
                    }
                    catch (Exception e)
                    {
                        // Catch-all OK. This is a third-party call-out.
                        CommandProcessorBase.CheckForSevereException(e);

                        suggestion["Enabled"] = false;
                        continue;
                    }

                    // If it returned results, evaluate its suggestion
                    if (LanguagePrimitives.IsTrue(result))
                    {
                        string suggestionText = GetSuggestionText(suggestion["Suggestion"], (object[])suggestion["SuggestionArgs"], invocationModule);

                        if (!String.IsNullOrEmpty(suggestionText))
                        {
                            string returnString = String.Format(
                                CultureInfo.CurrentCulture,
                                "Suggestion [{0},{1}]: {2}",
                                (int)suggestion["Id"],
                                (string)suggestion["Category"],
                                suggestionText);

                            returnSuggestions.Add(returnString);
                        }
                    }
                }
                else
                {
                    string matchText = String.Empty;

                    // Otherwise, this is a Regex match against the
                    // command or error
                    if (matchType == SuggestionMatchType.Command)
                    {
                        matchText = lastHistory.CommandLine;
                    }
                    else if (matchType == SuggestionMatchType.Error)
                    {
                        if (lastError != null)
                        {
                            Exception lastException = lastError as Exception;
                            if (lastException != null)
                            {
                                matchText = lastException.Message;
                            }
                            else
                            {
                                matchText = lastError.ToString();
                            }
                        }
                    }
                    else
                    {
                        suggestion["Enabled"] = false;

                        throw new ArgumentException(
                                  SuggestionStrings.InvalidMatchType,
                                  "MatchType");
                    }

                    // If the text matches, evaluate the suggestion
                    if (Regex.IsMatch(matchText, (string)suggestion["Rule"], RegexOptions.IgnoreCase))
                    {
                        string suggestionText = GetSuggestionText(suggestion["Suggestion"], (object[])suggestion["SuggestionArgs"], invocationModule);

                        if (!String.IsNullOrEmpty(suggestionText))
                        {
                            string returnString = String.Format(
                                CultureInfo.CurrentCulture,
                                "Suggestion [{0},{1}]: {2}",
                                (int)suggestion["Id"],
                                (string)suggestion["Category"],
                                suggestionText);

                            returnSuggestions.Add(returnString);
                        }
                    }
                }

                // If the rule generated an error, disable it
                if (errorList.Count != initialErrorCount)
                {
                    suggestion["Enabled"] = false;
                }
            }


            return(returnSuggestions);
        }
示例#4
0
        private void checkTimeline()
        {
            util.debugWriteLine("auto reserve checktimeline");
            var    url            = "https://public.api.nicovideo.jp/v1/timelines/nicolive/last-1-month/my/android/entries.json";
            string min            = null;
            var    recentUpdateDt = DateTime.MinValue;
            var    aiList         = check.form.alartListDataSource.ToList();

            aiList.AddRange(check.form.userAlartListDataSource.ToList());
            for (var i = 0; i < 5; i++)
            {
                try {
                    util.debugWriteLine("autoreserve i " + i);
                    var _url = url + (min == null ? "" : ("?untilId=" + min));
                    var res  = util.getPageSource(_url, check.container);
                    if (res == null)
                    {
                        break;
                    }

                    var timelineObj = Newtonsoft.Json.JsonConvert.DeserializeObject <ActivityTimeline>(res);
                    if (timelineObj.meta.status != "200")
                    {
                        util.debugWriteLine("auto reserve check timeline not status 200 " + res);
                        break;
                    }
                    if (!string.IsNullOrEmpty(timelineObj.meta.minId))
                    {
                        min = timelineObj.meta.minId;
                    }
                    foreach (var o in timelineObj.data)
                    {
                        if (o.updated > recentUpdateDt)
                        {
                            recentUpdateDt = o.updated;
                        }
                        if (o.updated <= lastCheckedItemTime)
                        {
                            i = 5;
                            continue;
                        }

                        if (o.title.EndsWith("予約しました"))
                        {
                            util.debugWriteLine("autoreserve data item opentime " + o.updated + " " + o.title);
                            var lvid = util.getRegGroup([email protected], "(lv\\d+)");
                            if (lvid == null)
                            {
                                continue;
                            }
                            var pageUrl  = "https://live.nicovideo.jp/watch/" + lvid;
                            var hig      = new HosoInfoGetter();
                            var higGetOk = hig.get(pageUrl, check.container);
                            if ((higGetOk && hig.openDt > DateTime.Now) || !higGetOk)
                            {
                                RssItem ri = null;
                                if (!isReserveAiLive(o, lvid, higGetOk ? hig : null, aiList, out ri))
                                {
                                    continue;
                                }

                                var ret = new Reservation(check.container, lvid, config).live2Reserve(bool.Parse(config.get("IsOverwriteOldReserve")));
                                if (ret == "ok")
                                {
                                    check.form.addLogText(lvid + " " + o.actor.name + "(" + hig.title + ")のタイムシフトを予約しました");
                                    var hi = new HistoryInfo(ri);
                                    check.form.addReserveHistoryList(hi);
                                }
                                else
                                {
                                    if (ret != "既に予約済みです。")
                                    {
                                        check.form.addLogText(lvid + " " + o.actor.name + "(" + hig.title + ")のタイムシフトの予約に失敗しました " + ret);
                                    }
                                }
                            }
                        }
                    }
                } catch (Exception e) {
                    util.debugWriteLine(e.Message + e.Source + e.StackTrace + e.TargetSite);
                }
            }
            if (recentUpdateDt > lastCheckedItemTime)
            {
                lastCheckedItemTime = recentUpdateDt;
            }
        }
示例#5
0
        /// <summary>
        /// 根据服务凭证、作业报告状态修改派工单状态和请求状态
        /// </summary>
        /// <param name="dispatchID">派工单编号</param>
        /// <param name="user">操作的用户信息</param>
        private void UpdateDispatchStatusByJournalAndReport(int dispatchID, UserInfo user)
        {
            int                 dispatchStatusID = 0;
            int                 requestStatusID  = 0;
            DispatchInfo        dispatch         = this.dispatchDao.GetDispatchByID(dispatchID);
            List <DispatchInfo> dispatches       = this.dispatchDao.GetOpenDispatchesByRequestID(dispatch.Request.ID);
            RequestInfo         request          = this.requestDao.QueryRequestByID(dispatch.Request.ID);

            if (dispatch.DispatchReport.Status.ID == DispatchReportInfo.DispatchReportStatus.Approved && dispatch.DispatchJournal.Status.ID == DispatchJournalInfo.DispatchJournalStatus.Approved)
            {   //Journal和Report全部审批结束 ——派工单显示已审批、请求更新状态
                dispatchStatusID = DispatchInfo.Statuses.Approved;

                DispatchReportInfo dispatchReport = GetDispatchReportByID(dispatch.DispatchReport.ID);
                dispatchReport.Dispatch.ID = dispatchID;
                if (request.Status.ID == RequestInfo.Statuses.Close)
                {
                    requestStatusID = RequestInfo.Statuses.Close;
                }
                else
                {
                    requestStatusID = DispatchReportInfo.SolutionResultStatuses.GetRequestStatusBySolutionResult(dispatchReport.SolutionResultStatus.ID);
                }

                this.requestDao.UpdateLastStatusID(dispatch.Request.ID, requestStatusID);
                if (requestStatusID == RequestInfo.Statuses.Close)
                {
                    this.requestDao.UpdateRequestCloseDate(dispatch.Request.ID);

                    dispatch.Request = this.requestManager.GetRequest(dispatch.Request.ID);
                    if (dispatch.Request.Source.ID == RequestInfo.Sources.SysRequest)
                    {
                        foreach (EquipmentInfo info in dispatch.Request.Equipments)
                        {
                            if (dispatch.RequestType.ID == RequestInfo.RequestTypes.Maintain)
                            {
                                this.equipmentManager.UpdateEquipmentLastMaintenanceCheck(info);
                            }
                            else if (dispatch.RequestType.ID == RequestInfo.RequestTypes.Correcting)
                            {
                                this.equipmentManager.UpdateEquipmentLastCorrectionCheck(info);
                            }
                            else if (dispatch.RequestType.ID == RequestInfo.RequestTypes.OnSiteInspection)
                            {
                                DateTime dt = dispatch.Request.SelectiveDate != DateTime.MinValue ? dispatch.Request.SelectiveDate : dispatch.Request.RequestDate;
                                this.equipmentManager.UpdateEquipmentLastPatrolCheck(info.ID, dt);
                            }
                        }
                    }
                }
                this.dispatchDao.UpdateDispatchEndDate(dispatchID);

                PassDispatchReportInternal(dispatchReport, user);

                HistoryInfo historyRequest = new HistoryInfo(dispatch.Request.ID, ObjectTypes.Request, user.ID, RequestInfo.Actions.Update);
                this.historyDao.AddHistory(historyRequest);//添加历史操作——请求 更新状态

                HistoryInfo historyDisptach = new HistoryInfo(dispatchID, ObjectTypes.Dispatch, user.ID, DispatchInfo.Actions.Finish);
                this.historyDao.AddHistory(historyDisptach);//添加历史操作——派工单 完成
            }
            else if (dispatch.DispatchReport.Status.ID < DispatchReportInfo.DispatchReportStatus.Pending && dispatch.DispatchJournal.Status.ID < DispatchJournalInfo.DispatchJournalStatus.Pending)
            {   //Journal和Report 未创建、两者均被退回、一者被退回 另一者未提交 未新建 ——派工单显示已响应,请求显示已响应
                dispatchStatusID = DispatchInfo.Statuses.Responded;
                if (request.Status.ID == RequestInfo.Statuses.Close)
                {
                    requestStatusID = RequestInfo.Statuses.Close;
                }
                else
                {
                    requestStatusID = RequestInfo.Statuses.Responded;
                    foreach (DispatchInfo info in dispatches)
                    {
                        if (info.ID != dispatchID && info.Status.ID == DispatchInfo.Statuses.Pending)
                        {
                            requestStatusID = RequestInfo.Statuses.Pending;
                            break;
                        }
                    }
                }
            }
            else
            {//其余情况均为 派工单状态——待审批
                dispatchStatusID = DispatchInfo.Statuses.Pending;
                if (request.Status.ID == RequestInfo.Statuses.Close)
                {
                    requestStatusID = RequestInfo.Statuses.Close;
                }
                else
                {
                    requestStatusID = RequestInfo.Statuses.Pending;
                }
            }

            this.requestDao.UpdateRequestStatus(dispatch.Request.ID, requestStatusID);
            this.dispatchDao.UpdateDispatchStatus(dispatchID, dispatchStatusID);
        }
示例#6
0
        public int SaveDispatchReport4App(DispatchReportInfo dispatchReport, UserInfo user)
        {
            if (dispatchReport.ID > 0)
            {
                DispatchReportInfo exsistReport = GetDispatchReportByID(dispatchReport.ID);
                this.dispatchReportDao.UpdateDispatchReport(dispatchReport);

                if (dispatchReport.FileInfo != null && dispatchReport.FileInfo.ID <= 0)
                {
                    this.fileManager.DeleteUploadFileByID(ObjectTypes.DispatchReport, exsistReport.FileInfo.ID);
                }
                else if (dispatchReport.FileInfo == null)
                {
                    this.fileManager.DeleteUploadFileByID(ObjectTypes.DispatchReport, exsistReport.FileInfo.ID);
                }
                if (dispatchReport.ReportComponent != null && dispatchReport.ReportComponent.Count > 0)
                {
                    List <int> newIdList = SQLUtil.GetIDListFromObjectList(dispatchReport.ReportComponent);

                    foreach (ReportComponentInfo info in (from ReportComponentInfo temp in exsistReport.ReportComponent where !newIdList.Contains(temp.ID) select temp))
                    {
                        DeleteReportComponent(info.ID);
                    }
                }
                else if ((dispatchReport.ReportComponent == null || dispatchReport.ReportComponent.Count == 0) && exsistReport.ReportComponent.Count > 0)
                {
                    foreach (ReportComponentInfo info in exsistReport.ReportComponent)
                    {
                        DeleteReportComponent(info.ID);
                    }
                }

                if (dispatchReport.ReportConsumable != null && dispatchReport.ReportConsumable.Count > 0)
                {
                    List <int> newIdList = SQLUtil.GetIDListFromObjectList(dispatchReport.ReportConsumable);

                    foreach (ReportConsumableInfo info in (from ReportConsumableInfo temp in exsistReport.ReportConsumable where !newIdList.Contains(temp.ID) select temp))
                    {
                        DeleteReportConsumable(info.ID);
                    }
                }
                else if ((dispatchReport.ReportConsumable == null || dispatchReport.ReportConsumable.Count == 0) && exsistReport.ReportConsumable.Count > 0)
                {
                    foreach (ReportConsumableInfo info in exsistReport.ReportConsumable)
                    {
                        DeleteReportConsumable(info.ID);
                    }
                }

                if (dispatchReport.ReportService != null && dispatchReport.ReportService.Count > 0)
                {
                    List <int> newIdList = SQLUtil.GetIDListFromObjectList(dispatchReport.ReportService);

                    foreach (ReportServiceInfo info in (from ReportServiceInfo temp in exsistReport.ReportService where !newIdList.Contains(temp.ID) select temp))
                    {
                        DeleteReportService(info.ID);
                    }
                }
                else if ((dispatchReport.ReportService == null || dispatchReport.ReportService.Count == 0) && exsistReport.ReportService.Count > 0)
                {
                    foreach (ReportServiceInfo info in exsistReport.ReportService)
                    {
                        DeleteReportService(info.ID);
                    }
                }
            }
            else
            {
                dispatchReport.ID = this.dispatchReportDao.AddDispatchReport(dispatchReport);
            }

            if (dispatchReport.FileInfo != null && !string.IsNullOrEmpty(dispatchReport.FileInfo.FileName) && dispatchReport.FileInfo.ID <= 0)
            {
                dispatchReport.FileInfo.ObjectID     = dispatchReport.ID;
                dispatchReport.FileInfo.ObjectTypeId = ObjectTypes.DispatchReport;
                this.fileManager.SaveUploadFile(dispatchReport.FileInfo);
            }

            if (dispatchReport.ReportComponent != null && dispatchReport.ReportComponent.Count > 0)
            {
                foreach (ReportComponentInfo info in (from ReportComponentInfo temp in dispatchReport.ReportComponent where temp.ID <= 0 select temp))
                {
                    info.DispatchReportID = dispatchReport.ID;
                    SaveReportComponent(info, info.FileInfos);
                }
            }
            if (dispatchReport.ReportConsumable != null && dispatchReport.ReportConsumable.Count > 0)
            {
                foreach (ReportConsumableInfo info in (from ReportConsumableInfo temp in dispatchReport.ReportConsumable where temp.ID <= 0 select temp))
                {
                    info.DispatchReportID = dispatchReport.ID;
                    SaveReportConsumable(info);
                }
            }
            if (dispatchReport.ReportService != null && dispatchReport.ReportService.Count > 0)
            {
                foreach (ReportServiceInfo info in (from ReportServiceInfo temp in dispatchReport.ReportService where temp.ID <= 0 select temp))
                {
                    info.DispatchReportID = dispatchReport.ID;
                    SaveReportService(info);
                }
            }
            if (dispatchReport.Status.ID == DispatchReportInfo.DispatchReportStatus.Pending)
            {
                UpdateDispatchStatusByJournalAndReport(dispatchReport.Dispatch.ID, user);

                HistoryInfo history = new HistoryInfo(dispatchReport.ID, ObjectTypes.DispatchReport, user.ID, DispatchReportInfo.Actions.Submit, dispatchReport.FujiComments);
                this.historyDao.AddHistory(history);
            }
            return(dispatchReport.ID);
        }
示例#7
0
 internal void AddToInvokeHistoryEntryList(HistoryInfo entry) => this._invokeHistoryIds.Add(entry.Id);
示例#8
0
 internal void RemoveFromInvokeHistoryEntryList(HistoryInfo entry) => this._invokeHistoryIds.Remove(entry.Id);
        private System.IO.Stream GetGroupsFromFilter(int userid, string GroupFilterId, HistoryInfo info)
        {
            PlexObject ret = new PlexObject(PlexHelper.NewMediaContainer(MediaContainerTypes.Show, info, false));

            if (!ret.Init())
            {
                return(new MemoryStream());
            }

            //List<Joint> retGroups = new List<Joint>();
            List <Video> retGroups = new List <Video>();

            try
            {
                int groupFilterID;
                int.TryParse(GroupFilterId, out groupFilterID);
                using (var session = JMMService.SessionFactory.OpenSession())
                {
                    if (groupFilterID == -1)
                    {
                        return(new MemoryStream());
                    }
                    DateTime start = DateTime.Now;
                    GroupFilterRepository repGF = new GroupFilterRepository();

                    GroupFilter gf;

                    if (groupFilterID == -999)
                    {
                        // all groups
                        gf = new GroupFilter();
                        gf.GroupFilterName = "All";
                    }
                    else
                    {
                        gf = repGF.GetByID(session, groupFilterID);
                        if (gf == null)
                        {
                            return(new MemoryStream());
                        }
                    }
                    //Contract_GroupFilterExtended contract = gf.ToContractExtended(user);

                    AnimeGroupRepository repGroups = new AnimeGroupRepository();
                    List <AnimeGroup>    allGrps   = repGroups.GetAll(session);



                    TimeSpan ts  = DateTime.Now - start;
                    string   msg = string.Format("Got groups for filter DB: {0} - {1} in {2} ms", gf.GroupFilterName,
                                                 allGrps.Count, ts.TotalMilliseconds);
                    logger.Info(msg);
                    start = DateTime.Now;



                    if ((StatsCache.Instance.StatUserGroupFilter.ContainsKey(userid)) &&
                        (StatsCache.Instance.StatUserGroupFilter[userid].ContainsKey(gf.GroupFilterID)))
                    {
                        HashSet <int> groups = StatsCache.Instance.StatUserGroupFilter[userid][gf.GroupFilterID];

                        foreach (AnimeGroup grp in allGrps)
                        {
                            if (groups.Contains(grp.AnimeGroupID))
                            {
                                Video v = StatsCache.Instance.StatPlexGroupsCache[userid][grp.AnimeGroupID];
                                if (v != null)
                                {
                                    v = v.Clone();

                                    retGroups.Add(v, info);
                                }
                            }
                        }
                    }
                    ts  = DateTime.Now - start;
                    msg = string.Format("Got groups for filter EVAL: {0} - {1} in {2} ms", gf.GroupFilterName,
                                        retGroups.Count, ts.TotalMilliseconds);
                    logger.Info(msg);
                    if ((groupFilterID == -999) || (gf.SortCriteriaList.Count == 0))
                    {
                        ret.Childrens = PlexHelper.ConvertToDirectoryIfNotUnique(retGroups.OrderBy(a => a.Group.SortName).ToList());
                        return(ret.GetStream());
                    }
                    List <Contract_AnimeGroup>         grps         = retGroups.Select(a => a.Group).ToList();
                    List <SortPropOrFieldAndDirection> sortCriteria = new List <SortPropOrFieldAndDirection>();
                    foreach (GroupFilterSortingCriteria g in gf.SortCriteriaList)
                    {
                        sortCriteria.Add(GroupFilterHelper.GetSortDescription(g.SortType, g.SortDirection));
                    }
                    grps = Sorting.MultiSort(grps, sortCriteria);
                    List <Video> joints2 = new List <Video>();
                    foreach (Contract_AnimeGroup gr in grps)
                    {
                        foreach (Video j in retGroups)
                        {
                            if (j.Group == gr)
                            {
                                joints2.Add(j);
                                retGroups.Remove(j);
                                break;
                            }
                        }
                    }
                    ret.Childrens = PlexHelper.ConvertToDirectoryIfNotUnique(joints2);
                    ts            = DateTime.Now - start;
                    msg           = string.Format("Got groups final: {0} - {1} in {2} ms", gf.GroupFilterName,
                                                  retGroups.Count, ts.TotalMilliseconds);
                    logger.Info(msg);
                    return(ret.GetStream());
                }
            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
            }
            return(new MemoryStream());
        }
示例#10
0
 internal bool PresentInInvokeHistoryEntryList(HistoryInfo entry) => this._invokeHistoryIds.Contains(entry.Id);
        public System.IO.Stream GetItemsFromSerie(int userid, string SerieId, HistoryInfo info)
        {
            PlexObject    ret    = null;
            enEpisodeType?eptype = null;
            int           serieID;

            if (SerieId.Contains("_"))
            {
                int      ept;
                string[] ndata = SerieId.Split('_');
                if (!int.TryParse(ndata[0], out ept))
                {
                    return(new MemoryStream());
                }
                eptype = (enEpisodeType)ept;
                if (!int.TryParse(ndata[1], out serieID))
                {
                    return(new MemoryStream());
                }
            }
            else
            {
                if (!int.TryParse(SerieId, out serieID))
                {
                    return(new MemoryStream());
                }
            }


            using (var session = JMMService.SessionFactory.OpenSession())
            {
                if (serieID == -1)
                {
                    return(new MemoryStream());
                }
                AnimeSeriesRepository repSeries = new AnimeSeriesRepository();
                AnimeSeries           ser       = repSeries.GetByID(session, serieID);
                if (ser == null)
                {
                    return(new MemoryStream());
                }
                AniDB_Anime anime = ser.GetAnime();
                if (anime == null)
                {
                    return(new MemoryStream());
                }
                Contract_AnimeSeries cseries = ser.ToContract(ser.GetUserRecord(userid), true);
                ImageDetails         fanart  = anime.GetDefaultFanartDetailsNoBlanks(session);

                //iOS Hack, since it uses the previous thumb, as overlay image on the episodes
                bool iosHack = false;
                if (WebOperationContext.Current != null && WebOperationContext.Current.IncomingRequest.Headers.AllKeys.Contains("X-Plex-Product"))
                {
                    string kh = WebOperationContext.Current.IncomingRequest.Headers.Get("X-Plex-Product").ToUpper();
                    if (kh.Contains(" IOS"))
                    {
                        iosHack = true;
                    }
                }

                List <AnimeEpisode> episodes = ser.GetAnimeEpisodes(session).Where(a => a.GetVideoLocals(session).Count > 0).ToList();
                if (eptype.HasValue)
                {
                    ret = new PlexObject(PlexHelper.NewMediaContainer(MediaContainerTypes.Episode, info, true));
                    if (!ret.Init())
                    {
                        return(new MemoryStream());
                    }
                    ret.MediaContainer.LeafCount       = (cseries.WatchedEpisodeCount + cseries.UnwatchedEpisodeCount).ToString();
                    ret.MediaContainer.ViewedLeafCount = cseries.WatchedEpisodeCount.ToString();
                    episodes = episodes.Where(a => a.EpisodeTypeEnum == eptype.Value).ToList();
                }
                else
                {
                    ret = new PlexObject(PlexHelper.NewMediaContainer(MediaContainerTypes.Show, info, true));
                    if (!ret.Init())
                    {
                        return(new MemoryStream());
                    }

                    ret.MediaContainer.LeafCount       = (cseries.WatchedEpisodeCount + cseries.UnwatchedEpisodeCount).ToString();
                    ret.MediaContainer.ViewedLeafCount = cseries.WatchedEpisodeCount.ToString();
                    List <enEpisodeType> types = episodes.Select(a => a.EpisodeTypeEnum).Distinct().ToList();
                    if (types.Count > 1)
                    {
                        List <PlexEpisodeType> eps = new List <PlexEpisodeType>();
                        foreach (enEpisodeType ee in types)
                        {
                            PlexEpisodeType k2 = new PlexEpisodeType();
                            PlexEpisodeType.EpisodeTypeTranslated(k2, ee, (AnimeTypes)anime.AnimeType, episodes.Count(a => a.EpisodeTypeEnum == ee));
                            eps.Add(k2);
                        }
                        List <SortPropOrFieldAndDirection> sortCriteria = new List <SortPropOrFieldAndDirection>();
                        sortCriteria.Add(new SortPropOrFieldAndDirection("Name", SortType.eString));
                        eps = Sorting.MultiSort(eps, sortCriteria);
                        List <Video> dirs            = new List <Video>();
                        bool         converttoseason = true;

                        foreach (PlexEpisodeType ee in  eps)
                        {
                            Video v = new Directory();
                            if (fanart != null)
                            {
                                v.Art = fanart.GenArt();
                            }
                            v.Title           = ee.Name;
                            v.LeafCount       = ee.Count.ToString();
                            v.ChildCount      = v.LeafCount;
                            v.ViewedLeafCount = "0";
                            v.Key             = PlexHelper.ConstructSerieIdUrl(userid, ee.Type + "_" + ser.AnimeSeriesID);
                            v.Thumb           = PlexHelper.ConstructSupportImageLink(ee.Image);
                            if ((ee.AnimeType == AnimeTypes.Movie) || (ee.AnimeType == AnimeTypes.OVA))
                            {
                                v = PlexHelper.MayReplaceVideo(v, ser, cseries, anime, JMMType.File, userid, false);
                            }
                            dirs.Add(v, info);
                            if (iosHack)
                            {
                                v.Thumb            = ret.MediaContainer.ParentThumb;
                                v.ParentThumb      = ret.MediaContainer.GrandparentThumb;
                                v.GrandparentThumb = ret.MediaContainer.GrandparentThumb;
                                v.ParentKey        = v.GrandparentKey;
                            }
                        }
                        ret.Childrens = dirs;
                        return(ret.GetStream());
                    }
                }
                List <Video> vids = new List <Video>();
                Video        nv   = new Video();
                PlexHelper.FillSerie(nv, ser, anime, cseries, userid);
                foreach (AnimeEpisode ep in episodes)
                {
                    Video             v      = new Video();
                    List <VideoLocal> locals = ep.GetVideoLocals(session);
                    if ((locals == null) || (locals.Count == 0))
                    {
                        continue;
                    }
                    AniDB_Episode aep = ep.AniDB_Episode;
                    if (aep == null)
                    {
                        continue;
                    }
                    VideoLocal current = locals[0];
                    try
                    {
                        PlexHelper.PopulateVideo(v, current, ep, ser, cseries, anime, nv, JMMType.File, userid);
                        vids.Add(v, info);
                        if (iosHack)
                        {
                            v.Art   = v.Thumb;
                            v.Thumb = ret.MediaContainer.ParentThumb;
                        }
                    }
                    catch (Exception e)
                    {
                        //Fast fix if file do not exist, and still is in db. (Xml Serialization of video info will fail on null)
                    }
                }

                List <SortPropOrFieldAndDirection> sortCriteria2 = new List <SortPropOrFieldAndDirection>();
                sortCriteria2.Add(new SortPropOrFieldAndDirection("EpNumber", SortType.eInteger));
                vids          = Sorting.MultiSort(vids, sortCriteria2);
                ret.Childrens = vids;

                return(ret.GetStream());
            }
        }
        public System.IO.Stream GetFilters(string uid)
        {
            int t = 0;

            int.TryParse(uid, out t);
            JMMUser user = t > 0 ? PlexHelper.GetJMMUser(uid) : PlexHelper.GetUser(uid);

            if (user == null)
            {
                return(new MemoryStream());
            }
            int         userid = user.JMMUserID;
            HistoryInfo info   = new HistoryInfo {
                Key = PlexHelper.ConstructFiltersUrl(userid), Title = "Anime"
            };
            PlexObject ret = new PlexObject(PlexHelper.NewMediaContainer(MediaContainerTypes.Show, info, false));

            if (!ret.Init())
            {
                return(new MemoryStream());
            }
            List <Video> dirs = new List <Video>();

            try
            {
                using (var session = JMMService.SessionFactory.OpenSession())
                {
                    GroupFilterRepository            repGF  = new GroupFilterRepository();
                    List <GroupFilter>               allGfs = repGF.GetAll(session);
                    Dictionary <int, HashSet <int> > gstats = StatsCache.Instance.StatUserGroupFilter[userid];
                    foreach (GroupFilter gg in allGfs.ToArray())
                    {
                        if ((!StatsCache.Instance.StatUserGroupFilter.ContainsKey(userid)) ||
                            (!StatsCache.Instance.StatUserGroupFilter[userid].ContainsKey(gg.GroupFilterID)))
                        {
                            allGfs.Remove(gg);
                        }
                    }


                    AnimeGroupRepository repGroups = new AnimeGroupRepository();
                    allGfs.Insert(0, new GroupFilter()
                    {
                        GroupFilterName = "All", GroupFilterID = -999
                    });
                    foreach (GroupFilter gg in allGfs)
                    {
                        Random    rnd = new Random(123456789);
                        Directory pp  = new Directory {
                            Type = "show"
                        };
                        pp.Key   = PlexHelper.ConstructFilterIdUrl(userid, gg.GroupFilterID);
                        pp.Title = gg.GroupFilterName;
                        HashSet <int> groups;
                        groups = gg.GroupFilterID == -999 ? new HashSet <int>(repGroups.GetAllTopLevelGroups(session).Select(a => a.AnimeGroupID)) : gstats[gg.GroupFilterID];
                        if (groups.Count != 0)
                        {
                            bool repeat;
                            int  nn = 0;
                            pp.LeafCount       = groups.Count.ToString();
                            pp.ViewedLeafCount = "0";
                            do
                            {
                                repeat = true;
                                int                grp  = groups.ElementAt(rnd.Next(groups.Count));
                                AnimeGroup         ag   = repGroups.GetByID(grp);
                                List <AnimeSeries> sers = ag.GetSeries(session);
                                if (sers.Count > 0)
                                {
                                    AnimeSeries ser  = sers[rnd.Next(sers.Count)];
                                    AniDB_Anime anim = ser.GetAnime(session);
                                    if (anim != null)
                                    {
                                        ImageDetails poster = anim.GetDefaultPosterDetailsNoBlanks(session);
                                        ImageDetails fanart = anim.GetDefaultFanartDetailsNoBlanks(session);
                                        if (poster != null)
                                        {
                                            pp.Thumb = poster.GenPoster();
                                        }
                                        if (fanart != null)
                                        {
                                            pp.Art = fanart.GenArt();
                                        }
                                        if (poster != null)
                                        {
                                            repeat = false;
                                        }
                                    }
                                }
                                nn++;
                                if ((repeat) && (nn == 15))
                                {
                                    repeat = false;
                                }
                            } while (repeat);
                            dirs.Add(pp, info);
                        }
                    }
                    VideoLocalRepository repVids = new VideoLocalRepository();
                    List <VideoLocal>    vids    = repVids.GetVideosWithoutEpisode();
                    if (vids.Count > 0)
                    {
                        Directory pp = new Directory()
                        {
                            Type = "show"
                        };
                        pp.Key             = PlexHelper.ConstructUnsortUrl(userid);
                        pp.Title           = "Unsort";
                        pp.Thumb           = PlexHelper.ConstructSupportImageLink("plex_unsort.png");
                        pp.LeafCount       = vids.Count.ToString();
                        pp.ViewedLeafCount = "0";
                        dirs.Add(pp, info);
                    }
                    var repPlaylist = new PlaylistRepository();
                    var playlists   = repPlaylist.GetAll();
                    if (playlists.Count > 0)
                    {
                        Directory pp = new Directory()
                        {
                            Type = "show"
                        };
                        pp.Key             = PlexHelper.ConstructPlaylistUrl(userid);
                        pp.Title           = "Playlists";
                        pp.Thumb           = PlexHelper.ConstructSupportImageLink("plex_playlists.png");
                        pp.LeafCount       = playlists.Count.ToString();
                        pp.ViewedLeafCount = "0";
                        dirs.Add(pp, info);
                    }
                    dirs = dirs.OrderBy(a => a.Title).ToList();
                }
                ret.Childrens = dirs;
                return(ret.GetStream());
            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
                return(new MemoryStream());
            }
        }
        public System.IO.Stream Search(string UserId, string limit, string query)
        {
            HistoryInfo info = new HistoryInfo {
                Key = PlexHelper.ConstructSearchUrl(UserId, limit, query), Title = "Search for '" + query + "'"
            };

            PlexObject            ret       = new PlexObject(PlexHelper.NewMediaContainer(MediaContainerTypes.Show, info, true));
            AniDB_AnimeRepository repAnime  = new AniDB_AnimeRepository();
            AnimeSeriesRepository repSeries = new AnimeSeriesRepository();
            int lim;

            if (!int.TryParse(limit, out lim))
            {
                lim = 20;
            }
            JMMUser user = PlexHelper.GetUser(UserId);

            if (user == null)
            {
                return(new MemoryStream());
            }
            List <Video>       ls     = new List <Video>();
            int                cnt    = 0;
            List <AniDB_Anime> animes = repAnime.SearchByName(query);

            foreach (AniDB_Anime anidb_anime in animes)
            {
                if (!user.AllowedAnime(anidb_anime))
                {
                    continue;
                }
                AnimeSeries ser = repSeries.GetByAnimeID(anidb_anime.AnimeID);
                if (ser != null)
                {
                    Contract_AnimeSeries cserie = ser.ToContract(ser.GetUserRecord(user.JMMUserID), true);
                    Video v = PlexHelper.FromSerieWithPossibleReplacement(cserie, ser, anidb_anime, user.JMMUserID);
                    switch (anidb_anime.AnimeTypeEnum)
                    {
                    case enAnimeType.Movie:
                        v.SourceTitle = "Anime Movies";
                        break;

                    case enAnimeType.OVA:
                        v.SourceTitle = "Anime Ovas";
                        break;

                    case enAnimeType.Other:
                        v.SourceTitle = "Anime Others";
                        break;

                    case enAnimeType.TVSeries:
                        v.SourceTitle = "Anime Series";
                        break;

                    case enAnimeType.TVSpecial:
                        v.SourceTitle = "Anime Specials";
                        break;

                    case enAnimeType.Web:
                        v.SourceTitle = "Anime Web Clips";
                        break;
                    }

                    ls.Add(v, info);
                    cnt++;
                    if (cnt == lim)
                    {
                        break;
                    }
                }
            }
            ret.MediaContainer.Childrens = PlexHelper.ConvertToDirectoryIfNotUnique(ls);
            return(ret.GetStream());
        }
        private System.IO.Stream GetItemsFromPlaylist(int userid, string id, HistoryInfo info)
        {
            var PlaylistID = -1;

            int.TryParse(id, out PlaylistID);
            var playlistRepository = new PlaylistRepository();
            var repo = new AnimeEpisodeRepository();

            if (PlaylistID == 0)
            {
                using (var session = JMMService.SessionFactory.OpenSession())
                {
                    var ret = new PlexObject(PlexHelper.NewMediaContainer(MediaContainerTypes.Show, info, false));
                    if (!ret.Init())
                    {
                        return(new MemoryStream());
                    }
                    var retPlaylists = new List <Video>();
                    var playlists    = playlistRepository.GetAll();
                    foreach (var playlist in playlists)
                    {
                        var dir = new Directory();
                        dir.Key   = PlexHelper.ConstructPlaylistIdUrl(userid, playlist.PlaylistID);
                        dir.Title = playlist.PlaylistName;
                        var episodeID = -1;
                        if (int.TryParse(playlist.PlaylistItems.Split('|')[0].Split(';')[1], out episodeID))
                        {
                            var anime = repo.GetByID(session, episodeID).GetAnimeSeries(session).GetAnime(session);
                            dir.Thumb = anime.GetDefaultPosterDetailsNoBlanks(session).GenPoster();
                            dir.Art   = anime.GetDefaultFanartDetailsNoBlanks(session).GenArt();
                        }
                        else
                        {
                            dir.Thumb = PlexHelper.ConstructSupportImageLink("plex_404V.png");
                        }
                        dir.LeafCount       = playlist.PlaylistItems.Split('|').Count().ToString();
                        dir.ViewedLeafCount = "0";
                        retPlaylists.Add(dir, info);
                    }
                    retPlaylists  = retPlaylists.OrderBy(a => a.Title).ToList();
                    ret.Childrens = retPlaylists;
                    return(ret.GetStream());
                }
            }
            if (PlaylistID > 0)
            {
                //iOS Hack, since it uses the previous thumb, as overlay image on the episodes
                bool iosHack = false;
                if (WebOperationContext.Current != null && WebOperationContext.Current.IncomingRequest.Headers.AllKeys.Contains("X-Plex-Product"))
                {
                    string kh = WebOperationContext.Current.IncomingRequest.Headers.Get("X-Plex-Product").ToUpper();
                    if (kh.Contains(" IOS"))
                    {
                        iosHack = true;
                    }
                }

                var playlist      = playlistRepository.GetByID(PlaylistID);
                var playlistItems = playlist.PlaylistItems.Split('|');
                var vids          = new List <Video>();
                var ret           = new PlexObject(PlexHelper.NewMediaContainer(MediaContainerTypes.Episode, info, true));
                if (!ret.Init())
                {
                    return(new MemoryStream());
                }
                using (var session = JMMService.SessionFactory.OpenSession())
                {
                    foreach (var item in playlistItems)
                    {
                        var episodeID = -1;
                        int.TryParse(item.Split(';')[1], out episodeID);
                        if (episodeID < 0)
                        {
                            return(new MemoryStream());
                        }
                        var ep     = repo.GetByID(session, episodeID);
                        var v      = new Video();
                        var locals = ep.GetVideoLocals(session);
                        if ((locals == null) || (locals.Count == 0))
                        {
                            continue;
                        }
                        var current = locals[0];
                        try
                        {
                            PlexHelper.PopulateVideo(v, current, JMMType.File, userid);
                            if (!string.IsNullOrEmpty(v.Duration))
                            {
                                vids.Add(v, info);
                                if (iosHack)
                                {
                                    v.Art   = v.Thumb;
                                    v.Thumb = ret.MediaContainer.ParentThumb;
                                }
                            }
                        }
                        catch (Exception e)
                        {
                            //Fast fix if file do not exist, and still is in db. (Xml Serialization of video info will fail on null)
                        }
                    }
                    ret.Childrens = vids;
                    return(ret.GetStream());
                }
            }
            return(new MemoryStream());
        }
示例#15
0
        protected HistoryInfo GetHistoryInfoCore(HistoryRequest historyRequest)
        {
            var transactionCount = 0;
            var historyInfo      = new HistoryInfo {
                Blocks = new List <HistoryInfo.BlockInfo>()
            };

            var unconfirmed = new List <HistoryInfo.TransactionInfo>();

            foreach (var item in this.metadata.MemoryPool.Entries.OrderByDescending(x => x.TransactionTime))
            {
                var tx = item.Transaction;
                var ti = new HistoryInfo.TransactionInfo {
                    TxType = tx.TxType, HashTx = tx.HashTx.ToString(), ValueAdded = tx.ValueAdded
                };
                unconfirmed.Add(ti);
                if (tx.Received != null)
                {
                    ti.TotalReceived = tx.Received.Values.Sum(x => x.Satoshis);
                }
                if (tx.Spent != null)
                {
                    ti.TotalSpent = tx.Spent.Values.Sum(x => x.Satoshis);
                }
                if (tx.Destinations != null)
                {
                    ti.Recipients = new Recipient[tx.Destinations.Count];
                    int recipientIndex = 0;
                    foreach (var d in tx.Destinations)
                    {
                        var r = new Recipient {
                            Address = d.Value.Address, Amount = d.Value.Satoshis
                        };
                        ti.Recipients[recipientIndex++] = r;
                    }
                }
                transactionCount++;
            }
            if (unconfirmed.Count > 0)
            {
                var bi = new HistoryInfo.BlockInfo {
                    Height = int.MaxValue, Time = this.metadata.MemoryPool.Entries.Max(x => x.TransactionTime), Transactions = unconfirmed
                };
                historyInfo.Blocks.Add(bi);
            }


            foreach ((int height, BlockMetadata block) in this.metadata.Blocks.Reverse())
            {
                var transactions = new List <HistoryInfo.TransactionInfo>();

                foreach (var tx in block.Transactions.Reverse())
                {
                    if (historyRequest.Take.HasValue)
                    {
                        if (transactionCount == historyRequest.Take.Value)
                        {
                            return(historyInfo);
                        }
                    }

                    var ti = new HistoryInfo.TransactionInfo {
                        TxType = tx.TxType, HashTx = tx.HashTx.ToString(), ValueAdded = tx.ValueAdded
                    };
                    transactions.Add(ti);

                    if (tx.Received != null)
                    {
                        ti.TotalReceived = tx.Received.Values.Sum(x => x.Satoshis);
                    }
                    if (tx.Spent != null)
                    {
                        ti.TotalSpent = tx.Spent.Values.Sum(x => x.Satoshis);
                    }
                    if (tx.Destinations != null)
                    {
                        ti.Recipients = new Recipient[tx.Destinations.Count];
                        int recipientIndex = 0;
                        foreach (var d in tx.Destinations)
                        {
                            var r = new Recipient {
                                Address = d.Value.Address, Amount = d.Value.Satoshis
                            };
                            ti.Recipients[recipientIndex++] = r;
                        }
                    }
                    transactionCount++;
                }

                if (transactions.Count > 0)
                {
                    var bi = new HistoryInfo.BlockInfo {
                        Height = height, Time = block.Time, HashBlock = block.HashBlock.ToString(), Transactions = transactions
                    };
                    historyInfo.Blocks.Add(bi);
                }
            }
            return(historyInfo);
        }