예제 #1
0
        void OpenDoc_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(_docPath.Text) || Equals(_docPath.Text, "Document path"))
            {
                return;
            }

            try
            {
                var intent = new Intent(Intent.ActionView);
                var uri    = FileProvider.GetUriForFile(this, $"{PackageName}.fileprovider", new Java.IO.File(_docPath.Text));
                var type   = MimeTypeMap.Singleton.GetMimeTypeFromExtension(MimeTypeMap.GetFileExtensionFromUrl(_docPath.Text));
                intent.SetDataAndType(uri, type);

                var resolveInfos = PackageManager.QueryIntentActivities(intent, PackageInfoFlags.MatchDefaultOnly);
                if (!resolveInfos.Any())
                {
                    Toast.MakeText(this, "Unable to open the file, no suitable app found", ToastLength.Long).Show();
                    return;
                }

                foreach (var ri in resolveInfos)
                {
                    GrantUriPermission(ri.ActivityInfo.PackageName, uri, ActivityFlags.GrantWriteUriPermission | ActivityFlags.GrantReadUriPermission);
                }

                StartActivity(intent);
            }
            catch (Exception ex)
            {
                Toast.MakeText(this, $"Unable to open the file {ex.Message}", ToastLength.Long).Show();
            }
        }
예제 #2
0
        public void StartOpenFile(string appPath)
        {
            try
            {
                // Create URI
                var file      = new File(this.BaseDir, appPath);
                var uri       = Android.Net.Uri.FromFile(file);
                var extension = MimeTypeMap.GetFileExtensionFromUrl(uri.ToString());
                var mimeType  = MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension);

                var intentUri = Build.VERSION.SdkInt >= BuildVersionCodes.M
                    ? FileProvider.GetUriForFile(this.context.Activity, ProviderAuthority, file)
                    : uri;

                var intent = new Intent();
                intent.AddFlags(ActivityFlags.GrantReadUriPermission);
                intent.SetAction(Intent.ActionView);
                intent.SetDataAndType(intentUri, mimeType);

                var activity = Mvx.Resolve <IMvxAndroidCurrentTopActivity>().Activity;
                if (intent.ResolveActivity(activity.PackageManager) == null)
                {
                    intent.SetDataAndType(uri, "*/*");
                }

                activity.StartActivityForResult(intent, 10);
            }
            catch
            {
                this.userInteraction.Toast("Failed to open.", ToastTime.Medium);
            }
        }
예제 #3
0
        /// <summary>
        /// Intercept request.
        /// </summary>
        /// <returns>The intercept request.</returns>
        /// <param name="view">View.</param>
        /// <param name="request">Request.</param>
        public override WebResourceResponse ShouldInterceptRequest(Android.Webkit.WebView view, IWebResourceRequest request)
        {
            string url  = request.Url.ToString();
            string ext  = MimeTypeMap.GetFileExtensionFromUrl(url);
            string mime = MimeTypeMap.Singleton.GetMimeTypeFromExtension(ext);

            if (url.ToLower().Contains("logoff"))
            {
                Xamarin.Forms.Device.BeginInvokeOnMainThread(App.Instance.Logout);
            }
            else if (request.Url.ToString().Contains("geofenceAutoCreate"))
            {
            }
            else if (mime != null)
            {
                HttpURLConnection conn = (HttpURLConnection) new URL(url).OpenConnection();
                foreach (var i in request.RequestHeaders)
                {
                    conn.SetRequestProperty(i.Key, i.Value);
                }
                var webResourceResponse = new WebResourceResponse(mime, "UTF-8", conn.InputStream);
                return(webResourceResponse);
            }

            BrowserPage.CheckWebSession();
            return(base.ShouldInterceptRequest(view, request));
        }
예제 #4
0
        public void ShowDocument(string fileName)
        {
            var appContext = CrossCurrentActivity.Current.AppContext;
            var context    = CrossCurrentActivity.Current.Activity;

            string dirPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);

            dirPath = Path.Combine(dirPath, "Reports");
            Java.IO.File file = new Java.IO.File(dirPath, fileName);

            if (!file.Exists())
            {
                return;
            }

            Device.BeginInvokeOnMainThread(() => {
                Android.Net.Uri uri = FileProvider.GetUriForFile(context, context.PackageName + ".fileprovider", file);
                Intent intent       = new Intent(Intent.ActionView);
                string mimeType     = MimeTypeMap.Singleton.GetMimeTypeFromExtension(MimeTypeMap.GetFileExtensionFromUrl((string)uri).ToLower());
                intent.SetDataAndType(uri, mimeType);

                intent.SetFlags(ActivityFlags.ClearWhenTaskReset | ActivityFlags.NewTask);
                intent.AddFlags(ActivityFlags.GrantReadUriPermission);

                try {
                    appContext.StartActivity(intent);
                } catch (Exception ex) {
                    Toast.MakeText(appContext, "No Application Available to View this file", ToastLength.Short).Show();
                }
            });
        }
예제 #5
0
        public override WebResourceResponse ShouldInterceptRequest(WebView view, IWebResourceRequest request)
        {
            if (request != null && request.Url != null)
            {
                var stream = Application.ContentProvider
                             .GetStreamAsync(new Uri(request.Url.ToString()))
                             .ConfigureAwait(false).GetAwaiter().GetResult();
                if (stream != null)
                {
                    var responseHeaders = new Dictionary <string, string>()
                    {
                        { "Cache-Control", "no-cache" },
                    };
                    var url  = request.Url.ToString().ToLowerInvariant();
                    var mime = MimeTypeMap.Singleton.GetMimeTypeFromExtension(
                        MimeTypeMap.GetFileExtensionFromUrl(
                            request.Url.ToString()));
                    Log.Info(Globals.LogTag,
                             $"Resource '{url}' successfully found in ContentProvider. We will return it the WebResource");
                    return(new WebResourceResponse(mime, "UTF-8", 200, "OK", responseHeaders, stream));
                }
                else
                {
                }
            }

            return(base.ShouldInterceptRequest(view, request));
        }
예제 #6
0
        public void OpenLocalDocument(string path, Action completed = null)
        {
            var fileProvider = GetFileProvider();
            var file         = new Java.IO.File(path);

            var context = Android.App.Application.Context;

            Android.Net.Uri uri       = FileProvider.GetUriForFile(context, fileProvider, file);
            string          extension = MimeTypeMap.GetFileExtensionFromUrl(Android.Net.Uri.FromFile(file).ToString());
            string          mimeType  = MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension);

            Intent viewIntent = new Intent(Intent.ActionView);

            viewIntent.SetDataAndType(uri, mimeType);
            viewIntent.AddFlags(ActivityFlags.NoHistory);
            viewIntent.AddFlags(ActivityFlags.GrantReadUriPermission);

            Context ctx  = CrossCurrentActivity.Current.Activity;
            var     apps = ctx.PackageManager.QueryIntentActivities(viewIntent, PackageInfoFlags.MatchDefaultOnly);

            if (apps.Any())
            {
                CrossCurrentActivity.Current.Activity.StartActivity(Intent.CreateChooser(viewIntent, "Choose App to View"));
            }
            else
            {
                throw new Exception("No application can perform this action");
            }

            completed?.Invoke();
        }
        private void Completed(object sender, AsyncCompletedEventArgs e)
        {
            try
            {
                Java.IO.File file = new Java.IO.File(filePath);

                if (e.Error != null)
                {
                }
                else
                {
                    Android.Net.Uri pdfPath = FileProvider.GetUriForFile(Android.App.Application.Context,
                                                                         Android.App.Application.Context.PackageName + ".provider",
                                                                         file);
                    string extension = MimeTypeMap.GetFileExtensionFromUrl(Android.Net.Uri.FromFile(file).ToString());
                    string mimeType  = MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension);

                    Intent intent = new Intent(Intent.ActionView);
                    intent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.NewTask);
                    intent.SetDataAndType(pdfPath, mimeType); //image/jpeg
                    intent.AddFlags(ActivityFlags.GrantReadUriPermission);
                    Forms.Context.StartActivity(intent);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
예제 #8
0
        public void FileReceivedDelegate(string fileName, string fileDescription, string filePath, int fileSize, TextView associatedTextView)
        {
            MimeTypeMap mime      = MimeTypeMap.Singleton;
            string      ext       = fileName.ToLower();
            string      extension = MimeTypeMap.GetFileExtensionFromUrl(ext);
            string      type      = null;

            if (extension != null)
            {
                type = MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension);
            }
            if (type == null)
            {
                type = "application/octet-stream";
            }

            DownloadManager downloadManager = DownloadManager.FromContext(Android.App.Application.Context);

            downloadManager.AddCompletedDownload(fileName, fileDescription, true, type, filePath, fileSize, true);

            CommClientAndroid client2 = ClientHolder.Client;

            client2.RemoveFile(associatedTextView.Text);
            ViewGroup parent = (ViewGroup)associatedTextView.Parent;

            parent.Post(delegate
            {
                parent.RemoveView(associatedTextView);
            });

            client.currentlyDownloadingFile = false;
        }
        public void showPhoto(string AttachmentName, byte[] AttachmentBytes)
        {
            string dirPath  = Xamarin.Forms.Forms.Context.GetExternalFilesDir(Android.OS.Environment.DirectoryPictures).Path;
            var    FileName = AttachmentName;

            Java.IO.File file = new Java.IO.File(dirPath, FileName);

            if (!file.Exists())
            {
                var filename = Path.Combine(dirPath, AttachmentName);
                File.WriteAllBytes(filename, AttachmentBytes);
            }

            Device.BeginInvokeOnMainThread(() =>
            {
                //var oDir = Xamarin.Forms.Forms.Context.FilesDir.AbsolutePath;
                Android.Net.Uri uri = Android.Net.Uri.FromFile(file);
                Intent intent       = new Intent(Intent.ActionView);
                String mimeType     = MimeTypeMap.Singleton.GetMimeTypeFromExtension(MimeTypeMap.GetFileExtensionFromUrl((string)uri).ToLower());
                intent.SetDataAndType(uri, mimeType);

                intent.SetFlags(ActivityFlags.ClearWhenTaskReset | ActivityFlags.NewTask);

                try
                {
                    Xamarin.Forms.Forms.Context.StartActivity(intent);
                }
                catch (System.Exception ex)
                {
                    Toast.MakeText(Xamarin.Forms.Forms.Context, "No Application Available to View this file", ToastLength.Short).Show();
                }
            });
        }
예제 #10
0
        private static string GetFileType(string url)
        {
            string type = null;
            var extension = MimeTypeMap.GetFileExtensionFromUrl(url);
            if (extension == null) return type;
            var mime = MimeTypeMap.Singleton;
            type = mime.GetMimeTypeFromExtension(extension);

            return type;
        }
예제 #11
0
        public bool SaveFile(byte[] fileData, string id, string fileName, string contentUri)
        {
            try
            {
                var activity = (MainActivity)CrossCurrentActivity.Current.Activity;

                if (contentUri != null)
                {
                    var uri    = Android.Net.Uri.Parse(contentUri);
                    var stream = activity.ContentResolver.OpenOutputStream(uri);
                    // Using java bufferedOutputStream due to this issue:
                    // https://github.com/xamarin/xamarin-android/issues/3498
                    var javaStream = new Java.IO.BufferedOutputStream(stream);
                    javaStream.Write(fileData);
                    javaStream.Flush();
                    javaStream.Close();
                    return(true);
                }

                // Prompt for location to save file
                var extension = MimeTypeMap.GetFileExtensionFromUrl(fileName.Replace(' ', '_').ToLower());
                if (extension == null)
                {
                    return(false);
                }

                string mimeType = MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension);
                if (mimeType == null)
                {
                    if (extension == "json")
                    {
                        // Explicit support for json since older versions of Android don't recognize the extension
                        mimeType = "text/json";
                    }
                    else
                    {
                        return(false);
                    }
                }

                var intent = new Intent(Intent.ActionCreateDocument);
                intent.SetType(mimeType);
                intent.AddCategory(Intent.CategoryOpenable);
                intent.PutExtra(Intent.ExtraTitle, fileName);

                activity.StartActivityForResult(intent, Constants.SaveFileRequestCode);
                return(true);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(">>> {0}: {1}", ex.GetType(), ex.StackTrace);
            }
            return(false);
        }
예제 #12
0
        // url = file path or whatever suitable URL you want.
        public static String GetMimeType(String url)
        {
            String type      = null;
            String extension = MimeTypeMap.GetFileExtensionFromUrl(url);

            if (extension != null)
            {
                MimeTypeMap mime = MimeTypeMap.Singleton;
                type = mime.GetMimeTypeFromExtension(extension.ToLowerInvariant());
            }
            return(type);
        }
예제 #13
0
        public static string GetMimeType(string url)
        {
            string type      = null;
            var    extension = MimeTypeMap.GetFileExtensionFromUrl(url);

            if (extension != null)
            {
                type = MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension);
            }

            return(type);
        }
예제 #14
0
        public EmailAttachment(Java.IO.File file)
        {
            if (file == null)
            {
                throw new ArgumentNullException(nameof(file));
            }

            var extension   = MimeTypeMap.GetFileExtensionFromUrl(file.Path);
            var contentType = MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension);

            File        = file;
            FilePath    = file.Path;
            FileName    = file.Name;
            ContentType = contentType;
        }
예제 #15
0
        public Tuple <byte[], string, string> ReadFile(string file)
        {
            var uri      = Android.Net.Uri.Parse(file);
            var activity = Xamarin.Forms.Forms.Context as MainActivity;

            // Data
            byte[] data = null;
            using (var inputStream = activity.ContentResolver.OpenInputStream(uri))
                using (var memoryStream = new MemoryStream())
                {
                    inputStream.CopyTo(memoryStream);
                    data = memoryStream.ToArray();
                }

            // Name
            string name   = "";
            var    cursor = activity.ContentResolver.Query(uri, null, null, null, null);

            try
            {
                if (cursor != null && cursor.MoveToFirst())
                {
                    var nameIndex = cursor.GetColumnIndex(OpenableColumns.DisplayName);
                    if (!cursor.IsNull(nameIndex))
                    {
                        name = cursor.GetString(nameIndex);
                    }
                }
            }
            finally
            {
                cursor?.Close();
            }

            // Mime
            string mime = null;

            if (uri.Scheme == ContentResolver.SchemeContent)
            {
                mime = activity.ContentResolver.GetType(uri);
            }
            else
            {
                var extension = MimeTypeMap.GetFileExtensionFromUrl(file);
                mime = MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension.ToLower());
            }
            return(new Tuple <byte[], string, string>(data, name, mime));
        }
예제 #16
0
        public void OpenFile(string filePath)
        {
            var localFile = new Java.IO.File(filePath);   // getting files from path

            var uri = FileProvider.GetUriForFile(MainActivity.Current, "com.gpoAplired.bcmweb.provider", localFile);

            Intent intent = new Intent(Intent.ActionView);

            intent.SetFlags(ActivityFlags.ClearWhenTaskReset | ActivityFlags.NewTask);
            var extension = MimeTypeMap.GetFileExtensionFromUrl(filePath);
            var mimeType  = MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension.ToLower());

            intent.AddFlags(ActivityFlags.GrantReadUriPermission);
            intent.SetDataAndType(uri, mimeType);
            MainActivity.Current.StartActivity(intent);
        }
        public void OpenFileByGivenPath(string sourcePath)
        {
            Java.IO.File    file      = new Java.IO.File(sourcePath);
            Android.Net.Uri uri       = FileProvider.GetUriForFile(Application.Context, "com.companyname.docandcom.fileprovider", file);
            string          extension = MimeTypeMap.GetFileExtensionFromUrl(Android.Net.Uri.FromFile(file).ToString());
            string          mimeType  = MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension);
            Intent          intent    = new Intent(Intent.ActionView);

            intent.SetDataAndType(uri, mimeType);
            intent.AddFlags(ActivityFlags.GrantReadUriPermission);
            intent.AddFlags(ActivityFlags.NoHistory);
            var chooserIntent = Intent.CreateChooser(intent, "Open file");

            chooserIntent.SetFlags(ActivityFlags.ClearWhenTaskReset | ActivityFlags.NewTask);
            Application.Context.StartActivity(chooserIntent);
        }
예제 #18
0
        public bool OpenFile(byte[] fileData, string id, string fileName)
        {
            if (!CanOpenFile(fileName))
            {
                return(false);
            }

            var extension = MimeTypeMap.GetFileExtensionFromUrl(fileName.Replace(' ', '_').ToLower());

            if (extension == null)
            {
                return(false);
            }

            var mimeType = MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension);

            if (mimeType == null)
            {
                return(false);
            }

            var cachePath = CrossCurrentActivity.Current.Activity.CacheDir;
            var filePath  = Path.Combine(cachePath.Path, fileName);

            File.WriteAllBytes(filePath, fileData);
            var file = new Java.IO.File(cachePath, fileName);

            if (!file.IsFile)
            {
                return(false);
            }

            try
            {
                var intent = new Intent(Intent.ActionView);
                var uri    = FileProvider.GetUriForFile(CrossCurrentActivity.Current.Activity.ApplicationContext,
                                                        "com.x8bit.bitwarden.fileprovider", file);
                intent.SetDataAndType(uri, mimeType);
                intent.SetFlags(ActivityFlags.GrantReadUriPermission);
                CrossCurrentActivity.Current.Activity.StartActivity(intent);
                return(true);
            }
            catch { }

            return(false);
        }
예제 #19
0
        protected override void OnPostExecute(Object result)
        {
            base.OnPostExecute(result);

            if ((bool)result)
            {
                Device.BeginInvokeOnMainThread(() =>
                {
                    Toast.MakeText(
                        CrossCurrentActivity.Current.AppContext,
                        "Image downloaded",
                        ToastLength.Long).Show();
                });

                var downloadPath = Path.Combine(
                    CrossCurrentActivity.Current.Activity.ApplicationContext.GetExternalFilesDir(null).AbsolutePath,
                    AEnvironment.DirectoryDownloads);
                var filePath = Path.Combine(downloadPath, _fileName);
                var file     = new File(filePath);

                var fileExtension = MimeTypeMap.GetFileExtensionFromUrl(filePath);
                var mimeType      = MimeTypeMap.Singleton.GetMimeTypeFromExtension(fileExtension.ToLower());

                var intent = new Intent(Intent.ActionView, Android.Net.Uri.Parse(filePath));
                intent.SetDataAndType(Android.Net.Uri.FromFile(file), mimeType);
                intent.SetFlags(ActivityFlags.ClearTop | ActivityFlags.SingleTop | ActivityFlags.NewTask);
                var pendingIntent = PendingIntent.GetActivity(CrossCurrentActivity.Current.Activity, 0, intent, 0);

                _builder.SetContentTitle("Download completed");
                _builder.SetContentText(_fileName);
                _builder.SetContentIntent(pendingIntent);
                _notificationManager.Notify(_notificationId, _builder.Build());
            }
            else
            {
                Device.BeginInvokeOnMainThread(() =>
                {
                    Toast.MakeText(
                        CrossCurrentActivity.Current.AppContext,
                        "Failed to download image",
                        ToastLength.Long).Show();
                });
                _builder.SetContentText("Download failed");
                _notificationManager.Notify(_notificationId, _builder.Build());
            }
        }
        string GetMimeType(string url)
        {
            string type = "*/*";

            try
            {
                string extension = MimeTypeMap.GetFileExtensionFromUrl(url);
                if (!string.IsNullOrEmpty(extension))
                {
                    type = MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension.ToLower());
                }
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex.ToString());
            }

            return(type);
        }
        private static string GetType(string filePath)
        {
            if (string.IsNullOrEmpty(filePath))
            {
                return(DEFAULT_MIME_TYPE);
            }

            string mimeType = MimeTypeMap.Singleton.GetMimeTypeFromExtension(MimeTypeMap.GetFileExtensionFromUrl(filePath));

            if (mimeType.NullOrEmpty())
            {
                if (!FILE_TYPES.TryGetValue(Path.GetExtension(filePath), out mimeType))
                {
                    return(DEFAULT_MIME_TYPE);
                }
            }

            return(mimeType);
        }
        public Task <string> PrintPdfFile(string filePath)
        {
            string result = null, packageName = null;
            string package1  = "com.hp.android.print";        //eprint
            string package2  = "com.hp.android.printservice"; //print service plugin
            string extension = MimeTypeMap.GetFileExtensionFromUrl(Android.Net.Uri.Parse(filePath).ToString());
            string mimeType  = MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension);

            try
            {
                if (extension?.ToLower() == "pdf")
                {
                    if (IsAppInstalled(package1))
                    {
                        packageName = package1;
                    }
                    else if (IsAppInstalled(package2))
                    {
                        packageName = package2;
                    }
                }
                if (packageName != null)
                {
                    Java.IO.File file = new Java.IO.File(filePath);
                    file.SetReadable(true);
                    Android.Net.Uri uri    = Android.Support.V4.Content.FileProvider.GetUriForFile(Android.App.Application.Context, Android.App.Application.Context.PackageName + ".fileprovider", file);
                    Intent          intent = new Intent(Intent.ActionSend);
                    intent.SetPackage(packageName);
                    intent.SetDataAndType(uri, mimeType);
                    intent.AddFlags(ActivityFlags.GrantReadUriPermission);
                    intent.AddFlags(ActivityFlags.NoHistory);
                    intent.AddFlags(ActivityFlags.ClearWhenTaskReset | ActivityFlags.NewTask);

                    Android.App.Application.Context.StartActivity(intent);
                    result = "success";
                }
            }
            catch (Exception ex)
            {
                result = ex.Message;
            }
            return(Task.FromResult(result));
        }
예제 #23
0
        public async Task DownloadAndInstall(DownloadManager manager)
        {
            string url     = @"https://app.cforce.live/com.payforce.apk";
            var    source  = Android.Net.Uri.Parse(url);
            var    request = new DownloadManager.Request(source);

            request.AllowScanningByMediaScanner();
            request.SetAllowedOverRoaming(true);
            request.SetDescription("Downloading PayForce");
            request.SetAllowedOverMetered(true);
            request.SetVisibleInDownloadsUi(true);
            string filename = URLUtil.GuessFileName(url, null, MimeTypeMap.GetFileExtensionFromUrl(url));

            MainActivity.FileName = filename;
            request.SetDestinationInExternalPublicDir(Android.OS.Environment.DirectoryDownloads, filename);
            request.SetNotificationVisibility(DownloadManager.Request.VisibilityVisibleNotifyCompleted);
            request.SetAllowedNetworkTypes(DownloadNetwork.Wifi | DownloadNetwork.Mobile);
            MainActivity.DownloadId = manager.Enqueue(request);
        }
예제 #24
0
        static string GetExtension(Context context, Android.Net.Uri uri)
        {
            string extension;

            //Check uri format to avoid null
            if (uri.Scheme.Equals(ContentResolver.SchemeContent))
            {
                //If scheme is a content
                MimeTypeMap mime = MimeTypeMap.Singleton;
                extension = mime.GetExtensionFromMimeType(context.ContentResolver.GetType(uri));
            }
            else
            {
                //If scheme is a File
                //This will replace white spaces with %20 and also other special characters. This will avoid returning null values on file name with spaces and special characters.
                extension = MimeTypeMap.GetFileExtensionFromUrl(Android.Net.Uri.FromFile(new Java.IO.File(uri.Path)).ToString());
            }

            return(extension);
        }
예제 #25
0
    public string getMimeType(Android.Net.Uri uri)
    {
        string mime_type = null;

        if (uri.Scheme.Equals(ContentResolver.SchemeContent))
        {
            ContentResolver cr = MainActivity.Instance.ContentResolver;
            mime_type = cr.GetType(uri);
        }
        else
        {
            string ext = MimeTypeMap.GetFileExtensionFromUrl(uri.ToString());
            mime_type = MimeTypeMap.Singleton.GetMimeTypeFromExtension(ext.ToLower());
        }
        if (mime_type == null)
        {
            mime_type = "*/*";
        }
        return(mime_type);
    }
예제 #26
0
        void IDocumentView.DocumentView(byte[] bytes, string name, string title)
        {
            var context = Android.App.Application.Context;

            try
            {
                var filePath = CommonLibrary.Helpers.FileHelper.WriteFileFromByteArray(bytes, Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads).Path, "fmsxapp.pdf");
                var mime     = MimeTypeMap.GetFileExtensionFromUrl(filePath);
                // if copying was successful, start Intent for opening this file
                if (System.IO.File.Exists(filePath))
                {
                    Android.Net.Uri pdfPath = FileProvider.GetUriForFile(context, "com.mydomain.fileprovider", new Java.IO.File(filePath));
                    context.GrantUriPermission(context.PackageName, pdfPath, ActivityFlags.GrantReadUriPermission);
                    Intent intent = new Intent();
                    intent.SetFlags(ActivityFlags.GrantReadUriPermission);
                    intent.SetAction(Android.Content.Intent.ActionView);
                    intent.SetDataAndType(pdfPath, $"application/{mime}");
                    context.StartActivity(intent);
                }
            }
            catch (ActivityNotFoundException anfe)
            {
                // android could not find a suitable app for this file
                var alert = new AlertDialog.Builder(context);
                alert.SetTitle("Error");
                alert.SetMessage("No suitable app found to open this file");
                alert.SetCancelable(false);
                alert.SetPositiveButton("Okay", (object sender, DialogClickEventArgs e) => ((AlertDialog)sender).Hide());
                alert.Show();
            }
            catch (Exception ex)
            {
                // another exception
                var alert = new AlertDialog.Builder(context);
                alert.SetTitle("Error");
                alert.SetMessage("Error when opening document");
                alert.SetCancelable(false);
                alert.SetPositiveButton("Okay", (object sender, DialogClickEventArgs e) => ((AlertDialog)sender).Hide());
                alert.Show();
            }
        }
예제 #27
0
        // for now it only downloads ifunny
        public bool TryDownloadFile(string input, out Exception ex)
        {
            ex = null;
            try
            {
                var parser = ParserFinder.FindParser(this.ctx, input, out var url);

                if (parser == null)
                {
                    Toast.MakeText(ctx, "Incompatible site.", ToastLength.Short).Show();
                    return(false);
                }

                parser.TryFetchVideoUrl(url, out string[] urls);

                foreach (var _url in urls)
                {
                    var    uri           = Android.Net.Uri.Parse(_url);
                    var    request       = new DownloadManager.Request(uri);
                    string fileExtension = MimeTypeMap.GetFileExtensionFromUrl(_url);
                    string filename      = $"download.{fileExtension}";

                    request.SetDestinationInExternalPublicDir(Android.OS.Environment.DirectoryDownloads,
                                                              $"DLBuddy/{parser.GetParserName()}/{filename}");

                    request.SetVisibleInDownloadsUi(true);
                    request.SetNotificationVisibility(DownloadVisibility.VisibleNotifyCompleted);
                    request.SetTitle($"DLBuddy - {parser.GetParserName()}");
                    manager.Enqueue(request);
                }


                return(true);
            }
            catch (Exception e)
            {
                ex = e;
                return(false);
            }
        }
예제 #28
0
        public bool CanOpenFile(string fileName)
        {
            var extension = MimeTypeMap.GetFileExtensionFromUrl(fileName.Replace(' ', '_').ToLower());

            if (extension == null)
            {
                return(false);
            }
            var mimeType = MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension);

            if (mimeType == null)
            {
                return(false);
            }
            var activity = (MainActivity)CrossCurrentActivity.Current.Activity;
            var intent   = new Intent(Intent.ActionView);

            intent.SetType(mimeType);
            var activities = activity.PackageManager.QueryIntentActivities(intent, PackageInfoFlags.MatchDefaultOnly);

            return((activities?.Count ?? 0) > 0);
        }
예제 #29
0
        protected virtual string GetMimeType(Uri uri, string path)
        {
            string application = MimeTypeMap.Singleton.GetMimeTypeFromExtension(
                MimeTypeMap.GetFileExtensionFromUrl(uri.Path));

            if (string.IsNullOrEmpty(application))
            {
                string type = Path.GetExtension(path);

                switch (type.ToLower())
                {
                case ".doc":
                case ".docx":
                    application = "application/msword";
                    break;

                case ".pdf":
                    application = "application/pdf";
                    break;

                case ".xls":
                case ".xlsx":
                    application = "application/vnd.ms-excel";
                    break;

                case ".jpg":
                case ".jpeg":
                case ".png":
                    application = "image/jpeg";
                    break;

                default:
                    application = "*/*";
                    break;
                }
            }

            return(application);
        }
예제 #30
0
        private Intent BuildOpenFileIntent(byte[] fileData, string fileName)
        {
            var extension = MimeTypeMap.GetFileExtensionFromUrl(fileName.Replace(' ', '_').ToLower());

            if (extension == null)
            {
                return(null);
            }
            var mimeType = MimeTypeMap.Singleton.GetMimeTypeFromExtension(extension);

            if (mimeType == null)
            {
                return(null);
            }

            var activity  = (MainActivity)CrossCurrentActivity.Current.Activity;
            var cachePath = activity.CacheDir;
            var filePath  = Path.Combine(cachePath.Path, fileName);

            File.WriteAllBytes(filePath, fileData);
            var file = new Java.IO.File(cachePath, fileName);

            if (!file.IsFile)
            {
                return(null);
            }

            try
            {
                var intent = new Intent(Intent.ActionView);
                var uri    = FileProvider.GetUriForFile(activity.ApplicationContext,
                                                        "io.cozy.pass.fileprovider", file);
                intent.SetDataAndType(uri, mimeType);
                intent.SetFlags(ActivityFlags.GrantReadUriPermission);
                return(intent);
            }
            catch { }
            return(null);
        }