// Add subtitle 'file' to the database // Used in FolderController public bool AddFile(HttpPostedFileBase file, Folder folder, SubFile subfile) { // Nær í skráarendinguna á textaskránni string extension = Path.GetExtension(file.FileName); // Athugar hvort skráin sé á löglegu formi (.srt ending) if (extension != ".srt") { return false; } // Tengja textaskrána við möppu og gefa henni nafn subfile.FolderID = folder.ID; // Mun halda utan um nafnið á þýðingarskránni string transName; if (subfile.LanguageID == 1) // Textaskráni er ensk og þýðingin íslensk { subfile.SubName = file.FileName.Substring(0, file.FileName.Count() - 4) + ".en.srt"; transName = file.FileName.Substring(0, file.FileName.Count() - 4) + ".is.srt"; } else // Textaskráni er íslensk og þýðingin ensk { subfile.SubName = file.FileName.Substring(0, file.FileName.Count() - 4) + ".is.srt"; transName = file.FileName.Substring(0, file.FileName.Count() - 4) + ".en.srt"; } // Setja möppuna og textaskrána í gagnagrunninn db.Folders.Add(folder); db.SubFiles.Add(subfile); SubFile trans = new SubFile() { FolderID = folder.ID, SubName = transName, LanguageID = 2 }; if (subfile.LanguageID == 2) { trans.LanguageID = 1; } // Setja þýðinguna í gagnagrunninn db.SubFiles.Add(trans); db.SaveChanges(); if (!ReadFile(file, folder, subfile, trans)) { return false; } return true; }
////////////////////////////////////////////////////////////////////////////////////////////////////// // Leer fichero ANA ////////////////////////////////////////////////////////////////////////////////////////////////////// private void buttonANA_Click(object sender, EventArgs e) { uint anafile_size; uint subfiles_count; if (openFileDialog.ShowDialog() == DialogResult.OK) { Files.Clear(); // Borrar archivos anteriores listBox.Items.Clear(); // Borrar lista anterior filename = openFileDialog.FileName; labelFilename.Text = Path.GetFileName(filename); BinaryReader file = new BinaryReader(File.Open(filename, FileMode.Open)); if (file.ReadUInt32() != 0x414E4140) // 40 41 4E 41 { MessageBox.Show("Incorrect header. Correct file?"); file.Close(); return; } file.ReadUInt32(); // Read (non)padding anafile_size = file.ReadUInt32(); // Read ANA size file.ReadUInt32(); // Read (non)padding subfiles_count = file.ReadUInt32(); file.ReadUInt32(); file.ReadUInt32(); file.ReadUInt32(); // Read padding for (uint i = 0; i < subfiles_count; i++) { SubFile temp = new SubFile(); temp.offset = file.ReadUInt32(); temp.size = file.ReadUInt32(); temp.filename = new String(file.ReadChars(8)).Trim('\0'); Files.Add(temp); listBox.Items.Add(temp.filename); } listBox.Sorted = false; // Meter el contenido de cada fichero en un buffer, para no liar el reemplazo demasiado for (int i = 0; i < Files.Count; i++) { file.BaseStream.Seek(Files[i].offset, SeekOrigin.Begin); Files[i].buffer = file.ReadBytes((int)Files[i].size); } // experimental // copiar fragmento ANT a un buffer para luego file.BaseStream.Seek(Files[Files.Count - 1].offset + Files[Files.Count - 1].size, SeekOrigin.Begin); ant_section = file.ReadBytes((int)file.BaseStream.Length - (int)file.BaseStream.Position); // experimental file_type = "ana"; file.Close(); } }
public ActionResult Create([Bind(Include="ID,CategoryID,FolderName,Link,Poster,Description,DateCreated")] Folder folder, HttpPostedFileBase file, SubFile subfile, int? requestID) { if (ModelState.IsValid) { if (!repo.AddFile(file, folder, subfile)) { return View("WrongFile"); } if (!repo.RequestFinished(requestID)) { return View("Error"); } repo.Save(); return RedirectToAction("Details", new { id = folder.ID }); } return View(folder); }
////////////////////////////////////////////////////////////////////////////////////////////////////// // Leer fichero XBB ////////////////////////////////////////////////////////////////////////////////////////////////////// private void buttonXBB_Click(object sender, EventArgs e) { if (openFileDialog.ShowDialog() == DialogResult.OK) { filename = openFileDialog.FileName; labelFilename.Text = Path.GetFileName(filename); BinaryReader file = new BinaryReader(File.Open(filename, FileMode.Open)); if (file.ReadUInt32() != 0x01424258) // 58 42 42 01 02 { MessageBox.Show("Incorrect header. Correct file?"); file.Close(); return; } file.ReadBytes(28); // Read padding Files.Clear(); // Borrar archivos anteriores listBox.Items.Clear(); // Borrar lista anterior while (true) // Leer los datos de los archivos contenidos { SubFile temp = new SubFile(); // Crear archivo temporal temp.offset = file.ReadUInt32(); // leer offset de inicio if (temp.offset > file.BaseStream.Length) // si el offset es mayor que el tamaño del archivo { break; } // es que ya no hay mas archivos temp.size = file.ReadUInt32(); // Tamaño del archivo temp.name_offset = file.ReadUInt32(); // posicion del nombre temp.identifier = file.ReadUInt32(); // identificador Files.Add(temp); // añadirlo a la lista de archivos } file.BaseStream.Seek(-4, SeekOrigin.Current); // Volver atras para leer el identificador for (int i = 0; i < Files.Count; i++) // Hay tantos ids como archivos conocidos { uint temp = file.ReadUInt32(); // leer el id for (int j = 0; j < Files.Count; j++) // buscar el archivo con ese id { if (Files[j].identifier == temp) { Files[j].ordinal = file.ReadUInt32(); } } // leer el ordinal } for (int i = 0; i < Files.Count; i++) // leer los nombres de cada archivo { file.BaseStream.Seek(Files[i].name_offset, SeekOrigin.Begin); // mover el puntero al offset del nombre char[] temp = new char[256]; while (true) { char temp2 = file.ReadChar(); if (temp2 == 0x00) { break; } // si es null terminar temp.SetValue(temp2, temp.Count(p => p != 0x00)); // ir añadiendo los caracteres } Files[i].filename = new String(temp).Trim('\0'); // asignar el nombre completo sin nulls string temp3 = Files[i].ordinal.ToString("D2"); temp3 += " "; temp3 += Files[i].filename; temp3 += " "; temp3 += Files[i].size.ToString(); temp3 += " "; temp3 += Files[i].offset.ToString(); listBox.Items.Add(temp3); // añadir la informacion al listbox } listBox.Sorted = true; // Meter el contenido de cada fichero en un buffer, para no liar el reemplazo demasiado for (int i = 0; i < Files.Count; i++) { file.BaseStream.Seek(Files[i].offset, SeekOrigin.Begin); Files[i].buffer = file.ReadBytes((int)Files[i].size); } file_type = "xbb"; file.Close(); // cerrar el archivo } }
// Read subtitle 'file' and add the lines to the database // Used in FolderController public bool ReadFile(HttpPostedFileBase file, Folder folder, SubFile subfile, SubFile trans) { //// Vistar textaskrána í ~/App_Data/Uploads //// Nær eingöngu í nafnið á skránni //var fileName = Path.GetFileName(file.FileName); //// store the file inside ~/App_Data/uploads folder //var path = Path.Combine(HttpContext.Current.Server.MapPath("~/App_Data/Uploads"), fileName); //file.SaveAs(path); //Regex reTime = new Regex(@"^(\d{1,2})(:\d{1,2})(:\d{1,2})(,\d{1,3})$"); List<string> _list = new List<string>(); using (StreamReader s = new StreamReader(file.InputStream, Encoding.GetEncoding("iso-8859-1"))) { string currLine; while ((currLine = s.ReadLine()) != null) { int value; // Línunúmer í textaskránni // 'currLine' er borið saman við 'value' til að // kanna hvort það sé heiltala. if ((int.TryParse(currLine, out value))) { _list.Add(currLine); // Tímalínurnar í textaskránni currLine = s.ReadLine(); if (currLine.Length < 17) { return false; } _list.Add(currLine.Substring(0, 12)); _list.Add(currLine.Substring(17)); } else // Textinn sjálfur { // Ef textinn er í meira en einni línu string nextLine = s.ReadLine(); while (nextLine != "") { if (nextLine == null) { break; } currLine += "\n" + nextLine; nextLine = s.ReadLine(); } _list.Add(currLine); } } } for (int i = 0; i < _list.Count(); ++i) { db.SubFileLines.Add(new SubFileLine() { SubFileID = subfile.ID, LineNumber = Convert.ToInt32(_list[i]), StartTime = _list[++i], EndTime = _list[++i], LineText = _list[++i] }); } // Nær í línurnar sem var verið að setja í gagnagrunninn IEnumerable<SubFileLine> subLines = subfile.SubFileLines.ToList(); ; foreach (var line in subLines) { // Býr til nýja línu, tengir hana við þýðingarskrána // og setur hana í gagnagrunninn db.SubFileLines.Add(new SubFileLine() { SubFileID = trans.ID, LineNumber = line.LineNumber, StartTime = line.StartTime, EndTime = line.EndTime, LineText = "" }); } return true; }
public byte[] GetFile(SubFile file) { rawStream.Seek(dataStart + file.Offset, SeekOrigin.Begin); return(rawStream.ReadBytes((int)file.Size)); }
public async Task <List <FileSystemStorageItemBase> > GetChildItemsAsync(bool IncludeHiddenItems, ItemFilters Filter = ItemFilters.File | ItemFilters.Folder) { if (WIN_Native_API.CheckLocationAvailability(Path)) { return(WIN_Native_API.GetStorageItems(Path, IncludeHiddenItems, Filter)); } else { LogTracer.Log($"Native API could not enum subitems in path: \"{Path}\", fall back to UWP storage API"); try { if (await GetStorageItemAsync() is StorageFolder Folder) { QueryOptions Options = new QueryOptions { FolderDepth = FolderDepth.Shallow, IndexerOption = IndexerOption.UseIndexerWhenAvailable }; Options.SetThumbnailPrefetch(Windows.Storage.FileProperties.ThumbnailMode.ListView, 150, Windows.Storage.FileProperties.ThumbnailOptions.UseCurrentScale); Options.SetPropertyPrefetch(Windows.Storage.FileProperties.PropertyPrefetchOptions.BasicProperties, new string[] { "System.Size", "System.DateModified" }); StorageItemQueryResult Query = Folder.CreateItemQueryWithOptions(Options); uint Count = await Query.GetItemCountAsync(); List <FileSystemStorageItemBase> Result = new List <FileSystemStorageItemBase>(Convert.ToInt32(Count)); for (uint i = 0; i < Count; i += 30) { IReadOnlyList <IStorageItem> CurrentList = await Query.GetItemsAsync(i, 30); foreach (IStorageItem Item in CurrentList.Where((Item) => (Item.IsOfType(StorageItemTypes.Folder) && Filter.HasFlag(ItemFilters.Folder)) || (Item.IsOfType(StorageItemTypes.File) && Filter.HasFlag(ItemFilters.File)))) { if (Item is StorageFolder SubFolder) { Result.Add(new FileSystemStorageFolder(SubFolder, await SubFolder.GetThumbnailBitmapAsync(), await SubFolder.GetModifiedTimeAsync())); } else if (Item is StorageFile SubFile) { Result.Add(new FileSystemStorageFile(SubFile, await SubFile.GetThumbnailBitmapAsync(), await SubFile.GetSizeRawDataAsync(), await SubFile.GetModifiedTimeAsync())); } } } return(Result); } else { return(new List <FileSystemStorageItemBase>(0)); } } catch { LogTracer.Log($"UWP API could not enum subitems in path: \"{Path}\""); return(new List <FileSystemStorageItemBase>(0)); } } }
public async IAsyncEnumerable <FileSystemStorageItemBase> SearchAsync(string SearchWord, bool SearchInSubFolders = false, bool IncludeHiddenItem = false, bool IsRegexExpresstion = false, bool IgnoreCase = true, [EnumeratorCancellation] CancellationToken CancelToken = default) { if (WIN_Native_API.CheckLocationAvailability(Path)) { List <FileSystemStorageItemBase> SearchResult = await Task.Run(() => { return(WIN_Native_API.Search(Path, SearchWord, SearchInSubFolders, IncludeHiddenItem, IsRegexExpresstion, IgnoreCase, CancelToken)); }); foreach (FileSystemStorageItemBase Item in SearchResult) { yield return(Item); if (CancelToken.IsCancellationRequested) { yield break; } } } else { if (await GetStorageItemAsync() is StorageFolder Folder) { QueryOptions Options = new QueryOptions { FolderDepth = SearchInSubFolders ? FolderDepth.Deep : FolderDepth.Shallow, IndexerOption = IndexerOption.UseIndexerWhenAvailable }; Options.SetThumbnailPrefetch(Windows.Storage.FileProperties.ThumbnailMode.ListView, 150, Windows.Storage.FileProperties.ThumbnailOptions.UseCurrentScale); Options.SetPropertyPrefetch(Windows.Storage.FileProperties.PropertyPrefetchOptions.BasicProperties, new string[] { "System.Size", "System.DateModified" }); if (!IsRegexExpresstion) { Options.ApplicationSearchFilter = $"System.FileName:*{SearchWord}*"; } StorageItemQueryResult Query = Folder.CreateItemQueryWithOptions(Options); uint FileCount = await Query.GetItemCountAsync(); for (uint Index = 0; Index < FileCount && !CancelToken.IsCancellationRequested; Index += 50) { IEnumerable <IStorageItem> Result = IsRegexExpresstion ? (await Query.GetItemsAsync(Index, 50)).Where((Item) => Regex.IsMatch(Item.Name, SearchWord, IgnoreCase ? RegexOptions.IgnoreCase : RegexOptions.None)) : (await Query.GetItemsAsync(Index, 50)).Where((Item) => Item.Name.Contains(SearchWord, IgnoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal)); foreach (IStorageItem Item in Result) { switch (Item) { case StorageFolder SubFolder: { yield return(new FileSystemStorageFolder(SubFolder, await SubFolder.GetThumbnailBitmapAsync(), await SubFolder.GetModifiedTimeAsync())); break; } case StorageFile SubFile: { yield return(new FileSystemStorageFile(SubFile, await SubFile.GetThumbnailBitmapAsync(), await SubFile.GetSizeRawDataAsync(), await SubFile.GetModifiedTimeAsync())); break; } } if (CancelToken.IsCancellationRequested) { yield break; } } } } } }