//public DailyViewModel dailyViewModel;

        public ListViewPage()
        {
            InitializeComponent();
            App.ParentPage = "ListView";
            putLayoutsIntoLists();
            user = App.User;

            dateTimeNow = DateTime.Now;
            //dateTimeNow = new DateTime(2020, 2, 19, 10, 0, 0);

            /*labelFont = Device.RuntimePlatform == Device.iOS ? "Lobster-Regular" :
             *  Device.RuntimePlatform == Device.Android ? "Lobster-Regular.ttf#Lobster-Regular" : "Assets/Fonts/Lobster-Regular.ttf#Lobster";*/

            SetupUI();

            AddTapGestures();

/*
 *          SetupUI();
 *
 *          AddTapGestures();*/

            firestoreService = new FirestoreService();

            StartTimer();
        }
Beispiel #2
0
        public async Task TestParseScanTime()
        {
            FirestoreService FSS = new FirestoreService(logger);
            ScanData         sd  = await FSS.GetScanData();

            Assert.NotNull(sd);
        }
Beispiel #3
0
 public ValuesController(IOrderService orderService, FirestoreService firestoreService, IRawRabbitWrapper rawRabbitClient, ILogger <ValuesController> logger)
 {
     _orderService     = orderService;
     _firestoreService = firestoreService;
     _rawRabbitClient  = rawRabbitClient;
     _logger           = logger;
 }
Beispiel #4
0
        public async Task DeleteAllTrackedTimezones()
        {
            try
            {
                await JSR.StorageUtils.LocalStorageDeleteItem(TrackedTimezonesKey);
            }
            catch (Exception)
            {
                Logger.LogError("Failed to delete from local storage.");
            }

            // Save to firestore
            var user = await AuthService.GetCurrentUser();

            if (user != null)
            {
                // Collection
                string       collection = "users";
                string       docId      = user.uid;
                UserDocument doc        = new UserDocument();

                FirestoreOperationResult <UserDocument> result =
                    await FirestoreService.UpdateDocument <UserDocument, UserDocument>(collection, docId, doc);

                Logger.LogInformation($"Doc save result: {result.Success}");
            }
        }
Beispiel #5
0
        private void FetchScratch(object sender, DoWorkEventArgs args)
        {
            FirestoreService firestoreService = new FirestoreService(new BaseClientService.Initializer
            {
                ApplicationName = "Sipp-PC",
                ApiKey          = "AIzaSyCpPmG-AYByk3hircLVnAY_MLcp5ytIsAI",
            }
                                                                     );

            ProjectsResource.DatabasesResource.DocumentsResource.ListRequest req = firestoreService.Projects.Databases.Documents.List("projects/sipp-1f4c4/databases/(default)/documents/products/scratch", "projects");
            try
            {
                ListDocumentsResponse rsp = req.Execute();
                scratchProjects = new List <ScratchData>();

                foreach (Document project in rsp.Documents)
                {
                    string title       = getStringValue(project, "name");
                    string coverUrl    = getStringValue(project, "cover_url");
                    string description = getStringValue(project, "description");
                    string scratchUrl  = getStringValue(project, "scratch_url");
                    string docUrl      = getStringValue(project, "doc_url");
                    scratchProjects.Add(new ScratchData(title, coverUrl, description, scratchUrl, docUrl));
                }
            }
            catch (Google.GoogleApiException e)
            {
                MessageBox.Show(e.ToString());
            }
        }
Beispiel #6
0
        /// <summary>
        /// Adds users email to the database with their chosen match objects.
        /// </summary>
        /// <param name="request"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task <APIGatewayProxyResponse> ConfirmSubscribe(APIGatewayProxyRequest request, ILambdaContext context)
        {
            var logger = new Esk8LambdaLogger(context.Logger);

            logger.Log("Confirm Subscribe endpoint reached");

            if (request.QueryStringParameters.ContainsKey("confirmkey"))
            {
                string encryptionkey = Environment.GetEnvironmentVariable("ESK8BST_ENCRYPTION_KEY");
                string b64payload    = request.QueryStringParameters["confirmkey"];
                logger.Log("Received this as the confirm key: " + request.QueryStringParameters["confirmkey"]);
                string decrypted          = EncryptorService.DecryptConfirmKey(b64payload, encryptionkey);
                PostedSubscribeObject pso = null;
                try {
                    JObject jobj = JObject.Parse(decrypted);
                    pso = PostedSubscribeObject.FromJson(jobj);
                } catch (Exception e) {
                    logger.Log($"Tried to parse malformed json and failed at Confirm Subscribe: {e.Message}");
                    return(new APIGatewayProxyResponse()
                    {
                        StatusCode = (int)HttpStatusCode.InternalServerError,
                        Body = "Failed to parse json properly",
                        Headers = new Dictionary <string, string> {
                            { "Content-Type", "text/plain" }
                        },
                    });
                }

                if (pso != null && pso.Email.Contains("@") && pso.Matches.Count > 0)
                {
                    FirestoreService FSS = new FirestoreService(logger);
                    await FSS.UpsertSubscriber(pso);

                    await FSS.InsertPreconfirmed(pso.Email);

                    return(new APIGatewayProxyResponse()
                    {
                        StatusCode = (int)HttpStatusCode.Created,
                        Body = "Alright! You've been confirmed as interested in receiving updates from https://esk8bst.com",
                        Headers = new Dictionary <string, string> {
                            { "Content-Type", "text/plain" }
                        },
                    });
                }
            }

            return(new APIGatewayProxyResponse()
            {
                StatusCode = (int)HttpStatusCode.BadRequest,
                Body = "Failed to properly parse the confirm link.",
                Headers = new Dictionary <string, string> {
                    { "Content-Type", "text/plain" }
                },
            });
        }
Beispiel #7
0
        public async Task TestParsePostedSubscribers()
        {
            FirestoreService FSS = new FirestoreService(logger);

            string s = await File.ReadAllTextAsync("resources/Subscribers.json");

            JArray subArray = JArray.Parse(s);
            List <PostedSubscribeObject> subs    = SubscriberParser.ParseSubscribers(subArray);
            List <Subscriber>            subtrue = subs.Select(x => Subscriber.FromPostedSubscriber(x)).ToList();

            Assert.Equal(6, subtrue.Count);
        }
Beispiel #8
0
        public void GetTracemapProcessedFilesList_ok()
        {
            // Arrange
            var firestoreService = new FirestoreService(ConfigurationService);

            // Act
            var processedFilesList = firestoreService.GetCumulativeTrackBuilderProcessedDays(false);

            // Assert
            Check.That(processedFilesList).IsNotNull();
            Check.That(processedFilesList).Not.IsEmpty();
        }
Beispiel #9
0
        public void GetLastProcesseFileName_Ok()
        {
            // Arrange
            var firestoreService = new FirestoreService(ConfigurationService);

            // Act
            var lastProcessedFileName = firestoreService.GetLastProcessedFile();

            // Assert
            Check.That(lastProcessedFileName).IsNotEmpty();
            Check.That(lastProcessedFileName).IsNotNull();
        }
        protected override void OnCreate(Bundle bundle)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource   = Resource.Layout.Toolbar;

            base.OnCreate(bundle);

            global::Xamarin.Forms.Forms.Init(this, bundle);
            LoadApplication(new App());

            FirestoreService.Init(this);
        }
Beispiel #11
0
        public async Task CheckIsPreconfirmed()
        {
            string           s   = "*****@*****.**";
            FirestoreService FSS = new FirestoreService(logger);
            await FSS.InsertPreconfirmed(s);

            bool isPreconfirmedFirst = await FSS.CheckIsPreconfirmed(s);

            bool isPreconfirmedSecond = await FSS.CheckIsPreconfirmed("lol");

            Assert.True(isPreconfirmedFirst);
            Assert.False(isPreconfirmedSecond);
        }
Beispiel #12
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource   = Resource.Layout.Toolbar;

            base.OnCreate(savedInstanceState);
            Firebase.FirebaseApp.InitializeApp(Application.Context);
            FirestoreService.Init(Application.Context);
            CrossCurrentActivity.Current.Init(this, savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
            Firebase.FirebaseApp.InitializeApp(this);
            LoadApplication(new App());
        }
Beispiel #13
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            TabLayoutResource = Resource.Layout.Tabbar;
            ToolbarResource   = Resource.Layout.Toolbar;

            base.OnCreate(savedInstanceState);

            Xamarin.Essentials.Platform.Init(this, savedInstanceState);
            global::Xamarin.Forms.Forms.Init(this, savedInstanceState);
            Xamarin.Forms.DependencyService.Register <FirebaseAuthentication>();
            Xamarin.Forms.DependencyService.Register <FirestoreService>();

            LoadApplication(new App());
            FirestoreService.Init(this);
        }
        protected override async void OnAppearing()
        {
            if (Application.Current.Properties.ContainsKey("accessToken") &&
                Application.Current.Properties.ContainsKey("refreshToken") &&
                Application.Current.Properties.ContainsKey("user_id"))
            {
                App.LoadApplicationProperties();

                firestoreService         = new FirestoreService();
                firebaseFunctionsService = new FirebaseFunctionsService();

                await firestoreService.LoadUser();

                await GoogleService.LoadTodaysEvents();

                await Navigation.PushAsync(new GoalsRoutinesTemplate());
            }
        }
Beispiel #15
0
        public async Task SaveTrackedTimezones(ISet <string> timezoneIds)
        {
            if (timezoneIds == null || timezoneIds.Count == 0)
            {
                Logger.LogError("No timezones to save.");
                return;
            }

            // Save to firestore
            var user = await AuthService.GetCurrentUser();

            if (user != null)
            {
                // Collection
                string       collection = "users";
                string       docId      = user.uid;
                UserDocument doc        = new UserDocument()
                {
                    TrackedTimezoneIds = timezoneIds
                };

                FirestoreOperationResult <UserDocument> result =
                    await FirestoreService.UpdateDocument <UserDocument, UserDocument>(collection, docId, doc);

                Logger.LogInformation($"Doc save result: {result.Success}");
            }

            // Let's save to local storage as well
            // We will retrieve this if user is not signed in
            try
            {
                await JSR.StorageUtils.LocalStorageSetItem(
                    TrackedTimezonesKey, JsonSerializer.Serialize(timezoneIds));
            }
            catch (Exception)
            {
                Logger.LogError("Failed to save to local storage.");
            }
        }
Beispiel #16
0
        public async Task <ISet <string> > GetTrackedTimezones()
        {
            // Get from firestore
            var user = await AuthService.GetCurrentUser();

            if (user != null)
            {
                // Collection
                string collection = "users";
                string docId      = user.uid;

                FirestoreOperationResult <UserDocument> result =
                    await FirestoreService.GetDocument <UserDocument>(collection, docId);

                Logger.LogInformation($"Doc get result: {result.Success}");

                if (result.Success && result.Document != null)
                {
                    return(result.Document.TrackedTimezoneIds);
                }
            }
            else
            {
                try
                {
                    string trackedTimezonesJson =
                        await JSR.StorageUtils.LocalStorageGetItem(TrackedTimezonesKey);

                    return(JsonSerializer.Deserialize <ISet <string> >(trackedTimezonesJson));
                }
                catch (Exception)
                {
                    Logger.LogError("Failed to get from local storage.");
                }
            }

            return(null);
        }
Beispiel #17
0
        /// <summary>
        /// The core function launched every hour.
        /// </summary>
        /// <param name="request"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task Scan(APIGatewayProxyRequest request, ILambdaContext context)
        {
            var logger = new Esk8LambdaLogger(context.Logger);

            logger.Log("Scan initiated endpoint reached");
            HttpClient Client = new HttpClient();
            /* Set up our Services */
            FirestoreService FSS = new FirestoreService(logger);
            Esk8Service      ESS = new Esk8Service(logger, Client);
            RedditService    RSS = new RedditService(logger, ESS, Client);
            MailgunService   MSS = new MailgunService(logger, Client);
            MatchService     LSS = new MatchService(logger);

            /* Get our Firebase last-scanned time */
            ScanData sd = await FSS.GetScanData();

            if (sd == null)
            {
                return; /* Something happened, so we quit. */
            }

            /* Check Firebase Subscribers */
            List <Subscriber> subscribers = await FSS.GetSubscribers();

            if (subscribers == null || subscribers.Count == 0)
            {
                ScanData updatedScanData = new ScanData()
                {
                    LastScanDate = DateTimeOffset.Now, MostRecentlySeen = DateTimeOffset.Now
                };
                await FSS.UpdateScanTime(updatedScanData);

                return;
            }

            /* Get the BST Thread */
            if (!(await RSS.GetRedditItem() is JObject frontPage))
            {
                /* Some kind of error ocurred, do not update */
                return;
            }
            string BSTUrl = RSS.FindBSTThreadUrl(frontPage);

            if (String.IsNullOrWhiteSpace(BSTUrl))
            {
                /* Some kind of error ocurred, do not update */
                return;
            }
            if (!(await RSS.GetRedditItem(BSTUrl) is JArray BSTPage))
            {
                /* Some kind of error ocurred, do not update */
                return;
            }

            /* Check if there are new posts, to save on Network requests fetching Company / Board information */
            if (!RSS.AnyNewPosts(BSTPage, sd.MostRecentlySeen))
            {
                /* There have been no new posts since last time. */
                ScanData updatedScanData = new ScanData()
                {
                    LastScanDate = DateTimeOffset.Now, MostRecentlySeen = DateTimeOffset.Now
                };
                await FSS.UpdateScanTime(updatedScanData);

                return;
            }


            /* Fetch Company and Product information from Esk8 servers */
            List <Product> prods = await ESS.GetCommonBoards();

            List <Company> comps = await ESS.GetCommonCompanies();

            comps = CompanyParser.CombineCompanyLists(comps, prods.Select(x => x.Company));

            List <RegexCategory <Company> > CompRs = ESS.GetCompanyRegexs(comps);
            List <RegexCategory <Product> > ProdRs = ESS.GetProductRegexs(prods);

            /* Parse the full thread for new posts */
            List <BSTComment> comments = RSS.ParseComments(BSTPage, CompRs, ProdRs, sd.LastScanDate);


            /* Line up potential Match Objects */
            /* At this point we don't update until emails have been sent out. */
            Dictionary <Subscriber, List <LambdaMatch> > lambdadelta = LSS.MakeMatches(subscribers, comments);

            /* Assemble the emails to send */
            IEnumerable <MailgunEmail> emails = lambdadelta.Select(x => MSS.MakeEmail(x.Key, x.Value));

            /* Send emails */
            bool SentSuccessfully = await MSS.BatchSend(emails);

            if (SentSuccessfully)
            {
                ScanData updatedScanData = new ScanData()
                {
                    LastScanDate = DateTimeOffset.Now, MostRecentlySeen = DateTimeOffset.Now
                };
                await FSS.UpdateScanTime(updatedScanData);
            }
        }
Beispiel #18
0
        /// <summary>
        /// Removes users email from the db
        /// </summary>
        /// <param name="request"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task <APIGatewayProxyResponse> Unsubscribe(APIGatewayProxyRequest request, ILambdaContext context)
        {
            var logger = new Esk8LambdaLogger(context.Logger);

            logger.Log("Unsubscribe endpoint reached");

            if (request.HttpMethod != HttpMethod.Get.Method)
            {
                return(new APIGatewayProxyResponse()
                {
                    StatusCode = (int)HttpStatusCode.MethodNotAllowed,
                    Body = "This endpoint only responds to GET requests",
                    Headers = new Dictionary <string, string> {
                        { "Content-Type", "text/plain" }
                    },
                });
            }

            string key  = Environment.GetEnvironmentVariable("ESK8BST_ENCRYPTION_KEY");
            string decr = "";

            if (request.QueryStringParameters.ContainsKey("confirmkey"))
            {
                string payload = request.QueryStringParameters["confirmkey"];
                if (!String.IsNullOrWhiteSpace(payload))
                {
                    decr = EncryptorService.Base64Decode(payload);
                    //decr = AESThenHMAC.SimpleDecryptWithPassword(payload, key);
                    if (String.IsNullOrWhiteSpace(decr) || !decr.Contains("@"))
                    {
                        return(new APIGatewayProxyResponse()
                        {
                            StatusCode = (int)HttpStatusCode.BadRequest,
                            Body = "An email was not found in the confirmkey parameter",
                            Headers = new Dictionary <string, string> {
                                { "Content-Type", "text/plain" }
                            },
                        });
                    }
                }
                else
                {
                    return(new APIGatewayProxyResponse()
                    {
                        StatusCode = (int)HttpStatusCode.BadRequest,
                        Body = "Missing value for parameter `confirmkey`",
                        Headers = new Dictionary <string, string> {
                            { "Content-Type", "text/plain" }
                        },
                    });
                }
            }
            else
            {
                return(new APIGatewayProxyResponse()
                {
                    StatusCode = (int)HttpStatusCode.BadRequest,
                    Body = "Missing parameter `confirmkey`",
                    Headers = new Dictionary <string, string> {
                        { "Content-Type", "text/plain" }
                    },
                });
            }
            FirestoreService FSS = new FirestoreService(logger);
            await FSS.DeleteSubscriber(decr.ToLowerInvariant());

            var response = new APIGatewayProxyResponse {
                StatusCode = (int)HttpStatusCode.OK,
                Body       = "Ok! You've been unsubscribed and will no longer receive updates. If you change your mind, you can always sign up again at https://esk8bst.com",
                Headers    = new Dictionary <string, string> {
                    { "Content-Type", "text/plain" }
                },
            };

            return(response);
        }
        public StepsPageViewModel(StepsPage mainPage, int a, int b, bool isRoutine)
        {
            this.mainPage = mainPage;
            Items         = new ObservableCollection <ListViewItemModel>();
            var firestoreService = new FirestoreService();

            firebaseFunctionsService = new FirebaseFunctionsService();

            if (isRoutine)
            {
                TopImage = App.User.routines[a].tasks[b].photo;
                TopLabel = App.User.routines[a].tasks[b].title;
                TaskName = App.User.routines[a].title;
                ExpectedCompletionTime = "Expected to take " +
                                         ((int)App.User.routines[a].expectedCompletionTime.TotalMinutes).ToString()
                                         + " minutes";

                int stepIdx = 0;
                int stepNum = 1;

                Console.WriteLine("step count: " + App.User.routines[a].tasks[b].steps.Count);

                foreach (step step in App.User.routines[a].tasks[b].steps)
                {
                    string        _checkmarkIcon = "graycheckmarkicon.png";
                    Command <int> _completeStep  = new Command <int>((int _stepIdx) => { });;

                    if (App.User.routines[a].tasks[b].steps[stepIdx].isComplete)
                    {
                        _checkmarkIcon = "greencheckmarkicon.png";
                    }
                    else
                    {
                        if (App.User.routines[a].tasks[b].steps[stepIdx].isInProgress)
                        {
                            _checkmarkIcon = "yellowclockicon.png";
                        }

                        _completeStep = new Command <int>(
                            async(int _stepIdx) =>
                        {
                            var routineId             = App.User.routines[a].id;
                            var taskId                = App.User.routines[a].tasks[b].id;
                            string stepDbIdx          = App.User.routines[a].tasks[b].steps[_stepIdx].dbIdx.ToString();
                            bool isPrevStepInProgress =
                                (_stepIdx == 0) ? false : App.User.routines[a].tasks[b].steps[_stepIdx - 1].isInProgress;
                            bool isPrevStepComplete =
                                (_stepIdx == 0) ? true : App.User.routines[a].tasks[b].steps[_stepIdx - 1].isComplete;
                            bool isStepInProgress = App.User.routines[a].tasks[b].steps[_stepIdx].isInProgress;
                            bool isStepComplete   = App.User.routines[a].tasks[b].steps[_stepIdx].isComplete;
                            var indexForCheckmark = _stepIdx;


                            if (!isStepComplete)
                            {
                                if (isPrevStepInProgress)
                                {
                                    if (_stepIdx - 1 >= 0)
                                    {
                                        App.User.routines[a].tasks[b].steps[_stepIdx - 1].isInProgress = false;
                                        App.User.routines[a].tasks[b].steps[_stepIdx - 1].isComplete   = true;
                                        Items[_stepIdx - 1].CheckmarkIcon = "greencheckmarkicon.png";
                                        string prevStepDbIdx = App.User.routines[a].tasks[b].steps[_stepIdx - 1].dbIdx.ToString();


                                        firebaseFunctionsService.UpdateStep(routineId, taskId, prevStepDbIdx);
                                    }

                                    Items[_stepIdx].CheckmarkIcon = "yellowclockicon.png";
                                    App.User.routines[a].tasks[b].steps[indexForCheckmark].isInProgress = true;

                                    firebaseFunctionsService.StartIS(routineId, taskId, stepDbIdx);
                                }
                                else
                                {
                                    if (isPrevStepComplete)
                                    {
                                        if (isStepInProgress)
                                        {
                                            App.User.routines[a].tasks[b].steps[indexForCheckmark].isInProgress = false;
                                            App.User.routines[a].tasks[b].steps[indexForCheckmark].isComplete   = true;
                                            Items[_stepIdx].CheckmarkIcon = "greencheckmarkicon.png";

                                            firebaseFunctionsService.UpdateStep(routineId, taskId, stepDbIdx);
                                        }
                                        else
                                        {
                                            Items[_stepIdx].CheckmarkIcon = "yellowclockicon.png";
                                            App.User.routines[a].tasks[b].steps[indexForCheckmark].isInProgress = true;

                                            firebaseFunctionsService.StartIS(routineId, taskId, stepDbIdx);
                                        }
                                    }
                                    else
                                    {
                                        await Application.Current.MainPage.DisplayAlert("Oops!", "Please complete each step in order", "OK");
                                    }
                                }
                            }
                        }
                            );
                    }

                    Items.Add(new ListViewItemModel
                              (
                                  stepNum + ". " + App.User.routines[a].tasks[b].steps[stepIdx].title,
                                  _checkmarkIcon,
                                  stepIdx,
                                  _completeStep
                              ));

                    stepIdx++;
                    stepNum++;
                }
            }
        }
Beispiel #20
0
 public async Task TestInsertPreconfirmed()
 {
     string           s   = "*****@*****.**";
     FirestoreService FSS = new FirestoreService(logger);
     await FSS.InsertPreconfirmed(s);
 }
Beispiel #21
0
        async void OnAuthCompleted(object sender, AuthenticatorCompletedEventArgs e)
        {
            var authenticator = sender as OAuth2Authenticator;

            if (authenticator != null)
            {
                authenticator.Completed -= OnAuthCompleted;
                authenticator.Error     -= OnAuthError;
            }

            if (e.IsAuthenticated)
            {
                loginButton.Opacity  = 0;
                loginButton.Clicked -= LoginClicked;
                // If the user is authenticated, request their basic user data from Google
                // UserInfoUrl = https://www.googleapis.com/oauth2/v2/userinfo
                var request  = new OAuth2Request("GET", new Uri(Constants.UserInfoUrl), null, e.Account);
                var response = await request.GetResponseAsync();

                JObject userJson = null;
                if (response != null)
                {
                    // Deserialize the data and store it in the account store
                    // The users email address will be used to identify data in SimpleDB
                    string userJsonString = await response.GetResponseTextAsync();

                    userJson = JObject.Parse(userJsonString);
                }
                else
                {
                    loginButton.Opacity  = 1;
                    loginButton.Clicked += LoginClicked;
                }

                if (userJson != null)
                {
                    Console.WriteLine("HERE is the TOKEN------------------------------------------------");
                    Console.WriteLine(e.Account.Properties["access_token"]);
                    Console.WriteLine("HERE is the REFRESH TOKEN----------------------------------------");
                    Console.WriteLine(e.Account.Properties["refresh_token"]);
                    Console.WriteLine("----------------------------------------------------------------");

                    //Reset accessToken
                    accessToken  = e.Account.Properties["access_token"];
                    refreshToken = e.Account.Properties["refresh_token"];

                    App.User = new user();
                    firebaseFunctionsService = new FirebaseFunctionsService();

                    //Query for email in Users collection
                    App.User.email = userJson["email"].ToString();
                    App.User.id    = firebaseFunctionsService.FindUserDoc(App.User.email).Result;

                    if (App.User.id == "")
                    {
                        await DisplayAlert("Oops!", "Looks like your trusted advisor hasn't registered your account yet. Please ask for their assistance!", "OK");

                        loginButton.Opacity  = 1;
                        loginButton.Clicked += LoginClicked;
                        return;
                    }

                    firestoreService = new FirestoreService();

                    //Save to App.User AND Update Firebase with pertitnent info
                    var googleService = new GoogleService();
                    await googleService.SaveAccessTokenToFireBase(accessToken);

                    Console.WriteLine(refreshToken);
                    await googleService.SaveRefreshTokenToFireBase(refreshToken);

                    //Save Properies inside phone for auto login
                    Application.Current.Properties["accessToken"]  = accessToken;
                    Application.Current.Properties["refreshToken"] = refreshToken;
                    Application.Current.Properties["user_id"]      = App.User.id;

                    App.LoadApplicationProperties();

                    await googleService.RefreshToken();

                    //Navigate to the Daily Page after Login
                    await Navigation.PushAsync(new LoadingPage());
                }
            }
        }
Beispiel #22
0
        /// <summary>
        /// The endpoint hit when a user submits their email to esk8bst
        /// This schedules a Mailgun Email that will include a Confirm Subscribe Link
        /// </summary>
        /// <param name="request"></param>
        /// <param name="context"></param>
        /// <returns></returns>
        public async Task <APIGatewayProxyResponse> Subscribe(APIGatewayProxyRequest request, ILambdaContext context)
        {
            var logger = new Esk8LambdaLogger(context.Logger);

            logger.Log("Subscribe endpoint reached");


            if (request.HttpMethod != HttpMethod.Post.Method)
            {
                return(new APIGatewayProxyResponse()
                {
                    StatusCode = (int)HttpStatusCode.MethodNotAllowed
                });
            }
            ;

            string postbody           = request.Body;
            PostedSubscribeObject pso = null;
            string confirmkey         = "";

            try {
                JObject jobj = JObject.Parse(postbody);
                pso = PostedSubscribeObject.FromJson(jobj);

                if (pso.Email.Contains("@") && pso.Matches.Count > 0)   // we can proceed

                {
                    FirestoreService FSS = new FirestoreService(logger);
                    if (await FSS.CheckIsPreconfirmed(pso.Email))
                    {
                        // Immediately subscribe the user, they've already been here.
                        await FSS.UpsertSubscriber(pso);

                        return(new APIGatewayProxyResponse()
                        {
                            StatusCode = (int)HttpStatusCode.Created,
                            Headers = new Dictionary <string, string> {
                                { "Content-Type", "text/plain" }
                            },
                            Body = "Alright! You've been confirmed as interested in receiving updates from https://esk8bst.com",
                        });
                    }
                    else
                    {
                        // Not pre-confirmed, send an opt-in email.
                        string encryptionKey = Environment.GetEnvironmentVariable("ESK8BST_ENCRYPTION_KEY");
                        confirmkey = EncryptorService.CreateConfirmKey(pso.ToJson().ToString(), encryptionKey);
                    }
                }
            } catch (Exception e) {
                logger.Log($"Tried to parse a malformed subscriber json: {e.Message}");
                return(new APIGatewayProxyResponse()
                {
                    StatusCode = (int)HttpStatusCode.InternalServerError,
                    Headers = new Dictionary <string, string> {
                        { "Content-Type", "text/plain" }
                    },
                    Body = "Failed to parse json properly",
                });
            }

            if (String.IsNullOrWhiteSpace(confirmkey))
            {
                return(new APIGatewayProxyResponse()
                {
                    StatusCode = (int)HttpStatusCode.InternalServerError,
                    Body = "Failed to parse json properly - no email found",
                    Headers = new Dictionary <string, string> {
                        { "Content-Type", "text/plain" }
                    },
                });
            }

            MailgunService MSS = new MailgunService(logger);
            MailgunEmail   m   = new MailgunEmail()
            {
                To = new List <string> {
                    pso.Email
                },
                From    = MailgunService.POSTMASTER,
                Subject = "Esk8Bst Notification Opt In Request",
                Body    = "" +
                          "Someone has registered you as being interested in receiving notifications about new electric skateboard postings from https://esk8bst.com.\n\n" +
                          "If this was you, please click the link below to confirm your email. If this was not you, or you no longer wish to receive emails from us, then ignore this message.\n\n" +
                          $"https://1lol87xzbj.execute-api.us-east-2.amazonaws.com/Prod/confirm?confirmkey={confirmkey}",
            };

            bool success = await MSS.Send(m);

            if (!success)
            {
                return(new APIGatewayProxyResponse()
                {
                    StatusCode = (int)HttpStatusCode.InternalServerError,
                    Body = "Failed to send email to recipent",
                    Headers = new Dictionary <string, string> {
                        { "Content-Type", "text/plain" }
                    },
                });
            }

            //An email has been sent to the address specified confirming your subscription
            var response = new APIGatewayProxyResponse {
                StatusCode = (int)HttpStatusCode.OK,
                Body       = "An email has been sent to the address specified confirming your subscription",
                Headers    = new Dictionary <string, string> {
                    { "Content-Type", "text/plain" }
                },
            };

            return(response);
        }
Beispiel #23
0
        void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            string address = "http://localhost:8080";

            // Start OWIN host
            try
            {
                var proxy = WebApp.Start <SippServer>(url: address);
            }
            catch (TargetInvocationException ex) {
                System.Diagnostics.Process.Start("http://127.0.0.1:8080/");
                MessageBox.Show("Please close the other application that bind 8080 port.\n For example, NI application web server.");
                Environment.Exit(0);
            }

            // load MAC
            try
            {
                var MAC = "";
                using (CINI oTINI = new CINI(Path.Combine(System.Windows.Forms.Application.StartupPath, "Setup.ini")))
                {
                    string sResult = oTINI.getKeyValue("Sensor Data", "MAC"); //Test5: Section;1:Key
                    //this.listBox1.Items.Add(sResult);
                    //MessageBox.Show(sResult);
                    if (sResult != "")
                    {
                        SippDevice.Text = sResult;
                    }
                    string sResult2 = oTINI.getKeyValue("Sensor Data", "Type"); //Test5: Section;1:Key
                    //this.listBox1.Items.Add(sResult);
                    if (sResult2 != "")
                    {
                        //SippDevice.Text = sResult;
                        if (sResult2 == "3x")
                        {
                            Type3XII.IsChecked = true;
                        }
                        if (sResult2 == "6x")
                        {
                            Type6X.IsChecked = true;
                        }
                        if (sResult2 == "9x")
                        {
                            Type9X.IsChecked = true;
                        }
                    }
                }
            }
            catch (TargetInvocationException ex)
            {
                System.Diagnostics.Process.Start("http://127.0.0.1:8080/");
                MessageBox.Show("Please close the other application that bind 8080 port.\n For example, NI application web server.");
                Environment.Exit(0);
            }

            FirestoreService firestoreService = new FirestoreService(new BaseClientService.Initializer
            {
                ApplicationName = "Sipp-PC",
                ApiKey          = "AIzaSyCpPmG-AYByk3hircLVnAY_MLcp5ytIsAI",
            }
                                                                     );

            data                = firestoreService.Projects.Databases.Documents;
            queryWorker         = new BackgroundWorker();
            queryWorker.DoWork += new DoWorkEventHandler(DoJob);

            scratch.Fetch();

            CheckSystemStatus();
            MonitorInsertEvent();
            MonitorRemoveEvent();
        }
        public async void nextpage(object sender, EventArgs args)
        {
            var completeActionCounter = 0;
            var goalId   = App.User.goals[a].id;
            var actionId = App.User.goals[a].actions[b].id;

            if (next.Text == "Done")
            {
                var firestoreService = new FirestoreService();

                firebaseFunctionsService.UpdateTask(goalId, actionId, App.User.goals[a].actions[b].dbIdx.ToString());

                // Set data model completion status
                App.User.goals[a].actions[b].isComplete   = true;
                App.User.goals[a].actions[b].isInProgress = false;
                TaskItemModel.IsComplete   = true;
                TaskItemModel.IsInProgress = false;
                App.User.goals[a].actions[b].dateTimeCompleted = DateTime.Now;

                foreach (action action in App.User.goals[a].actions)
                {
                    if (action.isComplete)
                    {
                        completeActionCounter++;
                    }
                }

                if (completeActionCounter == App.User.goals[a].actions.Count)
                {
                    firebaseFunctionsService.CompleteRoutine(goalId, App.User.goals[a].dbIdx.ToString());

                    // Set data model completion status
                    App.User.goals[a].isComplete   = true;
                    App.User.goals[a].isInProgress = false;
                    if (App.ParentPage != "ListView")
                    {
                        GRItemModel.IsComplete   = true;
                        GRItemModel.IsInProgress = false;
                        GRItemModel.Text         = "Done";
                    }
                    App.User.goals[a].dateTimeCompleted = DateTime.Now;
                }

                await Navigation.PopAsync();
            }

            else if (next.Text == "Start")
            {
                int idx = 0;
                while (App.User.goals[a].actions[b].instructions[idx].isComplete)
                {
                    idx++;
                    Console.WriteLine("instruction complete idx: " + idx);
                }
                //App.user.goals[a].actions[b].instructions[0].isComplete = true;
                next.Text = "Next";
                CarouselTasks.Position = idx;
                Console.WriteLine("CarouselTasks.Position: " + CarouselTasks.Position);
                await Task.Delay(2000);
            }

            else if (CarouselTasks.Position != App.User.goals[a].actions[b].instructions.Count - 1)
            {
                /*var firestoreService = new FirestoreService(App.User.id);
                 * var goalId = App.user.goals[a].id;
                 * var actionId = App.user.goals[a].actions[b].id;
                 * var isInstructionComplete = await firestoreService.UpdateInstruction(goalId, actionId, App.user.goals[a].actions[b].instructions[CarouselTasks.Position].dbIdx.ToString());
                 * if (isInstructionComplete)
                 * {
                 *  App.user.goals[a].actions[b].instructions[CarouselTasks.Position].isComplete = true;
                 *  App.user.goals[a].actions[b].instructions[CarouselTasks.Position].dateTimeCompleted = DateTime.Now;
                 * }*/
                App.User.goals[a].actions[b].instructions[CarouselTasks.Position].isComplete = true;
                pageModel.Items[CarouselTasks.Position].OkToCheckmark = true;
                firebaseFunctionsService.UpdateInstruction(goalId, actionId, App.User.goals[a].actions[b].instructions[CarouselTasks.Position].dbIdx.ToString());

                CarouselTasks.Position = CarouselTasks.Position + 1;
            }
            else if (CarouselTasks.Position == App.User.goals[a].actions[b].instructions.Count - 1)
            {
                App.User.goals[a].actions[b].instructions[CarouselTasks.Position].isComplete = true;
                pageModel.Items[CarouselTasks.Position].OkToCheckmark = true;
                firebaseFunctionsService.UpdateInstruction(goalId, actionId, App.User.goals[a].actions[b].instructions[CarouselTasks.Position].dbIdx.ToString());

                next.Text = "Done";
            }
            else if (CarouselTasks.Position != App.User.goals[a].actions[b].instructions.Count - 1)
            {
                App.User.goals[a].actions[b].instructions[CarouselTasks.Position].isComplete = true;
                pageModel.Items[CarouselTasks.Position].OkToCheckmark = true;
                firebaseFunctionsService.UpdateInstruction(goalId, actionId, App.User.goals[a].actions[b].instructions[CarouselTasks.Position].dbIdx.ToString());


                next.Text = "Done";
            }
        }
Beispiel #25
0
 public FirestoreHandler(IOrderService orderService, FirestoreService firestoreService, ILogger <FirestoreHandler> logger)
 {
     _orderService     = orderService;
     _firestoreService = firestoreService;
     _logger           = logger;
 }