Skip to content

Instantly share code, notes, and snippets.

@mayuki
Created February 11, 2010 12:41
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mayuki/301469 to your computer and use it in GitHub Desktop.
Save mayuki/301469 to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq.Expressions;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
namespace TumblrBulkUploader
{
class Program
{
static void Main(string[] args)
{
var sEmail = ""; // Login Email
var sPassword = ""; // password
var sGroup = ""; // <sub-blog-domain>.tumblr.com
var sTags = ""; // tags (comma sepalated)
var baseDir = @"C:\Path\To\Directory";
var uploadedDir = Path.Combine(baseDir, "Uploaded");
List<String> files = new List<string>(Directory.GetFiles(baseDir));
files.Sort((a,b) => {
var aNum = Int32.Parse(Regex.Replace(a, "[^0-9]", ""));
var bNum = Int32.Parse(Regex.Replace(b, "[^0-9]", ""));
return a == b ? 0
: (aNum > bNum) ? 1 : -1;
});
if (!Directory.Exists(uploadedDir))
Directory.CreateDirectory(uploadedDir);
foreach (var filePath in files)
{
if (!Regex.IsMatch(Path.GetExtension(filePath), "png|jpg|bmp"))
continue;
Console.WriteLine(filePath);
UploadToTumblr(filePath, sEmail, sPassword, sTags, sGroup);
File.Move(filePath, Path.Combine(uploadedDir, Path.GetFileName(filePath)));
}
}
static void UploadToTumblr(String filePath, String sEmail, String sPassword, String sTags, String sGroup)
{
using (WebClient webClient = new WebClient())
{
Byte[] bytes = File.ReadAllBytes(filePath);
String url = "http://www.tumblr.com/api/write";
String body = Utility.CreateUrlParameters(
email => sEmail,
password => sPassword,
type => "photo",
group => sGroup,
tags => sTags,
data => bytes
);
try
{
webClient.Headers["Content-Type"] = "application/x-www-form-urlencoded";
webClient.UploadString(url, body);
}
catch (WebException we)
{
using (Stream stream = we.Response.GetResponseStream())
using (StreamReader reader = new StreamReader(stream))
{
var resBody = reader.ReadToEnd();
Console.WriteLine("Error: "+resBody);
throw;
}
}
}
}
}
static class Utility
{
public static String CreateUrlParameters(params Expression<Func<Object, Object>>[] exprs)
{
StringBuilder sb = new StringBuilder();
foreach (var expr in exprs)
{
if (sb.Length != 0)
sb.Append("&");
sb.Append(HttpUtility.UrlEncode(expr.Parameters[0].Name));
sb.Append("=");
var obj = expr.Compile().Invoke(null);
if (obj is Byte[])
sb.Append(HttpUtility.UrlEncode((Byte[])obj));
else
sb.Append(HttpUtility.UrlEncode(obj.ToString()));
}
return sb.ToString();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment