public override void ProcessCommand()
		{
			
			try
			{
				VideoLocalRepository repVids = new VideoLocalRepository();
				VideoLocal vlocal = repVids.GetByID(VideoLocalID);
				if (vlocal == null) return;

				XMLService.Send_FileHash(vlocal);
			}
			catch (Exception ex)
			{
				logger.Error("Error processing CommandRequest_WebCacheSendFileHash: {0} - {1}", VideoLocalID, ex.ToString());
				return;
			}
		}
Ejemplo n.º 2
0
		public override void ProcessCommand()
		{
			logger.Info("Processing File: {0}", VideoLocalID);

			
			try
			{
				VideoLocalRepository repVids = new VideoLocalRepository();
				vlocal = repVids.GetByID(VideoLocalID);
				if (vlocal == null) return;

				//now that we have all the has info, we can get the AniDB Info
				ProcessFile_AniDB(vlocal);
			}
			catch (Exception ex)
			{
				logger.Error("Error processing CommandRequest_ProcessFile: {0} - {1}", VideoLocalID, ex.ToString());
				return;
			}

			// TODO update stats for group and series

			// TODO check for TvDB
		}
Ejemplo n.º 3
0
        public string SetVariationStatusOnFile(int videoLocalID, bool isVariation)
        {
            try
            {
                VideoLocalRepository repVids = new VideoLocalRepository();
                VideoLocal vid = repVids.GetByID(videoLocalID);
                if (vid == null)
                    return "Could not find video record";

                vid.IsVariation = isVariation ? 1 : 0;
                repVids.Save(vid);

                return "";

            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
                return ex.Message;
            }
        }
Ejemplo n.º 4
0
        public void DeleteFFDPreset(int videoLocalID)
        {
            try
            {
                VideoLocalRepository repVids = new VideoLocalRepository();
                FileFfdshowPresetRepository repFFD = new FileFfdshowPresetRepository();

                VideoLocal vid = repVids.GetByID(videoLocalID);
                if (vid == null) return;

                FileFfdshowPreset ffd = repFFD.GetByHashAndSize(vid.Hash, vid.FileSize);
                if (ffd == null) return;

                repFFD.Delete(ffd.FileFfdshowPresetID);
            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
            }
        }
Ejemplo n.º 5
0
        public Contract_VideoLocalRenamed RenameFilePreview(int videoLocalID, string renameRules)
        {
            Contract_VideoLocalRenamed ret = new Contract_VideoLocalRenamed();
            ret.VideoLocalID = videoLocalID;
            ret.Success = true;

            try
            {
                VideoLocalRepository repVids = new VideoLocalRepository();
                VideoLocal vid = repVids.GetByID(videoLocalID);
                if (vid == null)
                {
                    ret.VideoLocal = null;
                    ret.NewFileName = string.Format("ERROR: Could not find file record");
                    ret.Success = false;
                }
                else
                {
                    if (videoLocalID == 726)
                        Debug.Write("test");

                    ret.VideoLocal = null;
                    ret.NewFileName = RenameFileHelper.GetNewFileName(vid, renameRules);
                    if (string.IsNullOrEmpty(ret.NewFileName)) ret.Success = false;
                }
            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
                ret.VideoLocal = null;
                ret.NewFileName = string.Format("ERROR: {0}", ex.Message);
                ret.Success = false;
            }
            return ret;
        }
Ejemplo n.º 6
0
        public Contract_VideoLocalRenamed RenameFile(int videoLocalID, string renameRules)
        {
            Contract_VideoLocalRenamed ret = new Contract_VideoLocalRenamed();
            ret.VideoLocalID = videoLocalID;
            ret.Success = true;
            try
            {
                VideoLocalRepository repVids = new VideoLocalRepository();
                VideoLocal vid = repVids.GetByID(videoLocalID);
                if (vid == null)
                {
                    ret.VideoLocal = null;
                    ret.NewFileName = string.Format("ERROR: Could not find file record");
                    ret.Success = false;
                }
                else
                {
                    ret.VideoLocal = null;
                    ret.NewFileName = RenameFileHelper.GetNewFileName(vid, renameRules);

                    if (!string.IsNullOrEmpty(ret.NewFileName))
                    {
                        // check if the file exists
                        string fullFileName = vid.FullServerPath;
                        if (!File.Exists(fullFileName))
                        {
                            ret.NewFileName = "Error could not find the original file";
                            ret.Success = false;
                            return ret;
                        }

                        // actually rename the file
                        string path = Path.GetDirectoryName(fullFileName);
                        string newFullName = Path.Combine(path, ret.NewFileName);

                        try
                        {
                            logger.Info(string.Format("Renaming file From ({0}) to ({1})....", fullFileName, newFullName));

                            if (fullFileName.Equals(newFullName, StringComparison.InvariantCultureIgnoreCase))
                            {
                                logger.Info(string.Format("Renaming file SKIPPED, no change From ({0}) to ({1})", fullFileName, newFullName));
                                ret.NewFileName = newFullName;
                            }
                            else
                            {
                                File.Move(fullFileName, newFullName);
                                logger.Info(string.Format("Renaming file SUCCESS From ({0}) to ({1})", fullFileName, newFullName));
                                ret.NewFileName = newFullName;

                                string newPartialPath = "";
                                int folderID = vid.ImportFolderID;
                                ImportFolderRepository repFolders = new ImportFolderRepository();

                                DataAccessHelper.GetShareAndPath(newFullName, repFolders.GetAll(), ref folderID, ref newPartialPath);

                                vid.FilePath = newPartialPath;
                                repVids.Save(vid);
                            }
                        }
                        catch (Exception ex)
                        {
                            logger.Info(string.Format("Renaming file FAIL From ({0}) to ({1}) - {2}", fullFileName, newFullName, ex.Message));
                            logger.ErrorException(ex.ToString(), ex);
                            ret.Success = false;
                            ret.NewFileName = ex.Message;
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
                ret.VideoLocal = null;
                ret.NewFileName = string.Format("ERROR: {0}", ex.Message);
                ret.Success = false;
            }
            return ret;
        }
Ejemplo n.º 7
0
 private System.IO.Stream InternalGetFile(int userid, string Id)
 {
     int id;
     if (!int.TryParse(Id, out id))
         return new MemoryStream();
     KodiObject ret =new KodiObject(KodiHelper.NewMediaContainer("Unsort", true));
     if (!ret.Init())
         return new MemoryStream();
     List<Video> dirs= new List<Video>();
     Video v = new Video();
     dirs.Add(v);
     VideoLocalRepository repVids = new VideoLocalRepository();
     VideoLocal vi = repVids.GetByID(id);
     if (vi == null)
         return new MemoryStream();
     KodiHelper.PopulateVideo(v,vi,JMMType.File,userid);
     ret.Childrens = dirs;
     ret.MediaContainer.Art = v.Art;
     return ret.GetStream();
 }
Ejemplo n.º 8
0
        /// <summary>
        /// Delets the VideoLocal record and the associated physical file
        /// </summary>
        /// <param name="videoLocalID"></param>
        /// <returns></returns>
        public string DeleteVideoLocalAndFile(int videoLocalID)
        {
            try
            {
                VideoLocalRepository repVids = new VideoLocalRepository();
                VideoLocal vid = repVids.GetByID(videoLocalID);
                if (vid == null) return "Database entry does not exist";

                logger.Info("Deleting video local record and file: {0}", vid.FullServerPath);
                if (File.Exists(vid.FullServerPath))
                {
                    try
                    {
                        File.Delete(vid.FullServerPath);
                    }
                    catch { }
                }

                AnimeSeries ser = null;
                List<AnimeEpisode> animeEpisodes = vid.GetAnimeEpisodes();
                if (animeEpisodes.Count > 0)
                    ser = animeEpisodes[0].GetAnimeSeries();

                CommandRequest_DeleteFileFromMyList cmdDel = new CommandRequest_DeleteFileFromMyList(vid.Hash, vid.FileSize);
                cmdDel.Save();

                repVids.Delete(videoLocalID);

                if (ser != null)
                {
                    ser.QueueUpdateStats();
                    //StatsCache.Instance.UpdateUsingSeries(ser.AnimeSeriesID);
                }

                // For deletion of files from Trakt, we will rely on the Daily sync

                return "";
            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
                return ex.Message;
            }
        }
Ejemplo n.º 9
0
        public Contract_FileFfdshowPreset GetFFDPreset(int videoLocalID)
        {
            VideoLocalRepository repVids = new VideoLocalRepository();
            FileFfdshowPresetRepository repFFD = new FileFfdshowPresetRepository();

            try
            {
                VideoLocal vid = repVids.GetByID(videoLocalID);
                if (vid == null) return null;

                FileFfdshowPreset ffd = repFFD.GetByHashAndSize(vid.Hash, vid.FileSize);
                if (ffd == null) return null;

                return ffd.ToContract();
            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
            }
            return null;
        }
Ejemplo n.º 10
0
        public List<Contract_AnimeEpisode> GetEpisodesForFile(int videoLocalID, int userID)
        {
            List<Contract_AnimeEpisode> contracts = new List<Contract_AnimeEpisode>();
            try
            {

                VideoLocalRepository repVids = new VideoLocalRepository();
                VideoLocal vid = repVids.GetByID(videoLocalID);
                if (vid == null)
                    return contracts;

                foreach (AnimeEpisode ep in vid.GetAnimeEpisodes())
                {
                    contracts.Add(ep.ToContract(userID));
                }

                return contracts;
            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
                return contracts;
            }
        }
Ejemplo n.º 11
0
        public string AssociateSingleFileWithMultipleEpisodes(int videoLocalID, int animeSeriesID, int startEpNum, int endEpNum)
        {
            try
            {
                VideoLocalRepository repVids = new VideoLocalRepository();
                VideoLocal vid = repVids.GetByID(videoLocalID);
                if (vid == null)
                    return "Could not find video record";

                AnimeEpisodeRepository repEps = new AnimeEpisodeRepository();
                AnimeSeriesRepository repSeries = new AnimeSeriesRepository();
                AniDB_EpisodeRepository repAniEps = new AniDB_EpisodeRepository();
                CrossRef_File_EpisodeRepository repXRefs = new CrossRef_File_EpisodeRepository();

                AnimeSeries ser = repSeries.GetByID(animeSeriesID);
                if (ser == null)
                    return "Could not find anime series record";

                for (int i = startEpNum; i <= endEpNum; i++)
                {
                    List<AniDB_Episode> anieps = repAniEps.GetByAnimeIDAndEpisodeNumber(ser.AniDB_ID, i);
                    if (anieps.Count == 0)
                        return "Could not find the AniDB episode record";

                    AniDB_Episode aniep = anieps[0];

                    List<AnimeEpisode> eps = repEps.GetByAniEpisodeIDAndSeriesID(aniep.EpisodeID, ser.AnimeSeriesID);
                    if (eps.Count == 0)
                        return "Could not find episode record";

                    AnimeEpisode ep = eps[0];

                    CrossRef_File_Episode xref = new CrossRef_File_Episode();
                    xref.PopulateManually(vid, ep);
                    repXRefs.Save(xref);

                    CommandRequest_WebCacheSendXRefFileEpisode cr = new CommandRequest_WebCacheSendXRefFileEpisode(xref.CrossRef_File_EpisodeID);
                    cr.Save();
                }

                vid.RenameIfRequired();
                vid.MoveFileIfRequired();

                ser.QueueUpdateStats();

                // update epidsode added stats
                ser.EpisodeAddedDate = DateTime.Now;
                repSeries.Save(ser);

                AnimeGroupRepository repGroups = new AnimeGroupRepository();
                foreach (AnimeGroup grp in ser.AllGroupsAbove)
                {
                    grp.EpisodeAddedDate = DateTime.Now;
                    repGroups.Save(grp);
                }

                return "";

            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
            }

            return "";
        }
Ejemplo n.º 12
0
        public string AssociateSingleFile(int videoLocalID, int animeEpisodeID)
        {
            try
            {
                VideoLocalRepository repVids = new VideoLocalRepository();
                VideoLocal vid = repVids.GetByID(videoLocalID);
                if (vid == null)
                    return "Could not find video record";

                AnimeEpisodeRepository repEps = new AnimeEpisodeRepository();
                AnimeEpisode ep = repEps.GetByID(animeEpisodeID);
                if (ep == null)
                    return "Could not find episode record";

                CrossRef_File_EpisodeRepository repXRefs = new CrossRef_File_EpisodeRepository();
                CrossRef_File_Episode xref = new CrossRef_File_Episode();
                try
                {
                    xref.PopulateManually(vid, ep);
                }
                catch (Exception ex)
                {
                    string msg = string.Format("Error populating XREF: {0}", vid.ToStringDetailed());
                    throw;
                }
                repXRefs.Save(xref);

                vid.RenameIfRequired();
                vid.MoveFileIfRequired();

                CommandRequest_WebCacheSendXRefFileEpisode cr = new CommandRequest_WebCacheSendXRefFileEpisode(xref.CrossRef_File_EpisodeID);
                cr.Save();

                AnimeSeries ser = ep.GetAnimeSeries();
                ser.QueueUpdateStats();

                // update epidsode added stats
                AnimeSeriesRepository repSeries = new AnimeSeriesRepository();
                ser.EpisodeAddedDate = DateTime.Now;
                repSeries.Save(ser);

                AnimeGroupRepository repGroups = new AnimeGroupRepository();
                foreach (AnimeGroup grp in ser.AllGroupsAbove)
                {
                    grp.EpisodeAddedDate = DateTime.Now;
                    repGroups.Save(grp);
                }

                CommandRequest_AddFileToMyList cmdAddFile = new CommandRequest_AddFileToMyList(vid.Hash);
                cmdAddFile.Save();

                return "";

            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
            }

            return "";
        }
Ejemplo n.º 13
0
        public string AssociateMultipleFiles(List<int> videoLocalIDs, int animeSeriesID, int startingEpisodeNumber, bool singleEpisode)
        {
            try
            {
                CrossRef_File_EpisodeRepository repXRefs = new CrossRef_File_EpisodeRepository();
                AnimeSeriesRepository repSeries = new AnimeSeriesRepository();
                VideoLocalRepository repVids = new VideoLocalRepository();
                AniDB_EpisodeRepository repAniEps = new AniDB_EpisodeRepository();
                AnimeEpisodeRepository repEps = new AnimeEpisodeRepository();

                AnimeSeries ser = repSeries.GetByID(animeSeriesID);
                if (ser == null)
                    return "Could not find anime series record";

                int epNumber = startingEpisodeNumber;
                int count = 1;

                foreach (int videoLocalID in videoLocalIDs)
                {
                    VideoLocal vid = repVids.GetByID(videoLocalID);
                    if (vid == null)
                        return "Could not find video local record";

                    List<AniDB_Episode> anieps = repAniEps.GetByAnimeIDAndEpisodeNumber(ser.AniDB_ID, epNumber);
                    if (anieps.Count == 0)
                        return "Could not find the AniDB episode record";

                    AniDB_Episode aniep = anieps[0];

                    List<AnimeEpisode> eps = repEps.GetByAniEpisodeIDAndSeriesID(aniep.EpisodeID, ser.AnimeSeriesID);
                    if (eps.Count == 0)
                        return "Could not find episode record";

                    AnimeEpisode ep = eps[0];

                    CrossRef_File_Episode xref = new CrossRef_File_Episode();
                    xref.PopulateManually(vid, ep);

                    // TODO do this properly
                    if (singleEpisode)
                    {
                        xref.EpisodeOrder = count;
                        if (videoLocalIDs.Count > 5)
                            xref.Percentage = 100;
                        else
                            xref.Percentage = GetEpisodePercentages(videoLocalIDs.Count)[count - 1];
                    }

                    repXRefs.Save(xref);

                    vid.RenameIfRequired();
                    vid.MoveFileIfRequired();

                    CommandRequest_WebCacheSendXRefFileEpisode cr = new CommandRequest_WebCacheSendXRefFileEpisode(xref.CrossRef_File_EpisodeID);
                    cr.Save();

                    count++;
                    if (!singleEpisode) epNumber++;
                }

                ser.QueueUpdateStats();

                // update epidsode added stats
                ser.EpisodeAddedDate = DateTime.Now;
                repSeries.Save(ser);

                AnimeGroupRepository repGroups = new AnimeGroupRepository();
                foreach (AnimeGroup grp in ser.AllGroupsAbove)
                {
                    grp.EpisodeAddedDate = DateTime.Now;
                    repGroups.Save(grp);
                }

            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
            }

            return "";
        }
Ejemplo n.º 14
0
        public override void ProcessCommand()
        {
            logger.Info("Get AniDB file info: {0}", VideoLocalID);

            try
            {
                AniDB_FileRepository repAniFile = new AniDB_FileRepository();
                VideoLocalRepository repVids = new VideoLocalRepository();
                vlocal = repVids.GetByID(VideoLocalID);
                if (vlocal == null) return;

                AniDB_File aniFile = repAniFile.GetByHashAndFileSize(vlocal.Hash, vlocal.FileSize);

                /*// get anidb file info from web cache
                if (aniFile == null && ServerSettings.WebCache_AniDB_File_Get)
                {
                    AniDB_FileRequest fr = XMLService.Get_AniDB_File(vlocal.Hash, vlocal.FileSize);
                    if (fr != null)
                    {
                        aniFile = new AniDB_File();
                        aniFile.Populate(fr);

                        //overwrite with local file name
                        string localFileName = Path.GetFileName(vlocal.FilePath);
                        aniFile.FileName = localFileName;

                        repAniFile.Save(aniFile, false);
                        aniFile.CreateLanguages();
                        aniFile.CreateCrossEpisodes(localFileName);

                        StatsCache.Instance.UpdateUsingAniDBFile(vlocal.Hash);
                    }
                }*/

                Raw_AniDB_File fileInfo = null;
                if (aniFile == null || ForceAniDB)
                    fileInfo = JMMService.AnidbProcessor.GetFileInfo(vlocal);

                if (fileInfo != null)
                {
                    // save to the database
                    if (aniFile == null)
                        aniFile = new AniDB_File();

                    aniFile.Populate(fileInfo);

                    //overwrite with local file name
                    string localFileName = Path.GetFileName(vlocal.FilePath);
                    aniFile.FileName = localFileName;

                    repAniFile.Save(aniFile, false);
                    aniFile.CreateLanguages();
                    aniFile.CreateCrossEpisodes(localFileName);

                    if (!string.IsNullOrEmpty(fileInfo.OtherEpisodesRAW))
                    {
                        string[] epIDs = fileInfo.OtherEpisodesRAW.Split(',');
                        foreach (string epid in epIDs)
                        {
                            int id = 0;
                            if (int.TryParse(epid, out id))
                            {
                                CommandRequest_GetEpisode cmdEp = new CommandRequest_GetEpisode(id);
                                cmdEp.Save();
                            }
                        }
                    }

                    StatsCache.Instance.UpdateUsingAniDBFile(vlocal.Hash);
                }

            }
            catch (Exception ex)
            {
                logger.Error("Error processing CommandRequest_GetFile: {0} - {1}", VideoLocalID, ex.ToString());
                return;
            }
        }
Ejemplo n.º 15
0
        public string ToggleWatchedStatusOnVideo(int videoLocalID, bool watchedStatus, int userID)
        {
            try
            {
                VideoLocalRepository repVids = new VideoLocalRepository();
                VideoLocal vid = repVids.GetByID(videoLocalID);
                if (vid == null)
                    return "Could not find video local record";

                vid.ToggleWatchedStatus(watchedStatus, true, DateTime.Now, true, true, userID, true, true);

                return "";
            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
                return ex.Message;
            }
        }
Ejemplo n.º 16
0
        public Contract_VideoDetailed GetVideoDetailed(int videoLocalID, int userID)
        {
            try
            {
                VideoLocalRepository repVids = new VideoLocalRepository();
                VideoLocal vid = repVids.GetByID(videoLocalID);
                if (vid == null)
                    return null;

                return vid.ToContractDetailed(userID);
            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
                return null;
            }
        }
Ejemplo n.º 17
0
        public string UpdateFileData(int videoLocalID)
        {
            try
            {

                VideoLocalRepository repVids = new VideoLocalRepository();
                VideoLocal vid = repVids.GetByID(videoLocalID);
                if (vid == null) return "File could not be found";

                CommandRequest_GetFile cmd = new CommandRequest_GetFile(vid.VideoLocalID, true);
                cmd.Save();

            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
                return ex.Message;
            }
            return "";
        }
Ejemplo n.º 18
0
        public void RehashFile(int videoLocalID)
        {
            VideoLocalRepository repVidLocals = new VideoLocalRepository();
            VideoLocal vl = repVidLocals.GetByID(videoLocalID);

            if (vl != null)
            {
                CommandRequest_HashFile cr_hashfile = new CommandRequest_HashFile(vl.FullServerPath, true);
                cr_hashfile.Save();
            }
        }
Ejemplo n.º 19
0
        public override void ProcessCommand()
        {
            logger.Info("Reading Media Info for File: {0}", VideoLocalID);

            try
            {
                VideoLocalRepository repVids = new VideoLocalRepository();
                VideoLocal vlocal = repVids.GetByID(VideoLocalID);
                if (vlocal == null)
                {
                    logger.Error("Cound not find Video: {0}", VideoLocalID);
                    return;
                }

                if (!File.Exists(vlocal.FullServerPath))
                {
                    logger.Error("Cound not find physical file: {0}", vlocal.FullServerPath);
                    return;
                }

                int nshareID = -1;

                VideoInfoRepository repVidInfo = new VideoInfoRepository();
                VideoInfo vinfo = repVidInfo.GetByHash(vlocal.Hash);

                ImportFolderRepository repNS = new ImportFolderRepository();
                List<ImportFolder> shares = repNS.GetAll();

                string fileName = vlocal.FullServerPath;
                string filePath = "";
                DataAccessHelper.GetShareAndPath(fileName, shares, ref nshareID, ref filePath);

                FileInfo fi = new FileInfo(fileName);

                if (vinfo == null)
                {
                    vinfo = new VideoInfo();
                    vinfo.Hash = vlocal.Hash;

                    vinfo.Duration = 0;
                    vinfo.FileSize = fi.Length;
                    vinfo.DateTimeUpdated = DateTime.Now;
                    vinfo.FileName = filePath;

                    vinfo.AudioBitrate = "";
                    vinfo.AudioCodec = "";
                    vinfo.VideoBitrate = "";
                    vinfo.VideoBitDepth = "";
                    vinfo.VideoCodec = "";
                    vinfo.VideoFrameRate = "";
                    vinfo.VideoResolution = "";
                }

                logger.Trace("Getting media info for: {0}", fileName);
                MediaInfoResult mInfo = FileHashHelper.GetMediaInfo(fileName, true);

                vinfo.AudioBitrate = string.IsNullOrEmpty(mInfo.AudioBitrate) ? "" : mInfo.AudioBitrate;
                vinfo.AudioCodec = string.IsNullOrEmpty(mInfo.AudioCodec) ? "" : mInfo.AudioCodec;

                vinfo.DateTimeUpdated = vlocal.DateTimeUpdated;
                vinfo.Duration = mInfo.Duration;
                vinfo.FileName = filePath;
                vinfo.FileSize = fi.Length;

                vinfo.VideoBitrate = string.IsNullOrEmpty(mInfo.VideoBitrate) ? "" : mInfo.VideoBitrate;
                vinfo.VideoBitDepth = string.IsNullOrEmpty(mInfo.VideoBitDepth) ? "" : mInfo.VideoBitDepth;
                vinfo.VideoCodec = string.IsNullOrEmpty(mInfo.VideoCodec) ? "" : mInfo.VideoCodec;
                vinfo.VideoFrameRate = string.IsNullOrEmpty(mInfo.VideoFrameRate) ? "" : mInfo.VideoFrameRate;
                vinfo.VideoResolution = string.IsNullOrEmpty(mInfo.VideoResolution) ? "" : mInfo.VideoResolution;
                vinfo.FullInfo = string.IsNullOrEmpty(mInfo.FullInfo) ? "" : mInfo.FullInfo;
                repVidInfo.Save(vinfo);
            }
            catch (Exception ex)
            {
                logger.Error("Error processing CommandRequest_ReadMediaInfo: {0} - {1}", VideoLocalID, ex.ToString());
                return;
            }
        }
Ejemplo n.º 20
0
        public string RemoveAssociationOnFile(int videoLocalID, int aniDBEpisodeID)
        {
            try
            {
                VideoLocalRepository repVids = new VideoLocalRepository();
                CrossRef_File_EpisodeRepository repXRefs = new CrossRef_File_EpisodeRepository();

                VideoLocal vid = repVids.GetByID(videoLocalID);
                if (vid == null)
                    return "Could not find video record";

                int? animeSeriesID = null;
                foreach (AnimeEpisode ep in vid.GetAnimeEpisodes())
                {
                    if (ep.AniDB_EpisodeID != aniDBEpisodeID) continue;

                    animeSeriesID = ep.AnimeSeriesID;
                    CrossRef_File_Episode xref = repXRefs.GetByHashAndEpisodeID(vid.Hash, ep.AniDB_EpisodeID);
                    if (xref != null)
                    {
                        if (xref.CrossRefSource == (int)CrossRefSource.AniDB)
                            return "Cannot remove associations created from AniDB data";

                        // delete cross ref from web cache
                        CommandRequest_WebCacheDeleteXRefFileEpisode cr = new CommandRequest_WebCacheDeleteXRefFileEpisode(vid.Hash, ep.AniDB_EpisodeID);
                        cr.Save();

                        repXRefs.Delete(xref.CrossRef_File_EpisodeID);
                    }
                }

                if (animeSeriesID.HasValue)
                {
                    AnimeSeriesRepository repSeries = new AnimeSeriesRepository();
                    AnimeSeries ser = repSeries.GetByID(animeSeriesID.Value);
                    if (ser != null)
                        ser.QueueUpdateStats();
                }

                return "";

            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
                return ex.Message;
            }
        }
Ejemplo n.º 21
0
        private void Process(System.Net.HttpListenerContext obj)
        {
            Stream org = null;

            try
            {

                bool fname = false;
                string[] dta = obj.Request.RawUrl.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
                if (dta.Length < 3)
                    return;
                string cmd = dta[0].ToLower();
                string user = dta[1];
                string arg = dta[2];
                string fullname;
                int userid = 0;
                int.TryParse(user, out userid);
                VideoLocal loc=null;
                if (cmd == "videolocal")
                {
                    int sid = 0;
                    int.TryParse(arg, out sid);
                    if (sid == 0)
                    {
                        obj.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                        obj.Response.StatusDescription = "Stream Id missing.";
                        return;
                    }
                    VideoLocalRepository rep = new VideoLocalRepository();
                    loc = rep.GetByID(sid);
                    if (loc == null)
                    {
                        obj.Response.StatusCode = (int)HttpStatusCode.NotFound;
                        obj.Response.StatusDescription = "Stream Id not found.";
                        return;

                    }
                    fullname = loc.FullServerPath;
                }
                else if (cmd == "file")
                {
                    fullname = Base64DecodeUrl(arg);

                }
                else
                {
                    obj.Response.StatusCode = (int)HttpStatusCode.BadRequest;
                    obj.Response.StatusDescription = "Not know command";
                    return;
                }

                bool range = false;

                try
                {
                    if (!File.Exists(fullname))
                    {
                        obj.Response.StatusCode = (int)HttpStatusCode.NotFound;
                        obj.Response.StatusDescription = "File '" + fullname + "' not found.";
                        return;
                    }

                }
                catch (Exception)
                {
                    obj.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
                    obj.Response.StatusDescription = "Unable to access File '" + fullname + "'.";
                    return;
                }
                obj.Response.ContentType = GetMime(fullname);
                obj.Response.AddHeader("Accept-Ranges", "bytes");
                obj.Response.AddHeader("X-Plex-Protocol", "1.0");
                if (obj.Request.HttpMethod == "OPTIONS")
                {
                    obj.Response.AddHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT, HEAD");
                    obj.Response.AddHeader("Access-Control-Max-Age", "1209600");
                    obj.Response.AddHeader("Access-Control-Allow-Headers",
                        "accept, x-plex-token, x-plex-client-identifier, x-plex-username, x-plex-product, x-plex-device, x-plex-platform, x-plex-platform-version, x-plex-version, x-plex-device-name");
                    obj.Response.AddHeader("Cache-Control", "no-cache");
                    obj.Response.ContentType = "text/plain";
                    return;
                }
                string rangevalue = null;
                if (obj.Request.Headers.AllKeys.Contains("Range"))
                    rangevalue = obj.Request.Headers["Range"].Replace("bytes=", string.Empty).Trim();
                if (obj.Request.Headers.AllKeys.Contains("range"))
                    rangevalue = obj.Request.Headers["range"].Replace("bytes=", string.Empty).Trim();

                if (obj.Request.HttpMethod != "HEAD")
                {
                    org = new FileStream(fullname, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                    long totalsize = org.Length;
                    long start = 0;
                    long end = 0;
                    if (!string.IsNullOrEmpty(rangevalue))
                    {
                        range = true;
                        string[] split = rangevalue.Split('-');
                        if (split.Length == 2)
                        {
                            if (string.IsNullOrEmpty(split[0]) && !string.IsNullOrEmpty(split[1]))
                            {
                                long e = long.Parse(split[1]);
                                start = totalsize - e;
                                end = totalsize - 1;
                            }
                            else if (!string.IsNullOrEmpty(split[0]) && string.IsNullOrEmpty(split[1]))
                            {
                                start = long.Parse(split[0]);
                                end = totalsize - 1;
                            }
                            else if (!string.IsNullOrEmpty(split[0]) && !string.IsNullOrEmpty(split[1]))
                            {
                                start = long.Parse(split[0]);
                                end = long.Parse(split[1]);
                                if (start > totalsize - 1)
                                    start = totalsize - 1;
                                if (end > totalsize - 1)
                                    end = totalsize - 1;
                            }
                            else
                            {
                                start = 0;
                                end = totalsize - 1;
                            }
                        }
                    }
                    SubStream outstream;
                    if (range)
                    {
                        obj.Response.StatusCode = (int) HttpStatusCode.PartialContent;
                        obj.Response.AddHeader("Content-Range", "bytes " + start + "-" + end + "/" + totalsize);
                        outstream = new SubStream(org, start, end - start + 1);
                        obj.Response.ContentLength64 = end - start + 1;
                    }
                    else
                    {
                        outstream=new SubStream(org,0,totalsize);
                        obj.Response.ContentLength64 = totalsize;
                        obj.Response.StatusCode = (int) HttpStatusCode.OK;
                    }
                    if ((userid != 0) && (loc != null))
                    {
                        outstream.CrossPosition = (long) ((double) totalsize*WatchedThreshold);
                        outstream.CrossPositionCrossed += (a) =>
                        {
                            Task.Factory.StartNew(() =>
                            {
                                loc.ToggleWatchedStatus(true, userid);
                            }, new CancellationToken(), TaskCreationOptions.LongRunning, TaskScheduler.Default);
                        };
                    }
                    obj.Response.SendChunked = false;
                    outstream.CopyTo(obj.Response.OutputStream);
                    obj.Response.OutputStream.Close();
                    outstream.Close();
                }
                else
                {
                    obj.Response.SendChunked = false;
                    obj.Response.StatusCode = (int)HttpStatusCode.OK;
                    obj.Response.ContentLength64 = new FileInfo(fullname).Length;
                    obj.Response.KeepAlive = false;
                    obj.Response.OutputStream.Close();
                }
            }
            catch (HttpListenerException e)
            {
            }
            catch (Exception e)
            {
                logger.Error(e.ToString);
            }
            finally
            {
                if (org != null)
                    org.Close();
                if ((obj != null) && (obj.Response != null) && (obj.Response.OutputStream != null))
                    obj.Response.OutputStream.Close();
            }
        }
Ejemplo n.º 22
0
 private System.IO.Stream InternalGetFile(int userid, string Id, HistoryInfo info)
 {
     int id;
     if (!int.TryParse(Id, out id))
         return new MemoryStream();
     VideoLocalRepository repVids = new VideoLocalRepository();
     PlexObject ret = new PlexObject(PlexHelper.NewMediaContainer(MediaContainerTypes.File,info,true));
     VideoLocal vi = repVids.GetByID(id);
     if (vi == null)
         return new MemoryStream();
     List<Video> dirs = new List<Video>();
     Video v2 = new Video();
     PlexHelper.PopulateVideo(v2, vi, JMMType.File, userid);
     dirs.Add(v2,info);
     ret.MediaContainer.Childrens = dirs;
     return ret.GetStream();
 }