public void RemoveScreenOf(MultimediaObject mmo) { GameObject go = null; foreach (GameObject g in ActiveScreens) { if (g.GetComponent <MMOContainer>() != null && g.GetComponent <MMOContainer>().MultimediaObject.Equals(mmo)) { { go = g; break; } } } if (go != null) { var geoposed = go.GetComponent <GeoPositioned>(); if (geoposed != null) { arMapper.RemoveGeoPositioned(geoposed); } ActiveScreens.Remove(go); } }
public void Display(MultimediaObject mmo) { logger.Debug("Displaying"); if (DisplayAR) { logger.Debug("Trying to display AR style"); logger.Debug("AR Mapper state: " + arMapper.GetState()); if (arMapper.IsAvailable()) { Display3D(mmo); return; } if (!arMapper.IsInitialised()) { toDisplay = mmo; arMapper.SetOnInitialised(Display); uiManager.SwitchCams(true); uiManager.panelManager.ShowPanel("ar-display"); arMapper.Initialise(); return; } } Display2D(mmo); }
public void Present(MultimediaObject mmo) { DisplayInfo(mmo); imagePresenter.LoadImage(CineastUtils.GetThumbnailUrl(mmo)); active = mmo; titleLabel.text = "Result " + mmo.resultIndex; }
private void DisplayInfo(MultimediaObject mmo) { string dist = uiManager.GetRoundedDist(new GeoLocation(mmo.latitude, mmo.longitude), controller.GetLastKnownLocation()); infoLabel.text = string.Format("Dist: {0}m\nDate: {1}", dist, UIManager.FormatDate(mmo)); }
private void RestoreState() { logger.Debug("Restoring state"); if (IOUtils.ExistsPersitentData()) { SaveState save = IOUtils.LoadData(); logger.Debug("Restored state: " + JsonUtility.ToJson(save)); switch (save.state) { case State.LOCATION_STARTED: targetList = save.targetList; currentState = save.state; activeMmos = save.activeMmos; Invoke("RestoreChoice", 0.5f); // Restart location service // Run is-close check WatchAll(); break; case State.LOCATION_FOUND: case State.DISPLAYING: active = save.active; // Restart display service break; } } if (IOUtils.ExistsHeadingFile()) { headingDictionary = IOUtils.LoadHeadings(); Debug.Log("Loaded headings:\n" + JsonUtility.ToJson(headingDictionary)); } }
// If already in list, ignored public void AddToActiveList(MultimediaObject mmo) { if (!activeMmos.Contains(mmo)) { activeMmos.Add(mmo); } }
public void Present(MultimediaObject mmo, bool loadInRange = true) { Debug.Log("Presenting " + mmo.id); //panelSwitcher.SwitchToDisplay(); panelManager.ShowPanel("display"); presenter.LoadImage(CineastUtils.GetImageUrl(mmo)); logger.Debug("URL: " + CineastUtils.GetImageUrl(mmo)); alphaController.SetAlpha(0.5f); if (controller.GetHeading(mmo) != -1) { headingDisplay.targetHeading = controller.GetHeading(mmo); } infoText.text = string.Format("Index: {0}\nDate: {1}", mmo.resultIndex, FormatDate(mmo)); activeMmo = mmo; if (loadInRange) { Debug.Log("LOAD IN RANGE"); List <MultimediaObject> inRangeList = controller.GetInRange(activeMmo); temporalSlider.Setup(inRangeList, activeMmo); // ArgumentNull in DatetimeParser, parameter name s } controller.StopLocationServices(); // TODO Remove activeMMO and restart location service }
/** * Creates an object of a given metadataobject and sets the meta data * * Currently is only lat/lon supported * * @param meta - the meta data object. * * */ public static MultimediaObject ConvertFrom(MetaDataObject meta) { MultimediaObject output = new MultimediaObject(); output.id = meta.objectId; output.AddMetaData(meta); return(output); }
public ActionResult Add(CropAndAddMultimediaObjectViewModel Model) { if (ModelState.IsValid) { if (string.IsNullOrEmpty(Model.MultimediaObject.Url)) { ModelState.AddModelError("MultimediaObject.Url", "Podanie Adresu URL jest wymagane!"); var tt = _typeRespository.Types.Select(it => new { Value = it.Id, Text = it.Name + " szer: " + it.Width + "px wys: " + it.Height + "px" }); Model.MultimediaTypes = new SelectList(tt, "Value", "Text"); return(View(Model)); } int cropPointX = Model.x; int cropPointY = Model.y; int imageCropWidth = Model.w; int imageCropHeight = Model.h; MemoryStream target = new MemoryStream(); Model.inputFile.InputStream.CopyTo(target); byte[] imageBytes = target.ToArray(); byte[] croppedImage; if (imageCropHeight > 0 && imageCropWidth > 0) { croppedImage = ImageHelper.CropImage(imageBytes, cropPointX, cropPointY, imageCropWidth, imageCropHeight); } else { croppedImage = imageBytes; } ADServerDAL.Models.Type type = _typeRespository.GetById((int)Model.MultimediaObject.TypeId); croppedImage = ImageProcesorHelper.ResizeImage(type.Width, type.Height, croppedImage, false).ResizedImage; MultimediaObject image = new MultimediaObject { Contents = croppedImage, Content = croppedImage, FileName = Model.inputFile.FileName, MimeType = Model.inputFile.ContentType, TypeId = Model.MultimediaObject.TypeId, Name = Model.MultimediaObject.Name, UserId = User.GetUserIDInt(), Url = Model.MultimediaObject.Url, Campaigns = Model.MultimediaObject.Campaigns }; if (image.UserId == 0 || (!User.IsInRole("Admin") && User.GetUserIDInt() != image.UserId)) { image.UserId = User.GetUserIDInt(); } _repository.Save(image, Model.MultimediaObject.Campaigns.ToList()); return(RedirectToAction("Index")); } var t = _typeRespository.Types.Select(it => new { Value = it.Id, Text = it.Name + " szer: " + it.Width + "px wys: " + it.Height + "px" }); Model.MultimediaTypes = new SelectList(t, "Value", "Text"); return(View(Model)); }
public IObservable<Unit> InsertMultimediaObject(MultimediaObject mmo) { var res = InsertMMOCompleted.MakeObservableServiceResultSingle(mmo) .Select(_ => Unit.Default); var repoMmo = mmo.ToServiceObject(Mapping); WithCredentials(c => _svc.InsertMMOAsync(repoMmo, c, mmo)); return res; }
public IObservable<Unit> InsertMultimediaObject(MultimediaObject mmo) { var res = InsertMMOCompleted.MakeObservableServiceResultSingle(mmo) .Select(_ => Unit.Default); var repoMmo = mmo.ToServiceObject(Mapping); _svc.InsertMMOAsync(repoMmo, this.GetCreds(), mmo); return res; }
public int GetHeading(MultimediaObject mmo) { if (float.IsNaN(headingDictionary.GetHeading(mmo.id))) { return(-1); } return((int)headingDictionary.GetHeading(mmo.id)); }
private void HandleLocationFound(LocationObject target) { logger.Debug("HandleLocationFound " + target.latitude + "," + target.longitude); ChangeState(State.LOCATION_FOUND); active = FindMmo(target); Display(active); //unityLocation.StopService(); //nativeLocation.StopService(); }
public static MultimediaObject ConvertFrom(CineastObject obj) { MultimediaObject output = new MultimediaObject(); output.id = obj.objectId; output.name = obj.name; output.path = obj.path; return(output); }
/// <summary> /// Zapisuje obiekt multimedialny do bazy danych /// </summary> /// <param name="multimediaObject">Obiekt multimedialny</param> public ApiResponse SaveObject(MultimediaObject multimediaObject) { if (multimediaObject.UserId == 0 || (!User.IsInRole("Admin") && User.GetUserIDInt() != multimediaObject.UserId)) { multimediaObject.UserId = User.GetUserIDInt(); } List <Campaign> CampList = multimediaObject.Campaigns.ToList(); return(objectRepository.Save(multimediaObject, CampList)); }
private void Display2D(MultimediaObject mmo) { logger.Debug("Display Index:" + mmo.resultIndex); ChangeState(State.DISPLAYING); uiManager.Present(mmo); uiManager.viewDisplayHomeBtn.gameObject.SetActive(true); // Setup Cam // Retrieve Image // display image and all }
public MultimediaObject GetMultimediaObject(int index) { MultimediaObject ret = null; foreach (MultimediaObject mmo in mmoList) { if (mmo.resultIndex == index) { ret = mmo; } } return(ret); }
public static string FormatDate(MultimediaObject mmo) { DateTime dt = DateTime.MaxValue; try { dt = DateTime.Parse(mmo.datetime); } catch (ArgumentNullException ex) { // Silently ignoring } catch (FormatException e) { // silently ignoring } return(dt != DateTime.MaxValue ? dt.ToString("dd. MMM yyyy") : ""); }
private string ServiceFileName(MultimediaObject mmo, int CollectionOwnerID) { string extension; switch (mmo.MediaType) { case MediaType.Image: extension = "jpg"; break; case MediaType.Audio: extension = "wav"; break; case MediaType.Video: extension = "mp4"; break; default: throw new ArgumentException("Unknown Media Type"); } string ownerCode; switch (mmo.OwnerType) { case DBObjectType.Event: ownerCode = "EV"; break; case DBObjectType.Specimen: ownerCode = "SP"; break; case DBObjectType.IdentificationUnit: ownerCode = "IU"; break; default: throw new ArgumentException("Unsupported Media Owner"); } return string.Format("DM-{0}-{1}-{2}-{3}.{4}", ownerCode, CollectionOwnerID, mmo.TimeCreated.ToString("yyyyMMdd", CultureInfo.InvariantCulture), mmo.TimeCreated.ToString("HHmmss", CultureInfo.InvariantCulture), extension ); }
public IObservable<Uri> UploadMultimedia(MultimediaObject mmo, byte[] data) { var login = this.GetCreds(); var res = UploadMultimediaCompleted.MakeObservableServiceResultSingle(mmo) .Select(p => { var uriString = p.Result; if (!string.IsNullOrWhiteSpace(uriString) && uriString.ToLowerInvariant().StartsWith("http://")) return new Uri(p.Result, UriKind.Absolute); else throw new ServiceOperationException(p.Result); }); var collectionOwnerID = Mapping.EnsureKey(mmo.OwnerType, mmo.RelatedId); var filename = ServiceFileName(mmo, collectionOwnerID); _multimedia.SubmitAsync(Guid.NewGuid().ToString(), filename, mmo.MediaType.ToString(), 0, 0, 0, login.LoginName,mmo.TimeStamp.ToString(CultureInfo.InvariantCulture), login.ProjectID, data, mmo); return res; }
public List <MultimediaObject> GetInRange(MultimediaObject mmo, double dist = 75 /*m*/) { List <MultimediaObject> ret = new List <MultimediaObject>(); if (!double.IsNaN(mmo.latitude)) { foreach (MultimediaObject mo in activeMmos) { double d = Utilities.HaversineDistance(mmo.latitude, mmo.longitude, mo.latitude, mo.longitude); if (d <= dist) { ret.Add(mo); } } } return(ret); }
public static List <MultimediaObject> Convert(MetaDataObject[] metas) { List <MultimediaObject> objects = new List <MultimediaObject>(); foreach (MetaDataObject meta in metas) { MultimediaObject obj = ConvertFrom(meta); if (objects.Contains(obj)) { objects.Find(o => o.Equals(obj)).Merge(obj); } else { objects.Add(obj); } } return(objects); }
public static List <MultimediaObject> Convert(CineastObject[] objects) { List <MultimediaObject> list = new List <MultimediaObject>(); foreach (CineastObject obj in objects) { MultimediaObject mmo = ConvertFrom(obj); if (list.Contains(mmo)) { list.Find(o => o.Equals(mmo)).Merge(mmo); } else { list.Add(mmo); } } return(list); }
private void Display3D(MultimediaObject mmo) { logger.Debug("Displaying AR style! " + mmo.id); var scrn = Instantiate(ScreenPrefab); var mmoContainer = scrn.AddComponent <MMOContainer>(); var textured = scrn.GetComponentInChildren <WebTextured>(); if (textured == null) { textured = scrn.AddComponent <WebTextured>(); } textured.url = CineastUtils.GetImageUrl(mmo); // Too high res? //textured.url = CineastUtils.GetThumbnailUrl(mmo); textured.LoadImageFromWeb(); mmoContainer.MultimediaObject = mmo; var geoposed = scrn.AddComponent <GeoPositioned>(); geoposed.GeoCoordinates = new GeoArithmetic.GeoCoordinates(mmo.latitude, mmo.longitude); geoposed.Bearing = (float)mmo.bearing; arMapper.AddGeoPositioned(geoposed); ActiveScreens.Add(scrn); }
/** * -1 == empty similar result * -2 == empty result object * -3 == not found */ public static int GetIndexOf(MultimediaObject needle, SimilarResult haystack) { if (haystack.IsEmpty()) { return(-1); } foreach (ResultObject resultObject in haystack.results) { if (resultObject.IsEmpty()) { return(-2); } foreach (ContentObject contentObject in resultObject.content) { if (contentObject.key.Equals(needle.id + "_1"))// FIX hardcoded segment id { return(Array.IndexOf(resultObject.content, contentObject)); } } } return(-3); }
public void Setup(List <MultimediaObject> mmos, MultimediaObject active) { logger.Debug("Setup"); setupFinished = false; dict.Clear(); foreach (MultimediaObject mmo in mmos) { DateTime dt = DateTime.Parse(mmo.datetime); // mmo.dateitme is null, TODO investigate int key = dt.Year * 10; // times ten to have multiple entries per year (10) while (dict.ContainsKey(key)) { logger.Debug("Key {0} already used. decrease key by one", key, key - 1); key--; } dict.Add(key, mmo); logger.Debug("Added {0}/{1} to dict (origin year: {2})", key, mmo.id, dt.Year); } List <int> keys = new List <int>(dict.Keys); keys.Sort((i, j) => i - j); // basic integer sorting int min = keys[0]; int max = keys[keys.Count - 1]; logger.Debug("Range: {0} to {1}", min, max); lowerLabel.text = "" + min / 10; //dont disp on label upperLabel.text = "" + max / 10; //dont disp on label slider.minValue = 0; slider.maxValue = 1; slider.wholeNumbers = false; DateTime adt = DateTime.Parse(active.datetime); slider.value = keys.IndexOf(adt.Year * 10); logger.Debug("Slider should:({0},{1},{2})", min, adt.Year * 10, max); logger.Debug("Slider is:({0},{1},{2})", slider.minValue, slider.value, slider.maxValue); logger.Debug("Setup finished!"); setupFinished = true; }
private void AddObjectToScroll(MultimediaObject mmo) { Debug.Log(":AddObjectToScroll " + (mmo != null ? JsonUtility.ToJson(mmo) : "null")); GameObject panel = Instantiate(prefab); Debug.Log("panel: " + (panel == null ? "null" : "found")); panel.transform.SetParent(scrollContent, false); var ctrl = panel.GetComponent <DisplayController>(); Debug.Log("ctrl " + (ctrl == null ? "Null" : "received")); ctrl.SetTitle(string.Format("Result: {0}", mmo.resultIndex)); Debug.Log("initalGeoLoc: " + (initialGeoLocation == null ? "null" : "present")); double dist = Utilities.HaversineDistance(mmo.latitude, mmo.longitude, initialGeoLocation.latitude, initialGeoLocation.longitude); string footerText = string.Format("Distance: {0}m\nDate: {1}", Round(dist), FormatDate(mmo)); ctrl.SetFooter(footerText); ctrl.LoadImageFromWeb(CineastUtils.GetThumbnailUrl(mmo)); ctrl.Mmo = mmo; ctrl.UiManager = this; ctrl.Controller = controller; }
public MultimediaObject EditCamps(MultimediaObject image, List <int> CampsList) { //var image = Context.MultimediaObjects.FirstOrDefault(p => p.Id == imageId); foreach (var campItem in image.Campaigns.ToList()) { if (!CampsList.Contains(campItem.Id)) { image.Campaigns.Remove(campItem); } } foreach (var campItem in CampsList) { if (!image.Campaigns.Any(c => c.Id == campItem)) { var campa = Context.Campaigns.SingleOrDefault(c => c.Id == campItem); image.Campaigns.Add(campa); } } //Context.SaveChanges(); return(image); }
/// <summary> /// Zapisuje obiekt multimedialny do bazy /// </summary> /// <param name="multimediaObject">Obiekt multimedialny</param> public ApiResponse Save(MultimediaObject multimediaObject, List <Campaign> Camps) { var response = new ApiResponse(); if (!string.IsNullOrEmpty(multimediaObject.FileContent)) { var index = multimediaObject.FileContent.IndexOf("base64,"); if (index != -1) { multimediaObject.FileContent = multimediaObject.FileContent.Substring(index + "base64,".Length); } if (multimediaObject.Url == null) { throw new Exception("Nie ustawiono adres URL dla obiektu!"); } using (var transaction = Context.Database.BeginTransaction()) { try { dynamic dbEntry; var multimediaObjectType = Context.Types.FirstOrDefault(x => x.Id == multimediaObject.TypeId); if (multimediaObjectType == null) { throw new Exception("Nie znaleziono wskazanego typu obiektu. Możliwe zmiany na innym stanowisku."); } // Konwersja formatu base64 na tablicę bajtów var imageBytes = Convert.FromBase64String(multimediaObject.FileContent); byte[] thumbnail = imageBytes; #region Zapis danych podstawowych obiektu if (multimediaObject.Id > 0) { dbEntry = Context.MultimediaObjects.SingleOrDefault(f => f.Id == multimediaObject.Id); if (dbEntry != null) { dbEntry.UserId = multimediaObject.UserId; dbEntry.FileName = multimediaObject.FileName; dbEntry.MimeType = multimediaObject.MimeType; dbEntry.Name = multimediaObject.Name; dbEntry.TypeId = multimediaObject.TypeId; dbEntry.Url = multimediaObject.Url; dbEntry.Contents = imageBytes; dbEntry.Thumbnail = thumbnail; SetRelation(multimediaObject, ref dbEntry); Context.SaveChanges(); } } else { ICollection <Campaign> CampList = new List <Campaign>(); foreach (var camp in Camps) { Campaign c = Context.Campaigns.FirstOrDefault(p => p.Id == camp.Id); Context.Campaigns.Attach(c); CampList.Add(c); } dbEntry = new MultimediaObject { FileName = multimediaObject.FileName, MimeType = multimediaObject.MimeType, Name = multimediaObject.Name, TypeId = multimediaObject.TypeId, Url = multimediaObject.Url, Contents = imageBytes, Thumbnail = thumbnail, UserId = multimediaObject.UserId, Campaigns = CampList, Content = multimediaObject.Contents, }; SetRelation(multimediaObject, ref dbEntry); Context.MultimediaObjects.Add(dbEntry); Context.SaveChanges(); } #endregion transaction.Commit(); } catch (System.Data.Entity.Validation.DbEntityValidationException ex) { // Obsługa błędów EF using (var handler = new DbValidationErrorHandler(ex)) { if (handler.HasErrors) { response.Errors.AddRange(handler.ValidationErrors); } } } catch (Exception ex) { // Obsługa błędów pozostałych var hierarchy = new List <Exception>(); ExceptionsHandlingHelper.HierarchizeError(ex, ref hierarchy); if (hierarchy.Count > 0) { response.Errors.AddRange(hierarchy.Select(s => new ApiValidationErrorItem { Message = s.Message + Environment.NewLine + s.StackTrace }).Distinct().AsEnumerable()); } } if (response.Errors.Count > 0) { transaction.Rollback(); } } } else { response.Errors.Add(new ApiValidationErrorItem { Message = "Należy dołączyć plik multimedialny." }); } response.Accepted = response.Errors.Count == 0; return(response); }
public void RemoveFromActiveList(MultimediaObject mmo) { activeMmos.Remove(mmo); }
public static string GetThumbnailUrl(MultimediaObject mmo) { return(Configuration.imagesHost + "thumbnails/" + mmo.id + "/" + mmo.id + "_000001.png"); }
public IObservable<Uri> UploadMultimedia(MultimediaObject mmo, Stream data) { var maxPackageSize = 4193000; // < 4 MB -> Submit, else chunked upload var uri = string.Empty; var packageBuffer = new byte[maxPackageSize]; var rolledBack = false; Action readPackage = () => { var packageSize = data.Read(packageBuffer, 0, packageBuffer.Length); if (packageSize < packageBuffer.Length) { Array.Resize(ref packageBuffer, packageSize); } }; Action disposeStream = () => { if (data != null) { data.Dispose(); } }; var res = Observable.Merge( UploadMultimediaCompleted.FilterByUserState(mmo).Select(x => x as AsyncCompletedEventArgs), BeginTransactionCompleted.FilterByUserState(mmo).Select(x => x as AsyncCompletedEventArgs), EncodeFileCompleted.FilterByUserState(mmo).Select(x => x as AsyncCompletedEventArgs), CommitCompleted.FilterByUserState(mmo).Select(x => x as AsyncCompletedEventArgs), RollbackCompleted.FilterByUserState(mmo) ) .Select(p => { if (p.Error == null) { if (p is PhoneMediaService.BeginTransactionCompletedEventArgs) { // Result is a fake URI -> ignore and start first package upload // Package Data is still in the buffer _multimedia.EncodeFileAsync(packageBuffer, mmo); return null; } else if (p is PhoneMediaService.CommitCompletedEventArgs) { uri = (p as PhoneMediaService.CommitCompletedEventArgs).Result; } else if (p is PhoneMediaService.SubmitCompletedEventArgs) { uri = (p as PhoneMediaService.SubmitCompletedEventArgs).Result; } else if (p is PhoneMediaService.EncodeFileCompletedEventArgs) { readPackage(); if (packageBuffer.Length > 0) { // Send next package _multimedia.EncodeFileAsync(packageBuffer, mmo); } else { // Commit transaction _multimedia.CommitAsync(mmo); } return null; } else { // Rollback Completed successfully -> Alert the user. throw new ServiceOperationException("Upload failed, operation rolled back, please retry."); } try { return new Uri(uri, UriKind.Absolute); } catch (Exception ex) { int errorCode; if (int.TryParse(uri, out errorCode)) { throw new ServiceOperationException(string.Format("Multimedia Upload failed with error code: {0}", errorCode)); } throw new ServiceOperationException("Service returned invalid Image URI", ex); } } else { if (p.Error is FaultException && !rolledBack) { rolledBack = true; _multimedia.RollbackAsync(mmo); return null; } throw new ServiceOperationException(p.Error.Message, p.Error); } }) .Where(x => x != null) .ConvertToServiceErrors() .Finally(disposeStream) .Take(1) .Replay(1); var collectionOwnerID = Mapping.EnsureKey(mmo.OwnerType, mmo.RelatedId); var filename = ServiceFileName(mmo, collectionOwnerID); res.Connect(); readPackage(); WithCredentials(login => { if (packageBuffer.Length < maxPackageSize) { // Stream only contained enough for one package -> Submit with one service call _multimedia.SubmitAsync(Guid.NewGuid().ToString(), filename, mmo.MediaType.ToString(), 0, 0, 0, login.LoginName, mmo.TimeCreated.ToString(CultureInfo.InvariantCulture), login.ProjectID, packageBuffer, mmo); } else { // Start Chunked upload _multimedia.BeginTransactionAsync(Guid.NewGuid().ToString(), filename, mmo.MediaType.ToString(), 0, 0, 0, login.LoginName, mmo.TimeCreated.ToString(CultureInfo.InvariantCulture), login.ProjectID, mmo); } }); return res; }
public void StoreHeading(MultimediaObject mmo, int heading) { logger.Debug("Writing heading " + heading + " for mmo " + mmo.id); headingDictionary.Add(mmo.id, heading); }
private int Comparison(MultimediaObject mmo1, MultimediaObject mmo2) { return(mmo1.resultIndex - mmo2.resultIndex); }
public void InsertMMO(MultimediaObject mmo, UserCredentials login) { using (var db = login.GetConnection()) { try { switch (mmo.OwnerType) { case MultimediaOwner.EventSeries: CollectionEventSeriesImage cesi = mmo.ToSeriesImage(); db.Insert(cesi); break; case MultimediaOwner.Event: CollectionEventImage cei = mmo.ToEventImage(); db.Insert(cei); break; case MultimediaOwner.Specimen: case MultimediaOwner.IdentificationUnit: CollectionSpecimenImage csi = mmo.ToSpecimenImage(db); db.Insert(csi); break; default: throw new ArgumentException("unknown type"); } } catch (SqlException) { // Presumably Multiple Insert, meaning the object already exists // -> Success } } }
private void SetRelation(MultimediaObject MMobject, ref dynamic dbEntry) { ObjectRelationCampaign(MMobject.Campaigns, ref dbEntry); }