Esempio n. 1
0
        public override void ViewDidMoveToWindow()
        {
            base.ViewDidMoveToWindow();

            TrackName.StringValue  = currentDelegate.controller.Track;
            ArtistName.StringValue = currentDelegate.controller.Artist;

            if (currentDelegate.controller.App == "iTunes")
            {
                PlayerIcon.Image = new NSImage("icon_itunes.pdf");
                script           = new NSAppleScript(File.ReadAllText("Scripts/GetAlbumArtiTunes.txt"));
                result           = script.ExecuteAndReturnError(out errors);
                NSImage cover = new NSImage(result.Data);
                AlbumArtView.Image  = cover;
                ThumbnailView.Image = cover;
            }
            else
            {
                PlayerIcon.Image = new NSImage("icon_spotify.pdf");
                script           = new NSAppleScript(File.ReadAllText("Scripts/GetAlbumArtSpotify.txt"));
                result           = script.ExecuteAndReturnError(out errors);
                NSUrl   artworkurl = new NSUrl(result.StringValue);
                NSImage cover      = new NSImage(artworkurl);
                AlbumArtView.Image  = cover;
                ThumbnailView.Image = cover;
            }
        }
Esempio n. 2
0
        //itunesへApplescriptでリクエストを送信して結果を返す関数
        private NSAppleEventDescriptor Requesttoitunes(String _script)
        {
            NSAppleScript          appleScript = new NSAppleScript(_script);
            NSDictionary           error;
            NSAppleEventDescriptor result = appleScript.ExecuteAndReturnError(out error);

            return(result);
        }
Esempio n. 3
0
 //Method to handle Launch at Login functionality
 [Export("launch:")] 
 void Launch(NSObject sender) 

 {
     if (!NSUserDefaults.StandardUserDefaults.BoolForKey("LaunchLogin"))
     {
         script = new NSAppleScript(File.ReadAllText("Scripts/LoginAdd.txt"));
         script.ExecuteAndReturnError(out errors);
         NSUserDefaults.StandardUserDefaults.SetBool(true, "LaunchLogin");
     }
     else
     {
         script = new NSAppleScript(File.ReadAllText("Scripts/LoginRemove.txt"));
         script.ExecuteAndReturnError(out errors);
         NSUserDefaults.StandardUserDefaults.SetBool(false, "LaunchLogin");
     } 

 }
Esempio n. 4
0
        public void AppleScript_BasicTest()
        {
#pragma warning disable 0219
            const string  script = @"tell application ""Finder""
end tell";
            NSAppleScript s      = new NSAppleScript(script);

            NSDictionary errorInfo;
            bool         success = s.CompileAndReturnError(out errorInfo);
            Assert.IsTrue(success);
            Assert.IsNull(errorInfo);
            Assert.IsTrue(s.Compiled);

            NSAppleEventDescriptor descriptor = s.ExecuteAndReturnError(out errorInfo);
            Assert.IsNull(errorInfo);
#pragma warning restore 0219
        }
Esempio n. 5
0
        static void Main(string[] args)
        {
            NSApplication.Init();
            Logging.Log("iMessage Bridge 1.0");
            NSUserDefaults.StandardUserDefaults.RegisterDefaults(NSDictionary.FromFile(NSBundle.MainBundle.PathForResource("DefaultPreferences", "plist")));

            // Find out if user is logged into iMessage.
            NSAppleScript          asConnectionStatus = new NSAppleScript("tell application \"Messages\" to get 1st service's connection status whose service type = iMessage");
            NSDictionary           ei;
            NSAppleEventDescriptor aed = asConnectionStatus.ExecuteAndReturnError(out ei);

            if (ei == null)
            {
                if (aed.StringValue == "dcon") // iMessage service is disconnected.
                {
                    NSAlert alert = new NSAlert()
                    {
                        MessageText     = "It appears you're not signed in to iMessage.",
                        InformativeText = "The bridge will not work if you are not signed in. Would you like to sign in to iMessage?"
                    };
                    alert.AddButton("Yes");
                    alert.AddButton("Not now");
                    NSRunningApplication.CurrentApplication.Activate(NSApplicationActivationOptions.ActivateIgnoringOtherWindows);
                    if (alert.RunModal() == 1000) // User clicks yes.
                    {
                        Process.Start("/Applications/Messages.app");
                    }
                    Environment.Exit(1);
                }
            }
            DatabaseStore.Init();
            HttpServer.Start();
            StreamServer.Start();
            if (NSUserDefaults.StandardUserDefaults.BoolForKey("DiscoveryMode"))
            {
                Discovery.Register();
            }

            NSApplication app = NSApplication.SharedApplication;

            app.Delegate = new AppDelegate();
            app.Run();
        }
Esempio n. 6
0
        partial void SettingsButtonClick(NSObject sender) 

        {
            
 var current = NSApplication.SharedApplication.CurrentEvent; 

            //Checking if the app is in the login items or not
            var                    script      = "tell application \"System Events\"\n get the name of every login item\n if login item \"Ambar\" exists then\n return true\n else\n return false\n end if\n end tell";
            NSAppleScript          appleScript = new NSAppleScript(script);
            var                    errors      = new NSDictionary();
            NSAppleEventDescriptor result      = appleScript.ExecuteAndReturnError(out errors);

            isLoginItem = result.BooleanValue;

            if (!isLoginItem)
            {
                launch.State = NSCellStateValue.Off;
            }
            else if (isLoginItem)
            {
                launch.State = NSCellStateValue.On;
            }
            
 NSMenu.PopUpContextMenu(settingsMenu, current, sender as NSView); 

        }
Esempio n. 7
0
        public override void ViewDidMoveToWindow()
        {
            base.ViewDidMoveToWindow();

            LyricsTextView.Value   = currentDelegate.controller.TrackLyrics.message.body.lyrics.lyrics_body;
            TrackName.StringValue  = currentDelegate.controller.Track;
            ArtistName.StringValue = currentDelegate.controller.Artist;

            if (currentDelegate.controller.TrackLyrics.message.body.lyrics.@explicit == 1)
            {
                ExplicitTag.Hidden = false;
            }
            else
            {
                ExplicitTag.Hidden = true;
            }

            if (currentDelegate.controller.App == "iTunes")
            {
                PlayerIcon.Image = new NSImage("icon_itunes.pdf");
                script           = new NSAppleScript(File.ReadAllText("Scripts/GetAlbumArtiTunes.txt"));
                result           = script.ExecuteAndReturnError(out errors);
                NSImage cover = new NSImage(result.Data);
                AlbumArtView.Image  = cover;
                ThumbnailView.Image = cover;
            }
            else
            {
                PlayerIcon.Image = new NSImage("icon_spotify.pdf");
                script           = new NSAppleScript(File.ReadAllText("Scripts/GetAlbumArtSpotify.txt"));
                result           = script.ExecuteAndReturnError(out errors);
                NSUrl   artworkurl = new NSUrl(result.StringValue);
                NSImage cover      = new NSImage(artworkurl);
                AlbumArtView.Image  = cover;
                ThumbnailView.Image = cover;
            }

            containerHeight = (float)LyricsTextView.Bounds.Height;
        }
Esempio n. 8
0
        partial void btnApply(AppKit.NSButton sender)
        {
            string           pictureName = $"bing_wallpaper_{DateTime.Now.Year}{DateTime.Now.Month}{DateTime.Now.Day}.jpg";
            WallpaperService wallpaper   = new WallpaperService();
            var data = wallpaper.GetByte(url);
            var path = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures);

            File.WriteAllBytes(Path.Combine(path, pictureName), data);

            var fileName = Environment.GetFolderPath(Environment.SpecialFolder.MyPictures) + "/" + pictureName;
            var cmd      = $"tell application \"Finder\" to set desktop picture to \"{fileName}\" as POSIX file";

            using (var script = new NSAppleScript(cmd))
            {
                var errors = new NSDictionary();
                var result = script.ExecuteAndReturnError(out errors);
                //if (!string.IsNullOrEmpty(errors.Val))
                //{

                //}
            }
        }
Esempio n. 9
0
        

        [Export("launch:")] 
 void Launch(NSObject sender) 

        {
            
                                                                                                                                                                                 //Use NSAppleScript to add this app to Login item list of macOS.
            //The app must be in the Applications Folder

            String        script;
            NSAppleScript login;
            NSDictionary  errors = new NSDictionary();

            if (!isLoginItem)
            {
                //AppleScript to add app to login items
                script = "tell application \"System Events\"\n make new login item at end of login items with properties {name: \"Ambar\", path:\"/Applications/Ambar.app\", hidden:false}\n end tell";
                login  = new NSAppleScript(script);
                login.ExecuteAndReturnError(out errors);
            }
            else
            {
                //AppleScript to delete app from login items
                script = "tell application \"System Events\"\n delete login item \"Ambar\"\n end tell";
                login  = new NSAppleScript(script);
                login.ExecuteAndReturnError(out errors);
            } 

        }
Esempio n. 10
0
        private void FetchLyrics()
        {
            stateMachine.StartLoading();

            if (Reachability.IsNetworkAvailable())
            {
                script = new NSAppleScript(File.ReadAllText("Scripts/GetCurrentSong.txt"));
                result = script.ExecuteAndReturnError(out errors);

                //The NumberofItems property is being used to handle different use cases. Check GetCurrentSong.txt in Scripts folder to know more
                if (result.NumberOfItems == 3)
                {
                    artist = result.DescriptorAtIndex(1).StringValue;
                    track  = result.DescriptorAtIndex(2).StringValue;
                    app    = result.DescriptorAtIndex(3).StringValue;

                    var lyrics = lyricsHelper.GetLyrics(track, artist, (response, artist_name, share_url) =>
                    {
                        tracklyrics = JsonConvert.DeserializeObject <TrackLyrics.RootObject>(response);

                        if (tracklyrics.message.body.lyrics.instrumental == 0)
                        {
                            track_share_url = share_url;
                            stateMachine.ShowContent();
                        }
                        else
                        {
                            stateMachine.ShowEmpty();
                        }
                    });
                }
                else if (result.NumberOfItems == 0)
                {
                    switch (result.StringValue)
                    {
                    //Transitioning to error state of state machine and calling the corresponding delegate method
                    //These delegates method are being used so that one view can be reused for various error cases.
                    case "1":
                        stateMachine.ShowError();
                        NothingPlayingFound?.Invoke(this, null);
                        break;

                    case "2":
                        stateMachine.ShowError();
                        NoMusicAppRunningFound?.Invoke(this, null);
                        break;

                    case "3":
                        stateMachine.ShowError();
                        MultiPlayingFound?.Invoke(this, null);
                        break;
                    }
                }
                else
                {
                    stateMachine.ShowError();
                    LyricsNotFoundOccurred?.Invoke(this, null);
                }
            }

            else
            {
                stateMachine.ShowError();
                NetworkErrorOccurred?.Invoke(this, null);
            }
        }
Esempio n. 11
0
        static void ContextProcess(object o)
        {
            try
            {
                HttpListenerContext context = (HttpListenerContext)o;
                Logging.Log("[HttpServer] Request from " + context.Request.RemoteEndPoint + " : " + context.Request.Url.PathAndQuery);
                context.Response.ContentType = "application/json";
                using (StreamReader sr = new StreamReader(context.Request.InputStream))
                    using (StreamWriter sw = new StreamWriter(context.Response.OutputStream))
                        try
                        {
                            if (NSUserDefaults.StandardUserDefaults.BoolForKey("ServerAuthentication"))
                            {
                                HttpListenerBasicIdentity id = (HttpListenerBasicIdentity)context.User.Identity;
                                if (!(id.Name == "user" && id.Password.Length > 0 && id.Password == NSUserDefaults.StandardUserDefaults.StringForKey("ServerPassword")))
                                {
                                    context.Response.StatusCode = 401;
                                    sw.Write("{\"status\":\"access denied\"}");
                                    return;
                                }
                            }
                            NameValueCollection body = null;
                            if (context.Request.HttpMethod == "POST")
                            {
                                body = HttpUtility.ParseQueryString(sr.ReadToEnd());
                            }
                            switch (context.Request.Url.AbsolutePath)
                            {
                            case "/test":
                                sw.Write("{\"status\":\"ok\"}");
                                break;

                            case "/serverinfo":
                                sw.Write(string.Format("{{\"status\":\"ok\",\"bridgeVersion\":\"{0}\"}}",
                                                       ServerInfo.BridgeVersion));
                                break;

                            case "/recipients":
                                sw.Write(JSON.FormatDictionaryResponse(DatabaseStore.Recipients));
                                break;

                            case "/recipientpicture":
                                Recipient recipient = DatabaseStore.Recipients[Convert.ToInt32(context.Request.QueryString["id"])];
                                if (recipient != null)
                                {
                                    if (recipient.HasPicture)
                                    {
                                        context.Response.ContentType = "image/jpeg";
                                        context.Response.OutputStream.Write(recipient._picture, 0, recipient._picture.Length);
                                    }
                                    else
                                    {
                                        context.Response.StatusCode = 404;
                                    }
                                }
                                else
                                {
                                    context.Response.StatusCode = 404;
                                }
                                break;

                            case "/conversations":
                                sw.Write(JSON.FormatDictionaryResponse(DatabaseStore.Conversations));
                                break;

                            case "/messages":
                                sw.Write(JSON.FormatDictionaryResponse(DatabaseStore.Messages));
                                break;

                            case "/attachments":
                                sw.Write(JSON.FormatDictionaryResponse(DatabaseStore.Attachments));
                                break;

                            case "/attachment":
                                Attachment attachment = DatabaseStore.Attachments[Convert.ToInt32(context.Request.QueryString["id"])];
                                if (attachment != null)
                                {
                                    if (File.Exists(attachment.FullFileName))
                                    {
                                        context.Response.ContentType = attachment.MimeType;
                                        context.Response.AddHeader("Content-Disposition", "inline; filename=\"" + attachment.FileName + "\"");
                                        using (Stream fileStream = File.OpenRead(attachment.FullFileName))
                                            fileStream.CopyTo(context.Response.OutputStream);
                                    }
                                    else
                                    {
                                        context.Response.StatusCode = 404;
                                    }
                                }
                                else
                                {
                                    context.Response.StatusCode = 404;
                                }
                                break;

                            case "/send":
                                NSAppleScript appleScript;
                                if (string.IsNullOrEmpty(body["sms"]))
                                {
                                    // By default messages are sent using iMessage.
                                    appleScript = new NSAppleScript(string.Format(@"
                                        tell application ""Messages""
                                            set serviceID to id of 1st service whose service type = iMessage
                                            send ""{0}"" to buddy ""{1}"" of service id serviceID
                                        end tell", JSON.FormatString(body["text"]), body["recipient"]));
                                }
                                else
                                {
                                    // If the body has the "sms" parameter, send as SMS.
                                    appleScript = new NSAppleScript(string.Format(@"
                                        tell application ""Messages""
                                            send ""{0}"" to buddy ""{1}"" of service ""SMS""
                                        end tell", JSON.FormatString(body["text"]), body["recipient"]));
                                }
                                NSDictionary errorInfo;
                                appleScript.ExecuteAndReturnError(out errorInfo);
                                if (errorInfo == null)
                                {
                                    sw.Write("{\"status\":\"ok\"}");
                                }
                                else
                                {
                                    context.Response.StatusCode = 400;
                                    sw.Write(string.Format("{{\"status\":\"error\",\"error\":{{\"briefMessage\":\"{0}\",\"message\":\"{1}\",\"number\":{2}}}}}",
                                                           JSON.FormatString(errorInfo.ValueForKey(new NSString("NSAppleScriptErrorBriefMessage")).ToString()), JSON.FormatString(errorInfo.ValueForKey(new NSString("NSAppleScriptErrorMessage")).ToString()), JSON.FormatString(errorInfo.ValueForKey(new NSString("NSAppleScriptErrorNumber")).ToString())));
                                }
                                break;
                            }
                        }
                        catch (Exception ex)
                        {
                            context.Response.StatusCode = 500;
                            sw.Write(JSON.Error(ex));
                        }
            }
            catch (Exception ex)
            {
                Logging.Log("[HttpServer] ContextProcess error: " + ex.Message);
            }
        }
Esempio n. 12
0
        public void Execute(Sender session, Dictionary <string, InstructionParameter> parameters)
        {
            // Clean arguements
            string parsedArguments             = "";
            Dictionary <string, string> layers = new Dictionary <string, string>();

            foreach (string s in parameters.Keys)
            {
                string lowerKey = s.ToLower();

                switch (s.ToLower())
                {
                case "layer1":
                case "1":
                case "l1":
                    layers.Add("Master Layer 1", parameters[s].ToString());
                    parsedArguments += " L1:" + parameters[s];
                    break;

                case "layer2":
                case "2":
                case "l2":
                    layers.Add("Master Layer 2", parameters[s].ToString());
                    parsedArguments += " L2:" + parameters[s];
                    break;

                case "layer3":
                case "3":
                case "l3":
                    layers.Add("Master Layer 3", parameters[s].ToString());
                    parsedArguments += " L3:" + parameters[s];
                    break;

                case "layer4":
                case "4":
                case "l4":
                    layers.Add("Master Layer 4", parameters[s].ToString());
                    parsedArguments += " L4:" + parameters[s];
                    break;

                case "layer5":
                case "5":
                case "l5":
                    layers.Add("Master Layer 5", parameters[s].ToString());
                    parsedArguments += " L5:" + parameters[s];
                    break;
                }
            }

            // We do have something to do
            if (layers.Count > 0)
            {
                // Create apple script command
                string appleScript = "tell application \"Wirecast\"\n\r";

                // Add layers to change
                foreach (KeyValuePair <string, string> item in layers)
                {
                    appleScript += "\tset active shot of the layer named \"" + item.Key + "\" of last document to the shot named \"" + item.Value + "\" of last document\n\r";
                }

                // Append finalizing
                appleScript += "\tgo last document\n\rend tell\n\r";

                NSAppleScript scriptObject = new NSAppleScript(appleScript);

                Shared.Log.Message("Wirecast", "Changing to " + parsedArguments.Trim());

                NSDictionary executeResponse = new NSDictionary();
                scriptObject.ExecuteAndReturnError(out executeResponse);
                if (executeResponse != null && executeResponse.Keys != null && executeResponse.Keys.Length > 0)
                {
                    Shared.Log.Error("Wirecast", "An error occured. " + executeResponse.Values[0]);
                }
            }
        }