示例#1
0
        //-------------------------------------------------------------------------------------------------------------------------------
        /// <summary>
        ///     Gets the URL to the shared link created ...
        ///     Dropbox.Api.Sharing.FileAction.ShareLink
        ///     http://dropbox.github.io/dropbox-sdk-dotnet/html/T_Dropbox_Api_Sharing_FileAction_ShareLink.htm
        ///     http://stackoverflow.com/questions/32099136/is-there-a-way-to-check-if-a-file-folder-in-dropbox-has-a-shared-link-without-cr
        /// </summary>
        /// <param name="folder"></param>
        /// <param name="file"></param>
        /// <returns></returns>
        public static async Task <string> ShareFile(string folder, string file)
        {
            //RequestedVisibility rv = new
            //SharedLinkSettings sls = new SharedLinkSettings();
            //sls.R.LinkPassword = "";

            //RequestedVisibility.Public, "TEST");

            // Check to see if it exists
            ListSharedLinksResult lslr = await dbx.Sharing.ListSharedLinksAsync(folder + "/" + file);

            SharedLinkMetadata slmd = null;

            if (lslr.Links != null && lslr.Links.Count > 0)
            {
                slmd = lslr.Links[0];
            }
            else
            {
                // Create it
                slmd = await dbx.Sharing.CreateSharedLinkWithSettingsAsync(folder + "/" + file);
            }

            //SharedLinkMetadata slmd = await dbx.Sharing.CreateSharedLinkWithSettingsAsync(folder + "/" + file);

            Console.WriteLine("Shared link to " + slmd.Name + " is " + slmd.Url);

            return(slmd.Url);
        }
        public async Task <string> GetFileLink(int bookId)
        {
            var client = new DropboxClient(_applicationConfiguration.DropBoxAccessToken);

            string remotePath = $"/{bookId}.png";
            string rawOption  = "raw=1";
            string url        = string.Empty;
            string result     = string.Empty;

            try
            {
                ListSharedLinksResult links = await client.Sharing.ListSharedLinksAsync(remotePath);

                url = links.Links.FirstOrDefault().Url;
            }
            catch (Exception ex)
            {
                SharedLinkMetadata metadata = await client.Sharing.CreateSharedLinkWithSettingsAsync(remotePath);

                url = metadata.Url;
            }

            result = $"{url}&{rawOption}";

            return(result);
        }
 /// <summary>
 /// Checks if link has an equal or more 'visible' permission than requested visibility
 /// TeamOnly < Password < Public
 /// </summary>
 /// <param name="link"></param>
 /// <param name="requestedVisibility"></param>
 /// <returns></returns>
 public static bool IsMoreVisiblePermission(SharedLinkMetadata link, RequestedVisibility requestedVisibility)
 {
     if (ConvertResolvedVisibilityToInt(link.LinkPermissions.ResolvedVisibility)
         >= ConvertRequestedVisibilityToInt(requestedVisibility))
     {
         return(true);
     }
     else
     {
         return(false);
     }
 }
示例#4
0
        public string GetSharedLink(string path)
        {
//            if (path.StartsWith(@"/Getting")) return "";

            SharedLinkMetadata sharedLinkMetadata = null;

            try
            {
                var sharedLinksMetadata = dbx.Sharing.ListSharedLinksAsync(path, null, true).Result;
                sharedLinkMetadata = sharedLinksMetadata.Links.First();
            }
            catch
            {
                try
                {
                    sharedLinkMetadata = dbx.Sharing.CreateSharedLinkWithSettingsAsync(path).Result;
                }
                catch
                {
                    return("");
                }
            }
            return(sharedLinkMetadata.Url);

            //IDownloadResponse<SharedLinkMetadata> dr = null;
            //SharedLinkMetadata slm = null;
            //try
            //{
            //    dr = dbx.Sharing.GetSharedLinkFileAsync(path).Result;
            //}
            //catch
            //{
            //    try
            //    {
            //        slm = dbx.Sharing.CreateSharedLinkWithSettingsAsync(path).Result;
            //    }
            //    catch
            //    {
            //        return slm.Url;
            //    }
            //    return slm.Url;
            //}
            //if (dr.Response.Url != null)
            //    return dr.Response.Url;
            //return "";
        }
        public async Task <string> GetSharedLink(string path)
        {
            string Result = string.Empty;

            try
            {
                SharedLinkMetadata sharedMeta = await client.Sharing.CreateSharedLinkWithSettingsAsync(path);

                Result = sharedMeta.Url;
            }
            catch (ApiException <Dropbox.Api.Sharing.CreateSharedLinkWithSettingsError> )
            {
                ListSharedLinksResult sharedList = await client.Sharing.ListSharedLinksAsync(path : path);

                IList <SharedLinkMetadata> asdasd = sharedList.Links;
                Result = asdasd[asdasd.Count - 1].Url;
            }
            return(Result);
        }
        public static async Task <SharedLinkMetadata> HandleShareFile(DropboxClient client, Metadata file, RequestedVisibility requestedVisibility, string password = null, bool forceNewLink = false)
        {
            SharedLinkMetadata existingLink = await GetFileShareLink(client, file);

            if (existingLink != null)
            {
                if (forceNewLink)
                {
                    await RevokeFileShareLink(client, existingLink.Url);
                }
                else if (!IsMoreVisiblePermission(existingLink, requestedVisibility))
                {
                    return(await ChangeShareLinkPermissions(client, existingLink.Url, requestedVisibility));
                }
                else
                {
                    return(existingLink);
                }
            }

            return(await CreateFileShareLink(client, file, requestedVisibility, password));
        }
        private async void GetShareLink_Button_Click(object sender, RoutedEventArgs e)
        {
            FileShareLink_TextBox.Text = null;

            Metadata selectedItem = DropboxFolderContent.SelectedIndex > -1 ? ((Metadata)DropboxFolderContent.SelectedItem) : null;

            if (selectedItem == null)
            {
                return;
            }

            if (selectedItem.IsFolder)
            {
                MessageBox.Show("This is a folder. Please select a file to share.");
                return;
            }

            if (selectedItem.IsDeleted)
            {
                MessageBox.Show("This item has been deleted and cannot be shared. I don't even know why it's displaying here. I don't even know why I'm making this error, you should never see it... In fact it might be possible to share the file, I haven't checked. I'm just not going to let you try.");
                return;
            }

            SharedLinkMetadata share = await DropboxHandler.HandleShareFile(client, selectedItem, RequestedVisibility.Password.Instance, "password");

            if (share.Url != null)
            {
                FileShareLink_TextBox.Text = share.Url;
                try
                {
                    Clipboard.SetDataObject(share.Url);
                }
                catch (Exception error)
                {
                    MessageBox.Show("Unable to copy to clipboard. This can be caused by a an active WebEx session interfering with clipboard operations. Try again after closing your WebEx session.\n\n" + error.Message);
                }
            }
        }
示例#8
0
        public async Task <string> UploadFileAsync(IFormFile formFile, string folderUrl)
        {
            try
            {
                using (DropboxClient dbx = new DropboxClient(_dropbox.GetToken()))
                {
                    var extension  = Path.GetExtension(formFile.FileName);
                    var fileName   = Path.GetRandomFileName() + extension;
                    var filePath   = folderUrl + fileName;
                    var fileStream = formFile.OpenReadStream();
                    var upload     = await dbx.Files.UploadAsync(filePath, WriteMode.Overwrite.Instance, false, null, false, null, true, fileStream);

                    SharedLinkMetadata shared = await dbx.Sharing.CreateSharedLinkWithSettingsAsync(upload.PathDisplay);

                    string s = shared != null ? shared.Url : string.Empty;
                    s = s.Replace("?dl=0", "?dl=1");
                    return(s);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
示例#9
0
        public async Task <Uri> AddDocument(Meeting meeting, Document document, string path = "")
        {
            DropboxCertHelper.InitializeCertPinning();

            if (string.IsNullOrEmpty(accessToken))
            {
                throw new ArgumentException("accessToken");
            }

            // Specify socket level timeout which decides maximum waiting time when no bytes are
            // received by the socket.
            var httpClient = new HttpClient()
            {
                // Specify request level timeout which decides maximum time that can be spent on
                // download/upload files.
                Timeout = TimeSpan.FromMinutes(20)
            };

            var config = new DropboxClientConfig("OpenGovAlerts")
            {
                HttpClient = httpClient
            };

            var client = new DropboxClient(accessToken, config);

            if (string.IsNullOrEmpty(path))
            {
                path = Path.Combine(baseFolder, meeting.Source.Name, meeting.Title, meeting.Date.ToString("yyyy-MM-dd") + "-" + meeting.BoardName);
            }

            var filename = new string(document.Title.Select(ch => invalidFileNameChars.Contains(ch) ? '_' : ch).ToArray());

            try
            {
                CreateFolderResult result = await client.Files.CreateFolderV2Async(path, false);
            }
            catch (ApiException <CreateFolderError> ex)
            {
                if (ex.ErrorResponse.AsPath.Value.IsConflict)
                {
                    // The folder already exists. Fine. I feel like I need to shower now.
                }
                else
                {
                    // F**k it, I'm not looking at any of those other properties.
                    throw new ApplicationException(string.Format("Could not create/verify Dropbox folder {1} for document {0} because of error {2}", document.Url, path, ex.Message));
                }
            }
            catch (Exception e)
            {
                throw new ApplicationException(string.Format("Could not create/verify Dropbox folder {1} for document {0} because of error {2}", document.Url, path, e.Message));
            }

            string filePath = Path.Combine(path, filename);

            try
            {
                Stream input = await httpClient.GetStreamAsync(document.Url);

                FileMetadata file = await client.Files.UploadAsync(filePath, body : input);

                SharedLinkMetadata link = await client.Sharing.CreateSharedLinkWithSettingsAsync(new CreateSharedLinkWithSettingsArg(file.PathLower));

                return(new Uri(link.Url));
            }
            catch (ApiException <UploadError> ex)
            {
                throw new ApplicationException(string.Format("Could not upload document {0} to path {1} because of error {2}", document.Url, filePath, ex.Message));
            }
            catch (Exception e)
            {
                throw new ApplicationException(string.Format("Could not upload document {0} to path {1} because of error {2}", document.Url, filePath, e.Message));
            }
        }
示例#10
0
        private async void Button1_Click(object sender, EventArgs e)
        {
            string accessToken = "Lzk0cOUr-BoAAAAAAABn1QgKontvLa2ma0vtCU24NTo9vEeBTeFSjiROUL5rY_6F";
            string appKey      = "e7852uopirsqcja";
            string appSecret   = "dvhf2ijy2z99ckg";

            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                foreach (string fileName in openFileDialog1.FileNames)
                {
                    LogMessage(fileName);

                    Dropbox.DropboxClient client = new Dropbox.DropboxClient(appKey, appSecret);

                    if (Path.GetExtension(fileName) == ".mp4")
                    {
                        LogMessage($"Cannot process mp4 file {fileName}");

                        continue;
                    }

                    string fileNameOnDropbox = Path.GetFileName(fileName);

                    UploadFileRequest request = new UploadFileRequest(fileNameOnDropbox);

                    Image image = Image.FromFile(fileName);

                    using (MemoryStream stream = new MemoryStream())
                    {
                        image.Save(stream, image.RawFormat);

                        stream.Position = 0;

                        await client.UploadFileAsync(request, stream, accessToken);
                    }

                    using (var apiClient = new Dropbox.Api.DropboxClient(accessToken))
                    {
                        string fn = $"/{fileNameOnDropbox}";

                        ListSharedLinksResult sharedLinksResult = await apiClient.Sharing.ListSharedLinksAsync(new ListSharedLinksArg(fn));

                        string url = string.Empty;

                        if (sharedLinksResult.Links.Count > 0)
                        {
                            url = sharedLinksResult.Links[0].Url;
                        }
                        else
                        {
                            SharedLinkMetadata sharedLinkMetaData = await apiClient.Sharing.CreateSharedLinkWithSettingsAsync(fn);

                            url = sharedLinkMetaData.Url;

                            //DatabaseOperations.
                        }

                        textboxFeedBack.Text += $"Url = {url}";
                    }
                }
            }
        }
示例#11
0
        public static T Convert <T>(SharedLinkMetadata x) where T : SharedMetaDataDTO
        {
            var destinationType = x.GetType() == typeof(SharedFileMetadata) ? typeof(SharedFileDTO) : typeof(SharedFolderDTO);

            return((T)AutoMapper.Mapper.Map(x, x.GetType(), destinationType));
        }