/// <summary> /// On click "..." button - select file /// </summary> protected virtual void OnBtnSelectFileClicked(object sender, System.EventArgs e) { Gtk.FileChooserDialog fc = new Gtk.FileChooserDialog ( AddinManager.CurrentLocalizer.GetString ("Choose the file to open"), new Dialog(), Gtk.FileChooserAction.Open, AddinManager.CurrentLocalizer.GetString ("Cancel"), ResponseType.Cancel, AddinManager.CurrentLocalizer.GetString ("Open"), ResponseType.Accept); if (!string.IsNullOrEmpty (this.eCommand.Text)) { fc.SetFilename(this.eCommand.Text); } if (fc.Run() == (int) ResponseType.Accept) { // check UnixFileInfo info = new UnixFileInfo (fc.Filename); if ((info.FileAccessPermissions & FileAccessPermissions.UserExecute) != FileAccessPermissions.UserExecute) { MessageDialog md = new MessageDialog (new Dialog(), DialogFlags.DestroyWithParent, MessageType.Error, ButtonsType.Close, AddinManager.CurrentLocalizer.GetString ("Selected invalid file!\nShould be executable.")); md.Run (); md.Destroy(); } else { this.eCommand.Text = fc.Filename; } } fc.Destroy(); }
public override bool CanExecute(FilePath path) { UnixFileInfo fi = new UnixFileInfo (path); if (!fi.Exists) return false; return 0 != (fi.FileAccessPermissions & (FileAccessPermissions.UserExecute | FileAccessPermissions.GroupExecute | FileAccessPermissions.OtherExecute)); }
public static void Initialize() { try { SetDefaults (); sConsole.Menu.AddItem ("addins", "sbook", "Facebook", "addins/sbook/", 0); Include.Add (sConsole.Enums.IncludeType.Javascript, "/js/sbook.js", "SBOOK", 101); // Create symlinks if they dont exist. if (!Directory.Exists (SorentoLib.Services.Config.Get<string> (SorentoLib.Enums.ConfigKey.path_addins) + "sConsole/data/content/addins/sbook")) { UnixFileInfo dirinfo = new UnixFileInfo (SorentoLib.Services.Config.Get<string> (SorentoLib.Enums.ConfigKey.path_addins) + "sBook/data/content/addins/sbook"); dirinfo.CreateSymbolicLink (SorentoLib.Services.Config.Get<string> (SorentoLib.Enums.ConfigKey.path_addins) + "sConsole/data/content/addins/sbook"); } if (!Directory.Exists (SorentoLib.Services.Config.Get<string> (SorentoLib.Enums.ConfigKey.path_addins) + "sConsole/data/html/xml/addins/sbook")) { UnixFileInfo dirinfo = new UnixFileInfo (SorentoLib.Services.Config.Get<string> (SorentoLib.Enums.ConfigKey.path_addins) + "sBook/data/html/xml/addins/sbook"); dirinfo.CreateSymbolicLink (SorentoLib.Services.Config.Get<string> (SorentoLib.Enums.ConfigKey.path_addins) + "sConsole/data/html/xml/addins/sbook"); } if (!File.Exists (SorentoLib.Services.Config.Get<string> (SorentoLib.Enums.ConfigKey.path_addins) + "sConsole/data/html/js/sbook.js")) { UnixFileInfo dirinfo = new UnixFileInfo (SorentoLib.Services.Config.Get<string> (SorentoLib.Enums.ConfigKey.path_addins) + "sBook/data/html/js/sbook.js"); dirinfo.CreateSymbolicLink (SorentoLib.Services.Config.Get<string> (SorentoLib.Enums.ConfigKey.path_addins) + "sConsole/data/html/js/sbook.js"); } } catch (Exception exception) { // LOG: LogDebug.ExceptionUnknown // SorentoLib.Services.Logging.LogDebug (string.Format (SorentoLib.Strings.LogDebug.ExceptionUnknown, "SFORM.INITIALIZE", exception.Message)); } }
public void InitUnix () { //TODO: /tmp/.X1-lock //string lockFile = "/tmp/.X" + 1 + "-lock"; string path = "/tmp/.X11-unix/X" + 1; UnixFileInfo ufi = new UnixFileInfo (path); UnixEndPoint ep = new UnixEndPoint (path); listener = new Socket (AddressFamily.Unix, SocketType.Stream, 0); //Bind creates the socket file right now listener.Bind (ep); //savedEP = listener.LocalEndPoint; //listen backlog 1 for now listener.Listen (1); Socket client = listener.Accept (); listener.Shutdown (SocketShutdown.Both); listener.Close (); ufi.Delete (); }
public UnixLogger(HttpClient webClient, string logFile, string webHook) { file = new StreamWriter(logFile, true); counts = new int[Enum.GetValues(typeof(Logging)).Length]; if (File.Exists(ENDPOINT)) { File.Delete(ENDPOINT); } socket = new Socket(AddressFamily.Unix, SocketType.Stream, ProtocolType.IP); endpoint = new UnixEndPoint(ENDPOINT); try { socket.Bind(endpoint); socket.Listen(1); socket.BeginAccept(new AsyncCallback(AcceptCallback), null); var fileInfo = new Mono.Unix.UnixFileInfo(ENDPOINT); Syscall.chown(ENDPOINT, Syscall.getuid(), Syscall.getgrnam("netdata").gr_gid); Syscall.chmod(ENDPOINT, FilePermissions.S_IWGRP | FilePermissions.S_IWUSR | FilePermissions.S_IRGRP | FilePermissions.S_IRUSR); this.webHook = webHook; } catch (Exception) { socket.Close(); socket = null; } this.webClient = webClient; }
static void Main(string[] args) { if (args.Any(x => x.Equals("--download-ffmpeg"))) { Console.WriteLine("[INFO] - Downloading ffmpeg and exiting"); if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux) || RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { FFmpegDownloader.GetLatestVersion(FFmpegVersion.Official).Wait(); try { var filePermissions = new Mono.Unix.UnixFileInfo("ffmpeg"); filePermissions.FileAccessPermissions = FileAccessPermissions.UserRead | FileAccessPermissions.UserWrite | FileAccessPermissions.GroupRead | FileAccessPermissions.OtherRead | FileAccessPermissions.UserExecute | FileAccessPermissions.GroupExecute | FileAccessPermissions.OtherExecute; filePermissions.Refresh(); } catch { } } else { FFmpegDownloader.GetLatestVersion(FFmpegVersion.Full).Wait(); } Environment.Exit(1); } Options inputOptions = new Options(); var optionsResult = Parser.Default.ParseArguments <Options>(args).WithParsed(r => { inputOptions = r; }); if (optionsResult.Tag == ParserResultType.NotParsed) { Environment.Exit(1); } if (!File.Exists(ffmpegPath) && (inputOptions.FfmpegPath == null || !File.Exists(inputOptions.FfmpegPath)) && !ExistsOnPath(ffmpegPath)) { Console.WriteLine("[ERROR] - Unable to find ffmpeg, exiting. You can download ffmpeg automatically with the argument --download-ffmpeg"); Environment.Exit(1); } switch (inputOptions.RunMode) { case RunMode.VideoDownload: DownloadVideo(inputOptions); break; case RunMode.ClipDownload: DownloadClip(inputOptions); break; case RunMode.ChatDownload: DownloadChat(inputOptions); break; case RunMode.ChatRender: RenderChat(inputOptions); break; } }
/// <summary> /// Get exec rights to a file (Only does anything if on linux) /// </summary> /// <param name="filePath">Path to file</param> public static void GetExecRights(string filePath) { // Only get exec rights if on linux if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { if (File.Exists(filePath)) { var fileInfo = new Mono.Unix.UnixFileInfo(filePath); fileInfo.FileAccessPermissions = FileAccessPermissions.UserExecute; } } }
public void LoadXmlConfig(string file) { if (String.IsNullOrEmpty (file)) throw new ArgumentNullException ("file"); var doc = new XmlDocument (); doc.Load (file); if (Platform.IsUnix) { var fileInfo = new UnixFileInfo (file); ImportSettings (doc, true, file, fileInfo.OwnerUser.UserName, fileInfo.OwnerGroup.GroupName); } else ImportSettings (doc, true, file); }
public bool TryLoadXmlConfig (string file) { if (String.IsNullOrEmpty (file)) throw new ArgumentNullException ("file"); var doc = new XmlDocument (); try { doc.Load (file); } catch (FileNotFoundException e) { Console.Error.WriteLine("ERROR: Couldn't find configuration file {0}!", e.FileName); return false; } if (Platform.IsUnix) { var fileInfo = new UnixFileInfo (file); ImportSettings (doc, true, file, fileInfo.OwnerUser.UserName, fileInfo.OwnerGroup.GroupName); } else ImportSettings (doc, true, file); return true; }
public override void Listen (int backlog) { base.Listen (backlog); try { if (path.StartsWith("\0", StringComparison.Ordinal)) inode = null; else { var info = new UnixFileInfo (path); inode = info.Inode; if (permissions != null) Syscall.chmod (path, NativeConvert.ToFilePermissions (permissions.Value)); } } catch (InvalidOperationException e) { Logger.Write (LogLevel.Error, e.Message); Logger.Write (LogLevel.Error, "Path \"{0}\" doesn't exist?", path); throw; } }
[Test] //BXC #12461 public void EnumerateFilesListSymlinks () { if (!RunningOnUnix) return; var afile = Path.Combine (TempFolder, "afile.src"); var bfile = Path.Combine (TempFolder, "bfile.src"); var cdir = Path.Combine (TempFolder, "cdir.src"); File.AppendAllText (afile, "hello"); var info = new UnixFileInfo (afile); info.CreateSymbolicLink (bfile); Directory.CreateDirectory (cdir); var files0 = Directory.GetFiles (TempFolder, "*.src"); Array.Sort (files0); Assert.AreEqual (2, files0.Length, "#1"); Assert.AreEqual (afile, files0 [0], "#2"); Assert.AreEqual (bfile, files0 [1], "#3"); #if NET_4_0 var files1 = new List<string> (Directory.EnumerateFiles (TempFolder, "*.src")).ToArray (); Array.Sort (files1); Assert.AreEqual (2, files1.Length, "#1.b"); Assert.AreEqual (afile, files1 [0], "#2.b"); Assert.AreEqual (bfile, files1 [1], "#3.b"); #endif var files2 = Directory.GetFileSystemEntries (TempFolder, "*.src"); Array.Sort (files2); Assert.AreEqual (3, files2.Length, "#1.c"); Assert.AreEqual (afile, files2 [0], "#2.c"); Assert.AreEqual (bfile, files2 [1], "#3.c"); Assert.AreEqual (cdir, files2 [2], "#4.c"); #if NET_4_0 var files3 = new List<string> (Directory.EnumerateFileSystemEntries (TempFolder, "*.src")).ToArray (); Array.Sort (files3); Assert.AreEqual (3, files3.Length, "#1.d"); Assert.AreEqual (afile, files3 [0], "#2.d"); Assert.AreEqual (bfile, files3 [1], "#3.d"); Assert.AreEqual (cdir, files3 [2], "#4.d"); #endif }
public void Sync() { foreach(var r in _files) { if (File.Exists(r.Key)) { var ufi = new UnixFileInfo(r.Key); if (ufi.FileAccessPermissions != r.Value) { Console.WriteLine(String.Format("Permission {0} of path {1} does not match {2}", ufi.FileAccessPermissions, r.Key, r.Value)); Syscall.chmod(r.Key, (FilePermissions) (int) r.Value); } } } }
static void Main () { Process p = new Process (); p.StartInfo = new ProcessStartInfo (); p.StartInfo.FileName = "/bin/sh"; p.StartInfo.Arguments = "-c umask"; p.StartInfo.RedirectStandardOutput = true; p.StartInfo.UseShellExecute = false; p.Start (); Assert.IsTrue (p.WaitForExit (1000), "#1"); Assert.AreEqual (0, p.ExitCode, "#2"); string output = p.StandardOutput.ReadLine (); Assert.IsNotNull (output, "#3"); int umask = int.Parse (output, CultureInfo.InvariantCulture); int expected = 666 & ~umask; string fileName = Path.Combine (AppDomain.CurrentDomain.BaseDirectory, "file.tmp"); File.Create (fileName).Close (); UnixFileInfo file = new UnixFileInfo (fileName); FileAccessPermissions perm = file.FileAccessPermissions; int actual = 0; actual += (perm & FileAccessPermissions.UserRead) != 0 ? 400 : 0; actual += (perm & FileAccessPermissions.UserWrite) != 0 ? 200 : 0; actual += (perm & FileAccessPermissions.UserExecute) != 0 ? 100 : 0; actual += (perm & FileAccessPermissions.GroupRead) != 0 ? 40 : 0; actual += (perm & FileAccessPermissions.GroupWrite) != 0 ? 20 : 0; actual += (perm & FileAccessPermissions.GroupExecute) != 0 ? 10 : 0; actual += (perm & FileAccessPermissions.OtherRead) != 0 ? 4 : 0; actual += (perm & FileAccessPermissions.OtherWrite) != 0 ? 2 : 0; actual += (perm & FileAccessPermissions.OtherExecute) != 0 ? 1 : 0; Assert.AreEqual (expected, actual, "#4"); }
private void DisableHostKeyCheckingForHost(string host) { string path = SparkleConfig.DefaultConfig.HomePath; if (!(SparkleBackend.Platform == PlatformID.Unix || SparkleBackend.Platform == PlatformID.MacOSX)) { path = Environment.ExpandEnvironmentVariables ("%HOMEDRIVE%%HOMEPATH%"); } string ssh_config_path = Path.Combine (path, ".ssh"); string ssh_config_file_path = SparkleHelpers.CombineMore (path, ".ssh", "config"); string ssh_config = Environment.NewLine + "# <SparkleShare>" + Environment.NewLine + "Host " + host + Environment.NewLine + "\tStrictHostKeyChecking no" + Environment.NewLine + "# </SparkleShare>"; if (!Directory.Exists (ssh_config_path)) Directory.CreateDirectory (ssh_config_path); if (File.Exists (ssh_config_file_path)) { TextWriter writer = File.AppendText (ssh_config_file_path); writer.WriteLine (ssh_config); writer.Close (); } else { File.WriteAllText (ssh_config_file_path, ssh_config); } UnixFileSystemInfo file_info = new UnixFileInfo (ssh_config_file_path); file_info.FileAccessPermissions = (FileAccessPermissions.UserRead | FileAccessPermissions.UserWrite); SparkleHelpers.DebugInfo ("Fetcher", "Disabled host key checking " + host); }
public UnixSocket(string path) : this(CreateEndPoint (path)) { this.path = path; inode = new UnixFileInfo (path).Inode; }
public void Delete (SafeUri uri) { UnixFileInfo info = new UnixFileInfo (uri.LocalPath); info.Delete (); }
// Don't change the case of this method, since ngit does reflection on it public bool setExecutable (bool exec) { if (RunningOnLinux) { UnixFileInfo fi = new UnixFileInfo (path); FileAccessPermissions perms = fi.FileAccessPermissions; if (exec) { if (perms.HasFlag (FileAccessPermissions.UserRead)) perms |= FileAccessPermissions.UserExecute; if (perms.HasFlag (FileAccessPermissions.OtherRead)) perms |= FileAccessPermissions.OtherExecute; if ((perms.HasFlag (FileAccessPermissions.GroupRead))) perms |= FileAccessPermissions.GroupExecute; } else { if (perms.HasFlag (FileAccessPermissions.UserRead)) perms &= ~FileAccessPermissions.UserExecute; if (perms.HasFlag (FileAccessPermissions.OtherRead)) perms &= ~FileAccessPermissions.OtherExecute; if ((perms.HasFlag (FileAccessPermissions.GroupRead))) perms &= ~FileAccessPermissions.GroupExecute; } fi.FileAccessPermissions = perms; return true; } return false; }
// Don't change the case of this method, since ngit does reflection on it public bool canExecute () { if (RunningOnLinux) { UnixFileInfo fi = new UnixFileInfo (path); if (!fi.Exists) return false; return 0 != (fi.FileAccessPermissions & (FileAccessPermissions.UserExecute | FileAccessPermissions.GroupExecute | FileAccessPermissions.OtherExecute)); } return false; }
private void Init() { var interfaceNameOrPath = originalInterfaceNameOrPath; if(!Directory.Exists("/Library/Extensions/tap.kext/")) { this.Log(LogLevel.Warning, "No TUNTAP kernel extension found, running in dummy mode."); MAC = EmulationManager.Instance.CurrentEmulation.MACRepository.GenerateUniqueMAC(); return; } if(!File.Exists(interfaceNameOrPath)) { var tapDevicePath = ConfigurationManager.Instance.Get<string>("tap", "tap-device-path", Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)); interfaceNameOrPath = Path.Combine(tapDevicePath, interfaceNameOrPath); } deviceFile = File.Open(interfaceNameOrPath, FileMode.Open, FileAccess.ReadWrite); // let's find out to what interface the character device file belongs var deviceType = new UnixFileInfo(interfaceNameOrPath).DeviceType; var majorNumber = deviceType >> 24; var minorNumber = deviceType & 0xFFFFFF; if(majorNumber != ExpectedMajorNumber) { throw new ConstructionException(string.Format("Unexpected major device number for OS X's tap: {0}.", majorNumber)); } networkInterface = NetworkInterface.GetAllNetworkInterfaces().Single(x => x.Name == "tap" + minorNumber); MAC = (MACAddress)networkInterface.GetPhysicalAddress(); }
protected override BuildResult Build (IProgressMonitor monitor, SolutionEntityItem item, ConfigurationSelector configuration) { var proj = item as MonoMacProject; if (proj == null || proj.CompileTarget != CompileTarget.Exe) return base.Build (monitor, item, configuration); var conf = (MonoMacProjectConfiguration) configuration.GetConfiguration (item); var resDir = conf.AppDirectory.Combine ("Contents", "Resources"); var appDir = conf.AppDirectory; //make sure the codebehind files are updated before building var res = MacBuildUtilities.UpdateCodeBehind (monitor, proj.CodeBehindGenerator, proj.Files); if (res.ErrorCount > 0) return res; res = res.Append (base.Build (monitor, item, configuration)); if (res.ErrorCount > 0) return res; //copy exe, mdb, refs, copy-to-output, Content files to Resources var filesToCopy = GetCopyFiles (proj, configuration, conf).Where (NeedsBuilding).ToList (); if (filesToCopy.Count > 0) { monitor.BeginTask ("Copying resource files to app bundle", filesToCopy.Count); foreach (var f in filesToCopy) { f.EnsureOutputDirectory (); File.Copy (f.Input, f.Output, true); monitor.Log.WriteLine ("Copied {0}", f.Output.ToRelative (appDir)); monitor.Step (1); } monitor.EndTask (); } if (!PropertyService.IsMac) { res.AddWarning ("Cannot compile xib files on non-Mac platforms"); } else { //Interface Builder files if (res.Append (MacBuildUtilities.CompileXibFiles (monitor, proj.Files, resDir)).ErrorCount > 0) return res; } //info.plist var plistOut = conf.AppDirectory.Combine ("Contents", "Info.plist"); var appInfoIn = proj.Files.GetFile (proj.BaseDirectory.Combine ("Info.plist")); if (new FilePair (proj.FileName, plistOut).NeedsBuilding () || (appInfoIn != null && new FilePair (appInfoIn.FilePath, plistOut).NeedsBuilding ())) if (res.Append (MergeInfoPlist (monitor, proj, conf, appInfoIn, plistOut)).ErrorCount > 0) return res; //launch script var ls = conf.LaunchScript; if (!File.Exists (ls)) { if (!Directory.Exists (ls.ParentDirectory)) Directory.CreateDirectory (ls.ParentDirectory); var src = AddinManager.CurrentAddin.GetFilePath ("MonoMacLaunchScript.sh"); File.Copy (src, ls, true); var fi = new UnixFileInfo (ls); fi.FileAccessPermissions |= FileAccessPermissions.UserExecute | FileAccessPermissions.GroupExecute | FileAccessPermissions.OtherExecute; } //pkginfo var pkgInfo = conf.AppDirectory.Combine ("Contents", "PkgInfo"); if (!File.Exists (pkgInfo)) using (var f = File.OpenWrite (pkgInfo)) f.Write (new byte [] { 0X41, 0X50, 0X50, 0X4C, 0x3f, 0x3f, 0x3f, 0x3f}, 0, 8); // "APPL???" return res; }
// Installs a launcher so the user can launch SparkleShare // from the Internet category if needed public override void InstallLauncher() { string apps_path = SparkleHelpers.CombineMore (SparklePaths.HomePath, ".local", "share", "applications"); string desktopfile_path = SparkleHelpers.CombineMore (apps_path, "sparkleshare.desktop"); if (!File.Exists (desktopfile_path)) { if (!Directory.Exists (apps_path)) Directory.CreateDirectory (apps_path); TextWriter writer = new StreamWriter (desktopfile_path); writer.WriteLine ("[Desktop Entry]\n" + "Type=Application\n" + "Name=SparkleShare\n" + "Comment=Share documents\n" + "Exec=sparkleshare start\n" + "Icon=folder-sparkleshare\n" + "Terminal=false\n" + "Categories=Network;"); writer.Close (); // Give the launcher the right permissions so it can be launched by the user UnixFileInfo file_info = new UnixFileInfo (desktopfile_path); file_info.FileAccessPermissions = FileAccessPermissions.UserReadWriteExecute; SparkleHelpers.DebugInfo ("Controller", "Created '" + desktopfile_path + "'"); } }
public void LinkFromOrCopyTo (MBFile f, IBuildContext ctxt) { // FIXME: like MakeExecutable, probably a hack. string path = GetPath (ctxt); if (!RuntimeEnvironment.MonoUnixSupported) { // emulate with copying CopyTo (f, ctxt); return; } // Try and emulate the copy semantics by obliterating // f if it already exists. string other = f.GetPath (ctxt); try { File.Delete (other); } catch (IOException) { } // FIXME: does this create absolute paths always? // that would be highly lame. UnixFileInfo ufi = new UnixFileInfo (path); ctxt.Logger.Log ("io.file_link", other + " -> " + path); ufi.CreateSymbolicLink (other); }
//private Stack<DatabaseTrackInfo> stk=new Stack<DatabaseTrackInfo>(); public void ImportSheet(CueSheet s) { if (import_manager==null) { try { import_manager = new LibraryImportManager (false); /*import_manager.ImportResult+=delegate(object sender,DatabaseImportResultArgs args) { DatabaseTrackInfo trk=args.Track; stk.Push (trk); };*/ } catch (Exception ex) { Hyena.Log.Error (ex.ToString ()); } } Hyena.Log.Debug ("Importsheet: Starting transaction"); int i,N; for(i=0,N=s.nEntries ();i<N;i++) { try { CueSheetEntry e=s.entry (i); string file=e.file (); string uuid=Regex.Replace(e.id (),"\\s","_"); string ext=".mp3"; string uid=Guid.NewGuid ().ToString (); string u1=uid.Substring (0,1); string u2=uid.Substring (0,2); string dir=basedir+"/.banshee/"+u1; if (!Directory.Exists (dir)) { Directory.CreateDirectory(dir); } dir+="/"+u2; if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } uuid=dir+"/"+uuid+ext; UnixFileInfo f=new UnixFileInfo(file); if (File.Exists (uuid)) { File.Delete(uuid); } //f.CreateLink (uuid); f.CreateSymbolicLink(uuid); DatabaseTrackInfo trk=import_manager.ImportTrack(uuid); //File.Delete (uuid); /*if (trk==null) { Hyena.Log.Warning ("track = null (file="+e.file ()+")"); if (stk.Count>0) { trk=stk.Pop (); } }*/ if (trk==null) { Hyena.Log.Error ("track = null (file="+e.file ()+")"); } else { Hyena.Log.Information ("track!=null (file="+e.file ()+")"); //MySource.DbConnection.BeginTransaction(); trk.PartOfCue=1; trk.CueAudioFile=e.file (); trk.AlbumTitle=s.title (); //trk.Album=s.title (); trk.AlbumArtist=s.performer (); trk.Composer=(e.Composer=="") ? s.composer () : e.Composer; //trk.ArtworkId=s.getArtId (); //trk.Artist= trk.ArtistName=(e.performer ()=="") ? s.performer () : e.performer (); trk.TrackTitle=e.title (); trk.TrackNumber=i+1; trk.Genre=s.genre (); trk.BeginOffset=e.BeginOffset; trk.EndOffset=e.EndOffset; //trk.Uri=trk.CueAudioUri; //trk.MediaAttributes = TrackMediaAttributes.ExternalResource; //trk.PrimarySource = ServiceManager.SourceManager.MusicLibrary; trk.Save (); //MySource.DbConnection.CommitTransaction(); } } catch (Exception ex) { Hyena.Log.Error (ex.ToString ()); } } import_manager.NotifyAllSources (); }
static void CopyExecutableFile (FilePath src, FilePath dest) { if (File.Exists (dest)) return; if (!Directory.Exists (dest.ParentDirectory)) Directory.CreateDirectory (dest.ParentDirectory); File.Copy (src, dest, true); var fi = new UnixFileInfo (dest); fi.FileAccessPermissions |= FileAccessPermissions.UserExecute | FileAccessPermissions.GroupExecute | FileAccessPermissions.OtherExecute; }
private uint HandleReceiveFile() { var transferFileName = GetCurrentStringRegister(); try { OpenStreamForReading(transferFileName); state = State.FileReceive; this.Log(LogLevel.Info, "Sending file {0} to emulation started.", transferStream.Name); var info = new UnixFileInfo(transferStream.Name).FileAccessPermissions; return (uint)info; } catch(IOException e) { HandleException(e); return 0; } }
private void onStartSync(object o, EventArgs args) { Hyena.Log.Debug ("Start of Sync triggered!"); var options = View.GetOptions (); // target directory to copy to Hyena.Log.DebugFormat ("Target folder is set to: {0}", options.TargetFolder); // count all files for progress bar int totalFiles = 0; foreach (var playlist in options.SelectedPlaylists) { totalFiles += playlist.Tracks.Count (); } View.Progress.Text = AddinManager.CurrentLocalizer.GetString ("Preparing sync"); var progress_step = 1f / totalFiles; var current_progress = 0f; // begin sync worker thread ThreadStart syncStart = delegate() { Hyena.Log.Debug ("Sync thread started!"); // foreach playlist foreach (var playlist in options.SelectedPlaylists) { Stream m3u_stream = null; StreamWriter m3u_writer = null; if (options.CreateM3u) { var m3u_fileUri = new StringBuilder ().Append (options.TargetFolder) .Append (Path.DirectorySeparatorChar).Append (playlist.Name) .Append (".m3u").ToString (); m3u_stream = Banshee.IO.File.OpenWrite (new SafeUri (m3u_fileUri), true); Log.DebugFormat ("opened m3u playlist for writing: {0}", m3u_fileUri); m3u_writer = new StreamWriter (m3u_stream, System.Text.Encoding.UTF8); } // for each contained file foreach (var track in playlist.Tracks) { // get filename part of path var dest_path_suffix = track.GetFilepathSuffix (options.SubfolderDepth); // we dont want %20 etc. in the m3u since some android devices delete // playlists with that encoding in it (i.e. galaxy S) Hyena.Log.DebugFormat ("filename for m3u file is {0}", dest_path_suffix); // assemble new Uri of target track var destUri = new SafeUri (new StringBuilder ().Append (options.TargetFolder) .Append (Path.DirectorySeparatorChar) .Append (dest_path_suffix).ToString ()); // create subfolders if necessary string dest_path = options.TargetFolder; var folders = track.GetSubdirectories (options.SubfolderDepth); try { for (int i=0; i < folders.Count (); i++) { dest_path += folders [i] + "/"; Hyena.Log.DebugFormat ("creating folder {0}", dest_path); if (!Banshee.IO.Directory.Exists (dest_path)) Banshee.IO.Directory.Create (new SafeUri (dest_path)); } } catch { // folder creation failed, this is fatal, stop // TODO display a error popup break; } // copy file to selected folder try { var destExists = Banshee.IO.File.Exists (destUri); if (options.OverwriteExisting || !destExists) { if (options.CreateSymLinks) { var trackFilePath = SafeUri.UriToFilename (track.Uri); var destFilePath = SafeUri.UriToFilename (destUri); if (track.Uri.IsLocalPath) { var target = new UnixFileInfo (trackFilePath); // symbolic links need manual deletion, // otherwise an exception is thrown in CreateSymbolicLink() if (destExists) { var dest = new UnixFileInfo (destFilePath); dest.Delete (); } target.CreateSymbolicLink (destFilePath); } else { Hyena.Log.ErrorFormat ("Cannot create symlink to remote path {0} in {1}, skipping", track.Uri, destFilePath); } } else { Banshee.IO.File.Copy (track.Uri, destUri, true); } Hyena.Log.DebugFormat ("Copying {0} to {1}", track.Uri, destUri); } else Hyena.Log.Debug ("Not overwriting existing file {0}", destUri); } catch { Hyena.Log.ErrorFormat ("Error copying file {0} to {1}, skipping", track.Uri, destUri); } // increment the progressbar current_progress += progress_step; if (current_progress > 1.0f) current_progress = 1.0f; Gtk.Application.Invoke (delegate { View.Progress.Fraction = current_progress; View.Progress.Text = AddinManager.CurrentLocalizer.GetString ("Copying") + " " + track.Filepath; Gtk.Main.IterationDo (false); }); if (options.CreateM3u) { m3u_writer.Write (track.CreateM3uEntry (options.SubfolderDepth)); } } // close the m3u file before processing next playlist if (options.CreateM3u) { Hyena.Log.Debug ("closing m3u filedescriptor"); m3u_writer.Close (); m3u_writer.Dispose (); } Hyena.Log.Debug ("sync process finished"); } Gtk.Application.Invoke (delegate { View.Progress.Text = AddinManager.CurrentLocalizer.GetString ("Done!"); View.Progress.Fraction = 1f; Gtk.Main.IterationDo (false); }); Hyena.Log.Debug ("sync DONE, returning"); return; }; // end of sync worker thread syncThread = new Thread (syncStart); syncThread.Start (); return; }
private void EnableHostKeyCheckingForHost(string host) { string path = SparkleConfig.DefaultConfig.HomePath; if (!(SparkleBackend.Platform == PlatformID.Unix || SparkleBackend.Platform == PlatformID.MacOSX)) { path = Environment.ExpandEnvironmentVariables ("%HOMEDRIVE%%HOMEPATH%"); } string ssh_config_file_path = SparkleHelpers.CombineMore (path, ".ssh", "config"); if (File.Exists (ssh_config_file_path)) { string current_ssh_config = File.ReadAllText (ssh_config_file_path); current_ssh_config = current_ssh_config.Trim (); string [] lines = current_ssh_config.Split (Environment.NewLine.ToCharArray ()); string new_ssh_config = ""; bool in_sparkleshare_section = false; foreach (string line in lines) { if (line.StartsWith ("# <SparkleShare>")) { in_sparkleshare_section = true; continue; } if (line.StartsWith ("# </SparkleShare>")) { in_sparkleshare_section = false; continue; } if (in_sparkleshare_section) continue; new_ssh_config += line + Environment.NewLine; } if (string.IsNullOrWhiteSpace (new_ssh_config)) { File.Delete (ssh_config_file_path); } else { File.WriteAllText (ssh_config_file_path, new_ssh_config.Trim ()); UnixFileSystemInfo file_info = new UnixFileInfo (ssh_config_file_path); file_info.FileAccessPermissions = (FileAccessPermissions.UserRead | FileAccessPermissions.UserWrite); } } SparkleHelpers.DebugInfo ("Fetcher", "Enabled host key checking for " + host); }
// Don't change the case of this method, since ngit does reflection on it public bool setExecutable (bool exec) { try { UnixFileInfo fi = new UnixFileInfo (path); FileAccessPermissions perms = fi.FileAccessPermissions; if ((perms & FileAccessPermissions.UserRead) != 0) perms |= FileAccessPermissions.UserExecute; if ((perms & FileAccessPermissions.OtherRead) != 0) perms |= FileAccessPermissions.OtherExecute; if ((perms & FileAccessPermissions.GroupRead) != 0) perms |= FileAccessPermissions.GroupExecute; fi.FileAccessPermissions = perms; return true; } catch { return false; } }
/** BLOCKING */ public static DateTime LastChange(string path) { UnixFileSystemInfo f = new UnixFileInfo (path); try { if (f.LastWriteTime > f.LastStatusChangeTime) return f.LastWriteTime; else return f.LastStatusChangeTime; } catch (Exception) { return DefaultTime; } }
// Creates a .desktop entry in autostart folder to // start SparkleShare automatically at login public override void EnableSystemAutostart() { string autostart_path = Path.Combine (Environment.GetFolderPath ( Environment.SpecialFolder.ApplicationData), "autostart"); string desktopfile_path = Path.Combine (autostart_path, "sparkleshare.desktop"); if (!Directory.Exists (autostart_path)) Directory.CreateDirectory (autostart_path); if (!File.Exists (desktopfile_path)) { TextWriter writer = new StreamWriter (desktopfile_path); writer.WriteLine ("[Desktop Entry]\n" + "Type=Application\n" + "Name=SparkleShare\n" + "Exec=sparkleshare start\n" + "Icon=folder-sparkleshare\n" + "Terminal=false\n" + "X-GNOME-Autostart-enabled=true\n" + "Categories=Network"); writer.Close (); // Give the launcher the right permissions so it can be launched by the user UnixFileInfo file_info = new UnixFileInfo (desktopfile_path); file_info.Create (FileAccessPermissions.UserReadWriteExecute); SparkleHelpers.DebugInfo ("Controller", "Enabled autostart on login"); } }
/** BLOCKING */ public static DateTime LastModified(string path) { UnixFileSystemInfo f = new UnixFileInfo (path); return LastModified(f); }
public static void CreateArchive (ProgressMonitor mon, string folder, string targetFile) { string tf = Path.GetFileNameWithoutExtension (targetFile); if (tf.EndsWith (".tar")) tf = Path.GetFileNameWithoutExtension (tf); if (File.Exists (targetFile)) File.Delete (targetFile); using (Stream os = File.Create (targetFile)) { Stream outStream = os; // Create the zip file switch (GetArchiveExtension (targetFile)) { case ".tar.gz": outStream = new GZipOutputStream(outStream); goto case ".tar"; case ".tar.bz2": outStream = new BZip2OutputStream(outStream, 9); goto case ".tar"; case ".tar": TarArchive archive = TarArchive.CreateOutputTarArchive (outStream); archive.SetAsciiTranslation (false); archive.RootPath = folder; archive.ProgressMessageEvent += delegate (TarArchive ac, TarEntry e, string message) { if (message != null) mon.Log.WriteLine (message); }; foreach (FilePath f in GetFilesRec (new DirectoryInfo (folder))) { TarEntry entry = TarEntry.CreateEntryFromFile (f); entry.Name = f.ToRelative (folder); if (!Platform.IsWindows) { UnixFileInfo fi = new UnixFileInfo (f); entry.TarHeader.Mode = (int)fi.Protection; } else { entry.Name = entry.Name.Replace ('\\', '/'); FilePermissions p = FilePermissions.S_IFREG | FilePermissions.S_IROTH | FilePermissions.S_IRGRP | FilePermissions.S_IRUSR; if (!new FileInfo (f).IsReadOnly) p |= FilePermissions.S_IWUSR; entry.TarHeader.Mode = (int) p; } archive.WriteEntry(entry, false); } // HACK: GNU tar expects to find a double zero record at the end of the archive. TarArchive only emits one. // This hack generates the second zero block. FieldInfo tarOutField = typeof(TarArchive).GetField ("tarOut", BindingFlags.Instance | BindingFlags.NonPublic); if (tarOutField != null) { TarOutputStream tarOut = (TarOutputStream) tarOutField.GetValue (archive); tarOut.Finish (); } archive.CloseArchive (); break; case ".zip": ZipOutputStream zs = new ZipOutputStream (outStream); zs.SetLevel(5); byte[] buffer = new byte [8092]; foreach (FilePath f in GetFilesRec (new DirectoryInfo (folder))) { string name = f.ToRelative (folder); if (Platform.IsWindows) name = name.Replace ('\\', '/'); ZipEntry infoEntry = new ZipEntry (name); zs.PutNextEntry (infoEntry); using (Stream s = File.OpenRead (f)) { int nr; while ((nr = s.Read (buffer, 0, buffer.Length)) > 0) zs.Write (buffer, 0, nr); } } zs.Finish (); zs.Close (); break; default: mon.Log.WriteLine ("Unsupported file format: " + Path.GetFileName (targetFile)); return; } } }
public void Update() { // Check if data still exists. if (!File.Exists (this.DataPath)) { // EXCEPTION: Exception.MediaSaveData throw new Exception (string.Format (Strings.Exception.MediaSaveData, this._id)); } if (this._type != this._temptype) { string source = string.Empty; string destination = string.Empty; switch (this._type) { case Enums.MediaType.Temporary: { source = Services.Config.Get<string> (Enums.ConfigKey.path_temp); break; } case Enums.MediaType.TemporaryPublic: { source = Services.Config.Get<string> (Enums.ConfigKey.path_temp); break; } case Enums.MediaType.Public: { source = Services.Config.Get<string> (Enums.ConfigKey.path_media); break; } case Enums.MediaType.Restricted: { source = Services.Config.Get<string> (Enums.ConfigKey.path_media); break; } } switch (this._temptype) { case Enums.MediaType.Temporary: { destination = Services.Config.Get<string> (Enums.ConfigKey.path_temp); break; } case Enums.MediaType.TemporaryPublic: { destination = Services.Config.Get<string> (Enums.ConfigKey.path_temp); break; } case Enums.MediaType.Public: { destination = Services.Config.Get<string> (Enums.ConfigKey.path_media); break; } case Enums.MediaType.Restricted: { destination = Services.Config.Get<string> (Enums.ConfigKey.path_media); break; } } if ((this._path != this._temppath) || (this._type != this._temptype)) { // Remove old symlink if needed. if ((this._type == Enums.MediaType.Public) || (this._type == Enums.MediaType.TemporaryPublic)) { File.Delete (Services.Config.Get<string> (Enums.ConfigKey.path_publicmedia) + this._path); } } if (source != destination) { FileInfo file = new FileInfo (source + this._id); file.MoveTo (destination + this._id); } } this._path = this._temppath; this._type = this._temptype; // Create new symlink if needed. if ((this._temptype == Enums.MediaType.Public) || (this._temptype == Enums.MediaType.TemporaryPublic)) { // Check if path exists, if not create it. if (!System.IO.Directory.Exists (Services.Config.Get<string> (Enums.ConfigKey.path_publicmedia) + System.IO.Path.GetDirectoryName (this._temppath))) { System.IO.Directory.CreateDirectory (Services.Config.Get<string> (Enums.ConfigKey.path_publicmedia) + System.IO.Path.GetDirectoryName (this._temppath)); } // Create a new symlink. UnixFileInfo unixfileinfo = new UnixFileInfo (this.DataPath); unixfileinfo.CreateSymbolicLink (Services.Config.Get<string> (Enums.ConfigKey.path_publicmedia) + this._temppath); } string path = string.Empty; switch (this._type) { case Enums.MediaType.Temporary: { path = Services.Config.Get<string> (Enums.ConfigKey.path_temp); break; } case Enums.MediaType.TemporaryPublic: { path = Services.Config.Get<string> (Enums.ConfigKey.path_temp); break; } case Enums.MediaType.Public: { path = Services.Config.Get<string> (Enums.ConfigKey.path_media); break; } case Enums.MediaType.Restricted: { path = Services.Config.Get<string> (Enums.ConfigKey.path_media); break; } } // Get filesize FileInfo fileinfo = new FileInfo (path + this._id); this._size = fileinfo.Length; // Get mimetype this._mimetype = SNDK.IO.GetMimeType (path + this._id); }