Exemplo n.º 1
0
		public override void GenerateQRCode(MediaQRContent content)
		{
			SystemLogger.Log (SystemLogger.Module.PLATFORM, "1");
			try{
				MediaMetadata mediaData = new MediaMetadata();
				SystemLogger.Log (SystemLogger.Module.PLATFORM, "2");

				int size = content.Size;
				if (size == 0) {
					size = 256;
				}
				var writer = new ZXing.BarcodeWriter
				{ 
					Format = BarcodeFormat.QR_CODE, 
					Options = new EncodingOptions { Height = size, Width = size } 
				};
				//var img = writer.Write(content.Text);
				SystemLogger.Log (SystemLogger.Module.PLATFORM, "3");

				var uuid = Guid.NewGuid ();
				string s = uuid.ToString ();
				String filename = "QR_" + s;
				NSError err;
				DirectoryData dest = new DirectoryData(DEFAULT_ROOT_PATH);
				string path = Path.Combine(dest.FullName, filename+".png");
				SystemLogger.Log (SystemLogger.Module.PLATFORM, "4");
				content = encodeQRCodeContents(content);
				using(UIImage img = writer.Write(content.Text)) {
					
					using (var data = img.AsPNG ()) {
						data.Save (path, true, out err);
					}
				}
				SystemLogger.Log (SystemLogger.Module.PLATFORM, "5");

				mediaData.ReferenceUrl = filename+".png";
				mediaData.Title = filename;

				SystemLogger.Log (SystemLogger.Module.PLATFORM, "6");

				UIApplication.SharedApplication.InvokeOnMainThread (delegate {
					UIViewController viewController = UIApplication.SharedApplication.KeyWindow.RootViewController;
					FireUnityJavascriptEvent(viewController, "Appverse.Scanner.onGeneratedQR", mediaData);

				});
			}catch(Exception ex)
			{
				SystemLogger.Log (SystemLogger.Module.PLATFORM, "GenerateQRCode - exception: " + ex.Message);
			}
		}
Exemplo n.º 2
0
        internal async Task<MediaMetadata> GetMetadata(StorageFile targetFile)
        {
            if (targetFile == null) return null;
            var fileMetaData = new MediaMetadata();
            try
            {
                fileMetaData.ReferenceUrl = targetFile.Path.StartsWith(WindowsPhoneUtils.DocumentsFolder.Path) ? targetFile.Path.Replace(WindowsPhoneUtils.DocumentsFolder.Path, String.Empty) : String.Empty;
                fileMetaData.Size = (long)(await targetFile.GetBasicPropertiesAsync()).Size;
                fileMetaData.MimeType = targetFile.ContentType;
                fileMetaData.Type = MediaType.NotSupported;
                if (targetFile.ContentType.Contains("audio/"))
                {
                    var musicProperties = await targetFile.Properties.GetMusicPropertiesAsync();
                    fileMetaData.Album = musicProperties.Album;
                    fileMetaData.Artist = musicProperties.Artist;
                    fileMetaData.Category = musicProperties.Genre.Aggregate(new StringBuilder(), (sb, a) => sb.Append(String.Join(",", a)), sb => sb.ToString());
                    fileMetaData.Duration = (long)musicProperties.Duration.TotalSeconds;
                    fileMetaData.Title = musicProperties.Title;
                    fileMetaData.Type = MediaType.Audio;
                }
                else if (targetFile.ContentType.Contains("video/"))
                {
                    var videoProperties = await targetFile.Properties.GetVideoPropertiesAsync();
                    fileMetaData.Duration = (long)videoProperties.Duration.TotalSeconds;
                    fileMetaData.Artist = videoProperties.Directors.Aggregate(new StringBuilder(), (sb, a) => sb.Append(String.Join(",", a)), sb => sb.ToString());
                    fileMetaData.Title = videoProperties.Title;
                    fileMetaData.Category = videoProperties.Keywords.Aggregate(new StringBuilder(), (sb, a) => sb.Append(String.Join(",", a)), sb => sb.ToString());
                    fileMetaData.Type = MediaType.Video;

                }
                else if (targetFile.ContentType.Contains("image/"))
                {
                    var imgProperties = await targetFile.Properties.GetImagePropertiesAsync();
                    fileMetaData.Title = imgProperties.Title;
                    fileMetaData.Category = imgProperties.Keywords.Aggregate(new StringBuilder(), (sb, a) => sb.Append(String.Join(",", a)), sb => sb.ToString());
                    fileMetaData.Type = MediaType.Photo;
                }
                return fileMetaData;
            }
            catch (Exception ex)
            {
                WindowsPhoneUtils.Log(ex.Message);
                return null;
            }
        }
Exemplo n.º 3
0
        void HandleImagePickerControllerFinishedPickingMedia(object sender, UIImagePickerMediaPickedEventArgs e)
        {
            UIApplication.SharedApplication.InvokeOnMainThread (delegate {
                if(popover != null && popover.PopoverVisible) {
                    popover.Dismiss(true);
                    popover.Dispose();
                } else {
                    IPhoneServiceLocator.CurrentDelegate.MainUIViewController ().DismissModalViewControllerAnimated(true);
                }
            });

            SystemLogger.Log(SystemLogger.Module.PLATFORM, "FinishedPickingMedia " + e.Info);

            MediaMetadata mediaData = new MediaMetadata();
            mediaData.Type = MediaType.NotSupported;

            try {
                NSString mediaType = (NSString) e.Info.ValueForKey(UIImagePickerController.MediaType);
                UIImage image = (UIImage) e.Info.ValueForKey(UIImagePickerController.OriginalImage);
                object url = e.Info.ValueForKey(UIImagePickerController.ReferenceUrl);
                NSUrl nsReferenceUrl = new NSUrl(url.ToString());

                if(image != null && mediaType !=null && mediaType == "public.image") { // "public.image" is the default UTI (uniform type) for images.
                    mediaData.Type = MediaType.Photo;

                    string fileExtension = Path.GetExtension(nsReferenceUrl.Path.ToLower());
                    mediaData.MimeType = MediaMetadata.GetMimeTypeFromExtension(fileExtension);
                    mediaData.Title = this.GetImageMediaTitle(nsReferenceUrl.AbsoluteString);

                    NSData imageData = null;
                    if(mediaData.MimeType == "image/png" || mediaData.MimeType == "image/gif" || mediaData.MimeType == "image/tiff") {
                        imageData = image.AsPNG();
                    } else if (mediaData.MimeType == "image/jpeg" || mediaData.MimeType == "image/jpg") {
                        imageData = image.AsJPEG();
                    }

                    if(imageData !=null) {
                        SystemLogger.Log(SystemLogger.Module.PLATFORM, "Getting image data raw data...");

                        byte[] buffer = new byte[imageData.Length];
                        Marshal.Copy(imageData.Bytes, buffer,0,buffer.Length);

                        IFileSystem fileSystemService = (IFileSystem)IPhoneServiceLocator.GetInstance ().GetService ("file");
                        SystemLogger.Log(SystemLogger.Module.CORE, "Storing media file on application filesystem...");

                        mediaData.ReferenceUrl = fileSystemService.StoreFile(IPhoneMedia.ASSETS_PATH, mediaData.Title, buffer);
                    }

                    SystemLogger.Log(SystemLogger.Module.PLATFORM, mediaData.MimeType + ", "+ mediaData.ReferenceUrl + ", " + mediaData.Title);

                }
            } catch(Exception ex) {
                SystemLogger.Log(SystemLogger.Module.PLATFORM, "Error when extracting information from media file: " + ex.Message, ex);
            }

            IPhoneUtils.GetInstance().FireUnityJavascriptEvent("Unity.Media.onFinishedPickingImage", mediaData);
        }
Exemplo n.º 4
0
        void HandleCameraFinishedPickingMedia(object sender, UIImagePickerMediaPickedEventArgs e)
        {
            UIApplication.SharedApplication.InvokeOnMainThread (delegate {
                IPhoneServiceLocator.CurrentDelegate.MainUIViewController ().DismissModalViewControllerAnimated(true);
            });

            SystemLogger.Log(SystemLogger.Module.PLATFORM, "Camera FinishedPickingMedia " + e.Info);

            MediaMetadata mediaData = new MediaMetadata();

            try {
                NSString mediaType = (NSString) e.Info.ValueForKey(UIImagePickerController.MediaType);
                UIImage image = (UIImage) e.Info.ValueForKey(UIImagePickerController.OriginalImage);

                if(image != null && mediaType !=null && mediaType == "public.image") { // "public.image" is the default UTI (uniform type) for images.
                    mediaData.Type = MediaType.Photo;
                    mediaData.MimeType = MediaMetadata.GetMimeTypeFromExtension(".jpg");
                    mediaData.Title = (image.GetHashCode() & 0x7FFFFFFF) + ".JPG";

                    NSData imageData = image.AsJPEG();

                    if(imageData !=null) {
                        SystemLogger.Log(SystemLogger.Module.PLATFORM, "Getting image data raw data...");

                        byte[] buffer = new byte[imageData.Length];
                        Marshal.Copy(imageData.Bytes, buffer,0,buffer.Length);

                        IFileSystem fileSystemService = (IFileSystem)IPhoneServiceLocator.GetInstance ().GetService ("file");
                        SystemLogger.Log(SystemLogger.Module.CORE, "Storing media file on application filesystem...");

                        mediaData.ReferenceUrl = fileSystemService.StoreFile(IPhoneMedia.ASSETS_PATH, mediaData.Title, buffer);
                    }

                    SystemLogger.Log(SystemLogger.Module.PLATFORM, mediaData.MimeType + ", "+ mediaData.ReferenceUrl + ", " + mediaData.Title);

                }
            } catch(Exception ex) {
                SystemLogger.Log(SystemLogger.Module.PLATFORM, "Error when extracting information from media file: " + ex.Message, ex);
            }

            IPhoneUtils.GetInstance().FireUnityJavascriptEvent("Unity.Media.onFinishedPickingImage", mediaData);
        }
Exemplo n.º 5
0
        private MediaMetadata GetMetadataFromUrl(NSUrl nsUrl)
        {
            MediaMetadata currentMedia = new MediaMetadata();
            try {
                SystemLogger.Log(SystemLogger.Module.PLATFORM, "getting metadata from nsUrl RelativeString: "+ nsUrl.RelativeString);

                // Getting mime type
                currentMedia.MimeType = MediaMetadata.GetMimeTypeFromExtension(nsUrl.RelativeString);
                SystemLogger.Log(SystemLogger.Module.PLATFORM, "metadata mimetype: "+ currentMedia.MimeType);
                // Getting media type
                if(currentMedia.MimeType != null && currentMedia.MimeType.ToString().StartsWith("audio")) {
                    currentMedia.Type = MediaType.Audio;
                } else if (currentMedia.MimeType != null && currentMedia.MimeType.ToString().StartsWith("video")) {
                    currentMedia.Type = MediaType.Video;
                } else if (currentMedia.MimeType != null && currentMedia.MimeType.ToString().StartsWith("image")) {
                    currentMedia.Type = MediaType.Photo;
                } else {
                    currentMedia.Type = MediaType.NotSupported;
                }

                AVUrlAsset urlAsset = AVUrlAsset.FromUrl(nsUrl, new NSDictionary());
                if(urlAsset != null) {
                    currentMedia.Duration = urlAsset.Duration.Value;
                    if(urlAsset.Duration.TimeScale != 0) { // TimeScale could be null in some devices
                        currentMedia.Duration = urlAsset.Duration.Value / urlAsset.Duration.TimeScale;
                    }
                    AVMetadataItem[] metadataItems = urlAsset.CommonMetadata; // CommonMetadata could be null in some devices
                    if(metadataItems != null) {
                        foreach(AVMetadataItem metadataItem in metadataItems) {
                            if(metadataItem.CommonKey == "title") {
                                currentMedia.Title = metadataItem.StringValue.ToString();
                                currentMedia.Album = metadataItem.Value.ToString();

                            }
                            if(metadataItem.CommonKey == "artist") {
                                currentMedia.Artist = metadataItem.Value.ToString();
                            }
                            //TODO map category & handle
                        }
                    }
                }

            } catch (Exception ex) {
                SystemLogger.Log(SystemLogger.Module.PLATFORM, "Error getting metadata from [" + nsUrl +"]", ex);

                currentMedia = null;
            }

            return currentMedia;
        }
        public override async Task GenerateQRCode(MediaQRContent content)
        {
            if (!AppverseBridge.Instance.RuntimeHandler.RuntimeDispatcher.HasThreadAccess)
            {
                await AppverseBridge.Instance.RuntimeHandler.RuntimeDispatcher.RunAsync(CoreDispatcherPriority.High, () => GenerateQRCode(content));
            }
            else
            {
                if (content == null) return;
                try
                {
                    var size = (content.Size == 0) ? 256 : content.Size;
                    var writer = new BarcodeWriter
                    {
                        Format = BarcodeFormat.QR_CODE,
                        Options = new EncodingOptions { Height = size, Width = size }
                    };

                    //content = encodeQRCodeContents(content);
                    var resultWriteableBitmap = writer.Write(content.Text);

                    var QRFile = await WindowsPhoneUtils.DocumentsFolder.CreateFileAsync(String.Concat("QR_", Guid.NewGuid().ToString().Replace("-", String.Empty), ".png"));
                    //Open File Stream to write content
                    using (var writeStream = await QRFile.OpenAsync(FileAccessMode.ReadWrite))
                    {
                        byte[] pixels;
                        //Read pixels from generated image
                        using (var readStream = resultWriteableBitmap.PixelBuffer.AsStream())
                        {
                            pixels = new byte[readStream.Length];
                            await readStream.ReadAsync(pixels, 0, pixels.Length);
                        }
                        //Encode pixels in the stream
                        var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.PngEncoderId, writeStream);
                        encoder.SetPixelData(BitmapPixelFormat.Bgra8, BitmapAlphaMode.Premultiplied,
                            (uint)resultWriteableBitmap.PixelWidth, (uint)resultWriteableBitmap.PixelHeight, 96, 96,
                            pixels);
                        await encoder.FlushAsync();
                    }
                    var mediaData = new MediaMetadata
                    {
                        ReferenceUrl = QRFile.Path.Replace(WindowsPhoneUtils.DocumentsFolder.Path, String.Empty),
                        Title = QRFile.DisplayName
                    };
                    WindowsPhoneUtils.InvokeCallback("Appverse.Scanner.onGeneratedQR", WindowsPhoneUtils.CALLBACKID, JsonConvert.SerializeObject(mediaData));
                }
                catch (Exception ex)
                {
                    WindowsPhoneUtils.Log(String.Concat("Error while generating QR: ", ex.Message));
                }
            }

        }