Exemple #1
0
        public IDataBlock DetectData(IDataReader dataReader, IDataBlockBuilder dataBlockBuilder, IScanContext context)
        {
            bool isFragmented = context.IsFragmented;

            if (ReferenceHeaders != null)
            {
                var referenceHeaders = new Dictionary <IDataPacket, ISequenceState>();
                foreach (IReferenceHeader header in ReferenceHeaders)
                {
                    IInputFile headerFile = context.CreateReferenceHeaderFile(header);
                    using (var reader = headerFile.CreateDataReader())
                    {
                        var headerDataBlock = _carver.Carve(new BitStreamDataReader(reader), dataBlockBuilder, context);
                        if (headerDataBlock != null)
                        {
                            referenceHeaders[headerFile.CreateDataPacket()] = context.ReferenceHeader as ISequenceState;
                        }
                    }
                }

                context.ReferenceHeader = referenceHeaders;
            }

            // Restore scan context
            context.Results      = null;
            context.IsFragmented = isFragmented;
            // context.ReferenceHeader

            return(_carver.Carve(new BitStreamDataReader(dataReader), dataBlockBuilder, context));
        }
Exemple #2
0
        public IList <DataBlockVerification> VerifyScanOfFragmented(string fileName)
        {
            if (String.IsNullOrEmpty(_fileNameProject))
            {
                Assert.Fail("Incorrect Test Setup:WithProjectFile has not been called.");
            }
            if (!File.Exists(fileName))
            {
                Assert.Fail("Incorrect Test Setup:No file exists at " + Path.GetFullPath(fileName));
            }
            if (_videoDetector == null)
            {
                Assert.Fail("Incorrect Test Setup:WithDetector has not been called.");
            }
            File.Delete(_fileNameProject);
            // Scan test file
            IInputFile scannedFile = ScanFile(fileName);
            var        blocks      = _project.GetDataBlocks(scannedFile);
            var        verifyers   = new List <IDataBlock>(blocks).ConvertAll(block =>
            {
                var result = TestFramework.GetResults(block);
                var descr  = TestFramework.GetDescriptionText(result);
                return(new DataBlockVerification(block, result, "fragment " + block.FragmentIndex + " detected using " + (_systemDetector == null ? "" : _systemDetector.Name + " and ") + _videoDetector.Name + ", containing Results:" + descr));
            });

            return(verifyers);
        }
        public void SetUp()
        {
            File.Delete(ProjectPath);

            _mockRepository    = new MockRepository();
            _inputFile1        = MockRepository.GenerateStub <IInputFile>();
            _inputFile2        = MockRepository.GenerateStub <IInputFile>();
            _detector1         = MockRepository.GenerateStub <IDetector>();
            _detector2         = MockRepository.GenerateStub <IDetector>();
            _dataBlock1        = MockRepository.GenerateStub <IDataBlock>();
            _dataBlock2        = MockRepository.GenerateStub <IDataBlock>();
            _dataBlock3        = MockRepository.GenerateStub <IDataBlock>();
            _columnInfo1       = MockRepository.GenerateStub <IColumnInfo>();
            _columnInfo2       = MockRepository.GenerateStub <IColumnInfo>();
            _updatedColumnInfo = MockRepository.GenerateStub <IColumnInfo>();
            _createInputFile   = MockRepository.GenerateStub <Creator <IInputFile, IProject, string> >();

            _inputFile1.Stub(x => x.Name).Return(DummyFileName);
            _inputFile1.Stub(x => x.Length).Return(DummyFileLength);
            _inputFile2.Stub(x => x.Name).Return(EmptyFileName);
            _inputFile2.Stub(x => x.Length).Return(EmptyFileLength);
            _dataBlock1.Stub(x => x.InputFile).Return(_inputFile1);
            _dataBlock2.Stub(x => x.InputFile).Return(_inputFile2);
            _dataBlock3.Stub(x => x.InputFile).Return(_inputFile2);
            _columnInfo1.Stub(x => x.Name).Return(ColumnName1);
            _columnInfo1.Stub(x => x.Width).Return(ColumnWidth1);
            _columnInfo2.Stub(x => x.Name).Return(ColumnName2);
            _columnInfo2.Stub(x => x.Width).Return(ColumnWidth2);

            _project = new Project(_createInputFile, ProjectPath);

            _createInputFile.Stub(x => x(_project, FileName1)).Return(_inputFile1);
            _createInputFile.Stub(x => x(_project, FileName2)).Return(_inputFile2);
        }
        public void TestReaderGetDataBlocksVerifyContents()
        {
            IInputFile         inputFile  = _project.GetInputFiles()[0];
            IList <IDataBlock> dataBlocks = _project.GetDataBlocks(inputFile);

            Assert.AreEqual(inputFile, dataBlocks[0].InputFile, "DataBlock.InputFile");
            Assert.AreEqual(0, dataBlocks[0].StartOffset, "DataBlock.StartOffset");
            Assert.AreEqual(268, dataBlocks[0].Length, "DataBlock.Length");
            Assert.AreEqual(false, dataBlocks[0].IsFullFile, "DataBlock.IsFullFile");
            IResultNode results = TestFramework.GetResults(dataBlocks[0]);

            Assert.AreEqual(1, results.Children[0].Length, "DataBlock.StartResult.Length");
            Assert.AreEqual("correct type 1", results.Children[0].Name, "DataBlock.StartResult.Name");
            Assert.AreEqual(true, results.Children[0].Children != null && results.Children[0].Children.Count > 0, "DataBlock.StartResult.HasChildren");
            Assert.AreEqual(2, results.Children[0].Attributes.Count, "DataBlock.StartResult.Attributes.Count");

            Assert.AreEqual(inputFile, dataBlocks[1].InputFile, "DataBlock.InputFile");
            Assert.AreEqual(517, dataBlocks[1].StartOffset, "DataBlock.StartOffset");
            Assert.AreEqual(1, dataBlocks[1].Length, "DataBlock.Length");
            Assert.AreEqual(true, dataBlocks[1].IsFullFile, "DataBlock.IsFullFile");
            results = TestFramework.GetResults(dataBlocks[1]);
            Assert.AreEqual(1, results.Children[0].Length, "DataBlock.StartResult.Length");
            Assert.AreEqual("correct type 1", results.Children[0].Name, "DataBlock.StartResult.Name");
            Assert.AreEqual(false, results.Children[0].Children != null && results.Children[0].Children.Count > 0, "DataBlock.StartResult.HasChildren");
            Assert.AreEqual(2, results.Children[0].Attributes.Count, "DataBlock.StartResult.Attributes.Count");
        }
Exemple #5
0
        public void TestWriteDataBlockFile1()
        {
            string outputFilePath = string.Format("{0}{1}", _testDataFile1, @"_TestDefraser.MockDetectorSave_0000000000000000-0000000000000033.dat");

            try
            {
                IInputFile         inputFile  = Util.FindInputFile(_project1.GetInputFiles(), _testDataFile1);
                IList <IDataBlock> dataBlocks = _project1.GetDataBlocks(inputFile);
                TestFramework.SaveAsSeparateFiles(new List <object> {
                    dataBlocks[0]
                }, TestFilesPath);
                byte[] contents = new byte[51];
                Array.Copy(_fullFile1, contents, 51);
                foreach (FileInfo fi in new DirectoryInfo(TestFilesPath).GetFiles())
                {
                    Console.WriteLine(fi);
                }
                Util.AssertArrayEqualsFile(contents, outputFilePath);
            }
            finally
            {
                if (File.Exists(outputFilePath))
                {
                    File.Delete(outputFilePath);
                }
            }
        }
Exemple #6
0
        public async Task <IUpdates> SendUploadedDocument(

            IInputPeer peer,
            IInputFile file,
            string caption,
            string mimeType,
            TVector <IDocumentAttribute> attributes)
        {
            EnsureUserAuthorized();

            return(await SenderService.SendRequestAsync(new RequestSendMedia
            {
                RandomId = TlHelpers.GenerateRandomLong(),
                Background = false,
                ClearDraft = false,
                Media = new TInputMediaUploadedDocument
                {
                    File = file,
                    Caption = caption,
                    MimeType = mimeType,
                    Attributes = attributes
                },
                Peer = peer
            }).ConfigureAwait(false));
        }
Exemple #7
0
        public static async Task <string> UploadFileAsync(IInputFile file)
        {
            if (file == null || string.IsNullOrEmpty(file.Path))
            {
                _logger.Error("The file or the path of the file does not exist.");
                Environment.Exit(0);
            }

            string responseJson = string.Empty;

            try
            {
                using (var client = new HttpClient())
                    using (var fileStream = File.Open(file.Path, FileMode.Open, FileAccess.Read))
                    {
                        client.DefaultRequestHeaders.Add("apikey", _apikey);
                        var response = await client.PostAsync(_fileUrl, new StreamContent(fileStream));

                        response.EnsureSuccessStatusCode();
                        responseJson = await response.Content.ReadAsStringAsync();
                    }
            }
            catch (Exception ex)
            {
                _logger.Error(ex.Message);
                Environment.Exit(0);
            }
            return(responseJson);
        }
Exemple #8
0
        public static async Task <string> CheckHashAsync(IInputFile file)
        {
            if (file == null || string.IsNullOrEmpty(file.Hash))
            {
                _logger.Error("The file or the hash value of the file does not exist.");
                Environment.Exit(0);
            }

            string responseJson = string.Empty;

            using (var client = new HttpClient())
            {
                client.DefaultRequestHeaders.Add("apikey", _apikey);
                var url = Path.Combine(_hashLookupUrl, file.Hash);
                try
                {
                    var response = await client.GetAsync(url);

                    //Exception will be thrown when status codes do not represent success.
                    response.EnsureSuccessStatusCode();
                    responseJson = await response.Content.ReadAsStringAsync();
                }
                catch (Exception ex)
                {
                    _logger.Error(ex.Message);
                    Environment.Exit(0);
                }
            }
            return(responseJson);
        }
Exemple #9
0
        private static double GetScanRate(IInputFile inputFile)
        {
            double fileSizeInMbs = (double)inputFile.Length / (1024 * 1024);
            double seconds       = 0.001 * GetScanDuration(inputFile).TotalMilliseconds;

            return(fileSizeInMbs / seconds);
        }
Exemple #10
0
        private int SaveItem(object item, IDataReaderPool dataReaderPool, string path, OverallProgressReporter overallProgressReporter, HandledContainers handledContainers, bool createForensicIntegrityLog)
        {
            IInputFile inputFile = item as IInputFile;

            if (inputFile != null)
            {
                return(SaveInputFile(inputFile, dataReaderPool, path, overallProgressReporter, handledContainers, createForensicIntegrityLog));
            }

            IDataBlock dataBlock = item as IDataBlock;

            if (dataBlock != null)
            {
                return(SaveDataBlock(dataBlock, dataReaderPool, path, overallProgressReporter, handledContainers, createForensicIntegrityLog));
            }

            ICodecStream codecStream = item as ICodecStream;

            if (codecStream != null)
            {
                path = string.Format("{0}__{1}", path, ReplaceIllegalPathCharactersByUnderscore(codecStream.Name));
                return(SaveCodecStream(codecStream, dataReaderPool, path, overallProgressReporter, handledContainers, createForensicIntegrityLog));
            }

            return(0);                  // TODO: is this an error?
        }
Exemple #11
0
            internal DataBlock(DataBlockBuilder builder)
            {
                _appendDataPackets     = builder._appendDataPackets;
                _dataFormat            = builder.DataFormat;
                _detectors             = builder.Detectors;
                _inputFile             = builder.InputFile;
                _startOffset           = builder.StartOffset;
                _endOffset             = builder.EndOffset;
                _isFullFile            = builder.IsFullFile;
                _referenceHeaderOffset = builder.ReferenceHeaderOffset;
                _referenceHeader       = builder.ReferenceHeader;
                _codecStreams          = builder.BuildCodecStreams(this);

                IsFragmented = builder.IsFragmented;

                // Check for previous fragment and connect if one exists
                IFragment previousFragment = builder.PreviousFragment;

                if ((previousFragment != null) && previousFragment.IsFragmented)
                {
                    if (previousFragment.FragmentContainer == null)
                    {
                        previousFragment.FragmentContainer = new FragmentContainer();
                        previousFragment.FragmentContainer.Add(previousFragment);
                    }

                    FragmentContainer = previousFragment.FragmentContainer;
                    FragmentContainer.Add(this);

                    FragmentIndex = previousFragment.FragmentIndex + 1;
                }
            }
        /// <summary>
        /// This method looks for the beginning of an MPEG-4 header and if one is found it will parse it
        /// by calling Parser.Parse().
        /// </summary>
        override public IDataBlock DetectData(IDataReader dataReader, IDataBlockBuilder dataBlockBuilder, IScanContext context)
        {
            if (ReferenceHeaders != null)
            {
                var referenceHeaders = new Dictionary <IDataPacket, VideoObjectLayer>();
                foreach (IReferenceHeader header in ReferenceHeaders)
                {
                    IInputFile headerFile = context.CreateReferenceHeaderFile(header);
                    using (var parser = new Mpeg4Parser(new BitStreamDataReader(headerFile.CreateDataReader())))
                    {
                        Mpeg4Header root;
                        while (parser.ParseRoot(root = new Mpeg4Header(context.Detectors), parser.Length))
                        {
                            VideoObjectLayer vol = root.FindChild(Mpeg4HeaderName.VideoObjectLayer, true) as VideoObjectLayer;
                            if (vol != null)
                            {
                                referenceHeaders[headerFile.CreateDataPacket()] = vol;
                            }
                        }
                    }
                }

                context.ReferenceHeader = referenceHeaders;
            }

            return(Carve(dataReader, dataBlockBuilder, context));
        }
        private void ScanFile(string codecDetector)
        {
            // Locate detectors
            TestFramework.DetectorFactory.Initialize(".");
            IDetector[] containerDetectors = new IDetector[] {
                Util.FindDetector(TestFramework.DetectorFactory.ContainerDetectors, "MPEG-1/2 Systems"),
                Util.FindDetector(TestFramework.DetectorFactory.ContainerDetectors, "3GPP/QT/MP4")
            };
            IDetector[] codecDetectors = new IDetector[] {
                Util.FindDetector(TestFramework.DetectorFactory.CodecDetectors, codecDetector)
            };

            List <IDetector> detectors = new List <IDetector>();

            detectors.AddRange(containerDetectors);
            detectors.AddRange(codecDetectors);

            // Scan test file (1)
            _testFile1 = TestFramework.DetectData(containerDetectors, codecDetectors, _testProject1, FileName3GP);

            Array.Reverse(containerDetectors);

            // Scan test file (2)
            _testFile2 = TestFramework.DetectData(containerDetectors, codecDetectors, _testProject2, FileName3GP);
        }
Exemple #14
0
        private static bool CheckCodecDetectorResultForFile(IInputFile detectedFile, CodecID selectedCodec)
        {
            IList <IDataBlock> dataBlocks = detectedFile.Project.GetDataBlocks(detectedFile);

            foreach (IDataBlock fileDataBlock in dataBlocks)
            {
                if (fileDataBlock.CodecStreams.Count > 0)
                {
                    foreach (ICodecStream codecStream in fileDataBlock.CodecStreams)
                    {
                        if (codecStream.DataFormat != CodecID.Unknown)
                        {
                            if (CheckDetectors(codecStream.Detectors, selectedCodec))
                            {
                                return(true);
                            }
                        }
                    }
                }
                else if (fileDataBlock.DataFormat != CodecID.Unknown)
                {
                    if (CheckDetectors(fileDataBlock.Detectors, selectedCodec))
                    {
                        return(true);
                    }
                }
            }
            return(false);
        }
Exemple #15
0
        public IDataReader GetDataReader(IInputFile inputFile)
        {
            if (inputFile == null)
            {
                throw new ArgumentNullException("inputFile");
            }

            IDataReader dataReader;

            if (_dataReaders.TryGetValue(inputFile, out dataReader))
            {
                return(dataReader);
            }

            dataReader = new FileDataReader(new DataPacket(inputFile));
            // Add buffering decorator
            dataReader = new BufferedDataReader(dataReader, BufferSize);
            // Add progress reporting decorator
            IProgressReporter progressReporter = new FileScannerProgressReporter(_fileScanner, dataReader.Length);

            dataReader = new ProgressDataReader(dataReader, progressReporter);

            _dataReaders.Add(inputFile, dataReader);
            return(dataReader);
        }
Exemple #16
0
        private IDataPacket CreateH264StartCodePrefixDataPacket(IProject project)
        {
            string     defraserDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
            IInputFile inputFile         = _createInputFile(project, Path.Combine(defraserDirectory, "StartCodePrefix.h264"));

            return(inputFile.CreateDataPacket());
        }
        /// <inheritdoc />
        public async Task <IUpdates> SendUploadedDocumentAsync(IInputPeer peer,
                                                               IInputFile document,
                                                               string mimeType,
                                                               IReadOnlyList <IDocumentAttribute> attributes,
                                                               string message,
                                                               [AllowNull] IInputFile thumb        = null,
                                                               CancellationToken cancellationToken = default(CancellationToken))
        {
            ClientSettings.EnsureUserAuthorized();

            var request = new RequestSendMedia
            {
                RandomId   = Random.NextLong(),
                Background = false,
                ClearDraft = false,
                Message    = message,
                Media      = new TInputMediaUploadedDocument
                {
                    File       = document,
                    MimeType   = mimeType,
                    Thumb      = thumb,
                    Attributes = new TVector <IDocumentAttribute>(attributes.ToArray())
                },
                Peer = peer
            };

            return(await RequestSender.SendRequestAsync(request, cancellationToken).ConfigureAwait(false));
        }
        public void SetUp()
        {
            File.Delete(ProjectPath);

            _mockRepository              = new MockRepository();
            _inputFile1                  = MockRepository.GenerateStub <IInputFile>();
            _inputFile2                  = MockRepository.GenerateStub <IInputFile>();
            _detector1                   = MockRepository.GenerateStub <IDetector>();
            _detector2                   = MockRepository.GenerateStub <IDetector>();
            _dataBlock1                  = MockRepository.GenerateStub <IDataBlock>();
            _dataBlock2                  = MockRepository.GenerateStub <IDataBlock>();
            _dataBlock3                  = MockRepository.GenerateStub <IDataBlock>();
            _columnInfo1                 = MockRepository.GenerateStub <IColumnInfo>();
            _columnInfo2                 = MockRepository.GenerateStub <IColumnInfo>();
            _updatedColumnInfo           = MockRepository.GenerateStub <IColumnInfo>();
            _projectChangedEventHandler  = _mockRepository.StrictMock <EventHandler <ProjectChangedEventArgs> >();
            _propertyChangedEventHandler = _mockRepository.StrictMock <PropertyChangedEventHandler>();
            _createInputFile             = MockRepository.GenerateStub <Creator <IInputFile, IProject, string> >();

            _inputFile1.Stub(x => x.Name).Return(FileName1);
            _inputFile2.Stub(x => x.Name).Return(FileName2);
            _dataBlock1.Stub(x => x.InputFile).Return(_inputFile1);
            _dataBlock2.Stub(x => x.InputFile).Return(_inputFile2);
            _dataBlock3.Stub(x => x.InputFile).Return(_inputFile2);
            _columnInfo1.Stub(x => x.Name).Return(ColumnName1);
            _columnInfo1.Stub(x => x.Width).Return(ColumnWidth1);
            _columnInfo2.Stub(x => x.Name).Return(ColumnName2);
            _columnInfo2.Stub(x => x.Width).Return(ColumnWidth2);

            _project = new Project(_createInputFile, ProjectPath);

            _createInputFile.Stub(x => x(_project, FileName1)).Return(_inputFile1);
            _createInputFile.Stub(x => x(_project, FileName2)).Return(_inputFile2);
        }
Exemple #19
0
        public void TestSaveRandomResultsMultiProject()
        {
            IInputFile         inputFile1  = Util.FindInputFile(_project1.GetInputFiles(), _testDataFile1);
            IInputFile         inputFile2  = Util.FindInputFile(_project1.GetInputFiles(), _testDataFile2);
            IInputFile         inputFile3  = Util.FindInputFile(_project2.GetInputFiles(), _testDataFile3);
            IList <IDataBlock> dataBlocks1 = _project1.GetDataBlocks(inputFile1);
            IList <IDataBlock> dataBlocks2 = _project1.GetDataBlocks(inputFile2);
            IList <IDataBlock> dataBlocks3 = _project2.GetDataBlocks(inputFile3);
            IResultNode        results12   = TestFramework.GetResults(dataBlocks1[2]);
            IResultNode        results20   = TestFramework.GetResults(dataBlocks2[0]);
            IResultNode        results30   = TestFramework.GetResults(dataBlocks3[0]);

            IResultNode[] results = new IResultNode[5];
            results[0] = results30.Children[4].ShallowCopy();
            results[1] = results20.Children[0].ShallowCopy();
            results[2] = results12.Children[0].ShallowCopy();
            results[3] = results30.Children[1].ShallowCopy();
            results[4] = results20.Children[0].ShallowCopy();
            TestFramework.WriteResults(results, _testOutputFile);
            byte[] contents = new byte[57];
            Array.Copy(_fullFile3, 60, contents, 0, 15);
            Array.Copy(_fullFile2, 0, contents, 15, 5);
            Array.Copy(_fullFile1, 102, contents, 20, 17);
            Array.Copy(_fullFile3, 15, contents, 37, 15);
            Array.Copy(_fullFile2, 0, contents, 52, 5);
            Util.AssertArrayEqualsFile(contents, _testOutputFile);
        }
Exemple #20
0
        private static string GetFileName(object item)
        {
            IInputFile inputFile = item as IInputFile;

            if (inputFile != null)
            {
                return(Path.GetFileName(inputFile.Name));
            }

            IDataBlock containerStream = item as IDataBlock;

            if (containerStream != null)
            {
                return(Path.GetFileName(containerStream.InputFile.Name));
            }

            ICodecStream codecStream = item as ICodecStream;

            if (codecStream != null)
            {
                return(Path.GetFileName(codecStream.InputFile.Name));
            }

            Debug.Fail("item should be of type IInputFile, IDataBlock or ICodecStream");
            return(string.Empty);
        }
Exemple #21
0
        public void TestWriteRandomResultsFile1()
        {
            IInputFile         inputFile  = Util.FindInputFile(_project1.GetInputFiles(), _testDataFile1);
            IList <IDataBlock> dataBlocks = _project1.GetDataBlocks(inputFile);
            IResultNode        results0   = TestFramework.GetResults(dataBlocks[0]);
            IResultNode        results1   = TestFramework.GetResults(dataBlocks[1]);
            IResultNode        results2   = TestFramework.GetResults(dataBlocks[2]);
            IResultNode        results3   = TestFramework.GetResults(dataBlocks[3]);
            IResultNode        results4   = TestFramework.GetResults(dataBlocks[4]);

            IResultNode[] results = new IResultNode[5];
            results[0] = results0.Children[0].ShallowCopy();
            results[1] = results2.Children[0].ShallowCopy();
            results[2] = results4.Children[0].ShallowCopy();
            results[3] = results3.Children[0].ShallowCopy();
            results[4] = results1.Children[0].ShallowCopy();
            TestFramework.WriteResults(results, _testOutputFile);
            byte[] contents = new byte[85];
            Array.Copy(_fullFile1, 0, contents, 0, 17);
            Array.Copy(_fullFile1, 102, contents, 17, 17);
            Array.Copy(_fullFile1, 204, contents, 34, 17);
            Array.Copy(_fullFile1, 153, contents, 51, 17);
            Array.Copy(_fullFile1, 51, contents, 68, 17);
            Util.AssertArrayEqualsFile(contents, _testOutputFile);
        }
        private void ProjectManager_ProjectChanged(object sender, ProjectChangedEventArgs e)
        {
            switch (e.Type)
            {
            case ProjectChangedType.Closed:
                ClearDefaultCodecHeaders();
                break;

            case ProjectChangedType.FileDeleted:
                IInputFile inputFile = e.Item as InputFile;
                if (inputFile != null)
                {
                    List <CodecID> toRemoveKeys = new List <CodecID>();
                    foreach (KeyValuePair <CodecID, IResultNode> keyPair in _codecHeaderSource)
                    {
                        if (keyPair.Value != null && keyPair.Value.InputFile == inputFile)
                        {
                            toRemoveKeys.Add(keyPair.Key);
                        }
                    }
                    foreach (CodecID codecId in toRemoveKeys)
                    {
                        RemoveDefaultCodecHeader(codecId);
                    }
                }
                break;
            }
        }
        public static void DetectFile(string filePath, string projectFileName)
        {
            var builder = new ContainerBuilder();

            builder.RegisterModule(new FrameworkModule());
            builder.RegisterModule(new DataContractSerializerModule());

            using (var container = builder.Build())
            {
                string           detectorPath    = ConfigurationManager.AppSettings.Get("Defraser.DetectorPath") ?? AppDomain.CurrentDomain.BaseDirectory;
                IDetectorFactory detectorFactory = container.Resolve <IDetectorFactory>();
                detectorFactory.Initialize(detectorPath);

                File.Delete(projectFileName);
                ProjectManager projectManager = container.Resolve <ProjectManager>();
                IProject       project        = projectManager.CreateProject(projectFileName, "Console", DateTime.Now, "Batch process");

                IInputFile   inputFile   = project.AddFile(filePath, detectorFactory.ContainerDetectors.Union(detectorFactory.CodecDetectors));
                IFileScanner fileScanner = container.Resolve <IFileScanner>();
                fileScanner.ContainerDetectors = detectorFactory.ContainerDetectors;
                fileScanner.CodecDetectors     = detectorFactory.CodecDetectors;
                fileScanner.DataBlockDetected += (s, e) => project.AddDataBlock(e.DataBlock);
                fileScanner.Scan(inputFile, container.Resolve <IProgressReporter>());

                projectManager.SaveProject(project);
                projectManager.CloseProject(project);
            }
        }
Exemple #24
0
        public bool RunSearchHeader(IInputFile inputFile, CodecID codecId)
        {
            IProject           project    = inputFile.Project;
            IList <IDataBlock> dataBlocks = project.GetDataBlocks(inputFile);

            if (dataBlocks.Count > 0)
            {
                foreach (IDataBlock dataBlock in dataBlocks)
                {
                    if (DataBlockHasCodec(dataBlock, codecId))
                    {
                        if (dataBlock.CodecStreams.Count > 0)
                        {
                            return(SearchBlockOrStream(dataBlock.CodecStreams, SearchMode.CodecStream));
                        }
                        else
                        {
                            return(SearchBlockOrStream(dataBlock, SearchMode.DataBlock));
                        }
                    }
                }

                MessageBox.Show(this, "Selected codec stream was not found in file. Please select a different header source.",
                                "Couldn't find detector.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Close();
            }
            else
            {
                MessageBox.Show(this, "No datablocks are available. Please select a different header source.",
                                "Couldn't detect keyframe.", MessageBoxButtons.OK, MessageBoxIcon.Error);
                Close();
            }
            return(false);
        }
Exemple #25
0
        public virtual void TestFixtureSetup()
        {
            File.Delete(DataFileName);

            _fibonacci = new byte[DataFileSize];
            Buffer     = new byte[ReadBufferSize];
            InputFile  = MockRepository.GenerateStub <IInputFile>();
            InputFile.Stub(x => x.Name).Return(DataFileName);
            InputFile.Stub(x => x.Length).Return(DataFileSize);

            // Generate fibonacci numbers (periodic function)
            _fibonacci[0] = 0;
            _fibonacci[1] = 1;
            for (int i = 2; i < _fibonacci.Length; i++)
            {
                _fibonacci[i] = (byte)(_fibonacci[i - 1] + _fibonacci[i - 2]);
            }

            // Write test data to file
            using (FileStream fileStream = new FileStream(DataFileName, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                fileStream.Write(_fibonacci, 0, _fibonacci.Length);
                fileStream.Flush();
            }
        }
Exemple #26
0
            public void CountNumberOfParts(IEnumerable <object> items)
            {
                int codecStreamCount     = 0;
                int containerStreamCount = 0;
                int uniqueStreamCount    = 0;
                HashSet <IFragmentContainer> handledFragmentContainers = new HashSet <IFragmentContainer>();
                HashSet <Pair <IFragmentContainer, string> > handledFragmentContainerStreams = new HashSet <Pair <IFragmentContainer, string> >();

                foreach (object item in items)
                {
                    IInputFile   inputFile       = item as IInputFile;
                    IDataBlock   containerStream = item as IDataBlock;
                    ICodecStream codecStream     = item as ICodecStream;

                    if (inputFile != null)
                    {
                        IList <IDataBlock> dataBlocks = inputFile.Project.GetDataBlocks(inputFile);
                        containerStreamCount += dataBlocks.Count;

                        foreach (IDataBlock dataBlock in dataBlocks)
                        {
                            codecStreamCount  += dataBlock.CodecStreams.Count;
                            uniqueStreamCount += CountUniqueStreams(handledFragmentContainers, handledFragmentContainerStreams, dataBlock);
                        }
                    }
                    else if (containerStream != null)
                    {
                        containerStreamCount++;
                        codecStreamCount  += containerStream.CodecStreams.Count;
                        uniqueStreamCount += CountUniqueStreams(handledFragmentContainers, handledFragmentContainerStreams, containerStream);
                    }
                    else if (codecStream != null)
                    {
                        // Count the number of fragments for this codecStream.
                        //  The codec stream can be part of a fragmented codec stream
                        //  which on its turn can be part of a fragmented container stream
                        if (codecStream.DataBlock.FragmentContainer != null)
                        {
                            foreach (IDataBlock containerFragment in codecStream.DataBlock.FragmentContainer)
                            {
                                codecStreamCount += CountCodecStreamFragments(containerFragment, codecStream.Name);
                            }
                        }
                        else
                        {
                            codecStreamCount += CountCodecStreamFragments(codecStream.DataBlock, codecStream.Name);
                        }
                        if (FragmentedStreamAlreadySaved(handledFragmentContainers, handledFragmentContainerStreams, codecStream) == false)
                        {
                            uniqueStreamCount++;
                        }
                    }
                }

                // Progress is reported for each:
                // - codec stream (twice, once during DetectData and once during GetDataPacket)
                // - container stream and codec stream that is saved
                _partCount = codecStreamCount * 2 + containerStreamCount + uniqueStreamCount;
            }
Exemple #27
0
        public virtual void TestFixtureTeardown()
        {
            File.Delete(DataFileName);

            _fibonacci = null;
            Buffer     = null;
            InputFile  = null;
        }
Exemple #28
0
        private IDataBlockBuilder CreateBuilder(IInputFile file)
        {
            IDataBlockBuilder builder = TestFramework.CreateDataBlockBuilder();

            builder.Detectors = new[] { _detector };
            builder.InputFile = file;
            return(builder);
        }
Exemple #29
0
 private void ResetAllScanAttributes()
 {
     _activeScanFile           = null;
     _currentDataBlocks        = null;
     _currentDataBlockIndex    = -1;
     _currentValidCodecStreams = null;
     _currentCodecStreamIndex  = -1;
 }
Exemple #30
0
 public void TearDown()
 {
     _inputFile   = null;
     _dataReader  = null;
     _root        = null;
     _header      = null;
     _childHeader = null;
     _lastHeader  = null;
 }
Exemple #31
0
            private async Task SetProfilePhoto(Telegram service, TelegramClient client, IInputFile inputFile)
            {
                var iPhoto = await client.Methods.PhotosUploadProfilePhotoAsync(new PhotosUploadProfilePhotoArgs
                {
                    Caption = "",
                    Crop = new InputPhotoCropAuto(),
                    File = inputFile,
                    GeoPoint = new InputGeoPointEmpty()
                });

                var photo = iPhoto as PhotosPhoto;
                if (photo != null)
                {
                    service.Dialogs.AddUsers(photo.Users);
                }

                var photoObj = photo.Photo as Photo;

                if (photoObj == null)
                {
                    return;
                }

                await client.Methods.PhotosUpdateProfilePhotoAsync(new PhotosUpdateProfilePhotoArgs
                {
                    Id = new InputPhoto
                    {
                        Id = photoObj.Id,
                    },
                    Crop = new InputPhotoCropAuto()
                });
            }
Exemple #32
0
        private void SendFile(VisualBubble bubble, IInputFile inputFile)
        {
            var inputPeer = GetInputPeer(bubble.Address, bubble.Party, bubble.ExtendedParty);
            var imageBubble = bubble as ImageBubble;
            var fileBubble = bubble as FileBubble;
            var audioBubble = bubble as AudioBubble;

            using (var client = new FullClientDisposable(this))
            {
                if (imageBubble != null)
                {

                    var iUpdates = TelegramUtils.RunSynchronously(
                        client.Client.Methods.MessagesSendMediaAsync(new MessagesSendMediaArgs
                        {

                            Flags = 0,
                            Peer = inputPeer,
                            Media = new InputMediaUploadedPhoto
                            {
                                Caption = "",
                                File = inputFile,
                            },
                            RandomId = GenerateRandomId(),
                        }));
                    var messageId = GetMessageId(iUpdates);
                    imageBubble.IdService = messageId;
                    var updates = iUpdates as Updates;

                    SendToResponseDispatcher(iUpdates, client.Client);
                }
                else if (fileBubble != null)
                {
                    var documentAttributes = new List<IDocumentAttribute>
                    {
                        new DocumentAttributeFilename
                        {
                            FileName = fileBubble.FileName
                        }
                    };
                    var iUpdates = TelegramUtils.RunSynchronously(
                        client.Client.Methods.MessagesSendMediaAsync(new MessagesSendMediaArgs
                        {

                            Flags = 0,
                            Peer = inputPeer,
                            Media = new InputMediaUploadedDocument
                            {
                                Attributes = documentAttributes,
                                Caption = "",
                                File = inputFile,
                                MimeType = fileBubble.MimeType,
                            },
                            RandomId = GenerateRandomId(),
                        }));
                    var messageId = GetMessageId(iUpdates);
                    fileBubble.IdService = messageId;
                    SendToResponseDispatcher(iUpdates, client.Client);

                }
                else if (audioBubble != null)
                {
                    var documentAttributes = new List<IDocumentAttribute>();

                    if (audioBubble.Recording)
                    {
                        documentAttributes.Add(new DocumentAttributeAudio
                        {
                            Flags = 1024,
                            Duration = (uint)audioBubble.Seconds,
                            Voice = new True()
                        });
                    }
                    else if (audioBubble.FileName != null)
                    {
                        documentAttributes.Add(new DocumentAttributeAudio
                        {
                            Flags = 1,
                            Duration = (uint)audioBubble.Seconds,
                            Title = audioBubble.FileName
                        });
                    }
                    else 
                    {
                        documentAttributes.Add(new DocumentAttributeAudio
                        {
                            Flags = 0,
                            Duration = (uint)audioBubble.Seconds
                        });
                    }

                    var mimeType = Platform.GetMimeTypeFromPath(audioBubble.AudioPath);
                    var inputMedia = new InputMediaUploadedDocument
                    {
                        Attributes = documentAttributes,
                        Caption = "",
                        File = inputFile,
                        MimeType = mimeType,
                    };

                    var media = new MessagesSendMediaArgs
                    {
                        Flags = 0,
                        Media = inputMedia,
                        Peer = inputPeer,
                        RandomId = GenerateRandomId(),
                    };
                    var iUpdates = TelegramUtils.RunSynchronously(
                        client.Client.Methods.MessagesSendMediaAsync(media));
                    var messageId = GetMessageId(iUpdates);
                    audioBubble.IdService = messageId;
                    SendToResponseDispatcher(iUpdates, client.Client);
                }
            }
        }