Ejemplo n.º 1
0
 internal SDataResponse(HttpStatusCode statusCode,
     MediaType? contentType,
     string eTag,
     string location,
     DateTimeOffset? expires,
     DateTimeOffset? retryAfter,
     object content,
     IDictionary<string, string> form,
     IList<AttachedFile> files)
 {
     _statusCode = statusCode;
     _contentType = contentType;
     _eTag = eTag;
     _location = location;
     _expires = expires;
     _retryAfter = retryAfter;
     _content = content;
     _form = form;
     _files = files;
 }
Ejemplo n.º 2
0
 public MediaTypeComboBoxItem(MediaType?mediaType) => data = mediaType;
Ejemplo n.º 3
0
        /// <summary>
        /// 获取用户的时间线
        /// </summary>
        /// <param name="userId">用户Id</param>
        /// <param name="followGroupId"><para>关注用户分组Id</para><remarks>groupId为-1时获取相互关注的用户,为null时获取所有用户</remarks></param>
        /// <param name="applicationId">应用Id</param>
        /// <param name="mediaType"><see cref="MediaType"/></param>
        /// <param name="isOriginalThread">是不是原创主题</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="applicationIds">是否是移动客户端(针对于移动客户端,用来过滤动态)</param>
        ///<returns></returns>
        public PagingDataSet <Activity> GetMyTimeline(long userId, long?followGroupId, int?applicationId, MediaType?mediaType, bool?isOriginalThread, int pageIndex, List <string> applicationIds = null)
        {
            //按tn_Activities的LastModified倒排序
            return(GetPagingEntities(pageSize, pageIndex, CachingExpirationType.ObjectCollection, () =>
            {
                StringBuilder cacheKey = new StringBuilder(RealTimeCacheHelper.GetListCacheKeyPrefix(CacheVersionType.AreaVersion, "UserId", userId));
                cacheKey.Append("MyTimeline::");
                cacheKey.AppendFormat("UserId-{0}:", userId);
                if (followGroupId.HasValue)
                {
                    cacheKey.AppendFormat("FollowGroupId-{0}:", followGroupId.Value);
                }
                if (applicationId.HasValue && applicationId.Value > 0)
                {
                    cacheKey.AppendFormat("ApplicationId-{0}:", applicationId.Value);
                }
                if (mediaType.HasValue)
                {
                    cacheKey.AppendFormat("MediaType-{0}:", (int)mediaType.Value);
                }
                if (isOriginalThread.HasValue)
                {
                    cacheKey.AppendFormat("IsOriginalThread-{0}", isOriginalThread.Value);
                }
                if (applicationIds != null && applicationIds.Count() > 0)
                {
                    cacheKey.AppendFormat("IsMobileClient-{0}", string.Join(",", applicationIds));
                }
                return cacheKey.ToString();
            }, () =>
            {
                Sql sql = Sql.Builder;
                sql.From("tn_Activities")
                .InnerJoin("tn_ActivityUserInbox AUI")
                .On("tn_Activities.ActivityId = AUI.ActivityId")
                .Where("AUI.UserId=@0", userId);

                //done:zhengw,by mazq 相互关注怎么处理的?
                //zhengw回复:已修改
                //mazq回复:相互关注、悄悄关注 followGroupId.Value都是大于0的
                //zhengw回复:已删除判断followGroupId.Value>0
                if (followGroupId.HasValue)
                {
                    //sql.Where("tn_Activities.OwnerType=@0", ActivityOwnerTypes.Instance().User());
                    if (followGroupId.Value == FollowSpecifyGroupIds.Quietly)
                    {
                        sql.Where(@"tn_Activities.OwnerId in ( select FollowedUserId from tn_Follows where IsQuietly = 1 and UserId= @0)", userId);
                    }
                    else if (followGroupId.Value == FollowSpecifyGroupIds.Mutual)
                    {
                        sql.Where(@"tn_Activities.OwnerId in ( select FollowedUserId from tn_Follows where IsMutual = 1 and UserId= @0)", userId);
                    }
                    else if (followGroupId.Value > 0)
                    {
                        sql.Where("tn_Activities.OwnerType=@0", ActivityOwnerTypes.Instance().User())
                        .Where(@"tn_Activities.OwnerId in ( select F.FollowedUserId 
                                            from tn_Follows F inner join tn_ItemsInCategories IIC  on F.Id = IIC.ItemId 
                                            where F.UserId=@0 and IIC.CategoryId=@1 )", userId, followGroupId.Value);
                    }
                }
                if (applicationIds != null && applicationIds.Count() > 0)
                {
                    sql.Where("tn_Activities.ApplicationId in (@applicationIds)", new { applicationIds = applicationIds });
                    //.Where("tn_Activities.ReferenceId=@0", 0);
                }
                if (applicationId.HasValue && applicationId.Value > 0)
                {
                    sql.Where("tn_Activities.ApplicationId=@0", applicationId.Value);
                }
                if (mediaType.HasValue)
                {
                    switch (mediaType)
                    {
                    case MediaType.Audio:
                        sql.Where("tn_Activities.HasMusic=1");
                        break;

                    case MediaType.Image:
                        sql.Where("tn_Activities.HasImage=1");
                        break;

                    case MediaType.Video:
                        sql.Where("tn_Activities.HasVideo=1");
                        break;
                    }
                }
                if (isOriginalThread.HasValue)
                {
                    sql.Where("tn_Activities.IsOriginalThread=@0", isOriginalThread.Value);
                }

                sql.OrderBy("tn_Activities.LastModified desc");
                return sql;
            }));
        }
Ejemplo n.º 4
0
 /// <inheritdoc/>
 public Parameters(KnownSystem?system, MediaType?type, char driveLetter, string filename, int?driveSpeed, Options options)
     : base(system, type, driveLetter, filename, driveSpeed, options)
 {
 }
Ejemplo n.º 5
0
        public void ParametersValidTest(string parameters, char letter, bool isFloppy, MediaType?mediaType, bool expected)
        {
            var env = new DumpEnvironment
            {
                DICParameters = new Parameters(parameters),
                Drive         = isFloppy ? Drive.Floppy(letter) : Drive.Optical(letter, "", true),
                Type          = mediaType,
            };

            bool actual = env.ParametersValid();

            Assert.Equal(expected, actual);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Gets the list model for the specified folder, or the root
        /// folder if to folder id is given.
        /// </summary>
        /// <param name="folderId">The optional folder id</param>
        /// <returns>The list model</returns>
        public async Task <MediaListModel> GetList(Guid?folderId = null, MediaType?filter = null, int?width = null, int?height = null)
        {
            var model = new MediaListModel
            {
                CurrentFolderId = folderId,
                ParentFolderId  = null,
                Structure       = await _api.Media.GetStructureAsync()
            };

            model.RootCount  = model.Structure.MediaCount;
            model.TotalCount = model.Structure.TotalCount;

            if (folderId.HasValue)
            {
                var partial = model.Structure.GetPartial(folderId, true);

                if (partial.FirstOrDefault()?.MediaCount == 0 && partial.FirstOrDefault()?.FolderCount == 0)
                {
                    model.CanDelete = true;
                }
            }

            if (folderId.HasValue)
            {
                var folder = await _api.Media.GetFolderByIdAsync(folderId.Value);

                if (folder != null)
                {
                    model.CurrentFolderName = folder.Name;
                    model.ParentFolderId    = folder.ParentId;
                }
            }

            var holdMedia = (await _api.Media.GetAllByFolderIdAsync(folderId));

            if (filter.HasValue)
            {
                holdMedia = holdMedia
                            .Where(m => m.Type == filter.Value);
            }
            var pairMedia = holdMedia.Select(m => new { media = m, mediaItem = new MediaListModel.MediaItem
                                                        {
                                                            Id           = m.Id,
                                                            FolderId     = m.FolderId,
                                                            Type         = m.Type.ToString(),
                                                            Filename     = m.Filename,
                                                            PublicUrl    = m.PublicUrl.TrimStart('~'), //Will only enumerate the start of the string, probably a faster operation.
                                                            ContentType  = m.ContentType,
                                                            Title        = m.Title,
                                                            AltText      = m.AltText,
                                                            Description  = m.Description,
                                                            Properties   = m.Properties.ToArray().OrderBy(p => p.Key).ToList(),
                                                            Size         = Utils.FormatByteSize(m.Size),
                                                            Width        = m.Width,
                                                            Height       = m.Height,
                                                            LastModified = m.LastModified.ToString("yyyy-MM-dd")
                                                        } }).ToArray();

            model.Folders = model.Structure.GetPartial(folderId)
                            .Select(f => new MediaListModel.FolderItem
            {
                Id   = f.Id,
                Name = f.Name
            }).ToList();

            if (width.HasValue)
            {
                foreach (var mp in pairMedia.Where(m => m.media.Type == MediaType.Image))
                {
                    if (mp.media.Versions.Any(v => v.Width == width && v.Height == height))
                    {
                        mp.mediaItem.AltVersionUrl =
                            (await _api.Media.EnsureVersionAsync(mp.media, width.Value, height).ConfigureAwait(false))
                            .TrimStart('~');
                    }
                }
            }

            model.Media    = pairMedia.Select(m => m.mediaItem).ToList();
            model.ViewMode = model.Media.Count(m => m.Type == "Image") > model.Media.Count / 2 ? MediaListModel.GalleryView : MediaListModel.ListView;

            return(model);
        }
Ejemplo n.º 7
0
 public void ExtractOutputInformation(KnownSystem?knownSystem, MediaType?mediaType)
 {
     // TODO: Implement
     // TODO: Get sample output data for each of the major types
     Assert.True(true);
 }
Ejemplo n.º 8
0
 /// <summary>
 /// 获取拥有者的动态
 /// </summary>
 /// <param name="ownerType">动态拥有者类型</param>
 /// <param name="ownerId">动态拥有者Id</param>
 /// <param name="applicationId">应用Id</param>
 /// <param name="mediaType">媒体类型</param>
 /// <param name="isOriginalThread">是否原创</param>
 /// <param name="pageIndex">页码</param>
 /// <param name="userId">用户Id</param>
 ///<returns></returns>
 public PagingDataSet <Activity> GetOwnerActivities(int ownerType, long ownerId, int?applicationId, MediaType?mediaType, bool?isOriginalThread, bool?isPrivate, int pageIndex, long?userId = null)
 {
     //按tn_Activities的LastModified倒排序,仅获取IsPrivate=false的动态
     return(activityRepository.GetOwnerActivities(ownerType, ownerId, applicationId, mediaType, isOriginalThread, isPrivate, pageIndex, userId));
 }
Ejemplo n.º 9
0
 public async Task <Dictionary <string, Stats> > GetStatsAsync(MediaType?mediaType = null)
 {
     return((await client.InvokeAsync(this, "getStats", new { mediaType })).GetValue <Dictionary <string, Stats> >());
 }
Ejemplo n.º 10
0
 public async Task DisconnectAsync(MediaElement sink, MediaType?mediaType = null, string sourceMediaDescription = "", string sinkMediaDescription = "")
 {
     await client.InvokeAsync(this, "disconnect", new { sink, mediaType, sourceMediaDescription, sinkMediaDescription });
 }
Ejemplo n.º 11
0
 public async Task <ElementConnectionData[]> GetSinkConnectionsAsync(MediaType?mediaType = null, string description = "")
 {
     return((await client.InvokeAsync(this, "getSinkConnections", new { mediaType, description })).GetValue <ElementConnectionData[]>());
 }
Ejemplo n.º 12
0
        public void DriveSpeedSupportedTest(MediaType?mediaType, bool expected)
        {
            bool actual = mediaType.DoesSupportDriveSpeed();

            Assert.Equal(expected, actual);
        }
Ejemplo n.º 13
0
        public void ExtensionTest(MediaType?mediaType, string expected)
        {
            string actual = mediaType.Extension();

            Assert.Equal(expected, actual);
        }
Ejemplo n.º 14
0
 /// <summary>
 /// Get the default extension for a given disc type
 /// </summary>
 /// <param name="type">MediaType value to check</param>
 /// <returns>Valid extension (with leading '.'), null on error</returns>
 public static string Extension(MediaType?type)
 {
     // Aaru has a single, unified output format by default
     return(".aaruf");
 }
 public BlackMarkSensingPreset(int printWidth, int blackMarkOffset, PrintMode?printMode, MediaType?mediaType)
 {
     PrintWidth      = printWidth;
     BlackMarkOffset = blackMarkOffset;
     PrintMode       = printMode;
     MediaType       = mediaType;
 }
        internal SDataResponse(WebResponse response, string redirectLocation)
        {
            var httpResponse = response as HttpWebResponse;
            _statusCode = httpResponse != null ? httpResponse.StatusCode : 0;

            MediaType contentType;
            if (MediaTypeNames.TryGetMediaType(response.ContentType, out contentType))
            {
                _contentType = contentType;
            }

            _eTag = response.Headers[HttpResponseHeader.ETag];
            _location = response.Headers[HttpResponseHeader.Location] ?? redirectLocation;

            if (_statusCode != HttpStatusCode.NoContent && _contentType != null)
            {
                using (var stream = response.GetResponseStream())
                {
                    _content = LoadContent(stream, contentType);
                }
            }
        }
Ejemplo n.º 17
0
        internal SDataResponse(WebResponse response, string redirectLocation)
        {
            var httpResponse = response as HttpWebResponse;
            _statusCode = httpResponse != null ? httpResponse.StatusCode : 0;

            MediaType contentType;
            if (MediaTypeNames.TryGetMediaType(response.ContentType, out contentType))
            {
                _contentType = contentType;
            }

            _eTag = response.Headers["ETag"];
            _location = response.Headers["Location"] ?? redirectLocation;

            var header = response.Headers["Expires"];
            DateTimeOffset date;
            if (DateTimeOffset.TryParse(header, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out date))
            {
                _expires = date;
            }

            header = response.Headers["Retry-After"];
            int num;
            if (DateTimeOffset.TryParse(header, CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal, out date))
            {
                _retryAfter = date;
            }
            else if (int.TryParse(header, NumberStyles.Any, CultureInfo.InvariantCulture, out num))
            {
                _retryAfter = DateTimeOffset.UtcNow.AddSeconds(num);
            }

            _form = new Dictionary<string, string>();
            _files = new List<AttachedFile>();

            if (_statusCode != HttpStatusCode.NoContent)
            {
                using (var responseStream = response.GetResponseStream())
                {
                    string boundary;

                    if (_contentType == MediaType.Multipart && TryGetMultipartBoundary(response.ContentType, out boundary))
                    {
                        var multipart = MimeMessage.Parse(responseStream, boundary);
                        var isFormData = string.Equals(new ContentType(response.ContentType).SubType, "form-data", StringComparison.OrdinalIgnoreCase);

                        foreach (var part in multipart)
                        {
                            if (_content == null && MediaTypeNames.TryGetMediaType(part.ContentType, out contentType))
                            {
                                _contentType = contentType;
                                _content = LoadContent(part.Content, _contentType.Value);
                            }
                            else
                            {
                                if (isFormData)
                                {
                                    var name = ContentDisposition.Parse(part.ContentDisposition)["name"];
                                    if (name != null)
                                    {
                                        var value = new StreamReader(part.Content).ReadToEnd();
                                        _form.Add(name, value);
                                        continue;
                                    }
                                }

                                _files.Add(new AttachedFile(part));
                            }
                        }
                    }
                    else
                    {
                        _content = LoadContent(responseStream, _contentType);

                        if (_statusCode == HttpStatusCode.Accepted)
                        {
                            var tracking = ContentHelper.Deserialize<Tracking>(_content);
                            if (tracking != null)
                            {
                                _content = tracking;
                            }
                        }
                        else if (_statusCode >= HttpStatusCode.BadRequest)
                        {
                            if (ContentHelper.IsDictionary(_content))
                            {
                                var diagnosis = ContentHelper.Deserialize<Diagnosis>(_content);
                                if (diagnosis != null)
                                {
                                    throw new SDataException(new Diagnoses {diagnosis}, _statusCode);
                                }
                            }
                            else if (ContentHelper.IsCollection(_content))
                            {
                                var diagnoses = ContentHelper.Deserialize<Diagnoses>(_content);
                                if (diagnoses != null)
                                {
                                    throw new SDataException(diagnoses, _statusCode);
                                }
                            }
                        }
                    }
                }
            }
        }
Ejemplo n.º 18
0
 public static string ShortName(this MediaType?type)
 {
     return(Converters.MediaTypeToShortString(type));
 }
Ejemplo n.º 19
0
        /// <summary>
        /// Gets the list model for the specified folder, or the root
        /// folder if to folder id is given.
        /// </summary>
        /// <param name="folderId">The optional folder id</param>
        /// <returns>The list model</returns>
        public async Task <MediaListModel> GetList(Guid?folderId = null, MediaType?filter = null)
        {
            var model = new MediaListModel
            {
                CurrentFolderId = folderId,
                ParentFolderId  = null
            };

            if (folderId.HasValue)
            {
                var folder = await _api.Media.GetFolderByIdAsync(folderId.Value);

                if (folder != null)
                {
                    model.ParentFolderId = folder.ParentId;
                }
            }

            model.Media = (await _api.Media.GetAllAsync(folderId))
                          .Select(m => new MediaListModel.MediaItem
            {
                Id           = m.Id,
                FolderId     = m.FolderId,
                Type         = m.Type.ToString(),
                Filename     = m.Filename,
                PublicUrl    = m.PublicUrl.Replace("~", ""),
                ContentType  = m.ContentType,
                Size         = Utils.FormatByteSize(m.Size),
                Width        = m.Width,
                Height       = m.Height,
                LastModified = m.LastModified.ToString("yyyy-MM-dd")
            }).ToList();

            if (filter.HasValue)
            {
                model.Media = model.Media
                              .Where(m => m.Type == filter.Value.ToString())
                              .ToList();
            }

            if (model.Media.Where(m => m.Type == "Image").Count() > model.Media.Count / 2)
            {
                model.ViewMode = MediaListModel.GalleryView;
            }
            else
            {
                model.ViewMode = MediaListModel.ListView;
            }

            var structure = await _api.Media.GetStructureAsync();

            model.Folders = structure.GetPartial(folderId)
                            .Select(f => new MediaListModel.FolderItem
            {
                Id   = f.Id,
                Name = f.Name
            }).ToList();

            foreach (var folder in model.Folders)
            {
                //
                // TODO: Optimize, we don't need all this data
                //
                folder.ItemCount = (await _api.Media.GetAllAsync(folder.Id)).Count() + structure.GetPartial(folder.Id).Count();
            }
            return(model);
        }
Ejemplo n.º 20
0
 public static string Extension(this MediaType?type)
 {
     return(Converters.MediaTypeToExtension(type));
 }
Ejemplo n.º 21
0
 public void FoundAllFilesTest(MediaType?mediaType)
 {
     // TODO: Implement
     // TODO: Get sample output data for each of the major types
     Assert.True(true);
 }
Ejemplo n.º 22
0
        private IRestResponse <T[]> Browse <T>(
            string seriesType,
            int?year                           = null,
            Season?season                      = null,
            MediaType?type                     = null,
            AnimeStatus?status                 = null,
            IEnumerable <Genre> genres         = null,
            IEnumerable <Genre> excludedGenres = null,
            SortingMethod?sortingMethod        = null,
            bool?airingData                    = null,
            bool?fullPage                      = null,
            int?page                           = null)
        {
            var request        = MakeRequest($"browse/{seriesType}", Method.GET);
            var genreConverter = new GenreMapper();

            if (year != null)
            {
                request.AddParameter("year", year);
            }
            if (season != null)
            {
                request.AddParameter("season", new SeasonMapper().T2ToT1((Season)season));
            }
            if (type != null)
            {
                request.AddParameter("type", type);
            }
            if (status != null)
            {
                request.AddParameter("status", status);
            }
            if (genres != null)
            {
                var genresArray = genres as Genre[] ?? genres.ToArray();
                if (genresArray.Any())
                {
                    request.AddParameter("genres", string.Join(",", genresArray.Select(genre => genreConverter.T2ToT1(genre))));
                }
            }
            if (excludedGenres != null)
            {
                var genresArray = excludedGenres as Genre[] ?? excludedGenres.ToArray();
                if (genresArray.Any())
                {
                    request.AddParameter("genres_exclude", string.Join(",", genresArray.Select(genre => genreConverter.T2ToT1(genre))));
                }
            }
            if (sortingMethod != null)
            {
                request.AddParameter("sort", new SortMapper().T2ToT1((SortingMethod)sortingMethod));
            }
            if (airingData != null)
            {
                request.AddParameter("airing_data", airingData);
            }
            if (fullPage != null)
            {
                request.AddParameter("full_page", fullPage);
            }
            if (page != null)
            {
                request.AddParameter("page", page);
            }

            return(Execute <T[]>(request));
        }
Ejemplo n.º 23
0
        public void GetValidMediaTypesTest(KnownSystem?knownSystem, MediaType?expected)
        {
            var actual = Validators.GetValidMediaTypes(knownSystem);

            Assert.Contains(expected, actual);
        }
Ejemplo n.º 24
0
        public void ParametersFromSystemAndTypeTest(KnownSystem?knownSystem, MediaType?mediaType, DICCommand expected)
        {
            Parameters actual = new Parameters(knownSystem, mediaType, 'D', "disc.bin", 16, true, -1);

            Assert.Equal(expected, actual.Command);
        }
Ejemplo n.º 25
0
 public async Task <MediaListModel> List(Guid?folderId = null, [FromQuery] MediaType?filter = null, [FromQuery] int?width = null, [FromQuery] int?height = null)
 {
     return(await _service.GetList(folderId, filter, width, height));
 }
Ejemplo n.º 26
0
 public async Task <MediaListModel> List(Guid?folderId = null, MediaType?filter = null)
 {
     return(await _service.GetList(folderId, filter));
 }
Ejemplo n.º 27
0
 /// <inheritdoc/>
 public override string GetDefaultExtension(MediaType?mediaType) => Converters.Extension(mediaType);
Ejemplo n.º 28
0
        /// <summary>
        /// 附件列表
        /// </summary>
        public ActionResult _ListContentAttachments(string keyword = null, DateTime?startDate = null, DateTime?endDate = null, MediaType?mediaType = null, int pageIndex = 1)
        {
            IUser user = UserContext.CurrentUser;

            if (user == null)
            {
                return(new EmptyResult());
            }

            long?userId = null;

            if (!authorizer.IsAdministrator(CmsConfig.Instance().ApplicationId))
            {
                userId = user.UserId;
            }
            keyword = WebUtility.UrlDecode(keyword);
            PagingDataSet <ContentAttachment> attachments = new ContentAttachmentService().Gets(userId, keyword, startDate, endDate, mediaType, 12, pageIndex);

            return(View(attachments));
        }
Ejemplo n.º 29
0
        /// <summary>
        /// 获取拥有者的动态
        /// </summary>
        /// <param name="ownerType">动态拥有者类型</param>
        /// <param name="ownerId">动态拥有者Id</param>
        /// <param name="applicationId">应用Id</param>
        /// <param name="mediaType">媒体类型</param>
        /// <param name="isOriginalThread">是否原创</param>
        /// <param name="pageIndex">页码</param>
        /// <param name="userId">用户Id</param>
        /// <param name="isMobileClient">是否是移动客户端(针对于移动客户端,用来过滤动态)</param>
        ///<returns></returns>
        public PagingDataSet <Activity> GetOwnerActivities(int ownerType, long ownerId, int?applicationId, MediaType?mediaType, bool?isOriginalThread, bool?isPrivate, int pageIndex, long?userId, bool?isMobileClient = null)
        {
            //按tn_Activities的LastModified倒排序,仅获取IsPrivate=false的动态
            //使用GetPagingEntities
            return(GetPagingEntities(pageSize, pageIndex, CachingExpirationType.ObjectCollection, () =>
            {
                StringBuilder cacheKey = new StringBuilder(RealTimeCacheHelper.GetListCacheKeyPrefix(CacheVersionType.AreaVersion, "OwnerId", ownerId));
                cacheKey.Append("OwnerActivities::");
                cacheKey.AppendFormat("OwnerType-{0}", ownerType);
                if (applicationId.HasValue && applicationId.Value > 0)
                {
                    cacheKey.AppendFormat("ApplicationId-{0}", applicationId);
                }
                if (isPrivate.HasValue)
                {
                    cacheKey.AppendFormat("IsPrivate-{0}", isPrivate.Value);
                }
                if (mediaType.HasValue)
                {
                    cacheKey.AppendFormat("MediaType-{0}", (int)mediaType.Value);
                }
                if (isOriginalThread.HasValue)
                {
                    cacheKey.AppendFormat("IsOriginalThread-{0}", isOriginalThread.Value);
                }
                if (userId.HasValue)
                {
                    cacheKey.AppendFormat("UserId-{0}", userId.Value);
                }
                if (isMobileClient.HasValue)
                {
                    cacheKey.AppendFormat("IsMobileClient-{0}", isMobileClient.Value);
                }
                return cacheKey.ToString();
            }, () =>
            {
                Sql sql = Sql.Builder;
                sql.Select("ActivityId")
                .From("tn_Activities")
                .Where("OwnerId=@0", ownerId)
                .Where("OwnerType=@0", ownerType);

                if (isPrivate.HasValue)
                {
                    sql.Where("IsPrivate=@0", isPrivate);
                }
                if (userId.HasValue)
                {
                    sql.Where("UserId=@0", userId);
                }
                if (isMobileClient.HasValue && isMobileClient.Value)
                {
                    sql.Where("tn_Activities.ApplicationId in (@0,@1,@2,@3)", 1001, 1002, 1003, 1012)
                    .Where("tn_Activities.ReferenceId=@0", 0);
                }
                if (applicationId.HasValue)
                {
                    sql.Where("ApplicationId=@0", applicationId);
                }
                if (mediaType.HasValue)
                {
                    switch (mediaType)
                    {
                    case MediaType.Audio:
                        sql.Where("HasMusic=1");
                        break;

                    case MediaType.Image:
                        sql.Where("HasImage=1");
                        break;

                    case MediaType.Video:
                        sql.Where("HasVideo=1");
                        break;
                    }
                }

                if (isOriginalThread.HasValue)
                {
                    sql.Where("IsOriginalThread=@0", isOriginalThread);
                }

                sql.OrderBy("LastModified desc");
                return sql;
            }));
        }
Ejemplo n.º 30
0
        [InlineData(null, 72)]                // TODO: Update when fully determined
        public void GetAllowedDriveSpeedForMediaTypeTest(MediaType?mediaType, int maxExpected)
        {
            var actual = Constants.GetSpeedsForMediaType(mediaType);

            Assert.Equal(maxExpected, actual.Last());
        }
Ejemplo n.º 31
0
        private SDataRequest CreateBatchRequest(ICollection <SDataParameters> items)
        {
            Guard.ArgumentNotNull(items, "items");

            var       resources     = new SDataCollection <SDataResource>(items.Count);
            string    path          = null;
            MediaType?contentType   = null;
            var       include       = new List <string>();
            var       select        = new List <string>();
            int?      precedence    = null;
            MediaType?format        = null;
            string    language      = null;
            string    version       = null;
            var       accept        = new List <MediaType>();
            var       form          = new Dictionary <string, string>();
            var       files         = new List <AttachedFile>();
            var       extensionArgs = new Dictionary <string, string>();

            foreach (var parms in items)
            {
                if (parms.StartIndex != null)
                {
                    throw new NotSupportedException("StartIndex not supported in batch requests");
                }
                if (parms.Count != null)
                {
                    throw new NotSupportedException("Count not supported in batch requests");
                }
                if (parms.Where != null)
                {
                    throw new NotSupportedException("Where not supported in batch requests");
                }
                if (parms.OrderBy != null)
                {
                    throw new NotSupportedException("OrderBy not supported in batch requests");
                }
                if (parms.Search != null)
                {
                    throw new NotSupportedException("Search not supported in batch requests");
                }
                if (parms.TrackingId != null)
                {
                    throw new NotSupportedException("TrackingId not supported in batch requests");
                }
                if (parms.IncludeSchema != null)
                {
                    throw new NotSupportedException("IncludeSchema not supported in batch requests");
                }
                if (parms.ReturnDelta != null)
                {
                    throw new NotSupportedException("ReturnDelta not supported in batch requests");
                }
                if (parms.Path != path)
                {
                    if (path != null)
                    {
                        throw new SDataClientException("All non-null path values must be the same");
                    }
                    path = parms.Path;
                }
                if (parms.ContentType != contentType)
                {
                    if (contentType != null)
                    {
                        throw new SDataClientException("All non-null content type values must be the same");
                    }
                    contentType = parms.ContentType;
                }
                if (parms.Include != null)
                {
                    include.AddRange(parms.Include.Split(','));
                }
                if (parms.Select != null)
                {
                    select.AddRange(parms.Select.Split(','));
                }
                if (parms.Precedence != null && parms.Precedence != precedence)
                {
                    precedence = Math.Max(precedence ?? 0, parms.Precedence.Value);
                }
                if (parms.Format != format)
                {
                    if (format != null)
                    {
                        throw new SDataClientException("All non-null format values must be the same");
                    }
                    format = parms.Format;
                }
                if (parms.Language != language)
                {
                    if (language != null)
                    {
                        throw new SDataClientException("All non-null language values must be the same");
                    }
                    language = parms.Language;
                }
                if (parms.Version != version)
                {
                    if (version != null)
                    {
                        throw new SDataClientException("All non-null version values must be the same");
                    }
                    version = parms.Version;
                }
                if (parms.Accept != null)
                {
                    accept.AddRange(parms.Accept);
                }
                foreach (var data in parms.Form)
                {
                    form.Add(data.Key, data.Value);
                }
                files.AddRange(parms.Files);
                foreach (var arg in parms.ExtensionArgs)
                {
                    extensionArgs[arg.Key] = arg.Value;
                }

                SDataResource resource;
                if (parms.Content == null)
                {
                    resource = new SDataResource();
                }
                else
                {
                    var content = parms.Content;
                    if (parms.Method == HttpMethod.Put && DifferentialUpdate)
                    {
                        var tracking = content as IChangeTracking;
                        if (tracking != null)
                        {
                            content = tracking.GetChanges();
                            if (content == null)
                            {
                                throw new SDataClientException("Content doesn't have any changes");
                            }
                        }
                    }

                    resource = ContentHelper.Serialize(content, NamingScheme) as SDataResource;
                    if (resource == null)
                    {
                        throw new SDataClientException("Only resources can be submitted in batch requests");
                    }
                }

                resource.HttpMethod = parms.Method;
                if (parms.Method != HttpMethod.Post)
                {
                    if (resource.Key == null)
                    {
                        throw new SDataClientException("A selector must be specified for GET, PUT and DELETE batch requests");
                    }

                    var itemUri = new SDataUri(Uri)
                    {
                        Include    = parms.Include,
                        Select     = parms.Select,
                        Precedence = parms.Precedence
                    };
                    if (path != null)
                    {
                        itemUri.AppendPath(path);
                    }
                    itemUri.LastPathSegment.Selector = SDataUri.FormatConstant(resource.Key);
                    resource.Id  = itemUri.AbsoluteUri;
                    resource.Url = itemUri.Uri;
                }

                if (parms.ETag != null)
                {
                    resource.IfMatch = parms.ETag;
                }

                resources.Add(resource);
            }

            var uri = new SDataUri(Uri)
            {
                Precedence = precedence,
                Format     = format ?? Format,
                Language   = language ?? Language,
                Version    = version ?? Version
            };

            if (path != null)
            {
                uri.AppendPath(path);
            }
            uri.AppendPath("$batch");
            if (include.Count > 0)
            {
                uri.Include = string.Join(",", include.Distinct().ToArray());
            }
            if (select.Count > 0)
            {
                uri.Select = string.Join(",", select.Distinct().ToArray());
            }
            foreach (var arg in extensionArgs)
            {
                uri["_" + arg.Key] = arg.Value;
            }

            var request = CreateRequest(uri, HttpMethod.Post, resources);

            request.ContentType = contentType ?? Format;

            if (accept.Count > 0)
            {
                request.Accept = accept.Distinct().ToArray();
            }
            foreach (var data in form)
            {
                request.Form.Add(data.Key, data.Value);
            }
            foreach (var file in files)
            {
                request.Files.Add(file);
            }
            if (language != null)
            {
                request.AcceptLanguage = language ?? Language;
            }

            TraceRequest(request);
            return(request);
        }
Ejemplo n.º 32
0
        /// <summary>
        /// Process the current custom parameters back into UI values
        /// </summary>
        private void ProcessCustomParameters()
        {
            Env.SetParameters(ParametersTextBox.Text);
            if (Env.Parameters == null)
            {
                return;
            }

            int driveIndex = Drives.Select(d => d.Letter).ToList().IndexOf(Env.Parameters.InputPath[0]);

            if (driveIndex > -1)
            {
                DriveLetterComboBox.SelectedIndex = driveIndex;
            }

            int driveSpeed = Env.Parameters.Speed ?? -1;

            if (driveSpeed > 0)
            {
                DriveSpeedComboBox.SelectedValue = driveSpeed;
            }
            else
            {
                Env.Parameters.Speed = DriveSpeedComboBox.SelectedValue as int?;
            }

            // Disable automatic reprocessing of the textboxes until we're done
            RemovePathEventHandlers();

            // Save the current cursor positions
            int outputDirectorySelectionStart = OutputDirectoryTextBox.SelectionStart;
            int outputFilenameSelectionStart  = OutputFilenameTextBox.SelectionStart;

            string trimmedPath     = Env.Parameters.OutputPath?.Trim('"') ?? string.Empty;
            string outputDirectory = Path.GetDirectoryName(trimmedPath);
            string outputFilename  = Path.GetFileName(trimmedPath);

            (outputDirectory, outputFilename) = DumpEnvironment.NormalizeOutputPaths(outputDirectory, outputFilename, Options.InternalProgram == InternalProgram.DiscImageCreator);
            if (!string.IsNullOrWhiteSpace(outputDirectory))
            {
                OutputDirectoryTextBox.Text = outputDirectory;
            }
            else
            {
                outputDirectory = OutputDirectoryTextBox.Text;
            }
            if (!string.IsNullOrWhiteSpace(outputFilename))
            {
                OutputFilenameTextBox.Text = outputFilename;
            }
            else
            {
                outputFilename = OutputFilenameTextBox.Text;
            }

            // Set the cursor position back to where it was
            OutputDirectoryTextBox.SelectionStart  = outputDirectorySelectionStart;
            OutputDirectoryTextBox.SelectionLength = 0;
            OutputFilenameTextBox.SelectionStart   = outputFilenameSelectionStart;
            OutputFilenameTextBox.SelectionLength  = 0;

            // Re-enable automatic reprocessing of textboxes
            AddPathEventHandlers();

            MediaType?mediaType      = Env.Parameters.GetMediaType();
            int       mediaTypeIndex = MediaTypes.FindIndex(m => m == mediaType);

            if (mediaTypeIndex > -1)
            {
                MediaTypeComboBox.SelectedIndex = mediaTypeIndex;
            }
        }
        internal SDataResponse(WebResponse response, string redirectLocation)
        {
            var httpResponse = response as HttpWebResponse;
            _statusCode = httpResponse != null ? httpResponse.StatusCode : 0;

            MediaType contentType;
            if (MediaTypeNames.TryGetMediaType(response.ContentType, out contentType))
            {
                _contentType = contentType;
            }

            _eTag = response.Headers[HttpResponseHeader.ETag];
            _location = response.Headers[HttpResponseHeader.Location] ?? redirectLocation;
            _files = new List<AttachedFile>();

            if (_statusCode != HttpStatusCode.NoContent)
            {
                using (var responseStream = response.GetResponseStream())
                {
                    string boundary;

                    if (_contentType == MediaType.Multipart && TryGetMultipartBoundary(response.ContentType, out boundary))
                    {
                        var multipart = MimeMessage.Parse(responseStream, boundary);

                        foreach (var part in multipart)
                        {
                            if (_content == null && MediaTypeNames.TryGetMediaType(part.ContentType, out contentType))
                            {
                                _contentType = contentType;
                                _content = LoadContent(part.Content, null, _contentType.Value);
                            }
                            else
                            {
                                _files.Add(new AttachedFile(part));
                            }
                        }
                    }
                    else
                    {
                        _content = LoadContent(responseStream, _statusCode, _contentType);
                    }
                }
            }
        }
Ejemplo n.º 34
0
 /// <summary>
 /// 获取用户的时间线
 /// </summary>
 /// <param name="userId">用户Id</param>
 /// <param name="followGroupId"><para>关注用户分组Id</para><remarks>groupId为-1时获取相互关注的用户,为null时获取所有用户</remarks></param>
 /// <param name="applicationId">应用Id</param>
 /// <param name="mediaType"><see cref="MediaType"/></param>
 /// <param name="isOriginalThread">是不是原创主题</param>
 /// <param name="pageIndex">页码</param>
 ///<returns></returns>
 public PagingDataSet <Activity> GetMyTimeline(long userId, long?followGroupId, int?applicationId, MediaType?mediaType, bool?isOriginalThread, int pageIndex)
 {
     return(activityRepository.GetMyTimeline(userId, followGroupId, applicationId, mediaType, isOriginalThread, pageIndex));
 }