Пример #1
0
        private static async Task <string[]> UploadSpeciesGalleryAsync(MediaWikiClient client, EditHistory history, Species species)
        {
            // Upload all images in the given species' gallery.

            Picture[] pictures = await SpeciesUtils.GetPicturesAsync(species);

            List <string> uploadedFilenames = new List <string>();

            if (pictures != null)
            {
                foreach (Picture picture in pictures)
                {
                    // Skip the image if it's the same as the species' default image, because we would've already uploaded it

                    if (picture.url == species.Picture)
                    {
                        continue;
                    }

                    string uploadedFilename = GeneratePictureFilenameFromSpecies(species, picture.url);

                    if (!string.IsNullOrEmpty(uploadedFilename))
                    {
                        UploadParameters uploadParameters = new UploadParameters {
                            UploadFileName = uploadedFilename,
                            FilePath       = picture.url,
                            Text           = picture.description
                        };

                        uploadedFilename = await UploadPictureAsync(client, history, uploadParameters, true);

                        if (!string.IsNullOrEmpty(uploadedFilename))
                        {
                            uploadedFilenames.Add(uploadedFilename);
                        }
                    }
                    else
                    {
                        _log(string.Format("Failed to generate filename for picture: {0}", picture.url));
                    }
                }
            }

            return(uploadedFilenames.ToArray());
        }
Пример #2
0
        private static async Task <string> UploadSpeciesPictureAsync(MediaWikiClient client, EditHistory history, Species species)
        {
            // Generate a filename for the image, which will be the filename when it's uploaded to the wiki.

            string uploadedFilename = GeneratePictureFilenameFromSpecies(species);

            if (!string.IsNullOrEmpty(uploadedFilename))
            {
                // Attempt to upload the image.

                UploadParameters uploadParameters = new UploadParameters {
                    UploadFileName = uploadedFilename,
                    FilePath       = species.Picture
                };

                return(await UploadPictureAsync(client, history, uploadParameters, true));
            }

            return(string.Empty);
        }
Пример #3
0
        public MediaWikiApiRequestResult Upload(UploadParameters parameters)
        {
            string token   = _get_csrf_token();
            bool   success = false;

            if (!string.IsNullOrEmpty(token))
            {
                if (!IsLoggedIn)
                {
                    LogWarn(string.Format("uploading file \"{0}\" anonymously", parameters.UploadFileName));
                }
                else
                {
                    LogInfo(string.Format("uploading file \"{0}\"", parameters.UploadFileName));
                }

                if (Regex.IsMatch(parameters.FilePath, @"^https?://"))
                {
                    // Upload by URL.

                    NameValueCollection values = new NameValueCollection {
                        ["action"]         = "upload",
                        ["format"]         = "json",
                        ["filename"]       = parameters.UploadFileName,
                        ["url"]            = parameters.FilePath,
                        ["token"]          = token,
                        ["ignorewarnings"] = "1",
                        ["text"]           = parameters.Text,
                        ["comment"]        = parameters.Comment,
                    };

                    string data = _http_post(_get_api_url(), values);

                    string success_string = string.Empty;

                    if (JObject.Parse(data).ContainsKey("upload"))
                    {
                        success_string = JObject.Parse(data)["upload"]["result"].Value <string>();
                    }
                    else if (JObject.Parse(data).ContainsKey("error"))
                    {
                        // If an error occurred, return the error information to the caller.

                        return(new MediaWikiApiRequestResult(
                                   JObject.Parse(data)["error"]["code"].Value <string>(),
                                   JObject.Parse(data)["error"]["info"].Value <string>()));
                    }

                    success = !string.IsNullOrEmpty(success_string) && success_string.ToLower() == "success";
                }
                else
                {
                    throw new Exception("Uploading local files is not yet supported.");
                }
            }

            if (success)
            {
                LogInfo(string.Format("uploaded file \"{0}\"", parameters.UploadFileName));
            }
            else
            {
                LogError(string.Format("failed to upload file \"{0}\"", parameters.UploadFileName));
            }

            return(new MediaWikiApiRequestResult {
                Success = success
            });
        }
Пример #4
0
        private static async Task <string> UploadPictureAsync(MediaWikiClient client, EditHistory history, UploadParameters parameters, bool allowRetry)
        {
            // Check if we've already uploaded this file before.
            // If we've uploaded it before, return the filename that we uploaded it with.

            UploadRecord record = await history.GetUploadRecordAsync(parameters.FilePath);

            if (record is null)
            {
                // Get page for the file and check for the bot flag.
                // This prevents us from overwriting images that users uploaded manually.

                MediaWikiApiParseRequestResult page_content = client.Parse(parameters.PageTitle, new ParseParameters());

                if (page_content.ErrorCode == ErrorCode.MissingTitle || page_content.Text.Contains(BotFlag))
                {
                    // Attempt to upload the file.

                    try {
                        parameters.Text = BotFlag + '\n' + parameters.Text;

                        MediaWikiApiRequestResult result = client.Upload(parameters);

                        if (!result.Success)
                        {
                            _log(result.ErrorMessage);
                        }

                        if (result.ErrorCode == ErrorCode.VerificationError && allowRetry)
                        {
                            // This means that the file extension didn't match (e.g., filename has ".png" when the file format is actually ".jpg").
                            // Try changing the file extension and reuploading, because sometimes URLs stored in the bot will have this problem.

                            string ext = System.IO.Path.GetExtension(parameters.UploadFileName);
                            ext = (ext == ".png") ? ".jpg" : ".png";

                            parameters.UploadFileName = System.IO.Path.ChangeExtension(parameters.UploadFileName, ext);

                            _log("file extension didn't match, retrying upload");

                            return(await UploadPictureAsync(client, history, parameters, false));
                        }
                        else
                        {
                            if (result.Success || result.ErrorCode == ErrorCode.FileExistsNoChange)
                            {
                                // If the upload succeeded, record the file upload so that we can skip it in the future.
                                await history.AddUploadRecordAsync(parameters.FilePath, parameters.UploadFileName);

                                // Add the bot flag to the page content.
                                // client.Edit(parameters.PageTitle, new EditParameters { Text = BotFlag });
                            }
                            else
                            {
                                parameters.UploadFileName = string.Empty;
                            }
                        }
                    }
                    catch (Exception ex) {
                        parameters.UploadFileName = string.Empty;

                        _log(ex.ToString());
                    }
                }
                else
                {
                    _log(string.Format("skipping file \"{0}\" (manually edited)", parameters.UploadFileName));
                }
            }
            else
            {
                // This image has been uploaded previously, so just return its path.

                _log(string.Format("skipping file \"{0}\" (previously uploaded)", parameters.UploadFileName));

                parameters.UploadFileName = record.UploadFileName;
            }

            return(parameters.UploadFileName);
        }