public static Task<IPlatformClientBuilder[]> ImportFrom(this PlatformClientFactory factory, ICookieImporter source, IApiAccessor accessor = null)
 {
     return Task.Run(async () =>
         {
             accessor = accessor ?? new DefaultAccessor();
             return await accessor.GetAccountListAsync(ImportCookiesFrom(source));
         });
 }
 public PlatformClient(Uri plusBaseUrl, Uri talkBaseUrl,
     System.Net.CookieContainer cookie, IApiAccessor accessor,
     ICacheDictionary<string, ProfileCache, ProfileData> profileCacheStorage,
     CacheDictionary<string, ActivityCache, ActivityData> activityCacheStorage)
 {
     var handler = new System.Net.Http.HttpClientHandler() { CookieContainer = cookie };
     Cookies = cookie;
     ServiceApi = accessor;
     PlusBaseUrl = plusBaseUrl;
     TalkBaseUrl = talkBaseUrl;
     NormalHttpClient = new System.Net.Http.HttpClient(handler);
     NormalHttpClient.DefaultRequestHeaders.Add("user-agent", ApiAccessorUtility.UserAgent);
     StreamHttpClient = new System.Net.Http.HttpClient(handler);
     StreamHttpClient.Timeout = TimeSpan.FromMinutes(15);
     StreamHttpClient.DefaultRequestHeaders.Add("user-agent", ApiAccessorUtility.UserAgent);
     People = new PeopleContainer(this, profileCacheStorage);
     Activity = new ActivityContainer(this, activityCacheStorage);
     Notification = new NotificationContainer(this);
 }
Beispiel #3
0
        public static async Task <IApiResult <IEnumerable <TwitterStatus> > > GetHomeTimelineAsync(
            [NotNull] this IApiAccessor accessor,
            int?count, long?sinceId, long?maxId, CancellationToken cancellationToken)
        {
            if (accessor == null)
            {
                throw new ArgumentNullException(nameof(accessor));
            }
            var param = new Dictionary <string, object>
            {
                { "count", count },
                { "since_id", sinceId },
                { "max_id", maxId }
            }.SetExtended();

            return(await accessor.GetAsync("statuses/home_timeline.json", param,
                                           ResultHandlers.ReadAsStatusCollectionAsync, cancellationToken)
                   .ConfigureAwait(false));
        }
Beispiel #4
0
        public static async Task <IApiResult <TwitterSavedSearch> > SaveSearchAsync(
            [NotNull] this IApiAccessor accessor, [NotNull] string query,
            CancellationToken cancellationToken)
        {
            if (accessor == null)
            {
                throw new ArgumentNullException(nameof(accessor));
            }
            if (query == null)
            {
                throw new ArgumentNullException(nameof(query));
            }
            var param = new Dictionary <string, object>
            {
                { "query", query }
            };

            return(await accessor.PostAsync("saved_searches/create.json", param,
                                            ResultHandlers.ReadAsSavedSearchAsync, cancellationToken).ConfigureAwait(false));
        }
Beispiel #5
0
        public static async Task <IApiResult <ICursorResult <IEnumerable <TwitterList> > > > GetListMembershipsAsync(
            [NotNull] this IApiAccessor accessor,
            [NotNull] ListParameter targetList, long?cursor, CancellationToken cancellationToken)
        {
            if (accessor == null)
            {
                throw new ArgumentNullException(nameof(accessor));
            }
            if (targetList == null)
            {
                throw new ArgumentNullException(nameof(targetList));
            }
            var param = new Dictionary <string, object>()
            {
                { "cursor", cursor },
            }.ApplyParameter(targetList);

            return(await accessor.GetAsync("lists/memberships.json", param,
                                           ResultHandlers.ReadAsCursoredListsAsync, cancellationToken).ConfigureAwait(false));
        }
Beispiel #6
0
        public static async Task <IApiResult <IEnumerable <TwitterStatus> > > GetDirectMessagesAsync(
            [NotNull] this IApiAccessor accessor, int?count, long?sinceId, long?maxId,
            CancellationToken cancellationToken)
        {
            if (accessor == null)
            {
                throw new ArgumentNullException(nameof(accessor));
            }
            var param = new Dictionary <string, object>
            {
                { "count", count },
                { "since_id", sinceId },
                { "max_id", maxId },
                { "full_text", true } // full_text mode is always applied
            }.SetExtended();

            return(await accessor.GetAsync("direct_messages.json", param,
                                           ResultHandlers.ReadAsStatusCollectionAsync, cancellationToken)
                   .ConfigureAwait(false));
        }
Beispiel #7
0
        public static async Task <IApiResult <IEnumerable <TwitterStatus> > > GetFavoritesAsync(
            [NotNull] this IApiAccessor accessor, [CanBeNull] UserParameter targetUser,
            int?count, long?sinceId, long?maxId,
            CancellationToken cancellationToken)
        {
            if (accessor == null)
            {
                throw new ArgumentNullException(nameof(accessor));
            }
            var param = new Dictionary <string, object>
            {
                { "count", count },
                { "since_id", sinceId },
                { "max_id", maxId },
            }.ApplyParameter(targetUser).SetExtended();

            return(await accessor.GetAsync("favorites/list.json", param,
                                           ResultHandlers.ReadAsStatusCollectionAsync, cancellationToken)
                   .ConfigureAwait(false));
        }
Beispiel #8
0
        public static async Task <IApiResult <TwitterUser> > UpdateProfileImageAsync(
            [NotNull] this IApiAccessor accessor,
            [NotNull] byte[] image, CancellationToken cancellationToken)
        {
            if (accessor == null)
            {
                throw new ArgumentNullException(nameof(accessor));
            }
            if (image == null)
            {
                throw new ArgumentNullException(nameof(image));
            }
            var content = new MultipartFormDataContent
            {
                { new StringContent("true"), "skip_status" },
                { new ByteArrayContent(image), "image", "image.png" }
            };

            return(await accessor.PostAsync("account/update_profile_image.json",
                                            content, ResultHandlers.ReadAsUserAsync, cancellationToken).ConfigureAwait(false));
        }
Beispiel #9
0
        public static async Task <IApiResult <TwitterUser> > UpdateProfileAsync(
            [NotNull] this IApiAccessor accessor, [CanBeNull] string name, [CanBeNull] string url,
            [CanBeNull] string location, [CanBeNull] string description,
            CancellationToken cancellationToken)
        {
            if (accessor == null)
            {
                throw new ArgumentNullException(nameof(accessor));
            }
            var param = new Dictionary <string, object>
            {
                { "name", name },
                { "url", url },
                { "location", location },
                { "description", description },
                { "skip_status", true },
            };

            return(await accessor.PostAsync("account/update_profile.json",
                                            param, ResultHandlers.ReadAsUserAsync, cancellationToken).ConfigureAwait(false));
        }
Beispiel #10
0
        private static async Task <IApiResult <IEnumerable <TwitterUser> > > LookupUserCoreAsync(
            [NotNull] IApiAccessor accessor, IEnumerable <long> userIds, IEnumerable <string> screenNames,
            CancellationToken cancellationToken)
        {
            if (accessor == null)
            {
                throw new ArgumentNullException(nameof(accessor));
            }
            var userIdsString = userIds == null
                ? null
                : String.Join(",", userIds.Select(s => s.ToString(CultureInfo.InvariantCulture)));
            var param = new Dictionary <string, object>
            {
                { "user_id", userIdsString },
                { "screen_name", screenNames == null ? null : String.Join(",", screenNames) }
            };

            return(await accessor.GetAsync("users/lookup.json", param,
                                           ResultHandlers.ReadAsUserCollectionAsync, cancellationToken)
                   .ConfigureAwait(false));
        }
Beispiel #11
0
        private static async Task <Tuple <IApiResult <IEnumerable <T> >, ApiContinuationReader <IEnumerable <T> > > > ReadCursorApi <T>(
            this IApiAccessor accessor, long cursor,
            Func <IApiAccessor, long, Task <IApiResult <ICursorResult <IEnumerable <T> > > > > reader,
            CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();

            var r = await reader(accessor, cursor).ConfigureAwait(false);

            cancellationToken.ThrowIfCancellationRequested();

            var cr = r.Result;
            var ir = ApiResult.Create(cr.Result, r.RateLimit);
            ApiContinuationReader <IEnumerable <T> > callback = null;

            if (cr.CanReadNext)
            {
                callback = () => ReadCursorApi(accessor, cr.NextCursor, reader, cancellationToken);
            }
            return(Tuple.Create(ir, callback));
        }
Beispiel #12
0
        public static async Task <IApiResult <IEnumerable <TwitterStatus> > > GetListTimelineAsync(
            [NotNull] this IApiAccessor accessor,
            [NotNull] ListParameter listTarget, long?sinceId, long?maxId, int?count, bool?includeRts,
            CancellationToken cancellationToken)
        {
            if (accessor == null)
            {
                throw new ArgumentNullException(nameof(accessor));
            }
            var param = new Dictionary <string, object>()
            {
                { "since_id", sinceId },
                { "max_id", maxId },
                { "count", count },
                { "include_rts", includeRts },
            }.ApplyParameter(listTarget).SetExtended();

            return(await accessor.GetAsync("lists/statuses.json", param,
                                           ResultHandlers.ReadAsStatusCollectionAsync, cancellationToken)
                   .ConfigureAwait(false));
        }
Beispiel #13
0
        public static async Task <IApiResult <IEnumerable <TwitterUser> > > SearchUserAsync(
            [NotNull] this IApiAccessor accessor, [NotNull] string query, int?page, int?count,
            CancellationToken cancellationToken)
        {
            if (accessor == null)
            {
                throw new ArgumentNullException(nameof(accessor));
            }
            if (query == null)
            {
                throw new ArgumentNullException(nameof(query));
            }
            var param = new Dictionary <string, object>
            {
                { "q", query },
                { "page", page },
                { "count", count },
            };

            return(await accessor.GetAsync("users/search.json", param,
                                           ResultHandlers.ReadAsUserCollectionAsync, cancellationToken)
                   .ConfigureAwait(false));
        }
Beispiel #14
0
        public static async Task <IApiResult <TwitterFriendship> > ShowFriendshipAsync(
            [NotNull] this IApiAccessor accessor,
            [NotNull] UserParameter sourceUser, [NotNull] UserParameter targetUser, CancellationToken cancellationToken)
        {
            if (accessor == null)
            {
                throw new ArgumentNullException(nameof(accessor));
            }
            if (sourceUser == null)
            {
                throw new ArgumentNullException(nameof(sourceUser));
            }
            if (targetUser == null)
            {
                throw new ArgumentNullException(nameof(targetUser));
            }
            sourceUser.SetKeyAsSource();
            targetUser.SetKeyAsTarget();
            var param = sourceUser.ToDictionary().ApplyParameter(targetUser);

            return(await accessor.GetAsync("friendships/show.json", param,
                                           ResultHandlers.ReadAsFriendshipAsync, cancellationToken).ConfigureAwait(false));
        }
Beispiel #15
0
        public static async Task <IApiResult <TwitterFriendship> > UpdateFriendshipAsync(
            [NotNull] this IApiAccessor accessor,
            [NotNull] UserParameter screenName, bool?enableDeviceNotifications, bool?showRetweet,
            CancellationToken cancellationToken)
        {
            if (accessor == null)
            {
                throw new ArgumentNullException(nameof(accessor));
            }
            if (screenName == null)
            {
                throw new ArgumentNullException(nameof(screenName));
            }

            var param = new Dictionary <string, object>
            {
                { "device", enableDeviceNotifications },
                { "retweets", showRetweet },
            }.ApplyParameter(screenName);

            return(await accessor.PostAsync("friendships/update.json", param,
                                            ResultHandlers.ReadAsFriendshipAsync, cancellationToken).ConfigureAwait(false));
        }
Beispiel #16
0
        public static async Task <IApiResult <long?> > GetMyRetweetIdOfStatusAsync(
            [NotNull] this IApiAccessor accessor, long id,
            CancellationToken cancellationToken)
        {
            if (accessor == null)
            {
                throw new ArgumentNullException(nameof(accessor));
            }
            var param = new Dictionary <string, object>
            {
                { "id", id },
                { "include_my_retweet", true }
            };

            return(await accessor.GetAsync("statuses/show.json", param,
                                           async resp =>
            {
                var json = await resp.ReadAsStringAsync().ConfigureAwait(false);
                var graph = MeteorJson.Parse(json);
                return graph.ContainsKey("current_user_retweet")
                        ? graph["current_user_retweet"]["id_str"].AsString().ParseLong()
                        : (long?)null;
            }, cancellationToken).ConfigureAwait(false));
        }
Beispiel #17
0
        public static async Task <IApiResult <TwitterStatus> > SendDirectMessageAsync(
            [NotNull] this IApiAccessor accessor, [NotNull] UserParameter recipient, [NotNull] string text,
            CancellationToken cancellationToken)
        {
            if (accessor == null)
            {
                throw new ArgumentNullException(nameof(accessor));
            }
            if (recipient == null)
            {
                throw new ArgumentNullException(nameof(recipient));
            }
            if (text == null)
            {
                throw new ArgumentNullException(nameof(text));
            }
            var param = new Dictionary <string, object>
            {
                { "text", text }
            }.ApplyParameter(recipient).SetExtended();

            return(await accessor.PostAsync("direct_messages/new.json", param,
                                            ResultHandlers.ReadAsStatusAsync, cancellationToken).ConfigureAwait(false));
        }
Beispiel #18
0
 internal Asset(IApiAccessor api)
 {
     this._api = api;
 }
 public DestroySearchQueryRequest([NotNull] IApiAccessor accessor, long id)
 {
     Accessor = accessor ?? throw new ArgumentNullException(nameof(accessor));
     Id       = id;
 }
 public DeleteRetweetRequest([NotNull] IApiAccessor accessor, long targetId)
 {
     Accessor = accessor ?? throw new ArgumentNullException(nameof(accessor));
     TargetId = targetId;
 }
Beispiel #21
0
 internal Workflow(IApiAccessor api)
 {
     this._api = api;
 }
Beispiel #22
0
 public void Attach(IApiAccessor api)
 {
     api.Configuration.DefaultHeaders.Add("AccessToken", AccessToken);
 }
Beispiel #23
0
 public FavoriteRequest([NotNull] IApiAccessor accessor, long targetTweetId, bool createFavorite)
 {
     Accessor       = accessor ?? throw new ArgumentNullException(nameof(accessor));
     TargetTweetId  = targetTweetId;
     CreateFavorite = createFavorite;
 }
Beispiel #24
0
 public static Task <IApiResult <TwitterUploadedMedia> > UploadLargeMediaAsync(
     [NotNull] this IApiAccessor accessor, [NotNull] byte[] media, [NotNull] string mimeType,
     [CanBeNull] long[] additionalOwners, CancellationToken cancellationToken)
 {
     return(accessor.UploadLargeMediaAsync(media, mimeType, additionalOwners, null, null, cancellationToken));
 }
Beispiel #25
0
 public UpdateMuteRequest([NotNull] IApiAccessor accessor, [NotNull] UserParameter target, bool mute)
 {
     Accessor = accessor ?? throw new ArgumentNullException(nameof(accessor));
     Mute     = mute;
     Target   = target ?? throw new ArgumentNullException(nameof(target));
 }
Beispiel #26
0
        public static async Task <IApiResult <TwitterUploadedMedia> > UploadLargeMediaAsync(
            [NotNull] this IApiAccessor accessor, [NotNull] byte[] media, [NotNull] string mimeType,
            [CanBeNull] long[] additionalOwners, int?chunkSize, [CanBeNull] IProgress <int> sentBytesCallback,
            CancellationToken cancellationToken)
        {
            if (accessor == null)
            {
                throw new ArgumentNullException(nameof(accessor));
            }
            if (media == null)
            {
                throw new ArgumentNullException(nameof(media));
            }
            if (mimeType == null)
            {
                throw new ArgumentNullException(nameof(mimeType));
            }

            var mediaType = MediaFileUtility.GetMediaType(media);

            // maximum video size is 15MB (maximum image is 5MB)
            if (media.Length > 15 * 1024 * 1024)
            {
                throw new ArgumentOutOfRangeException(nameof(media), "media file must be smaller than 5MB.");
            }

            // check the bit array could be chunked
            var csize = chunkSize ?? 5 * 1024 * 1024;

            if (!mediaType.IsMovie() && media.Length <= csize)
            {
                // this item is not needed to split it into pieces
                return(await accessor.UploadMediaAsync(media, additionalOwners, cancellationToken)
                       .ConfigureAwait(false));
            }
            if (csize < 1 || media.Length / csize > 999)
            {
                throw new ArgumentOutOfRangeException(nameof(chunkSize), "chunk size is not appropriate.");
            }

            // chunking media
            var chunks = media.Select((b, i) => new { Data = b, Index = i / csize })
                         .GroupBy(b => b.Index)
                         .Select(g => g.Select(b => b.Data).ToArray())
                         .ToArray();

            // send INIT request
            var initialContent = new MultipartFormDataContent
            {
                { new StringContent("INIT"), "command" },
                { new StringContent(media.Length.ToString()), "total_bytes" },
                { new StringContent(mimeType), "media_type" }
            };

            if (additionalOwners != null)
            {
                initialContent.Add(new StringContent(additionalOwners.Select(id => id.ToString()).JoinString(",")),
                                   "additional_owners");
            }
            var initialResult =
                await accessor.UploadMediaCoreAsync(initialContent, cancellationToken).ConfigureAwait(false);

            // read initial result and prepare sending content
            var mediaId  = initialResult.Result.MediaId;
            var fileName = System.IO.Path.GetRandomFileName();

            var index    = 0;
            var sentSize = 0;

            // send APPEND request for uploading contents
            foreach (var part in chunks)
            {
                var content = new MultipartFormDataContent
                {
                    { new StringContent("APPEND"), "command" },
                    { new StringContent(mediaId.ToString()), "media_id" },
                    { new ByteArrayContent(part), "media", fileName },
                    { new StringContent(index.ToString()), "segment_index" }
                };
                await UploadCoreAsync(accessor, content, cancellationToken).ConfigureAwait(false);

                sentSize += part.Length;
                sentBytesCallback?.Report(sentSize);
                index++;
            }

            // send FINALIZE
            var finalContent = new MultipartFormDataContent
            {
                { new StringContent("FINALIZE"), "command" },
                { new StringContent(mediaId.ToString()), "media_id" }
            };

            return(await UploadMediaCoreAsync(accessor, finalContent, cancellationToken).ConfigureAwait(false));
        }
 public async Task<PlatformClient> Create(System.Net.CookieContainer cookie,
     int accountIndex, IApiAccessor[] accessors = null,
     CacheDictionary<string, ProfileCache, ProfileData> profileCacheStorage = null,
     CacheDictionary<string, ActivityCache, ActivityData> activityCacheStorage = null)
 {
     var accountPrefix = string.Format("u/{0}/", accountIndex);
     accessors = accessors ?? new IApiAccessor[] { new DefaultAccessor() };
     //accessors内で使えるものを検索
     //G+apiバージョンで降順にしたIApiAccessor配列が用いられることを想定してる
     foreach (var item in accessors)
     {
         var client = new PlatformClient(
             new Uri(PlusBaseUrl, accountPrefix),
             new Uri(TalkBaseUrl, accountPrefix), cookie, item,
             profileCacheStorage ?? new CacheDictionary<string, ProfileCache, ProfileData>(1200, 400, true, dt => new ProfileCache() { Value = dt }),
             activityCacheStorage ?? new CacheDictionary<string, ActivityCache, ActivityData>(1200, 400, true, dt => new ActivityCache() { Value = dt }));
         try
         {
             await client.UpdateHomeInitDataAsync(true);
             return client;
         }
         catch (FailToOperationException)
         { client.Dispose(); }
     }
     throw new FailToOperationException("Create()に失敗。使用できるIApiAccessorがありませんでした。", null);
 }
 public DeleteStatusRequest([NotNull] IApiAccessor accessor, long id, StatusType type)
 {
     Accessor = accessor ?? throw new ArgumentNullException(nameof(accessor));
     Id       = id;
     Type     = type;
 }
 public SentDirectMessagesReceiver([NotNull] IApiAccessor accessor, [NotNull] Action <TwitterStatus> handler,
                                   [CanBeNull] Action <Exception> exceptionHandler, int receiveCount = 100) : base(handler, exceptionHandler)
 {
     _accessor     = accessor ?? throw new ArgumentNullException(nameof(accessor));
     _receiveCount = receiveCount;
 }
Beispiel #30
0
        protected static async Task <IApiResult <IEnumerable <T> > > RetrieveCursoredResult <T>(IApiAccessor accessor,
                                                                                                Func <IApiAccessor, long, Task <IApiResult <ICursorResult <IEnumerable <T> > > > > func,
                                                                                                Action <Exception> exceptionHandler, CancellationToken token)
        {
            var resultList = new List <T>();

            CursorResultExtension.ApiContinuationReader <IEnumerable <T> > reader =
                () => accessor.ReadCursorApi(func, token);
            var lastRateLimit = RateLimitDescription.Empty;

            while (reader != null)
            {
                try
                {
                    var result = await reader().ConfigureAwait(false);

                    resultList.AddRange(result.Item1.Result);
                    lastRateLimit = result.Item1.RateLimit;
                    reader        = result.Item2;
                }
                catch (Exception ex)
                {
                    exceptionHandler(ex);
                    break;
                }
            }
            return(ApiResult.Create(resultList, lastRateLimit));
        }
Beispiel #31
0
 public MutesReceiver([NotNull] IApiAccessor accessor, [NotNull] Action <IEnumerable <long> > handler,
                      [CanBeNull] Action <Exception> exceptionHandler) : base(handler, exceptionHandler)
 {
     _accessor = accessor ?? throw new ArgumentNullException(nameof(accessor));
 }
Beispiel #32
0
 public OwnedListsInfoReceiver([NotNull] IApiAccessor accessor, [NotNull] Action <TwitterList> handler,
                               [CanBeNull] Action <Exception> exceptionHandler) : base(exceptionHandler)
 {
     _accessor = accessor ?? throw new ArgumentNullException(nameof(accessor));
     _handler  = handler ?? throw new ArgumentNullException(nameof(handler));
 }
Beispiel #33
0
 private async Task <IApiResult <TwitterList> > ReceiveListDescription(IApiAccessor accessor,
                                                                       ListParameter parameter)
 {
     return(await accessor.ShowListAsync(parameter, CancellationToken.None));
 }
 public Task<PlatformClient> Build(IApiAccessor[] accessors = null)
 { return PlatformClient.Factory.Create(_cookies, AccountIndex, accessors); }