示例#1
0
        /// <param name="fileUrl">The URL for the file.</param>
        /// <param name="parentItemIdentifier">The parent directory's persistent identifier.</param>
        /// <param name="completionHandler">A handler to run after the operation completes.</param>
        /// <summary>When implemented by the developer, imports the resource at the specified <paramref name="fileUrl" /> into the directory that is identified by <paramref name="parentItemIdentifier" />.</summary>
        /// <remarks>
        ///   <para>(More documentation for this node is coming)</para>
        ///   <para tool="threads">This can be used from a background thread.</para>
        /// </remarks>
        public override void ImportDocument(NSUrl fileUrl, string parentItemIdentifier, Action <INSFileProviderItem, NSError> completionHandler)
        {
            try
            {
                fileUrl.StartAccessingSecurityScopedResource();
                FolderMetadata parentMetadata = StorageManager.GetFolderMetadata(parentItemIdentifier);
                if (!parentMetadata.IsExists)
                {
                    completionHandler?.Invoke(null, NSFileProviderErrorFactory.CreateNonExistentItemError(parentItemIdentifier));
                    return;
                }

                IEnumerable <string> existsNames = StorageManager.GetFolderChildrenMetadatas(parentMetadata).Select(x => x.Name);
                string       fileName            = GetNewFileName(fileUrl.LastPathComponent, existsNames);
                FileMetadata createdFile         = StorageManager.CreateFileOnServer(parentMetadata, fileName);
                createdFile = StorageManager.WriteFileContentOnServer(createdFile, fileUrl.Path);
                completionHandler?.Invoke(ProviderItem.CreateFromMetadata(createdFile), null);
                this.StorageManager.NotifyEnumerator(parentItemIdentifier);
            }
            catch (Exception ex)
            {
                NSError error = this.MapError(ex);
                completionHandler?.Invoke(null, error);
            }
            finally
            {
                fileUrl.StopAccessingSecurityScopedResource();
            }
        }
示例#2
0
        public void PickedDocument(NSUrl url)
        {
            url.StartAccessingSecurityScopedResource();
            var doc      = new UIDocument(url);
            var fileName = doc.LocalizedName;

            if (string.IsNullOrWhiteSpace(fileName))
            {
                var path = doc.FileUrl?.ToString();
                if (path != null)
                {
                    path = WebUtility.UrlDecode(path);
                    var split = path.LastIndexOf('/');
                    fileName = path.Substring(split + 1);
                }
            }
            var fileCoordinator = new NSFileCoordinator();

            fileCoordinator.CoordinateRead(url, NSFileCoordinatorReadingOptions.WithoutChanges,
                                           out NSError error, (u) =>
            {
                var data = NSData.FromUrl(u).ToArray();
                SelectFileResult(data, fileName ?? "unknown_file_name");
            });
            url.StopAccessingSecurityScopedResource();
        }
示例#3
0
        /// <summary>
        /// Get the archived data from a URL Path
        /// </summary>
        private void FetchArchivedWorldMap(NSUrl url, Action <NSData, NSError> closure)
        {
            DispatchQueue.DefaultGlobalQueue.DispatchAsync(() =>
            {
                try
                {
                    _        = url.StartAccessingSecurityScopedResource();
                    var data = NSData.FromUrl(url);
                    closure(data, null);
                }
                catch
                {
                    // TODO:
                    //DispatchQueue.MainQueue.DispatchAsync(() =>
                    //{
                    //    this.ShowAlert(error.LocalizedDescription);
                    //});

                    //closure(null, error);
                }
                finally
                {
                    url.StopAccessingSecurityScopedResource();
                }
            });
        }
示例#4
0
        void PrintOutsideFileContent(NSUrl securityScopedUrl)
        {
            if (!securityScopedUrl.StartAccessingSecurityScopedResource())
            {
                return;
            }

            PrintFileContent(securityScopedUrl);

            securityScopedUrl.StopAccessingSecurityScopedResource();
        }
示例#5
0
        internal UIDocumentFileResult(NSUrl url)
            : base()
        {
            url.StartAccessingSecurityScopedResource();

            var doc = new UIDocument(url);

            FullPath = doc.FileUrl?.Path;
            FileName = doc.LocalizedName ?? Path.GetFileName(FullPath);

            // immediately open a file stream, in case iOS cleans up the picked file
            fileStream = File.OpenRead(FullPath);

            url.StopAccessingSecurityScopedResource();
        }
示例#6
0
        FileData ParseUrl(NSUrl p_url)
        {
            p_url.StartAccessingSecurityScopedResource();

            var    doc  = new UIDocument(p_url);
            string name = doc.LocalizedName;
            string path = doc.FileUrl?.Path;

            // iCloud drive can return null for LocalizedName.
            if (name == null && path != null)
            {
                name = Path.GetFileName(path);
            }
            var fd = new FileData(path, name, _fileManager.GetAttributes(path).Size.Value);

            p_url.StopAccessingSecurityScopedResource();
            return(fd);
        }
示例#7
0
        internal BookmarkDataFileResult(NSUrl url)
            : base()
        {
            try
            {
                url.StartAccessingSecurityScopedResource();

                var newBookmark = url.CreateBookmarkData(0, Array.Empty <string>(), null, out var bookmarkError);
                if (bookmarkError != null)
                {
                    throw new NSErrorException(bookmarkError);
                }

                UpdateBookmark(url, newBookmark);
            }
            finally
            {
                url.StopAccessingSecurityScopedResource();
            }
        }
示例#8
0
 public static IDisposable BeginScope(NSUrl url)
 {
     lock (_syncLock)
     {
         var absoluteString = url.AbsoluteString;
         if (!_activeScopes.TryGetValue(absoluteString, out var disposable) || disposable.IsDisposed)
         {
             bool scopeStarted = false;
             try
             {
                 scopeStarted = url.StartAccessingSecurityScopedResource();
             }
             catch (Exception ex)
             {
                 throw new UnauthorizedAccessException("Could not access file system item. " + ex);
             }
             if (scopeStarted)
             {
                 disposable = new RefCountDisposable(Disposable.Create(() =>
                 {
                     lock (_syncLock)
                     {
                         url.StopAccessingSecurityScopedResource();
                         _activeScopes.Remove(absoluteString);
                     }
                 }));
                 _activeScopes[absoluteString] = disposable;
                 return(disposable);
             }
             else
             {
                 return(Disposable.Empty);
             }
         }
         else
         {
             return(disposable.GetDisposable());
         }
     }
 }
		void PrintOutsideFileContent(NSUrl securityScopedUrl)
		{
			if (!securityScopedUrl.StartAccessingSecurityScopedResource ())
				return;

			PrintFileContent (securityScopedUrl);

			securityScopedUrl.StopAccessingSecurityScopedResource ();
		}
示例#10
0
        public override bool OpenUrl(UIApplication app, NSUrl url, NSDictionary options)
        {
            Task.Run(async() =>
            {
                if ("Inbox".Equals(Path.GetFileName(Path.GetDirectoryName(url.Path))))
                {
                    IFolder incoming = await App.Storage.CreateFolderAsync("Incoming", CreationCollisionOption.OpenIfExists);
                    IFile f          = await FileSystem.Current.GetFileFromPathAsync(url.Path);
                    await f.MoveAsync(Path.Combine(incoming.Path, f.Name), NameCollisionOption.GenerateUniqueName);
                    Xamarin.Forms.Device.BeginInvokeOnMainThread(async() =>
                    {
                        App.MainTab.SelectedItem = App.MainTab.Children[3];
                        await App.MainTab.Children[3].Navigation.PopToRootAsync();
                        await App.MainTab.Children[3].Navigation.PushAsync(new FileBrowser(incoming));
                    });
                }
                else if (url.Path?.EndsWith(".cb5") ?? false)
                {
                    url.StartAccessingSecurityScopedResource();
                    try {
                        //using (MemoryStream s = new MemoryStream()) {
                        //    NSInputStream stream = NSInputStream.FromUrl(url);
                        //    byte[] buffer = new byte[1024];
                        //    while (stream.HasBytesAvailable()) {
                        //        int read = (int)stream.Read(buffer, 1024);
                        //        s.Write(buffer, 0, read);
                        //    }
                        //    s.Seek(0, SeekOrigin.Begin);
                        //NSFileHandle fs = NSFileHandle.OpenReadUrl(url, out NSError err);
                        //NSData data = fs.ReadDataToEndOfFile();
                        //fs.CloseFile();
                        //using (Stream f = data.AsStream()) {AsStream
                        //new MyInputStream(NSInputStream.FromUrl(url))) {
                        //NSData d = await url.LoadDataAsync("text/xml");
                        //File.OpenRead(url.Path)
                        using (Stream s = File.OpenRead(url.Path)) {
                            Player player          = Player.Serializer.Deserialize(s) as Player;
                            BuilderContext Context = new BuilderContext(player);
                            PluginManager manager  = new PluginManager();
                            manager.Add(new SpellPoints());
                            manager.Add(new SingleLanguage());
                            manager.Add(new CustomBackground());
                            manager.Add(new NoFreeEquipment());
                            Context.Plugins = manager;


                            Context.UndoBuffer     = new LinkedList <Player>();
                            Context.RedoBuffer     = new LinkedList <Player>();
                            Context.UnsavedChanges = 0;

                            Xamarin.Forms.Device.BeginInvokeOnMainThread(async() =>
                            {
                                LoadingProgress loader   = new LoadingProgress(Context);
                                LoadingPage l            = new LoadingPage(loader, false);
                                App.MainTab.SelectedItem = App.MainTab.Children[1];
                                await App.MainTab.Children[2].Navigation.PushModalAsync(l);
                                var t = l.Cancel.Token;
                                try
                                {
                                    await loader.Load(t).ConfigureAwait(false);
                                    t.ThrowIfCancellationRequested();
                                    PlayerBuildModel model = new PlayerBuildModel(Context);
                                    Xamarin.Forms.Device.BeginInvokeOnMainThread(async() =>
                                    {
                                        await App.MainTab.Children[1].Navigation.PopModalAsync(false);
                                        await App.MainTab.Children[1].Navigation.PushModalAsync(new NavigationPage(new FlowPage(model)));
                                    });
                                } catch (Exception e) {
                                    ConfigManager.LogError(e);
                                }
                            });
                        }
                        url.StopAccessingSecurityScopedResource();
                    }
                    catch (Exception e)
                    {
                        ConfigManager.LogError(e);
                    }
                }
                else if (url.Path.StartsWith(App.Storage.Path, System.StringComparison.Ordinal))
                {
                    Xamarin.Forms.Device.BeginInvokeOnMainThread(async() =>
                    {
                        App.MainTab.SelectedItem = App.MainTab.Children[3];
                        await App.MainTab.Children[3].Navigation.PopToRootAsync();
                        await App.MainTab.Children[3].Navigation.PushAsync(new FileBrowser(await FileSystem.Current.GetFolderFromPathAsync(Path.GetDirectoryName(url.Path))));
                    });
                }
                else
                {
                    url.StartAccessingSecurityScopedResource();
                    IFolder incoming = await App.Storage.CreateFolderAsync("Incoming", CreationCollisionOption.OpenIfExists);
                    IFile target     = await incoming.CreateFileAsync(url.LastPathComponent, CreationCollisionOption.GenerateUniqueName);
                    using (Stream f = File.OpenRead(url.Path))
                    {
                        using (Stream o = await target.OpenAsync(PCLStorage.FileAccess.ReadAndWrite))
                        {
                            await f.CopyToAsync(o);
                        }
                    }
                    url.StopAccessingSecurityScopedResource();
                    Xamarin.Forms.Device.BeginInvokeOnMainThread(async() =>
                    {
                        App.MainTab.SelectedItem = App.MainTab.Children[3];
                        await App.MainTab.Children[3].Navigation.PopToRootAsync();
                        await App.MainTab.Children[3].Navigation.PushAsync(new FileBrowser(incoming));
                    });
                }
            }).Forget();
            return(true);
        }