Example #1
0
        public static Azure_UserInfo GetUserInfoData(string vidPlayer = "")
        {
            try
            {
                if (string.IsNullOrEmpty(ServerSettings.Instance.AniDb.Username))
                {
                    return(null);
                }

                Azure_UserInfo uinfo = new Azure_UserInfo
                {
                    DateTimeUpdated    = DateTime.Now,
                    DateTimeUpdatedUTC = 0,

                    // Optional JMM Desktop data
                    DashboardType = null,
                    VideoPlayer   = vidPlayer
                };
                System.Reflection.Assembly a = System.Reflection.Assembly.GetEntryAssembly();
                try
                {
                    if (a != null)
                    {
                        uinfo.JMMServerVersion = Utils.GetApplicationVersion(a);
                    }
                }
                catch
                {
                    // ignored
                }

                uinfo.UsernameHash   = Utils.GetMd5Hash(ServerSettings.Instance.AniDb.Username);
                uinfo.DatabaseType   = ServerSettings.Instance.Database.Type.ToString();
                uinfo.WindowsVersion = Utils.GetOSInfo();
                uinfo.TraktEnabled   = ServerSettings.Instance.TraktTv.Enabled ? 1 : 0;

                uinfo.CountryLocation = string.Empty;

                // this field is not actually used
                uinfo.LastEpisodeWatchedAsDate = DateTime.Now.AddDays(-5);

                uinfo.LocalUserCount = (int)Repo.Instance.JMMUser.GetTotalRecordCount();

                uinfo.FileCount = Repo.Instance.VideoLocal.GetTotalRecordCount();

                SVR_AnimeEpisode_User rec = Repo.Instance.AnimeEpisode_User.GetLastWatchedEpisode();
                uinfo.LastEpisodeWatched = 0;
                if (rec != null)
                {
                    uinfo.LastEpisodeWatched = Commons.Utils.AniDB.GetAniDBDateAsSeconds(rec.WatchedDate);
                }

                return(uinfo);
            }
            catch (Exception ex)
            {
                logger.Error(ex, ex.ToString());
                return(null);
            }
        }
Example #2
0
        public static void CreateAnimeEpisode(this AniDB_Episode episode, ISession session, int animeSeriesID)
        {
            // check if there is an existing episode for this EpisodeID
            SVR_AnimeEpisode existingEp = RepoFactory.AnimeEpisode.GetByAniDBEpisodeID(episode.EpisodeID) ??
                                          new SVR_AnimeEpisode();

            existingEp.Populate(episode);
            existingEp.AnimeSeriesID = animeSeriesID;
            RepoFactory.AnimeEpisode.Save(existingEp);

            // We might have removed our AnimeEpisode_User records when wiping out AnimeEpisodes, recreate them if there's watched files
            var vlUsers = existingEp?.GetVideoLocals()
                          .SelectMany(a => RepoFactory.VideoLocalUser.GetByVideoLocalID(a.VideoLocalID)).ToList();

            // get the list of unique users
            var users = vlUsers.Select(a => a.JMMUserID).Distinct();

            if (vlUsers.Count > 0)
            {
                // per user. An episode is watched if any file is
                foreach (int uid in users)
                {
                    // get the last watched file
                    var vlUser = vlUsers.Where(a => a.JMMUserID == uid && a.WatchedDate != null)
                                 .MaxBy(a => a.WatchedDate).FirstOrDefault();
                    // create or update the record
                    var epUser = RepoFactory.AnimeEpisode_User.GetByUserIDAndEpisodeID(uid, existingEp.AnimeEpisodeID);
                    if (epUser == null)
                    {
                        epUser = new SVR_AnimeEpisode_User
                        {
                            JMMUserID      = uid,
                            WatchedDate    = vlUser?.WatchedDate,
                            PlayedCount    = vlUser != null ? 1 : 0,
                            WatchedCount   = vlUser != null ? 1 : 0,
                            AnimeSeriesID  = animeSeriesID,
                            AnimeEpisodeID = existingEp.AnimeEpisodeID
                        };
                        RepoFactory.AnimeEpisode_User.Save(epUser);
                    }
                }
            }
            else
            {
                // since these are created with VideoLocal_User,
                // these will probably never exist, but if they do, cover our bases
                foreach (var episodeUser in RepoFactory.AnimeEpisode_User.GetByEpisodeID(existingEp.AnimeEpisodeID))
                {
                    RepoFactory.AnimeEpisode_User.Save(episodeUser);
                }
            }
        }
Example #3
0
        /*public static void UpdateWatchedStatus(int animeID, enEpisodeType epType, int lastWatchedEpNumber)
         *      {
         *              try
         *              {
         *                      if (string.IsNullOrEmpty(ServerSettings.MAL_Username) || string.IsNullOrEmpty(ServerSettings.MAL_Password))
         *                              return;
         *
         *                      AniDB_EpisodeRepository repAniEps = new AniDB_EpisodeRepository();
         *                      List<AniDB_Episode> aniEps = repAniEps.GetByAnimeIDAndEpisodeTypeNumber(animeID, epType, lastWatchedEpNumber);
         *                      if (aniEps.Count == 0) return;
         *
         *                      AnimeEpisodeRepository repEp = new AnimeEpisodeRepository();
         *                      AnimeEpisode ep = repEp.GetByAniDBEpisodeID(aniEps[0].EpisodeID);
         *                      if (ep == null) return;
         *
         *                      MALHelper.UpdateMAL(ep);
         *              }
         *              catch (Exception ex)
         *              {
         *                      logger.Error( ex,ex.ToString());
         *              }
         *      }*/

        public static void UpdateMALSeries(SVR_AnimeSeries ser)
        {
            try
            {
                if (string.IsNullOrEmpty(ServerSettings.MAL_Username) ||
                    string.IsNullOrEmpty(ServerSettings.MAL_Password))
                {
                    return;
                }

                // Populate MAL animelist hashtable if isNeverDecreaseWatched set
                Hashtable   animeListHashtable = new Hashtable();
                myanimelist malAnimeList       = GetMALAnimeList();
                if (ServerSettings.MAL_NeverDecreaseWatchedNums)
                //if set, check watched number before update: take some time, as user anime list must be loaded
                {
                    if (malAnimeList != null && malAnimeList.anime != null)
                    {
                        for (int i = 0; i < malAnimeList.anime.Length; i++)
                        {
                            animeListHashtable.Add(malAnimeList.anime[i].series_animedb_id, malAnimeList.anime[i]);
                        }
                    }
                }

                // look for MAL Links
                List <CrossRef_AniDB_MAL> crossRefs = ser.GetAnime().GetCrossRefMAL();
                if (crossRefs == null || crossRefs.Count == 0)
                {
                    logger.Warn("Could not find MAL link for : {0} ({1})", ser.GetAnime().GetFormattedTitle(),
                                ser.GetAnime().AnimeID);
                    return;
                }

                List <SVR_AnimeEpisode> eps = ser.GetAnimeEpisodes();

                // find the anidb user
                List <SVR_JMMUser> aniDBUsers = RepoFactory.JMMUser.GetAniDBUsers();
                if (aniDBUsers.Count == 0)
                {
                    return;
                }

                SVR_JMMUser user = aniDBUsers[0];

                int score = 0;
                if (ser.GetAnime().UserVote != null)
                {
                    score = (int)(ser.GetAnime().UserVote.VoteValue / 100);
                }

                // e.g.
                // AniDB - Code Geass R2
                // MAL Equivalent = AniDB Normal Eps 1 - 25 / Code Geass: Hangyaku no Lelouch R2 / hxxp://myanimelist.net/anime/2904/Code_Geass:_Hangyaku_no_Lelouch_R2
                // MAL Equivalent = AniDB Special Eps 1 - 9 / Code Geass: Hangyaku no Lelouch R2 Picture Drama / hxxp://myanimelist.net/anime/5163/Code_Geass:_Hangyaku_no_Lelouch_R2_Picture_Drama
                // MAL Equivalent = AniDB Special Eps 9 - 18 / Code Geass: Hangyaku no Lelouch R2: Flash Specials / hxxp://myanimelist.net/anime/9591/Code_Geass:_Hangyaku_no_Lelouch_R2:_Flash_Specials
                // MAL Equivalent = AniDB Special Eps 20 / Code Geass: Hangyaku no Lelouch - Kiseki no Birthday Picture Drama / hxxp://myanimelist.net/anime/8728/Code_Geass:_Hangyaku_no_Lelouch_-_Kiseki_no_Birthday_Picture_Drama

                foreach (CrossRef_AniDB_MAL xref in crossRefs)
                {
                    // look for the right MAL id
                    int malID        = -1;
                    int epNumber     = -1;
                    int totalEpCount = -1;

                    List <string> fanSubGroups = new List <string>();

                    // for each cross ref (which is a series on MAL) we need to update the data
                    // so find all the episodes which apply to this cross ref
                    int lastWatchedEpNumber = 0;
                    int downloadedEps       = 0;

                    foreach (SVR_AnimeEpisode ep in eps)
                    {
                        int epNum = ep.AniDB_Episode.EpisodeNumber;
                        if (xref.StartEpisodeType == (int)ep.EpisodeTypeEnum && epNum >= xref.StartEpisodeNumber &&
                            epNum <= GetUpperEpisodeLimit(crossRefs, xref))
                        {
                            malID    = xref.MALID;
                            epNumber = epNum - xref.StartEpisodeNumber + 1;

                            // find the total episode count
                            if (totalEpCount < 0)
                            {
                                if (ep.EpisodeTypeEnum == enEpisodeType.Episode)
                                {
                                    totalEpCount = ser.GetAnime().EpisodeCountNormal;
                                }
                                if (ep.EpisodeTypeEnum == enEpisodeType.Special)
                                {
                                    totalEpCount = ser.GetAnime().EpisodeCountSpecial;
                                }
                                totalEpCount = totalEpCount - xref.StartEpisodeNumber + 1;
                            }

                            // any episodes here belong to the MAL series
                            // find the latest watched episod enumber
                            SVR_AnimeEpisode_User usrRecord = ep.GetUserRecord(user.JMMUserID);
                            if (usrRecord != null && usrRecord.WatchedDate.HasValue && epNum > lastWatchedEpNumber)
                            {
                                lastWatchedEpNumber = epNum;
                            }

                            List <CL_VideoDetailed> contracts = ep.GetVideoDetailedContracts(user.JMMUserID);

                            // find the latest episode number in the collection
                            if (contracts.Count > 0)
                            {
                                downloadedEps++;
                            }

                            foreach (CL_VideoDetailed contract in contracts)
                            {
                                if (!string.IsNullOrEmpty(contract.AniDB_Anime_GroupNameShort) &&
                                    !fanSubGroups.Contains(contract.AniDB_Anime_GroupNameShort))
                                {
                                    fanSubGroups.Add(contract.AniDB_Anime_GroupNameShort);
                                }
                            }
                        }
                    }

                    string fanSubs = "";
                    foreach (string fgrp in fanSubGroups)
                    {
                        if (!string.IsNullOrEmpty(fanSubs))
                        {
                            fanSubs += ",";
                        }
                        fanSubs += fgrp;
                    }

                    // determine status
                    int status = 1; //watching
                    if (animeListHashtable.ContainsKey(malID))
                    {
                        myanimelistAnime animeInList = (myanimelistAnime)animeListHashtable[malID];
                        status = animeInList.my_status;
                    }

                    // over-ride is user has watched an episode
                    // don't override on hold (3) or dropped (4) but do override plan to watch (6)
                    if (status == 6 && lastWatchedEpNumber > 0)
                    {
                        status = 1;                                         //watching
                    }
                    if (lastWatchedEpNumber == totalEpCount)
                    {
                        status = 2;                                      //completed
                    }
                    if (lastWatchedEpNumber > totalEpCount)
                    {
                        logger.Error("updateMAL, episode number > matching anime episode total : {0} ({1}) / {2}",
                                     ser.GetAnime().GetFormattedTitle(), ser.GetAnime().AnimeID, epNumber);
                        continue;
                    }

                    if (malID <= 0 || totalEpCount <= 0)
                    {
                        logger.Warn("Could not find MAL link for : {0} ({1})", ser.GetAnime().GetFormattedTitle(),
                                    ser.GetAnime().AnimeID);
                        continue;
                    }

                    string confirmationMessage = "";
                    if (animeListHashtable.ContainsKey(malID))
                    {
                        ModifyAnime(malID, lastWatchedEpNumber, status, score, downloadedEps, fanSubs);
                        confirmationMessage = string.Format(
                            "MAL successfully updated (MAL MODIFY), mal id: {0}, ep: {1}, score: {2}", malID,
                            lastWatchedEpNumber, score);
                    }
                    else
                    {
                        AddAnime(malID, lastWatchedEpNumber, status, score, downloadedEps, fanSubs);
                        confirmationMessage = string.Format(
                            "MAL successfully updated (MAL ADD), mal id: {0}, ep: {1}, score: {2}", malID,
                            lastWatchedEpNumber, score);
                    }
                    logger.Trace(confirmationMessage);
                }
            }
            catch (Exception ex)
            {
                logger.Error(ex, ex.ToString());
            }
        }
Example #4
0
        public override void ProcessCommand()
        {
            logger.Info("Processing CommandRequest_MALDownloadStatusFromMAL");

            try
            {
                if (string.IsNullOrEmpty(ServerSettings.MAL_Username) ||
                    string.IsNullOrEmpty(ServerSettings.MAL_Password))
                {
                    return;
                }

                // find the latest eps to update

                myanimelist mal = MALHelper.GetMALAnimeList();
                if (mal == null || mal.anime == null)
                {
                    return;
                }


                // find the anidb user
                List <SVR_JMMUser> aniDBUsers = RepoFactory.JMMUser.GetAniDBUsers();
                if (aniDBUsers.Count == 0)
                {
                    return;
                }

                SVR_JMMUser user = aniDBUsers[0];


                foreach (myanimelistAnime malAnime in mal.anime)
                {
                    // look up the anime
                    CrossRef_AniDB_MAL xref = RepoFactory.CrossRef_AniDB_MAL.GetByMALID(malAnime.series_animedb_id);
                    if (xref == null)
                    {
                        continue;
                    }

                    if (malAnime.series_animedb_id == 8107 || malAnime.series_animedb_id == 10737)
                    {
                        Console.Write("");
                    }

                    // check if this anime has any other links
                    List <CrossRef_AniDB_MAL> allXrefs = RepoFactory.CrossRef_AniDB_MAL.GetByAnimeID(xref.AnimeID);
                    if (allXrefs.Count == 0)
                    {
                        continue;
                    }

                    // find the range of watched episodes that this applies to
                    int startEpNumber = xref.StartEpisodeNumber;
                    int endEpNumber   = GetUpperEpisodeLimit(allXrefs, xref);

                    List <AniDB_Episode> aniEps = RepoFactory.AniDB_Episode.GetByAnimeID(xref.AnimeID);
                    foreach (AniDB_Episode aniep in aniEps)
                    {
                        if (aniep.EpisodeType != xref.StartEpisodeType)
                        {
                            continue;
                        }

                        SVR_AnimeEpisode ep = RepoFactory.AnimeEpisode.GetByAniDBEpisodeID(aniep.EpisodeID);
                        if (ep == null)
                        {
                            continue;
                        }

                        int adjustedWatchedEps = malAnime.my_watched_episodes + xref.StartEpisodeNumber - 1;
                        int epNum = aniep.EpisodeNumber;

                        if (epNum < startEpNumber || epNum > endEpNumber)
                        {
                            continue;
                        }

                        SVR_AnimeEpisode_User usrRec = ep.GetUserRecord(user.JMMUserID);

                        if (epNum <= adjustedWatchedEps)
                        {
                            // update if the user doesn't have a record (means not watched)
                            // or it is currently un-watched
                            bool update = false;
                            if (usrRec == null)
                            {
                                update = true;
                            }
                            else if (!usrRec.WatchedDate.HasValue)
                            {
                                update = true;
                            }

                            if (update)
                            {
                                ep.ToggleWatchedStatus(true, true, DateTime.Now, user.JMMUserID, false);
                            }
                        }
                        else
                        {
                            if (usrRec != null && usrRec.WatchedDate.HasValue)
                            {
                                ep.ToggleWatchedStatus(false, true, DateTime.Now, user.JMMUserID, false);
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error processing CommandRequest_MALDownloadStatusFromMAL: {0}", ex);
            }
        }
        public override void ProcessCommand()
        {
            logger.Info("Processing CommandRequest_AddFileToMyList: {0}", Hash);


            try
            {
                vid = RepoFactory.VideoLocal.GetByHash(this.Hash);
                List <SVR_AnimeEpisode> animeEpisodes = new List <SVR_AnimeEpisode>();
                if (vid != null)
                {
                    animeEpisodes = vid.GetAnimeEpisodes();
                }

                if (vid != null)
                {
                    // when adding a file via the API, newWatchedStatus will return with current watched status on AniDB
                    // if the file is already on the user's list

                    bool isManualLink = false;
                    List <CrossRef_File_Episode> xrefs = vid.EpisodeCrossRefs;
                    if (xrefs.Count > 0)
                    {
                        isManualLink = xrefs[0].CrossRefSource != (int)CrossRefSource.AniDB;
                    }

                    // mark the video file as watched
                    DateTime?watchedDate      = null;
                    bool     newWatchedStatus = false;

                    if (isManualLink)
                    {
                        newWatchedStatus = ShokoService.AnidbProcessor.AddFileToMyList(xrefs[0].AnimeID,
                                                                                       xrefs[0].GetEpisode().EpisodeNumber,
                                                                                       ref watchedDate);
                    }
                    else
                    {
                        newWatchedStatus = ShokoService.AnidbProcessor.AddFileToMyList(vid, ref watchedDate);
                    }

                    // do for all AniDB users
                    List <SVR_JMMUser> aniDBUsers = RepoFactory.JMMUser.GetAniDBUsers();


                    if (aniDBUsers.Count > 0)
                    {
                        SVR_JMMUser juser = aniDBUsers[0];
                        vid.ToggleWatchedStatus(newWatchedStatus, false, watchedDate, false, false, juser.JMMUserID,
                                                false, true);
                        logger.Info("Adding file to list: {0} - {1}", vid.ToString(), watchedDate);

                        // if the the episode is watched we may want to set the file to watched as well
                        if (ServerSettings.Import_UseExistingFileWatchedStatus && !newWatchedStatus)
                        {
                            if (animeEpisodes.Count > 0)
                            {
                                SVR_AnimeEpisode      ep     = animeEpisodes[0];
                                SVR_AnimeEpisode_User epUser = null;

                                foreach (SVR_JMMUser tempuser in aniDBUsers)
                                {
                                    // only find the first user who watched this
                                    if (epUser == null)
                                    {
                                        epUser = ep.GetUserRecord(tempuser.JMMUserID);
                                    }
                                }

                                if (epUser != null)
                                {
                                    logger.Info(
                                        "Setting file as watched, because episode was already watched: {0} - user: {1}",
                                        vid.ToString(),
                                        juser.Username);
                                    vid.ToggleWatchedStatus(true, true, epUser.WatchedDate, false, false,
                                                            epUser.JMMUserID, false, true);
                                }
                            }
                        }
                    }

                    SVR_AnimeSeries ser = animeEpisodes[0].GetAnimeSeries();
                    // all the eps should belong to the same anime
                    ser.QueueUpdateStats();
                    //StatsCache.Instance.UpdateUsingSeries(ser.AnimeSeriesID);

                    // lets also try adding to the users trakt collecion
                    if (ser != null && ServerSettings.Trakt_IsEnabled &&
                        !string.IsNullOrEmpty(ServerSettings.Trakt_AuthToken))
                    {
                        foreach (SVR_AnimeEpisode aep in animeEpisodes)
                        {
                            CommandRequest_TraktCollectionEpisode cmdSyncTrakt =
                                new CommandRequest_TraktCollectionEpisode
                                (
                                    aep.AnimeEpisodeID, TraktSyncAction.Add);
                            cmdSyncTrakt.Save();
                        }
                    }

                    // sync the series on MAL
                    if (ser != null && !string.IsNullOrEmpty(ServerSettings.MAL_Username) &&
                        !string.IsNullOrEmpty(ServerSettings.MAL_Password))
                    {
                        CommandRequest_MALUpdatedWatchedStatus cmdMAL =
                            new CommandRequest_MALUpdatedWatchedStatus(ser.AniDB_ID);
                        cmdMAL.Save();
                    }
                }
            }
            catch (Exception ex)
            {
                logger.Error("Error processing CommandRequest_AddFileToMyList: {0} - {1}", Hash, ex.ToString());
                return;
            }
        }