instant-image-uploader /HatenaPhotLife/HatenaPhotLifeClient.cs

Language C# Lines 125
MD5 Hash cea1659afb418bd4466a8f69bcda1f26 Estimated Cost $2,560 (why?)
Repository https://bitbucket.org/ugaya40/instant-image-uploader View Raw File View Project SPDX
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reactive;
using System.Reactive.Linq;
using System.Security.Cryptography;
using System.Net;
using System.IO;
using System.Xml.Linq;
using System.Xml;


namespace HatenaPhotLife
{
    public class HatenaPhotLifeClient
    {
        private string _userId;
        private string _password;

        public HatenaPhotLifeClient(string userId, string password)
        {
            _userId = userId;
            _password = password;
        }

        public IObservable<string> UploadAsObservable(string imageFilePath,string folder)
        {
            XNamespace ns = "http://purl.org/atom/ns#";

            return Observable.Defer(() =>
                {
                    var request = (HttpWebRequest)HttpWebRequest.Create("http://f.hatena.ne.jp/atom");
                    request.Headers.Add("X-WSSE", GetWSSEHeader(_userId, _password));
                    request.ContentType = "application/x.atom+xml";
                    return Observable.FromAsyncPattern<WebResponse>(request.BeginGetResponse, request.EndGetResponse)();
                })
                .GetResponseAsXElement()
                .Select(responseXElement =>
                    (string)responseXElement.Descendants(ns + "link")
                    .Where(element => (string)element.Attribute("rel") == "service.post")
                    .First()
                    .Attribute("href"))
                .SelectMany(url => Observable.Defer(() =>
                    {
                        var request = (HttpWebRequest)HttpWebRequest.Create(url);
                        request.Method = "POST";
                        request.Headers.Add("X-WSSE", GetWSSEHeader(_userId, _password));
                        request.ContentType = "application/x.atom+xml";
                        using (var requestStream = request.GetRequestStream())
                        using (var writer = new XmlTextWriter(requestStream, Encoding.UTF8))
                        {
                            GenerateXml(imageFilePath,folder).WriteTo(writer);
                        }
                        return Observable.FromAsyncPattern<WebResponse>(request.BeginGetResponse, request.EndGetResponse)();
                    }))
                .GetResponseAsXElement()
                .Select(responseXElement => responseXElement.Descendants(ns + "link").Where(element => (string)element.Attribute("rel") == "alternate"))
                .Select(elements => (string)elements.First().Attribute("href"));
        }

        private static string GetWSSEHeader(string userid, string password)
        {
            var createdAtTime = DateTime.Now.ToUniversalTime().ToString("s");
            var nonce = new byte[40];
            new Random().NextBytes(nonce);
            string passwordDigest;

            var digestSource = nonce.Concat(createdAtTime.GetUTF8Bytes()).Concat(password.GetUTF8Bytes());

            using (SHA1Managed sha = new SHA1Managed())
            {
                passwordDigest = Convert.ToBase64String(sha.ComputeHash(digestSource.ToArray()));
            }

            return string.Format(@"UsernameToken Username=""{0}"", PasswordDigest=""{1}"", Nonce=""{2}"", Created=""{3}""",
                                            userid,
                                            passwordDigest,
                                            Convert.ToBase64String(nonce),
                                            createdAtTime
                        );
        }

        private static XElement GenerateXml(string imageFilePath,string folderName)
        {
            XNamespace ns = "http://purl.org/atom/ns#";
            XNamespace dc = "http://purl.org/dc/elements/1.1/";

            var root = new XElement(ns + "entry", new XAttribute(XNamespace.Xmlns + "dc", dc));

            var contentElement = new XElement("content", Convert.ToBase64String(File.ReadAllBytes(imageFilePath)));
            contentElement.SetAttributeValue("mode", "Base64");
            contentElement.SetAttributeValue("type", "image/png");
            root.Add(contentElement);

            if (!string.IsNullOrEmpty(folderName))
            {
                var folderElement = new XElement(dc + "subject", folderName);
                root.Add(folderElement);
            }

            var toolElement = new XElement("generator", "InstantImageUploader");
            root.Add(toolElement);

            return root;
        }
    }

    public static class CommonExtension
    {
        public static byte[] GetUTF8Bytes(this string source)
        {
            return Encoding.UTF8.GetBytes(source);
        }

        public static IObservable<XElement> GetResponseAsXElement(this IObservable<WebResponse> source)
        {
            return source.Select(response => response.GetResponseStream())
                .Select(stream => new StreamReader(stream).ReadToEnd())
                .Select(responseText => XElement.Parse(responseText));
        }
    }

}
Back to Top