summaryrefslogtreecommitdiff
path: root/Juick/ViewModels/AppViewModel.cs
blob: 07ba7cfd868d12cc8d3ddf2e142b1c8927084c97 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Net.NetworkInformation;
using Juick.Classes;
using JuickApi;
using Microsoft.Phone.Net.NetworkInformation;
using RestSharp;
using Microsoft.Phone.Notification;
using System.Diagnostics;
using System.Text;

namespace Juick.ViewModels
{
    public class AppViewModel : ViewModelBase
    {
        static readonly string IsNetworkAvailablePropertyName = ExpressionHelper.GetPropertyName<AppViewModel>(x => x.NetworkUnavailable);
        readonly HttpNotificationChannel _pushChannel; 

        // The name of our push channel.
        private const string channelName = "JuickChannel";

        public void UpdateNetworkStatus()
        {
            NetworkUnavailable = !DeviceNetworkInformation.IsNetworkAvailable;
        }

        public AppViewModel()
        {
            UpdateNetworkStatus();
            NetworkChange.NetworkAddressChanged += (sender, args) => UpdateNetworkStatus();
            _pushChannel = HttpNotificationChannel.Find(channelName);

                  // If the channel was not found, then create a new connection to the push service.
            if (_pushChannel == null)
            {
                _pushChannel = new HttpNotificationChannel(channelName);

                // Register for all the events before attempting to open the channel.
                _pushChannel.ChannelUriUpdated += (sender, e) => EnableNotifications(e.ChannelUri.ToString());
                _pushChannel.ErrorOccurred += (sender, e) => DisableNotifications();

                // Register for this notification only if you need to receive the notifications while your application is running.
                // Register for this notification only if you need to receive the notifications while your application is running.
                _pushChannel.ShellToastNotificationReceived += (sender, e) =>
                {
                    var message = new StringBuilder();
                    string relativeUri = string.Empty;

                    message.AppendFormat("Received Toast {0}:\n", DateTime.Now.ToShortTimeString());

                    // Parse out the information that was part of the message.
                    foreach (string key in e.Collection.Keys)
                    {
                        message.AppendFormat("{0}: {1}\n", key, e.Collection[key]);

                        if (string.Compare(
                            key,
                            "wp:Param",
                            System.Globalization.CultureInfo.InvariantCulture,
                            System.Globalization.CompareOptions.IgnoreCase) == 0)
                        {
                            relativeUri = e.Collection[key];
                        }
                    }
                    Debug.WriteLine("Received: " + message.ToString());
                };

                _pushChannel.Open();

                // Bind this new channel for toast events.
                _pushChannel.BindToShellToast();

            }
            else
            {
                // The channel was already open, so just register for all the events.
                _pushChannel.ChannelUriUpdated += (sender, e) => EnableNotifications(e.ChannelUri.ToString());
                _pushChannel.ErrorOccurred += (sender, e) => DisableNotifications();

                // Register for this notification only if you need to receive the notifications while your application is running.
                _pushChannel.ShellToastNotificationReceived += (sender, e) =>
                {
                    StringBuilder message = new StringBuilder();
                    string relativeUri = string.Empty;

                    message.AppendFormat("Received Toast {0}:\n", DateTime.Now.ToShortTimeString());

                    // Parse out the information that was part of the message.
                    foreach (string key in e.Collection.Keys)
                    {
                        message.AppendFormat("{0}: {1}\n", key, e.Collection[key]);

                        if (string.Compare(
                            key,
                            "wp:Param",
                            System.Globalization.CultureInfo.InvariantCulture,
                            System.Globalization.CompareOptions.IgnoreCase) == 0)
                        {
                            relativeUri = e.Collection[key];
                        }
                    }
                    Debug.WriteLine("Received: " + message.ToString());
                };

                EnableNotifications(_pushChannel.ChannelUri.ToString());
            }
        }
        private ObservableCollection<PageViewModel> _pages;
        public ObservableCollection<PageViewModel> Pages
        {
            get { return _pages ?? (_pages = new ObservableCollection<PageViewModel>()); }
        }

        static readonly string IsDataLoadingPropertyName = ExpressionHelper.GetPropertyName<AppViewModel>(x => x.IsDataLoading);
        bool _isDataLoading;

        public bool IsDataLoading
        {
            get { return _isDataLoading; }
            set
            {
                _isDataLoading = value;
                NotifyPropertyChanged(IsDataLoadingPropertyName);
                foreach (var page in Pages)
                {
                    page.LoadMessagesPageCommand.NotifyCanExecuteChanged();
                }
            }
        }

        private bool _isNetworkUnavailable;
        public bool NetworkUnavailable
        {
            get { return _isNetworkUnavailable; }
            set
            {
                _isNetworkUnavailable = value; 
                NotifyPropertyChanged(IsNetworkAvailablePropertyName);
            }
        }


        private AccountManager _acc;

        public AccountManager Account
        {
            get { return _acc ?? (_acc = new AccountManager()); }
        }

        private RestClient _cl;
        public RestClient Client
        {
            get
            {
                return _cl ?? (_cl = new RestClient("http://api.juick.com")
                {
                    UserAgent = "Juick 1.1/Windows Phone " + Environment.OSVersion.Version
                });
            }
        }

        public void EnableNotifications(string Url)
        {
            if (!Account.IsAuthenticated) return;
            Client.Authenticator = new HttpBasicAuthenticator(Account.UserName, Account.Password);
            Debug.WriteLine(Url.ToString());
            if (string.IsNullOrEmpty(Account.NotificationUri) || Account.NotificationUri == Url)
            {
                Account.NotificationUri = Url;
                RegisterNotificationUrl(Url);
            }
            else
            {
                UnregisterNotificationUrl(Account.NotificationUri);
                Account.NotificationUri = Url;
                RegisterNotificationUrl(Url);
            }
        }

        public void DisableNotifications()
        {
            UnregisterNotificationUrl(Account.NotificationUri);
            Account.NotificationUri = string.Empty;            
        }

        void RegisterNotificationUrl(string newUrl)
        {
            Client.ExecuteAsync(new RestRequest("/winphone/register?url=" + newUrl), response => Debug.WriteLine(response.StatusCode));
        }
        void UnregisterNotificationUrl(string oldUrl)
        {
            Client.ExecuteAsync(new RestRequest("/winphone/unregister?url=" + oldUrl), response => Debug.WriteLine(response.StatusCode));
        }
    }
}