Пример #1
0
        private DownloadType IdentifyFileType(IFileProvider provider)
        {
            if (provider.FileExists("beatonmod.json"))
            {
                return(DownloadType.ModFile);
            }
            else if (provider.FileExists("info.dat"))
            {
                return(DownloadType.SongFile);
            }
            else if (provider.FileExists("info.json"))
            {
                return(DownloadType.OldSongFile);
            }
            else
            {
                var files = provider.FindFiles("*");
                //check if all of the files are .json files, and guess that maybe it's a playlist or two
                if (!files.Any(x => !x.ToLower().EndsWith(".json")))
                {
                    //going to guess maybe this is a playlist, becuase there aren't any other options right now
                    return(DownloadType.Playlist);
                }
            }

            return(DownloadType.Unknown);
        }
Пример #2
0
        private async Task SafeMoveFile(string source, string dest, string temp, bool copy)
        {
            string swapPath = null;

            try {
                if (copy)
                {
                    await _fileService.Copy(source, temp);
                }
                else
                {
                    await Task.Run(() => _fileService.Move(source, temp));
                }

                if (_fileService.FileExists(dest))
                {
                    swapPath = PathUtil.GetTempFilePath(dest);
                    _fileService.Move(dest, swapPath);
                }

                _fileService.Move(temp, dest);
            }
            finally {
                if (_fileService.FileExists(temp))
                {
                    _fileService.Delete(temp);
                }
                if (swapPath != null && _fileService.FileExists(swapPath) && _fileService.FileExists(dest))
                {
                    _fileService.Delete(swapPath);
                }
            }
        }
Пример #3
0
        public void FileProvider_FileExists()
        {
            Assert.IsFalse(FileProvider.FileExists(Constants.FileName));

            Setup.CreateEmptyFile(Constants.FilePath);

            Assert.IsTrue(FileProvider.FileExists(Constants.FileName));
        }
        public object Get(string id)
        {
            FileId fileId = FileId.FromUuid(id);

            if (!_provider.FileExists(fileId.PhysicalPath) && !_provider.DirectoryExists(fileId.PhysicalPath))
            {
                return(NotFound());
            }

            return(_helper.ToJsonModel(fileId.PhysicalPath));
        }
Пример #5
0
        public IActionResult Head(string id)
        {
            FileId fileId = FileId.FromUuid(id);

            if (!_fileProvider.FileExists(fileId.PhysicalPath))
            {
                return(NotFound());
            }

            AddHttpLinkHeader(fileId);

            Context.Response.WriteFileContentHeaders(fileId.PhysicalPath, _fileProvider);

            return(new EmptyResult());
        }
Пример #6
0
        public SetupSettings LoadSettings(string setupSettingsFilePath = null)
        {
            if (_setupSettings != null && _setupSettings.HasSetupDatabase && _setupSettings.HasSeededData)
            {
                return(_setupSettings);
            }

            setupSettingsFilePath ??= SetupSettingsConst.SetupConfigurationPath;
            if (!_fileProvider.FileExists(setupSettingsFilePath))
            {
                var installSettings = new SetupSettings()
                {
                    IsInitialized = true,
                    CreateDatabaseScriptFilePath = SetupSettingsConst.CreateDatabaseSchemaPath,
                    SeedDataJsonFilePath         = SetupSettingsConst.PrepareDataPath
                };

                SaveSettings(installSettings, setupSettingsFilePath);
                _setupSettings.IsInitialized = true;
                return(installSettings);
            }

            var settingText = _fileProvider.ReadText(setupSettingsFilePath, Encoding.UTF8);

            if (string.IsNullOrEmpty(settingText))
            {
                return(new SetupSettings());
            }

            var setupSettings = JsonConvert.DeserializeObject <SetupSettings>(settingText);

            _setupSettings.HasSetupDatabase = setupSettings.HasSetupDatabase;
            _setupSettings.HasSeededData    = setupSettings.HasSeededData;
            return(setupSettings);
        }
Пример #7
0
        public virtual IEnumerable <ItemType> ProcessOperation(IEnumerable <Definitions.ObjectType> objectTypes)
        {
            List <ItemType> itemTypes = new List <ItemType>();

            foreach (var objectType in objectTypes)
            {
                var possibleFileItems = this.ProcessOperation(objectType);
                foreach (var possibleItem in possibleFileItems)
                {
                    var filepathValue = GetCompleteFilepath(possibleItem);
                    if (!FileProvider.FileExists(filepathValue))
                    {
                        possibleItem.status = StatusEnumeration.doesnotexist;
                    }

                    itemTypes.Add(possibleItem);
                }
            }

            if (itemTypes.Count > 1)
            {
                return(itemTypes.Where(item => item.status != StatusEnumeration.doesnotexist));
            }

            return(itemTypes);
        }
        internal string UpdateFile(dynamic model, string physicalPath)
        {
            DateTime?created      = null;
            DateTime?lastAccess   = null;
            DateTime?lastModified = null;

            var file = _fileProvider.GetFile(physicalPath);

            if (model == null)
            {
                throw new ApiArgumentException("model");
            }

            created      = DynamicHelper.To <DateTime>(model.created);
            lastAccess   = DynamicHelper.To <DateTime>(model.last_access);
            lastModified = DynamicHelper.To <DateTime>(model.last_modified);

            if (model.name != null)
            {
                string name = DynamicHelper.Value(model.name);

                if (!PathUtil.IsValidFileName(name))
                {
                    throw new ApiArgumentException("name");
                }

                var newPath = Path.Combine(file.Parent.Path, name);

                if (!newPath.Equals(physicalPath, StringComparison.OrdinalIgnoreCase))
                {
                    if (_fileProvider.FileExists(newPath) || _fileProvider.DirectoryExists(newPath))
                    {
                        throw new AlreadyExistsException("name");
                    }

                    _fileProvider.Move(physicalPath, newPath);

                    physicalPath = newPath;
                }
            }

            _fileProvider.SetFileTime(physicalPath, lastAccess, lastModified, created);

            return(physicalPath);
        }
Пример #9
0
        public static bool Patch(IFileProvider apk, FilePatch patch)
        {
            string binaryFile = patch.Filename;

            if (!apk.FileExists(binaryFile))
            {
                Console.WriteLine("Binary file to patch doesn't exist in the APK!");
                return(false);
            }
            byte[] binaryBytes = apk.Read(binaryFile);
            if (binaryBytes.Length != patch.ExpectedFileSize)
            {
                Console.WriteLine("Binary file to patch is the wrong length!");
                return(false);
            }
            List <Patch> toApply = new List <Patch>();

            Console.WriteLine("Verifying patches binary...");
            using (MemoryStream msBinary = new MemoryStream(binaryBytes))
            {
                //verify each of the patches can be applied or already are applied
                foreach (Patch p in patch.Patches)
                {
                    msBinary.Seek(p.Address, SeekOrigin.Begin);
                    byte[] readVals = new byte[p.ExpectedData.Count];
                    msBinary.Read(readVals, 0, p.ExpectedData.Count);

                    if (!readVals.SequenceEqual(p.ExpectedData))
                    {
                        msBinary.Seek(p.Address, SeekOrigin.Begin);
                        readVals = new byte[p.PatchData.Count];
                        msBinary.Read(readVals, 0, p.PatchData.Count);
                        if (readVals.SequenceEqual(p.PatchData))
                        {
                            Console.WriteLine($"Patch {p.Name} already appears to be applied.");
                            continue;
                        }
                        else
                        {
                            Console.WriteLine($"Patch {p.Name} can't be applied to this binary, the code at the patch location doesn't match what was expected.  Aborting any patching...");
                            //if one patch can't be applied, abort the whole thing
                            return(false);
                        }
                    }
                }
                foreach (Patch p in toApply)
                {
                    msBinary.Seek(p.Address, SeekOrigin.Begin);
                    msBinary.Write(p.PatchData.ToArray(), 0, p.PatchData.Count);
                }
                msBinary.Seek(0, SeekOrigin.Begin);

                apk.Write(binaryFile, msBinary.ToArray(), true, true);
            }
            Console.WriteLine("Done patching binary!");
            return(true);
        }
        public IActionResult Head(string id)
        {
            var dl = _downloadService.Get(id);

            if (dl == null)
            {
                return(NotFound());
            }

            if (!_fileProvider.FileExists(dl.PhysicalPath))
            {
                _downloadService.Remove(dl.Id);
                return(NotFound());
            }

            Context.Response.WriteFileContentHeaders(dl.PhysicalPath, _fileProvider);

            return(new EmptyResult());
        }
Пример #11
0
        private static string FindFirstOfSplit(IFileProvider fp, string assetsFile)
        {
            int lastDot = assetsFile.LastIndexOf('.');

            if (lastDot > 0)
            {
                string afterDot = assetsFile.Substring(lastDot, assetsFile.Length - lastDot);
                string noSplit;
                if (afterDot.ToLower().StartsWith(".split"))
                {
                    noSplit = assetsFile.Substring(0, lastDot);
                    if (fp.FileExists(noSplit))
                    {
                        return(noSplit);
                    }
                }
                else
                {
                    noSplit = assetsFile;
                }
                if (fp.FileExists(noSplit))
                {
                    return(noSplit);
                }

                var split0 = noSplit + ".split0";
                if (fp.FileExists(split0))
                {
                    return(split0);
                }
            }
            else if (fp.FileExists(assetsFile))
            {
                return(assetsFile);
            }
            else if (fp.FileExists(assetsFile + ".split0"))
            {
                return(assetsFile + ".split0");
            }

            return(null);
        }
        public object Get(string id)
        {
            FileId fileId = new FileId(id);
            Site   site   = SiteHelper.GetSite(fileId.SiteId);

            if (site == null)
            {
                return(NotFound());
            }

            var physicalPath = FilesHelper.GetPhysicalPath(site, fileId.Path);

            if (!_fileProvider.FileExists(physicalPath) && !_fileProvider.DirectoryExists(physicalPath))
            {
                return(NotFound());
            }

            var fields = Context.Request.GetFields();

            return(_filesHelper.ToJsonModel(site, fileId.Path, fields));
        }
        public IActionResult Post([FromBody] dynamic model)
        {
            if (_downloadService == null)
            {
                throw new NotFoundException(typeof(IDownloadService).GetTypeInfo().Assembly.FullName);
            }

            if (model == null)
            {
                throw new ApiArgumentException("model");
            }
            if (model.file == null)
            {
                throw new ApiArgumentException("file");
            }
            if (!(model.file is JObject))
            {
                throw new ApiArgumentException("file", ApiArgumentException.EXPECTED_OBJECT);
            }

            //
            // Check Id
            string fileUuid = DynamicHelper.Value(model.file.id);

            if (fileUuid == null)
            {
                throw new ApiArgumentException("file.id");
            }

            int?ttl = DynamicHelper.To <int>(model.ttl);

            FileId fileId = FileId.FromUuid(fileUuid);

            if (!_fileService.FileExists(fileId.PhysicalPath))
            {
                throw new NotFoundException(fileId.PhysicalPath);
            }

            var dl = _downloadService.Create(fileId.PhysicalPath, ttl);

            // Inform client location points to downloadable attachment
            Context.Response.Headers.Add("Pragma", "attachment");

            return(Created(dl.Href, null));
        }
Пример #14
0
        public void ClearOrphanSources()
        {
            foreach (var generatedFile in fileProvider.GetAllFiles(generatedDirectory, ".g.cs"))
            {
                var outputFile = Path.Combine(generatedDirectory, generatedFile);
                var inputFile  = MakeInputFilePath(outputFile);

                if (inputFile == null)
                {
                    continue;                    // 뭔가 문제가 있으면 하지 않는다
                }
                if (!fileProvider.FileExists(inputFile))
                {
                    Console.Error.WriteLine($"{Path.GetFullPath(outputFile)}(1, 1): warning PR0004: removed, input file doesn't exist({inputFile})");
                    fileProvider.RemoveFile(outputFile);
                }
            }
        }
Пример #15
0
        private ModDefinition LoadModDef(IFileProvider provider, string path = "")
        {
            ModDefinition def = null;

            if (!provider.FileExists(path.CombineFwdSlash(MOD_FILE_NAME)))
            {
                throw new Exception($"ModDefinition can't load zip file becase it does not contain {MOD_FILE_NAME}");
            }
            using (JsonTextReader jr = new JsonTextReader(new StreamReader(provider.GetReadStream(path.CombineFwdSlash(MOD_FILE_NAME)))))
            {
                def = new JsonSerializer().Deserialize <ModDefinition>(jr);
            }
            if (def == null)
            {
                throw new Exception("ModDefinition failed to deserialize.");
            }

            return(def);
        }
Пример #16
0
        // TODO maybe move some (or all) of this to the TemplateResolver
        public static TemplateInfo Load(TemplateResolver resolver, IFileProvider source, string name)
        {
            string specPath = System.IO.Path.Combine(name, Template.TemplateDefinitionFileName);
            if (!source.FileExists(specPath))
                throw new FileNotFoundException("Couldn't find template specification: " + specPath + " from " + source.ToString(), specPath);

            Dictionary<string, TemplateParameterInfo> parameters = new Dictionary<string, TemplateParameterInfo>();

            TemplateInfo inheritedTemplate = null;

            using (var fileStream = source.OpenFile(specPath, FileMode.Open))
            {
                XDocument templateSpec = XDocument.Load(fileStream);
                XAttribute inheritsAttr = templateSpec.Element("template").Attribute("inherits");
                
                if (inheritsAttr != null)
                {
                    string inheritedTemplateName = inheritsAttr.Value;
                    if (!resolver.TryResolve(inheritedTemplateName, out inheritedTemplate))
                        throw new Exception("Failed to resolve inherted template: " + inheritedTemplateName);

                    // add inherited parameters
                    foreach (TemplateParameterInfo param in inheritedTemplate.Parameters)
                        parameters.Add(param.Name, param);
                }

                IEnumerable<XElement> parameterElements = templateSpec.XPathSelectElements("/template/parameter");
                foreach (XElement parameterElement in parameterElements)
                {
                    string paramName = parameterElement.Attribute("name").Value;
                    string defaultValue = ReadOptionalAttribute(parameterElement, "select");
                    string description = ReadOptionalAttribute(parameterElement, "description");

                    // add or override inherited parameter default value
                    parameters[paramName] = new TemplateParameterInfo(paramName, description, defaultValue);
                }
            }

            return new TemplateInfo(source, specPath, name, parameters.Values.ToArray(), inheritedTemplate);
        }
Пример #17
0
 public bool FileExists(string fileName) =>
 _fileProvider.FileExists(fileName);
Пример #18
0
 public bool FileExists(string fileName)
 {
     return(_fileProvider.FileExists(fileName));
 }
Пример #19
0
 /// <summary>
 /// Attempts to locate all of the dependencies required by LibDDS
 /// </summary>
 /// <param name="fileProvider">File provider</param>
 /// <returns>True if LibDDS is available, otherwise false</returns>
 public static bool FindDependencies(IFileProvider fileProvider)
 {
     IsAvailable = fileProvider.FileExists("LibDDS.dll");
     return(IsAvailable);
 }
Пример #20
0
 public static bool FindDependencies(IFileProvider fileProvider)
 {
     return(fileProvider.FileExists("oo2core_7_win64.dll"));
 }
Пример #21
0
        public object Post([FromBody] dynamic model)
        {
            string   name;
            FileType fileType;
            FileId   fileId, parentId;

            _helper.EnsurePostModelValid(model, out name, out fileId, out parentId);

            try {
                fileType = FilesHelper.GetFileType(fileId.PhysicalPath);
            }
            catch (FileNotFoundException) {
                throw new NotFoundException("file");
            }

            if (!_fileService.DirectoryExists(parentId.PhysicalPath))
            {
                throw new NotFoundException("parent");
            }

            var src = fileType == FileType.File ? _fileService.GetFile(fileId.PhysicalPath) : _fileService.GetDirectory(fileId.PhysicalPath);

            string destPath = Path.Combine(parentId.PhysicalPath, name == null ? src.Name : name);

            if (PathUtil.IsAncestor(src.Path, destPath) || src.Path.Equals(destPath, StringComparison.OrdinalIgnoreCase))
            {
                throw new ApiArgumentException("parent", "The destination folder is a subfolder of the source");
            }

            if (fileType == FileType.File && _fileService.DirectoryExists(destPath) || fileType == FileType.Directory && _fileService.FileExists(destPath))
            {
                throw new AlreadyExistsException("name");
            }

            MoveOperation copy = InitiateCopy(src, destPath);

            Context.Response.StatusCode = (int)HttpStatusCode.Accepted;
            Context.Response.Headers.Add("Location", MoveHelper.GetLocation(copy.Id, true));

            return(_helper.ToJsonModel(copy));
        }