public override void ProcessCommand()
		{
			logger.Info("Processing CommandRequest_UpdateMyListFileStatus: {0}", Hash);

			
			try
			{
				VideoLocalRepository repVids = new VideoLocalRepository();
				AnimeEpisodeRepository repEpisodes = new AnimeEpisodeRepository();

				// NOTE - we might return more than one VideoLocal record here, if there are duplicates by hash
				VideoLocal vid = repVids.GetByHash(this.Hash);
				if (vid != null)
				{
					bool isManualLink = false;
					List<CrossRef_File_Episode> xrefs = vid.EpisodeCrossRefs;
					if (xrefs.Count > 0)
						isManualLink = xrefs[0].CrossRefSource != (int)CrossRefSource.AniDB;

					if (isManualLink)
					{
						JMMService.AnidbProcessor.UpdateMyListFileStatus(xrefs[0].AnimeID, xrefs[0].Episode.EpisodeNumber, this.Watched);
						logger.Info("Updating file list status (GENERIC): {0} - {1}", vid.ToString(), this.Watched);
					}
					else
					{
						if (WatchedDateAsSecs > 0)
						{
							DateTime? watchedDate = Utils.GetAniDBDateAsDate(WatchedDateAsSecs);
							JMMService.AnidbProcessor.UpdateMyListFileStatus(vid, this.Watched, watchedDate);
						}
						else
							JMMService.AnidbProcessor.UpdateMyListFileStatus(vid, this.Watched, null);
						logger.Info("Updating file list status: {0} - {1}", vid.ToString(), this.Watched);
					}

					if (UpdateSeriesStats)
					{
						// update watched stats
						List<AnimeEpisode> eps = repEpisodes.GetByHash(vid.ED2KHash);
						if (eps.Count > 0)
						{
							// all the eps should belong to the same anime
							eps[0].GetAnimeSeries().UpdateStats(true, false, true);
							//eps[0].AnimeSeries.TopLevelAnimeGroup.UpdateStatsFromTopLevel(true, true, false);
						}
					}
				}

				
			}
			catch (Exception ex)
			{
				logger.Error("Error processing CommandRequest_UpdateMyListFileStatus: {0} - {1}", Hash, ex.ToString());
				return;
			}
		}
Esempio n. 2
0
		public VideoLocal_User GetVideoLocalUserRecord(int userID)
		{
			VideoLocalRepository repVids = new VideoLocalRepository();

			VideoLocal vid = repVids.GetByHash(Hash);
			if (vid != null)
			{
				VideoLocal_User vidUser = vid.GetUserRecord(userID);
				if (vidUser != null) return vidUser;
			}

			return null;
		}
		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;
			}
		}
Esempio n. 4
0
        public static void InitCache()
        {
            string t = "VideoLocal";

            ServerState.Instance.CurrentSetupStatus = string.Format(JMMServer.Properties.Resources.Database_Cache, t, string.Empty);
            VideoLocalRepository repo = new VideoLocalRepository();

            Cache         = new PocoCache <int, VideoLocal>(repo.InternalGetAll(), a => a.VideoLocalID);
            Hashes        = new PocoIndex <int, VideoLocal, string>(Cache, a => a.Hash);
            Paths         = new PocoIndex <int, VideoLocal, string>(Cache, a => a.FilePath);
            Ignored       = new PocoIndex <int, VideoLocal, int>(Cache, a => a.IsIgnored);
            ImportFolders = new PocoIndex <int, VideoLocal, int>(Cache, a => a.ImportFolderID);
            int cnt = 0;
            List <VideoLocal> grps = Cache.Values.Where(a => a.MediaVersion < VideoLocal.MEDIA_VERSION || a.MediaBlob == null).ToList();
            int max = grps.Count;

            foreach (VideoLocal g in grps)
            {
                try
                {
                    if (File.Exists(g.FullServerPath))
                    {
                        repo.Save(g, false);
                    }
                }
                catch (Exception)
                {
                    // ignored
                }
                cnt++;
                if (cnt % 10 == 0)
                {
                    ServerState.Instance.CurrentSetupStatus = string.Format(JMMServer.Properties.Resources.Database_Cache, t,
                                                                            " DbRegen - " + cnt + "/" + max);
                }
            }
            ServerState.Instance.CurrentSetupStatus = string.Format(JMMServer.Properties.Resources.Database_Cache, t,
                                                                    " DbRegen - " + max + "/" + max);
        }
		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
		}
Esempio n. 6
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;
            }
        }
Esempio n. 7
0
        public List<Contract_VideoLocal> SearchForFiles(int searchType, string searchCriteria, int userID)
        {
            try
            {
                List<Contract_VideoLocal> vids = new List<Contract_VideoLocal>();

                FileSearchCriteria sType = (FileSearchCriteria)searchType;

                VideoLocalRepository repVids = new VideoLocalRepository();
                switch (sType)
                {
                    case FileSearchCriteria.Name:

                        List<VideoLocal> results1 = repVids.GetByName(searchCriteria.Trim());
                        foreach (VideoLocal vid in results1)
                            vids.Add(vid.ToContract(userID));

                        break;

                    case FileSearchCriteria.ED2KHash:

                        VideoLocal vidByHash = repVids.GetByHash(searchCriteria.Trim());
                        if (vidByHash != null)
                            vids.Add(vidByHash.ToContract(userID));

                        break;

                    case FileSearchCriteria.Size:

                        break;

                    case FileSearchCriteria.LastOneHundred:

                        List<VideoLocal> results2 = repVids.GetMostRecentlyAdded(100);
                        foreach (VideoLocal vid in results2)
                            vids.Add(vid.ToContract(userID));

                        break;
                }

                return vids;
            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
            }
            return new List<Contract_VideoLocal>();
        }
Esempio n. 8
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;
            }
        }
Esempio n. 9
0
        public static UserInfo GetUserInfoData(string dashType = "", string vidPlayer = "")
        {
            try
            {
                if (string.IsNullOrEmpty(ServerSettings.AniDB_Username)) return null;

                UserInfo uinfo = new UserInfo();

                uinfo.DateTimeUpdated = DateTime.Now;
                uinfo.DateTimeUpdatedUTC = 0;

                // Optional JMM Desktop data
                uinfo.DashboardType = null;
                uinfo.VideoPlayer = vidPlayer;

                System.Reflection.Assembly a = System.Reflection.Assembly.GetExecutingAssembly();
                try
                {
                    if (a != null) uinfo.JMMServerVersion = Utils.GetApplicationVersion(a);
                }
                catch {}

                uinfo.UsernameHash = Utils.GetMd5Hash(ServerSettings.AniDB_Username);
                uinfo.DatabaseType = ServerSettings.DatabaseType;
                uinfo.WindowsVersion = Utils.GetOSInfo();
                uinfo.TraktEnabled = ServerSettings.Trakt_IsEnabled ? 1 : 0;
                uinfo.MALEnabled = string.IsNullOrEmpty(ServerSettings.MAL_Username) ? 0 : 1;

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

                JMMUserRepository repUsers = new JMMUserRepository();
                uinfo.LocalUserCount = (int)(repUsers.GetTotalRecordCount());

                VideoLocalRepository repVids = new VideoLocalRepository();
                uinfo.FileCount = repVids.GetTotalRecordCount();

                AnimeEpisode_UserRepository repEps = new AnimeEpisode_UserRepository();
                List<AnimeEpisode_User> recs = repEps.GetLastWatchedEpisode();
                uinfo.LastEpisodeWatched = 0;
                if (recs.Count > 0)
                    uinfo.LastEpisodeWatched = Utils.GetAniDBDateAsSeconds(recs[0].WatchedDate);

                return uinfo;
            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
                return null;
            }
        }
Esempio n. 10
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;
            }
        }
Esempio n. 11
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;
            }
        }
Esempio n. 12
0
		void workerMediaInfo_DoWork(object sender, DoWorkEventArgs e)
		{
			VideoLocalRepository repVidLocals = new VideoLocalRepository();

			// first build a list of files that we already know about, as we don't want to process them again
			List<VideoLocal> filesAll = repVidLocals.GetAll();
			Dictionary<string, VideoLocal> dictFilesExisting = new Dictionary<string, VideoLocal>();
			foreach (VideoLocal vl in filesAll)
			{
				CommandRequest_ReadMediaInfo cr = new CommandRequest_ReadMediaInfo(vl.VideoLocalID);
				cr.Save();
			}
		}
Esempio n. 13
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;
        }
Esempio n. 14
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;
        }
Esempio n. 15
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();
            }
        }
Esempio n. 16
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;
            }
        }
Esempio n. 17
0
        /*public List<Contract_VideoLocalRenamed> RandomFileRenamePreview(int maxResults, int userID, string renameRules)
        {
            List<Contract_VideoLocalRenamed> ret = new List<Contract_VideoLocalRenamed>();
            try
            {
                VideoLocalRepository repVids = new VideoLocalRepository();
                foreach (VideoLocal vid in repVids.GetRandomFiles(maxResults))
                {
                    Contract_VideoLocalRenamed vidRen = new Contract_VideoLocalRenamed();
                    vidRen.VideoLocalID = vid.VideoLocalID;
                    vidRen.VideoLocal = vid.ToContract(userID);
                    vidRen.NewFileName = RenameFileHelper.GetNewFileName(vid, renameRules);
                    ret.Add(vidRen);
                }
            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);

            }
            return ret;
        }*/
        public List<Contract_VideoLocal> RandomFileRenamePreview(int maxResults, int userID)
        {
            List<Contract_VideoLocal> ret = new List<Contract_VideoLocal>();
            try
            {
                VideoLocalRepository repVids = new VideoLocalRepository();
                foreach (VideoLocal vid in repVids.GetRandomFiles(maxResults))
                    ret.Add(vid.ToContract(userID));

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

            }
            return ret;
        }
Esempio n. 18
0
        /// <summary>
        /// Delete a series, and everything underneath it (episodes, files)
        /// </summary>
        /// <param name="animeSeriesID"></param>
        /// <param name="deleteFiles">also delete the physical files</param>
        /// <returns></returns>
        public string DeleteAnimeSeries(int animeSeriesID, bool deleteFiles, bool deleteParentGroup)
        {
            try
            {
                AnimeEpisodeRepository repEps = new AnimeEpisodeRepository();
                AnimeSeriesRepository repAnimeSer = new AnimeSeriesRepository();
                VideoLocalRepository repVids = new VideoLocalRepository();
                AnimeGroupRepository repGroups = new AnimeGroupRepository();

                AnimeSeries ser = repAnimeSer.GetByID(animeSeriesID);
                if (ser == null) return "Series does not exist";

                int animeGroupID = ser.AnimeGroupID;

                foreach (AnimeEpisode ep in ser.GetAnimeEpisodes())
                {
                    foreach (VideoLocal vid in ep.GetVideoLocals())
                    {
                        if (deleteFiles)
                        {
                            logger.Info("Deleting video local record and file: {0}", vid.FullServerPath);
                            if (!File.Exists(vid.FullServerPath)) return "File could not be found";
                            File.Delete(vid.FullServerPath);
                        }
                        CommandRequest_DeleteFileFromMyList cmdDel = new CommandRequest_DeleteFileFromMyList(vid.Hash, vid.FileSize);
                        cmdDel.Save();

                        repVids.Delete(vid.VideoLocalID);
                    }

                    repEps.Delete(ep.AnimeEpisodeID);
                }
                repAnimeSer.Delete(ser.AnimeSeriesID);

                // finally update stats
                AnimeGroup grp = repGroups.GetByID(animeGroupID);
                if (grp != null)
                {
                    if (grp.GetAllSeries().Count == 0)
                    {
                        DeleteAnimeGroup(grp.AnimeGroupID, false);
                    }
                    else
                    {
                        grp.TopLevelAnimeGroup.UpdateStatsFromTopLevel(true, true, true);
                        StatsCache.Instance.UpdateUsingGroup(grp.TopLevelAnimeGroup.AnimeGroupID);
                    }
                }

                return "";

            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
                return ex.Message;
            }
        }
Esempio n. 19
0
        public List<Contract_VideoLocal> GetVideoLocalsForAnime(int animeID, int userID)
        {
            List<Contract_VideoLocal> contracts = new List<Contract_VideoLocal>();
            try
            {

                VideoLocalRepository repVids = new VideoLocalRepository();
                foreach (VideoLocal vid in repVids.GetByAniDBAnimeID(animeID))
                {
                    contracts.Add(vid.ToContract(userID));
                }
            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
            }
            return contracts;
        }
Esempio n. 20
0
        public string UpdateAnimeData(int animeID)
        {
            try
            {
                using (var session = JMMService.SessionFactory.OpenSession())
                {
                    JMMService.AnidbProcessor.GetAnimeInfoHTTP(session, animeID, true, false);

                    // also find any files for this anime which don't have proper media info data
                    // we can usually tell this if the Resolution == '0x0'
                    VideoLocalRepository repVids = new VideoLocalRepository();
                    AniDB_FileRepository repFiles = new AniDB_FileRepository();

                    foreach (VideoLocal vid in repVids.GetByAniDBAnimeID(session, animeID))
                    {
                        AniDB_File aniFile = vid.GetAniDBFile(session);
                        if (aniFile == null) continue;

                        if (aniFile.File_VideoResolution.Equals("0x0", StringComparison.InvariantCultureIgnoreCase))
                        {
                            CommandRequest_GetFile cmd = new CommandRequest_GetFile(vid.VideoLocalID, true);
                            cmd.Save(session);
                        }
                    }

                    // update group status information
                    CommandRequest_GetReleaseGroupStatus cmdStatus = new CommandRequest_GetReleaseGroupStatus(animeID, true);
                    cmdStatus.Save(session);
                }

            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
            }
            return "";
        }
Esempio n. 21
0
		private void ProcessFile_AniDB(VideoLocal vidLocal)
		{
			logger.Trace("Checking for AniDB_File record for: {0} --- {1}", vidLocal.Hash, vidLocal.FilePath);
			// check if we already have this AniDB_File info in the database
			
			AniDB_FileRepository repAniFile = new AniDB_FileRepository();
			AniDB_EpisodeRepository repAniEps = new AniDB_EpisodeRepository();
			AniDB_AnimeRepository repAniAnime = new AniDB_AnimeRepository();
			AnimeSeriesRepository repSeries = new AnimeSeriesRepository();
			VideoLocalRepository repVidLocals = new VideoLocalRepository();
			AnimeEpisodeRepository repEps = new AnimeEpisodeRepository();
			CrossRef_File_EpisodeRepository repXrefFE = new CrossRef_File_EpisodeRepository();

			AniDB_File aniFile = null;

			if (!ForceAniDB)
			{
				aniFile = repAniFile.GetByHashAndFileSize(vidLocal.Hash, vlocal.FileSize);

				if (aniFile == null)
					logger.Trace("AniDB_File record not found");
			}

			int animeID = 0;

			if (aniFile == null)
			{
				// get info from AniDB
				logger.Debug("Getting AniDB_File record from AniDB....");
				Raw_AniDB_File fileInfo = JMMService.AnidbProcessor.GetFileInfo(vidLocal);
				if (fileInfo != null)
				{
					// check if we already have a record
					aniFile = repAniFile.GetByHashAndFileSize(vidLocal.Hash, vlocal.FileSize);

					if (aniFile == null)
						aniFile = new AniDB_File();

					aniFile.Populate(fileInfo);

					//overwrite with local file name
					string localFileName = Path.GetFileName(vidLocal.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();
                            }
                        }
                    }

					animeID = aniFile.AnimeID;
				}
			}

			bool missingEpisodes = false;

			// if we still haven't got the AniDB_File Info we try the web cache or local records
			if (aniFile == null)
			{
				// check if we have any records from previous imports
				List<CrossRef_File_Episode> crossRefs = repXrefFE.GetByHash(vidLocal.Hash);
				if (crossRefs == null || crossRefs.Count == 0)
				{
					// lets see if we can find the episode/anime info from the web cache
					if (ServerSettings.WebCache_XRefFileEpisode_Get)
					{
						crossRefs = XMLService.Get_CrossRef_File_Episode(vidLocal);
						if (crossRefs == null || crossRefs.Count == 0)
						{
							logger.Debug("Cannot find AniDB_File record or get cross ref from web cache record so exiting: {0}", vidLocal.ED2KHash);
							return;
						}
						else
						{
							foreach (CrossRef_File_Episode xref in crossRefs)
							{
								// in this case we need to save the cross refs manually as AniDB did not provide them
								repXrefFE.Save(xref);
							}
						}
					}
					else
					{
						logger.Debug("Cannot get AniDB_File record so exiting: {0}", vidLocal.ED2KHash);
						return;
					}
				}

				// we assume that all episodes belong to the same anime
				foreach (CrossRef_File_Episode xref in crossRefs)
				{
					animeID = xref.AnimeID;
					
					AniDB_Episode ep = repAniEps.GetByEpisodeID(xref.EpisodeID);
					if (ep == null) missingEpisodes = true;
				}
			}
			else
			{
				// check if we have the episode info
				// if we don't, we will need to re-download the anime info (which also has episode info)

				if (aniFile.EpisodeCrossRefs.Count == 0)
				{
					animeID = aniFile.AnimeID;

					// if we have the anidb file, but no cross refs it means something has been broken
					logger.Debug("Could not find any cross ref records for: {0}", vidLocal.ED2KHash);
					missingEpisodes = true;
				}
				else
				{
					foreach (CrossRef_File_Episode xref in aniFile.EpisodeCrossRefs)
					{
						AniDB_Episode ep = repAniEps.GetByEpisodeID(xref.EpisodeID);
						if (ep == null)
							missingEpisodes = true;

						animeID = xref.AnimeID;
					}
				}
			}

			// get from DB
			AniDB_Anime anime = repAniAnime.GetByAnimeID(animeID);
			bool animeRecentlyUpdated = false;

			if (anime != null)
			{
				TimeSpan ts = DateTime.Now - anime.DateTimeUpdated;
				if (ts.TotalHours < 4) animeRecentlyUpdated = true;
			}

			// even if we are missing episode info, don't get data  more than once every 4 hours
			// this is to prevent banning
			if (missingEpisodes && !animeRecentlyUpdated)
			{
				logger.Debug("Getting Anime record from AniDB....");

				// try using the cache first
				using (var session = JMMService.SessionFactory.OpenSession())
				{
					anime = JMMService.AnidbProcessor.GetAnimeInfoHTTPFromCache(session, animeID, ServerSettings.AutoGroupSeries);
				}

				// if not in cache try from AniDB
				if (anime == null)
					anime = JMMService.AnidbProcessor.GetAnimeInfoHTTP(animeID, true, ServerSettings.AutoGroupSeries);
			}

			// create the group/series/episode records if needed
			AnimeSeries ser = null;
			if (anime != null)
			{
				logger.Debug("Creating groups, series and episodes....");
				// check if there is an AnimeSeries Record associated with this AnimeID
				ser = repSeries.GetByAnimeID(animeID);
				if (ser == null)
				{
					// create a new AnimeSeries record
					ser = anime.CreateAnimeSeriesAndGroup();
				}

				
				ser.CreateAnimeEpisodes();

				// check if we have any group status data for this associated anime
				// if not we will download it now
				AniDB_GroupStatusRepository repStatus = new AniDB_GroupStatusRepository();
				if (repStatus.GetByAnimeID(anime.AnimeID).Count == 0)
				{
					CommandRequest_GetReleaseGroupStatus cmdStatus = new CommandRequest_GetReleaseGroupStatus(anime.AnimeID, false);
					cmdStatus.Save();
				}

				// update 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);
				}
			}

			vidLocal.RenameIfRequired();
			vidLocal.MoveFileIfRequired();
			

			// update stats for groups and series
			if (ser != null)
			{
				// update all the groups above this series in the heirarchy
				ser.UpdateStats(true, true, true);
				StatsCache.Instance.UpdateUsingSeries(ser.AnimeSeriesID);
			}
			

			// Add this file to the users list
			if (ServerSettings.AniDB_MyList_AddFiles)
			{
				CommandRequest_AddFileToMyList cmd = new CommandRequest_AddFileToMyList(vidLocal.ED2KHash);
				cmd.Save();
			}

			// lets also try adding to the users trakt collecion by sync'ing the series
			if (ser != null)
			{
				CommandRequest_TraktSyncCollectionSeries cmdTrakt = new CommandRequest_TraktSyncCollectionSeries(ser.AnimeSeriesID, ser.GetAnime().MainTitle);
				cmdTrakt.Save();
			}

			// sync the series on MAL
			if (ser != null)
			{
				CommandRequest_MALUpdatedWatchedStatus cmdMAL = new CommandRequest_MALUpdatedWatchedStatus(ser.AniDB_ID);
				cmdMAL.Save();
			}
		}
Esempio n. 22
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 "";
        }
Esempio n. 23
0
        public List<Contract_AnimeSeries> GetSeriesWithoutAnyFiles(int userID)
        {
            List<Contract_AnimeSeries> contracts = new List<Contract_AnimeSeries>();

            VideoLocalRepository repVids = new VideoLocalRepository();
            AnimeSeriesRepository repSeries = new AnimeSeriesRepository();

            try
            {
                foreach (AnimeSeries ser in repSeries.GetAll())
                {
                    if (repVids.GetByAniDBAnimeID(ser.AniDB_ID).Count == 0)
                    {
                        contracts.Add(ser.ToContract(ser.GetUserRecord(userID)));
                    }
                }
            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
            }
            return contracts;
        }
Esempio n. 24
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;
            }
        }
Esempio n. 25
0
        public void SaveFFDPreset(Contract_FileFfdshowPreset preset)
        {
            try
            {
                VideoLocalRepository repVids = new VideoLocalRepository();
                FileFfdshowPresetRepository repFFD = new FileFfdshowPresetRepository();

                VideoLocal vid = repVids.GetByHashAndSize(preset.Hash, preset.FileSize);
                if (vid == null) return;

                FileFfdshowPreset ffd = repFFD.GetByHashAndSize(preset.Hash, preset.FileSize);
                if (ffd == null) ffd = new FileFfdshowPreset();

                ffd.FileSize = preset.FileSize;
                ffd.Hash = preset.Hash;
                ffd.Preset = preset.Preset;

                repFFD.Save(ffd);

            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
            }
        }
Esempio n. 26
0
		void workerMyAnime2_DoWork(object sender, DoWorkEventArgs e)
		{
			MA2Progress ma2Progress = new MA2Progress();
			ma2Progress.CurrentFile = 0;
			ma2Progress.ErrorMessage = "";
			ma2Progress.MigratedFiles = 0;
			ma2Progress.TotalFiles = 0;

			try
			{
				string databasePath = e.Argument as string;

				string connString = string.Format(@"data source={0};useutf16encoding=True", databasePath);
				SQLiteConnection myConn = new SQLiteConnection(connString);
				myConn.Open();

				// get a list of unlinked files
				VideoLocalRepository repVids = new VideoLocalRepository();
				AniDB_EpisodeRepository repAniEps = new AniDB_EpisodeRepository();
				AniDB_AnimeRepository repAniAnime = new AniDB_AnimeRepository();
				AnimeSeriesRepository repSeries = new AnimeSeriesRepository();
				AnimeEpisodeRepository repEps = new AnimeEpisodeRepository();

				List<VideoLocal> vids = repVids.GetVideosWithoutEpisode();
				ma2Progress.TotalFiles = vids.Count;

				foreach (VideoLocal vid in vids)
				{
					ma2Progress.CurrentFile = ma2Progress.CurrentFile + 1;
					workerMyAnime2.ReportProgress(0, ma2Progress);

					// search for this file in the XrossRef table in MA2
					string sql = string.Format("SELECT AniDB_EpisodeID from CrossRef_Episode_FileHash WHERE Hash = '{0}' AND FileSize = {1}", vid.ED2KHash, vid.FileSize);
					SQLiteCommand sqCommand = new SQLiteCommand(sql);
					sqCommand.Connection = myConn;

					SQLiteDataReader myReader = sqCommand.ExecuteReader();
					while (myReader.Read())
					{
						int episodeID = 0;
						if (!int.TryParse(myReader.GetValue(0).ToString(), out episodeID)) continue;
						if (episodeID <= 0) continue;

						sql = string.Format("SELECT AnimeID from AniDB_Episode WHERE EpisodeID = {0}", episodeID);
						sqCommand = new SQLiteCommand(sql);
						sqCommand.Connection = myConn;

						SQLiteDataReader myReader2 = sqCommand.ExecuteReader();
						while (myReader2.Read())
						{
							int animeID = myReader2.GetInt32(0);

							// so now we have all the needed details we can link the file to the episode
							// as long as wehave the details in JMM
							AniDB_Anime anime = null;
							AniDB_Episode ep = repAniEps.GetByEpisodeID(episodeID);
							if (ep == null)
							{
								logger.Debug("Getting Anime record from AniDB....");
								anime = JMMService.AnidbProcessor.GetAnimeInfoHTTP(animeID, true, ServerSettings.AutoGroupSeries);
							}
							else
								anime = repAniAnime.GetByAnimeID(animeID);

							// create the group/series/episode records if needed
							AnimeSeries ser = null;
							if (anime == null) continue;

							logger.Debug("Creating groups, series and episodes....");
							// check if there is an AnimeSeries Record associated with this AnimeID
							ser = repSeries.GetByAnimeID(animeID);
							if (ser == null)
							{
								// create a new AnimeSeries record
								ser = anime.CreateAnimeSeriesAndGroup();
							}


							ser.CreateAnimeEpisodes();

							// check if we have any group status data for this associated anime
							// if not we will download it now
							AniDB_GroupStatusRepository repStatus = new AniDB_GroupStatusRepository();
							if (repStatus.GetByAnimeID(anime.AnimeID).Count == 0)
							{
								CommandRequest_GetReleaseGroupStatus cmdStatus = new CommandRequest_GetReleaseGroupStatus(anime.AnimeID, false);
								cmdStatus.Save();
							}

							// update 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);
							}


							AnimeEpisode epAnime = repEps.GetByAniDBEpisodeID(episodeID);
							if (epAnime == null)
								continue;

							CrossRef_File_EpisodeRepository repXRefs = new CrossRef_File_EpisodeRepository();
							CrossRef_File_Episode xref = new CrossRef_File_Episode();

							try
							{
								xref.PopulateManually(vid, epAnime);
							}
							catch (Exception ex)
							{
								string msg = string.Format("Error populating XREF: {0} - {1}", vid.ToStringDetailed(), ex.ToString());
								throw;
							}

							repXRefs.Save(xref);

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

							// update stats for groups and series
							if (ser != null)
							{
								// update all the groups above this series in the heirarchy
								ser.UpdateStats(true, true, true);
								StatsCache.Instance.UpdateUsingSeries(ser.AnimeSeriesID);
							}


							// Add this file to the users list
							if (ServerSettings.AniDB_MyList_AddFiles)
							{
								CommandRequest_AddFileToMyList cmd = new CommandRequest_AddFileToMyList(vid.ED2KHash);
								cmd.Save();
							}

							ma2Progress.MigratedFiles = ma2Progress.MigratedFiles + 1;
							workerMyAnime2.ReportProgress(0, ma2Progress);

						}
						myReader2.Close();


						//Console.WriteLine(myReader.GetString(0));
					}
					myReader.Close();
				}


				myConn.Close();

				ma2Progress.CurrentFile = ma2Progress.CurrentFile + 1;
				workerMyAnime2.ReportProgress(0, ma2Progress);

			}
			catch (Exception ex)
			{
				logger.ErrorException(ex.ToString(), ex);
				ma2Progress.ErrorMessage = ex.Message;
				workerMyAnime2.ReportProgress(0, ma2Progress);
			}
		}
Esempio n. 27
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);
            }
        }
Esempio n. 28
0
        public List<Contract_VideoLocalRenamed> RenameFiles(List<int> videoLocalIDs, string renameRules)
        {
            List<Contract_VideoLocalRenamed> ret = new List<Contract_VideoLocalRenamed>();
            try
            {
                VideoLocalRepository repVids = new VideoLocalRepository();
                foreach (int vid in videoLocalIDs)
                {

                }
            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.ToString(), ex);
            }
            return ret;
        }
Esempio n. 29
0
 public List<Contract_VideoLocal> GetUnrecognisedFiles(int userID)
 {
     List<Contract_VideoLocal> contracts = new List<Contract_VideoLocal>();
     try
     {
         VideoLocalRepository repVids = new VideoLocalRepository();
         foreach (VideoLocal vid in repVids.GetVideosWithoutEpisode())
         {
             contracts.Add(vid.ToContract(userID));
         }
     }
     catch (Exception ex)
     {
         logger.ErrorException(ex.ToString(), ex);
     }
     return contracts;
 }
Esempio n. 30
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();
            }
        }
Esempio n. 31
0
        public void RescanUnlinkedFiles()
        {
            try
            {
                // files which have been hashed, but don't have an associated episode
                VideoLocalRepository repVidLocals = new VideoLocalRepository();
                List<VideoLocal> filesWithoutEpisode = repVidLocals.GetVideosWithoutEpisode();

                foreach (VideoLocal vl in filesWithoutEpisode)
                {
                    CommandRequest_ProcessFile cmd = new CommandRequest_ProcessFile(vl.VideoLocalID, true);
                    cmd.Save();
                }
            }
            catch (Exception ex)
            {
                logger.ErrorException(ex.Message, ex);
            }
        }