public static void ProcessItem(Item fileItem, DatabaseOperations dbOp) { // Set the fileItem's source path. The source path may be used by meta providers. fileItem.SourcePath = dbOp.BagLocation + "\\" + fileItem.Id; List <IMetaProvider> provOut; _metaProviderMap.TryGetValue(fileItem.Extension.ToLower(), out provOut); List <IMetaProvider> providers = new List <IMetaProvider>(); // Add the default provider providers.Add(_defaultMetaProvider); if (provOut != null) { providers.AddRange(provOut); } // Iterate over all providers and let them do their thing foreach (IMetaProvider provider in providers) { TableRow row = provider.ProcessItem(fileItem); // Always add an itemId column. This should be the table's key. if (row != null) { row.AddColumn("itemId", fileItem.Id); } // Insert the newly obtained metadata in the database try { dbOp.InsertTableRow(row); } catch (SQLiteException ex) { MjDebug.Log(ex.Message); } } }
/// <summary> /// Return a map of all discovered bag volumes. This method will scan all volumes. /// Only use this methods when you explicitly need to re-discover all volumes, otherwise use <see cref="DiscoveredBagVolumes"/> to retrieve a list of already discovered volumes. /// </summary> /// <returns></returns> public Dictionary <string, DatabaseOperations> DiscoverBagVolumes() { Dictionary <string, DatabaseOperations> result = new Dictionary <string, DatabaseOperations>(); // Scan all volumes for a configuration file foreach (DriveInfo dinfo in DriveInfo.GetDrives()) { DatabaseOperations op; if (_mountedBagVolumes.TryGetValue(dinfo.ToString(), out op)) { result.Add(dinfo.ToString(), op); // Bag volume already registered, re-use old entry } else { try { foreach (FileInfo finfo in dinfo.RootDirectory.GetFiles()) { if (finfo.Name == CONFIG_FILE_NAME) { MjDebug.Log("Found bag volume on '" + dinfo + "'"); op = dbMan.OpenConnection(dinfo + CONFIG_FILE_NAME); // Open connection result.Add(dinfo.ToString(), op); break; } } } catch (IOException) { // Drive unavailable or not enough rights. This is not critical, log it. MjDebug.Log("Unable to scan files on drive " + dinfo); } } } _discoveredBagVolumes = result; // Update map return(result); // Return the map as well }
public void MountBagVolume(string drive) { MjDebug.Log("Mounting bag volume on '" + drive + "'"); DatabaseOperations op; if (_discoveredBagVolumes.TryGetValue(drive, out op)) { _mountedBagVolumes.Add(drive, op); } else { throw new VolumeMountManagerException("Cannot mount unregistered bag volume."); } }
public static string lastBasePath; // Last bag location from which files were loaded /// <summary> /// Turn any MjFS path in to a valid path to a file located inside a bag /// </summary> /// <param name="path"></param> /// <returns></returns> public static string ResolvePath(string path) { Dictionary <string, DatabaseOperations> bagVolumes = volMan.MountedBagVolumes; List <DriveInfo> removable = new List <DriveInfo>(); if (bagVolumes.Count == 1) { // There is a single bag mounted. Directly return the item's location. KeyValuePair <string, DatabaseOperations> entry = bagVolumes.First(); string driveLetter = entry.Key; string bagLocation = entry.Value.BagLocation; string result = bagLocation + Path.GetFileName(path); lastBasePath = bagLocation; MjDebug.Log("Resolved " + path + " to " + result); if (File.Exists(result)) { return(result); } } else if (bagVolumes.Count > 1) { // Multiple bags mounted. Look through all to confirm the item's location. lastBasePath = bagVolumes.First().Key + bagVolumes.First().Value.BagLocation; foreach (KeyValuePair <string, DatabaseOperations> entry in bagVolumes) { string fileName = Path.GetFileName(path); if (entry.Value.GetItem(fileName) != null) { string driveLetter = entry.Key; string bagLocation = entry.Value.BagLocation; string result = driveLetter + bagLocation + "\\" + fileName; if (File.Exists(result)) { return(result); } } else { continue; } } } else { // There are no mounted bags. No need to search. } return(null); }
/// <summary> /// Removes the volume from the mounted bags and closes the associated database connection /// </summary> /// <param name="drive"></param> public void UnmountBagVolume(string drive) { MjDebug.Log("Unmounting bag volume on '" + drive + "'"); DatabaseOperations op; if (_discoveredBagVolumes.TryGetValue(drive, out op)) { dbMan.CloseConnection(op); _mountedBagVolumes.Remove(drive); } else { throw new VolumeMountManagerException("Cannot unmount unregistered bag volume."); } }
private void OnLogicalVolumesChanges(object sender, EventArrivedEventArgs e) { if (lastChange != null) { DateTime now = DateTime.Now; if ((now - lastChange).TotalSeconds < 4) { // Discard this 'change' if the last change was less than 5 seconds ago return; } else { lastChange = now; } } MjDebug.Log("Logical volumes (un)mounted"); MountBagVolumes(); }
public TableRow ProcessItem(Item fileItem) { TableRow res = new TableRow(TABLE_NAME); string path = fileItem.SourcePath; try { using (ExifReader reader = new ExifReader(path)) { string outputStr; double outputDouble; DateTime outputDate; UInt16 outputUInt16; if (reader.GetTagValue <string>(ExifTags.Artist, out outputStr)) { res.AddColumn("artist", outputStr); } if (reader.GetTagValue <double>(ExifTags.FNumber, out outputDouble)) { res.AddColumn("f-stop", Convert.ToString(outputDouble)); } if (reader.GetTagValue <UInt16>(ExifTags.PhotographicSensitivity, out outputUInt16)) { res.AddColumn("iso", Convert.ToString(outputUInt16)); } if (reader.GetTagValue <string>(ExifTags.Model, out outputStr)) { res.AddColumn("model", outputStr); } } } catch (ExifLibException ex) { MjDebug.Log(ex.Message); return(null); } catch (IOException ex) { MjDebug.Log(ex.Message); return(null); } return(res); }
public DatabaseOperations(EntityContext context) { this._connection = (SQLiteConnection)context.Database.Connection; this._context = context; if (_context.Database.Exists()) { if (_context.Database.CompatibleWithModel(false)) { try { _bagPath = this.GetBagLocation() + "\\"; MjDebug.Log("Initialized DatabaseOperations for '" + _bagPath + "'"); } catch (Exception ex) { // This happens when initializing an empty database //MjDebug.Halt("Error during database initialization", ex); } } else { MjDebug.Log("Connected database is not compatible with current model!"); } } }
/// <summary> /// Finds a collection of files for the given directory /// </summary> /// <param name="directoryPath"></param> /// <returns></returns> public static IList <FileInformation> FindFiles(string directoryPath) { List <FileInformation> result = new List <FileInformation>(); List <string> dupTags = new List <string>(); HashSet <string> tags = Helper.GetTagsFromPath(directoryPath); List <DriveInfo> deprecateNextList = new List <DriveInfo>(); foreach (KeyValuePair <string, DatabaseOperations> entry in volMan.MountedBagVolumes) { try { if (directoryPath == "\\") { // Display all tags marked rootVisible from the DB foreach (MetaTable tag in entry.Value.GetRootTables()) { if (!dupTags.Contains(tag.tableName)) { dupTags.Add(tag.tableName); FileInformation finfo = new FileInformation(); finfo.FileName = Helper.StringToProper(tag.friendlyName); finfo.Attributes = System.IO.FileAttributes.Directory; finfo.LastAccessTime = DateTime.Now; finfo.LastWriteTime = DateTime.Now; finfo.CreationTime = DateTime.Now; result.Add(finfo); } } } else { DatabaseOperations op = entry.Value; MetaTable table = op.GetTableByFriendlyName(tags.First <string>()); if (tags.Count == 1) { // TODO: this is just a test foreach (ItemMeta item in op.GetItems(table.tableName)) { FileInformation finfo = new FileInformation(); finfo.FileName = item.name + "." + item.ext; finfo.Attributes = (FileAttributes)Enum.Parse(typeof(FileAttributes), item.attr); finfo.LastAccessTime = Convert.ToDateTime(item.lat); finfo.LastWriteTime = Convert.ToDateTime(item.lwt); finfo.CreationTime = Convert.ToDateTime(item.ct); result.Add(finfo); } List <MetaTable> tables = op.GetExtendingTables(table.tableName); tables.Add(table); // Create a set of folders to further sort the items foreach (MetaTable extTable in tables) { foreach (MetaAlias alias in op.GetAliases(extTable.tableName)) { // Add a folder for this alias FileInformation finfo = new FileInformation(); finfo.FileName = "By " + alias.alias; finfo.Attributes = System.IO.FileAttributes.Directory; finfo.LastAccessTime = DateTime.Now; finfo.LastWriteTime = DateTime.Now; finfo.CreationTime = DateTime.Now; result.Add(finfo); } } } /* * // Create a set of 'inner tags' by removing the tags already in the path * List<string> innerTags = entry.Value.GetInnerTags(tags.ToList()).Except(tags).ToList(); * // Add the set of innerTags * foreach (string tag in innerTags) { * FileInformation finfo = new FileInformation(); * finfo.FileName = Helper.StringToProper(tag); * finfo.Attributes = System.IO.FileAttributes.Directory; * finfo.LastAccessTime = DateTime.Now; * finfo.LastWriteTime = DateTime.Now; * finfo.CreationTime = DateTime.Now; * result.Add(finfo); * } * items.AddRange(entry.Value.GetItemsByCompositeTag(tags.ToList<string>()));*/ } } catch (SQLiteException ex) { // Display any exceptions, but continue working. We will remove this drive later. MjDebug.Log(ex.StackTrace + "\n" + ex.Message, LogSeverity.MEDIUM); deprecateNextList.Add(new DriveInfo(entry.Key)); } } // Unmount any entry that caused an exception foreach (DriveInfo dinfo in deprecateNextList) { volMan.UnmountBagVolume(dinfo.ToString()); } return(result); }
/// <summary> /// Start synchronization of the given bag volume entry /// </summary> /// <param name="entry"></param> public void StartSynchronization(string drive) { if (!_watchedDrives.ContainsKey(drive)) { if (vMan.DiscoveredBagVolumes.Count == 0) { throw new SynchronizationManagerException("Unable to start synchronization: there are no registered bag volumes."); } FileSystemWatcher fsw = new FileSystemWatcher(); DatabaseOperations op; if (!vMan.DiscoveredBagVolumes.TryGetValue(drive, out op)) { throw new SynchronizationManagerException("Unable to start synchronization: bag volume is not registered."); } fsw.Path = op.BagLocation; fsw.EnableRaisingEvents = true; _watchedDrives.Add(drive, fsw); // Assign event handlers for the FileWathcer on this volume #region fsw event handlers fsw.Created += (s, e) => { FileInfo fInfo = new FileInfo(e.FullPath); DriveInfo dInfo = new DriveInfo(fInfo.Directory.Root.Name); MjDebug.Log("Detected new file '" + fInfo.Name + "'"); DatabaseOperations dbOp = VolumeMountManager.GetInstance().DiscoveredBagVolumes[dInfo.ToString()]; Item fileItem = Helper.GetItemFromFileInfo(fInfo); if (fileItem != null) { try { // Old tag processor //dbOp.InsertItem(fileItem); //dbOp.InsertDefaultItemTag(fileItem); // New meta service MetaService.ProcessItem(fileItem, dbOp); } catch (SQLiteException ex) { MjDebug.Log("Database reports: \n" + ex.Message); } } else { MjDebug.Log("Fileitem is null"); } }; fsw.Deleted += (s, e) => { FileInfo fInfo = new FileInfo(e.FullPath); DriveInfo dInfo = new DriveInfo(fInfo.Directory.Root.Name); MjDebug.Log("Removed file '" + fInfo.Name + "'"); DatabaseOperations tempOp = VolumeMountManager.GetInstance().DiscoveredBagVolumes[dInfo.ToString()]; Item fileItem = Helper.GetItemFromId(fInfo.Name); if (fileItem != null) { try { //tempOp.DeleteItem(fileItem); } catch (SQLiteException ex) { MjDebug.Log("Database reports: \n" + ex.Message); } } else { MjDebug.Log("Fileitem is null"); } }; fsw.Renamed += (s, e) => { FileInfo fInfo = new FileInfo(e.FullPath); FileInfo oldfInfo = new FileInfo(e.OldFullPath); DriveInfo dInfo = new DriveInfo(fInfo.Directory.Root.Name); MjDebug.Log("Renamed file '" + oldfInfo.Name + "' to '" + fInfo.Name + "'"); DatabaseOperations dbOp = VolumeMountManager.GetInstance().DiscoveredBagVolumes[dInfo.ToString()]; Item fileItem = Helper.GetItemFromFileInfo(fInfo); Item oldFileItem = Helper.GetItemFromId(oldfInfo.Name); if (fileItem != null && oldfInfo != null) { try { //dbOp.DeleteItem(oldFileItem); // Old tag processor //dbOp.InsertItem(fileItem); //dbOp.InsertDefaultItemTag(fileItem); // New meta service MetaService.ProcessItem(fileItem, dbOp); } catch (SQLiteException ex) { MjDebug.Log("Database reports: \n" + ex.Message); } } else { MjDebug.Log("Fileitem is null"); } }; #endregion } }