Exemplo n.º 1
0
        private async void StartTask(AppTask taskData)
        {
            switch (taskData.TaskType.IdName)
            {
            case "DRAW":
            case "DRAW_PHOTO":
                DrawingViewController drawingController = Storyboard.InstantiateViewController("DrawingController") as DrawingViewController;
                drawingController.StartTask(DisplayedActivity, taskData, TaskResultReturned, NavigationController);

                // check to see if should draw on previous task's result
                if (taskData.JsonData.StartsWith("TASK::", StringComparison.OrdinalIgnoreCase))
                {
                    int id = -1;
                    int.TryParse(taskData.JsonData.Substring(6), out id);
                    string[] paths = JsonConvert.DeserializeObject <string[]>(
                        ((TaskViewSource)TableView.Source).GetWithId(id)?.CompletionData.JsonData);

                    if (paths != null && paths.Length > 0)
                    {
                        drawingController.previousImage = paths[0];
                    }
                }

                break;

            case "LISTEN_AUDIO":
                ResultMediaViewerController listenAudioController = Storyboard.InstantiateViewController("MediaViewerController") as ResultMediaViewerController;
                listenAudioController.FilePath     = GetCacheFilePath(taskData.JsonData, DisplayedActivity.Id, ServerUtils.GetFileExtension(taskData.TaskType.IdName));;
                listenAudioController.Task         = taskData;
                listenAudioController.DeleteResult = null;
                NavigationController.PushViewController(listenAudioController, true);

                // Mark as complete
                TaskResultReturned(null, taskData.Id);

                break;

            case "MAP_MARK":
                MapMarkingViewController mapMarkController = Storyboard.InstantiateViewController("MapMarkController") as MapMarkingViewController;
                mapMarkController.StartTask(DisplayedActivity, taskData, TaskResultReturned, NavigationController);
                break;

            case "LOC_HUNT":
                LocationHuntViewController locHuntController = Storyboard.InstantiateViewController("LocationHuntController") as LocationHuntViewController;
                locHuntController.StartTask(DisplayedActivity, taskData, TaskResultReturned, NavigationController);
                break;

            case "ENTER_TEXT":
                EnterTextViewController textController = Storyboard.InstantiateViewController("EnterTextController") as EnterTextViewController;
                textController.StartTask(DisplayedActivity, taskData, TaskResultReturned, NavigationController);
                break;

            case "MULT_CHOICE":
                MultipleChoiceController mcController = Storyboard.InstantiateViewController("MultipleChoiceController") as MultipleChoiceController;
                mcController.StartTask(DisplayedActivity, taskData, TaskResultReturned, NavigationController);
                break;

            case "TAKE_VIDEO":
                bool hasMicPerms = await AppUtils.AuthorizeMic();

                if (!hasMicPerms)
                {
                    AppUtils.ShowSimpleDialog(this, "Requires Microphone", "Please grant OurPlace microphone access in the system settings to complete this task!", "Ok");
                    return;
                }
                goto case "TAKE_PHOTO";     // eew C# why u do dis

            case "MATCH_PHOTO":
            case "TAKE_PHOTO":
                bool hasCamPerms = await AppUtils.AuthorizeCamera();

                if (!hasCamPerms)
                {
                    AppUtils.ShowSimpleDialog(this, "Requires Camera", "Please grant OurPlace camera access in the system settings to complete this task!", "Ok");
                    return;
                }
                CameraViewController camController = Storyboard.InstantiateViewController("PhotoTaskViewController") as CameraViewController;
                camController.StartTask(DisplayedActivity, taskData, TaskResultReturned, NavigationController);
                break;

            case "REC_AUDIO":
                hasMicPerms = await AppUtils.AuthorizeMic();

                if (!hasMicPerms)
                {
                    AppUtils.ShowSimpleDialog(this, "Requires Microphone", "Please grant OurPlace microphone access in the system settings to complete this task!", "Ok");
                    return;
                }
                RecordAudioController audioController = Storyboard.InstantiateViewController("RecordAudioController") as RecordAudioController;
                audioController.StartTask(DisplayedActivity, taskData, TaskResultReturned, NavigationController);
                break;

            case "SCAN_QR":
                StartScanning(taskData);
                break;

            default:
                Console.WriteLine("Unknown task type: " + taskData.TaskType.IdName);
                break;
            }
        }
Exemplo n.º 2
0
        public override async void ViewDidLoad()
        {
            base.ViewDidLoad();

            fileName = DateTime.Now.ToString("yyyy-MM-dd_HH-mm-ss") + ".m4a";

            if (!createMode)
            {
                if (thisTask == null || thisActivity == null)
                {
                    AppUtils.ShowSimpleDialog(this, "ERROR", "Error loading task data", "Ok");
                    NavigationController.PopViewController(true);
                    return;
                }

                TaskDescriptionLabel.Text = thisTask.Description;

                folderName = Common.LocalData.Storage.GetCacheFolder(thisActivity.Id.ToString());
            }
            else
            {
                // set up for recording to 'listen to audio' tasks
                folderName = Common.LocalData.Storage.GetCacheFolder("created");
            }

            filePath = Path.Combine(folderName, fileName);


            // Sanity check for permissions - if we're here, it should be safe
            bool hasPerm = await AppUtils.AuthorizeMic();

            if (!hasPerm)
            {
                AppUtils.ShowSimpleDialog(this, "Requires Microphone", "Please grant OurPlace microphone access in the system settings to record audio clips!", "Ok");
                NavigationController.PopViewController(true);
                return;
            }

            // Set up audio recording session
            audioSession = AVAudioSession.SharedInstance();
            NSError err = audioSession.SetCategory(AVAudioSessionCategory.PlayAndRecord);

            if (err != null)
            {
                Console.WriteLine("ERROR setting up audio session: " + err.LocalizedDescription);
                return;
            }

            err = audioSession.SetActive(true);
            if (err != null)
            {
                Console.WriteLine("ERROR activating audio session: " + err.LocalizedDescription);
                return;
            }

            //set up the NSObject Array of values that will be combined with the keys to make the NSDictionary
            NSObject[] values = new NSObject[]
            {
                NSNumber.FromFloat(16000.0f),                                   //Sample Rate
                NSNumber.FromInt32((int)AudioToolbox.AudioFormatType.MPEG4AAC), //AVFormat
                NSNumber.FromInt32(1),                                          //Channels
                NSNumber.FromInt32(16),                                         //PCMBitDepth
                NSNumber.FromBoolean(false),                                    //IsBigEndianKey
                NSNumber.FromBoolean(false)                                     //IsFloatKey
            };

            //Set up the NSObject Array of keys that will be combined with the values to make the NSDictionary
            NSObject[] keys = new NSObject[]
            {
                AVAudioSettings.AVSampleRateKey,
                AVAudioSettings.AVFormatIDKey,
                AVAudioSettings.AVNumberOfChannelsKey,
                AVAudioSettings.AVLinearPCMBitDepthKey,
                AVAudioSettings.AVLinearPCMIsBigEndianKey,
                AVAudioSettings.AVLinearPCMIsFloatKey
            };

            //Set Settings with the Values and Keys to create the NSDictionary
            settings = NSDictionary.FromObjectsAndKeys(values, keys);

            //Set recorder parameters
            recorder = AVAudioRecorder.Create(NSUrl.FromFilename(filePath), new AudioSettings(settings), out error);

            recorder.PrepareToRecord();
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            NSNotificationCenter.DefaultCenter.AddObserver(UIKeyboard.DidShowNotification, KeyboardUpNotification);

            ActivityTitle.ShouldReturn          += TextFieldShouldReturn;
            ActivityTitle.EditingDidBegin       += TextFieldEditingDidBegin;
            ActivityDescription.ShouldReturn    += TextFieldShouldReturn;
            ActivityDescription.EditingDidBegin += TextFieldEditingDidBegin;

            // Limit how long the title and description strings can be
            ActivityTitle.ShouldChangeCharacters += (textField, range, replacementString) =>
            {
                var newLength = textField.Text.Length + replacementString.Length - range.Length;
                return(newLength <= 36 || (replacementString.Length - range.Length <= 0));
            };

            ActivityDescription.ShouldChangeCharacters += (textField, range, replacementString) =>
            {
                var newLength = textField.Text.Length + replacementString.Length - range.Length;
                return(newLength <= 128 || (replacementString.Length - range.Length <= 0));
            };

            UITapGestureRecognizer tapGestureRecognizer =
                new UITapGestureRecognizer(() => View.EndEditing(true));

            View.AddGestureRecognizer(tapGestureRecognizer);

            UITapGestureRecognizer imageTapGesture = new UITapGestureRecognizer(ImageTapped)
            {
                NumberOfTapsRequired = 1
            };

            ActivityLogo.UserInteractionEnabled = true;
            ActivityLogo.AddGestureRecognizer(imageTapGesture);

            folderPath = Common.LocalData.Storage.GetCacheFolder("created");

            if (thisActivity != null)
            {
                // Load previously entered data into fields
                ActivityTitle.Text       = thisActivity.Name;
                ActivityDescription.Text = thisActivity.Description;
                if (!string.IsNullOrWhiteSpace(thisActivity.ImageUrl))
                {
                    previousImagePath = thisActivity.ImageUrl;
                    Console.WriteLine("Existing image path: " + previousImagePath);

                    if (thisActivity.ImageUrl.StartsWith("upload"))
                    {
                        ImageService.Instance.LoadUrl(ServerUtils.GetUploadUrl(previousImagePath))
                        .Transform(new CircleTransformation())
                        .Into(ActivityLogo);
                    }
                    else
                    {
                        string url = AppUtils.GetPathForLocalFile(previousImagePath);

                        var suppress = ImageService.Instance.InvalidateCacheEntryAsync(url, FFImageLoading.Cache.CacheType.All, true);
                        ImageService.Instance.LoadFile(url).Transform(new CircleTransformation()).Into(ActivityLogo);
                    }
                }
            }

            ContinueButton.TouchUpInside += ContinuePressed;
            CancelButton.TouchUpInside   += CancelPressed;
        }
        private async void RefreshFeed()
        {
            ShowLoading();

            if (dbManager == null)
            {
                dbManager = await Storage.GetDatabaseManager();
            }

            // If we don't have internet, don't bother getting the location or
            // polling the server
            if (!AppDelegate.Online)
            {
                Console.WriteLine("No Internet access, loading cached feed");
                Toast.ShowToast("Couldn't reach the server - please check your connection!");
                AppDelegate.WhenOnline = RefreshFeed; // Reload if connection returns
                HideLoading();
                return;
            }

            Common.ServerResponse <List <LearningActivity> > results =
                await Common.ServerUtils.Get <List <LearningActivity> >(
                    "/api/learningactivities/getfromuser/?creatorId=" + dbManager.currentUser.Id);

            if (results == null)
            {
                var suppress = AppUtils.SignOut(this);
            }

            List <ActivityFeedSection> feed = new List <ActivityFeedSection>();


            string unsubmittedActivitiesJson = dbManager.currentUser.LocalCreatedActivitiesJson;

            unsubmittedActivities = null;

            if (!string.IsNullOrWhiteSpace(unsubmittedActivitiesJson))
            {
                unsubmittedActivities = JsonConvert.DeserializeObject <List <LearningActivity> >(
                    unsubmittedActivitiesJson,
                    new JsonSerializerSettings
                {
                    TypeNameHandling      = TypeNameHandling.Objects,
                    ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
                    MaxDepth = 10
                });
            }

            // Add a section to the feed if the user has activities which they didn't finish creating
            if (unsubmittedActivities != null && unsubmittedActivities.Count > 0)
            {
                feed.Add(new ActivityFeedSection
                {
                    Title       = "In Progress",
                    Description = "Tap to continue making these activities.",
                    Activities  = unsubmittedActivities
                });
            }

            List <LearningActivity> activitiesList = null;

            if (results.Success && results.Data != null)
            {
                activitiesList = results.Data.OrderByDescending((LearningActivity arg) => arg.CreatedAt).ToList();

                // Save this in the offline cache
                dbManager.currentUser.RemoteCreatedActivitiesJson = JsonConvert.SerializeObject(results.Data,
                                                                                                new JsonSerializerSettings
                {
                    TypeNameHandling      = TypeNameHandling.Objects,
                    ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
                    MaxDepth = 6
                });
                dbManager.AddUser(dbManager.currentUser);
            }
            else
            {
                Toast.ShowToast("Couldn't reach the server - please check your connection!");
                if (!string.IsNullOrWhiteSpace(dbManager.currentUser.RemoteCreatedActivitiesJson))
                {
                    activitiesList = JsonConvert.DeserializeObject <List <LearningActivity> >(
                        dbManager.currentUser.RemoteCreatedActivitiesJson);
                }
            }

            if (activitiesList != null && activitiesList.Count > 0)
            {
                feed.Add(new ActivityFeedSection
                {
                    Title       = "Your Uploaded Activities",
                    Description = "These are the activities that you have previously uploaded",
                    Activities  = activitiesList
                });
            }

            hasContent = feed.Count > 0;

            if (feed.Count == 0)
            {
                feed.Add(new ActivityFeedSection
                {
                    Title       = "No Activities Created",
                    Description = "You haven't made any activities yet! Click the '+' button in the top right to get started.",
                    Activities  = new List <LearningActivity>()
                });
            }

            source.Rows = feed;

            collectionView.ReloadData();

            HideLoading();
        }
Exemplo n.º 5
0
        private async Task <bool> UploadResults(int index, Action OnFinish)
        {
            ShowLoading();

            AppDataUpload upload = viewSource.Rows[index];

            DatabaseManager dbManager = await Storage.GetDatabaseManager();

            // Upload relevent files
            bool success = await Storage.UploadFiles(
                JsonConvert.DeserializeObject <List <FileUpload> >(upload.FilesJson),
                index,
                (percentage) =>
            {
                Console.WriteLine("Upload percentage: " + percentage);
                loadPop.loadingLabel.Text = string.Format("Uploading: {0}%", percentage);
            },
                (listPos, jsonData) =>
            {
                viewSource.Rows[listPos].FilesJson = jsonData;
                dbManager.UpdateUpload(viewSource.Rows[listPos]);
                viewSource.UpdateData(dbManager.GetUploadQueue().ToList());
                upload = viewSource.Rows[index];
            },
                (upload.UploadType == UploadType.NewActivity ||
                 upload.UploadType == UploadType.UpdatedActivity)?Storage.GetCacheFolder() : Storage.GetUploadsFolder()
                );

            if (!success)
            {
                HideLoading();
                AppUtils.ShowSimpleDialog(this, "Unable to Upload", "Something went wrong, please try again later.", "Got it");
                return(false);
            }

            ServerResponse <string> resp = new ServerResponse <string>();

            if (upload.UploadType == UploadType.NewActivity ||
                upload.UploadType == UploadType.UpdatedActivity)
            {
                resp = await ServerUtils.UploadActivity(upload, upload.UploadType == UploadType.UpdatedActivity);
            }
            else
            {
                // Uploading activity results
                List <FileUpload> files = JsonConvert.DeserializeObject <List <FileUpload> >(upload.FilesJson);

                AppTask[] results = JsonConvert.DeserializeObject <AppTask[]>(upload.JsonData) ?? new AppTask[0];
                resp = await ServerUtils.UpdateAndPostResults(results, files, upload.UploadRoute);
            }

            HideLoading();

            if (resp == null)
            {
                // do this but for iOS, fool
                var suppress = AppUtils.SignOut(this);
                return(false);
            }

            if (!resp.Success)
            {
                AppUtils.ShowSimpleDialog(this, "Unable to Upload", "Something went wrong, please try again later.", "Got it");
                return(false);
            }

            dbManager.DeleteUpload(upload);

            var newList = dbManager.GetUploadQueue().ToList();

            viewSource.UpdateData(newList);
            TableView.ReloadData();

            await(ParentViewController as MainTabBarController).UpdateUploadsBadge(newList.Count);
            ManageNavItems();

            OnFinish?.Invoke();

            return(true);
        }
Exemplo n.º 6
0
 private void UploadsComplete()
 {
     AppUtils.ShowSimpleDialog(this, "Uploaded!", "Successfully uploaded. Go to ourplace.app to view your submissions!", "Got it");
 }
Exemplo n.º 7
0
        private async Task GetFromServer()
        {
            ShowLoading();

            double lat = 0;
            double lon = 0;

            if (lastLoc != null)
            {
                lat = lastLoc.Coordinate.Latitude;
                lon = lastLoc.Coordinate.Longitude;
            }

            Common.ServerResponse <List <ActivityFeedSection> > remoteResults = await Common.ServerUtils.Get <List <ActivityFeedSection> >(
                string.Format("/api/learningactivities/GetFeed?lat={0}&lon={1}", lat, lon));

            HideLoading();

            if (remoteResults == null)
            {
                var suppress = AppUtils.SignOut(this);
            }

            List <ActivityFeedSection> feed = new List <ActivityFeedSection>();

            // add already cached section
            if (recentActivities != null)
            {
                feed.Add(recentActivities);
            }

            if (remoteResults.Success && remoteResults.Data != null)
            {
                lastFromServer = remoteResults.Data;

                // Save this in the offline cache
                dbManager.currentUser.CachedActivitiesJson = JsonConvert.SerializeObject(remoteResults.Data,
                                                                                         new JsonSerializerSettings
                {
                    TypeNameHandling      = TypeNameHandling.Objects,
                    ReferenceLoopHandling = ReferenceLoopHandling.Serialize,
                    MaxDepth = 6
                });
                dbManager.AddUser(dbManager.currentUser);
            }
            else
            {
                Toast.ShowToast("Couldn't reach the server - please check your connection!");
                lastFromServer = JsonConvert.DeserializeObject <List <ActivityFeedSection> >(
                    dbManager.currentUser.CachedActivitiesJson);
            }

            if (lastFromServer != null)
            {
                feed.AddRange(lastFromServer);
            }

            source.Rows = feed;

            collectionView.ReloadData();
        }