Пример #1
0
        public async Task FindPhotosAsync_TwoLevelDirectory_SingleFile_JpegFormatAsync()
        {
            // Create deeper directory structure
            var tempDirectory = PathHelper.GetTemporaryDirectory();
            var newDirectory  = Path.Combine(tempDirectory, Path.GetRandomFileName());

            Directory.CreateDirectory(newDirectory);

            // Find expected path from the file creation
            var tempFileName = PathHelper.CreateImageFile(newDirectory, ImageFormat.Jpeg);
            var expectedPath = Path.Combine(newDirectory, tempFileName);

            // Find actual path
            var photoList = new List <Photo>();

            await foreach (var p in PhotoHandler.FindPhotosAsync(tempDirectory))
            {
                photoList.Add(p);
            }

            var photo      = photoList.FirstOrDefault();
            var actualPath = photo.FilePath;

            // Assert the two paths are equal
            Assert.Equal(expectedPath, actualPath);
        }
Пример #2
0
        static void Main(string[] args)
        {
            System.Console.WriteLine("Using Custome Delegates: ");
            Photo photo = new Photo()
            {
                Name = "Sai.jpg"
            };
            PhotoHandler photohand = new PhotoHandler();

            PhotoProcessor.PhotoEventHandler photoehand = photohand.loadPhoto;
            photoehand += photohand.enhancePhoto;

            PhotoProcessor pp = new PhotoProcessor();

            pp.Process(photo, photoehand);

            System.Console.WriteLine("Using Action Delegates: ");
            System.Action <Photo> actionhand = photohand.loadPhoto;
            actionhand += photohand.enhancePhoto;

            pp = new PhotoProcessor();
            pp.Process(photo, actionhand);

            System.Console.ReadLine();
        }
Пример #3
0
        public async Task FindPhotosAsync_FlatDirectory_MultipleFiles_JpegFormatAsync()
        {
            var tempDirectory = PathHelper.GetTemporaryDirectory();

            // Creates the expected paths set from the file creation
            var expectedPaths = new HashSet <string>();

            for (var i = 0; i < 10; i++)
            {
                var path = Path.Combine(tempDirectory, PathHelper.CreateImageFile(tempDirectory, ImageFormat.Jpeg));
                expectedPaths.Add(path);
            }

            // Creates set containing the actual paths
            var photoList = new List <Photo>();

            await foreach (var p in PhotoHandler.FindPhotosAsync(tempDirectory))
            {
                photoList.Add(p);
            }

            var actualPaths = new HashSet <string>();

            foreach (var photo in photoList)
            {
                actualPaths.Add(photo.FilePath);
            }

            // Assert the two sets are equal
            Assert.Subset(expectedPaths, actualPaths);
            Assert.Superset(expectedPaths, actualPaths);
        }
Пример #4
0
        private void ListBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (listBox.SelectedItem != null)
            {
                string text = (string)listBox.SelectedItem;

                TextName.Text = text;
                Contact selectedItem = getContactByUsername(text);
                if (selectedItem.Photo != null)
                {
                    imageProfile.Source = PhotoHandler.ToImage(selectedItem.Photo);
                }
                else
                {
                    imageProfile.Source = new BitmapImage(new Uri(AppDomain.CurrentDomain.BaseDirectory + @"../../Img/user.png"));
                }
                if (selectedItem != null)
                {
                    if (selectedItem.IsFavourite)
                    {
                        favourite.Content = "Remove from favourites";
                    }
                    else
                    {
                        favourite.Content = "Mark as favourite";
                    }
                }

                ButtonSet(true, false, false);
            }
            else
            {
                ButtonSet(false, false, false);
            }
        }
Пример #5
0
    private void InitInstance()
    {
        bool isAlone = !(Instance != null && Instance != this);

        Assert.IsTrue(isAlone);

        Instance = this;
    }
Пример #6
0
        public async Task FindPhotosAsync_InvalidPathAsync()
        {
            var path      = @"BlahBlahBuh";
            var photoList = new List <Photo>();

            await foreach (var photo in PhotoHandler.FindPhotosAsync(path))
            {
                photoList.Add(photo);
            }

            Assert.Empty(photoList);
        }
Пример #7
0
        /// <summary>
        /// Runs the organizer by recursively searching every directory from the given <paramref name="inputDirectory" />.
        /// </summary>
        /// <param name="inputDirectory">Path to initial directory to search for media files.</param>
        /// <param name="database">Indicates whether a database is used.</param>
        public async Task RunOrganizerAsync(string inputDirectory)
        {
            // if input directory does not exist, throw exception and end run
            inputDirectory.EnsureDirectoryExists();

            // preliminary setup
            var hashAlgorithm = _configuration.GetValue <Algorithm>("hash-algorithm");
            var checksum      = new Checksum(hashAlgorithm);

            var photoCounter = 0;

            if (!(_context is null))
            {
                await _context.Database.EnsureCreatedAsync();
            }

            _logger.LogInformation($"Begin organizing in { inputDirectory }");

            await foreach (var photo in PhotoHandler.FindPhotosAsync(inputDirectory))
            {
                using var fs = File.OpenRead(photo.FilePath);

                // Compute checksum
                photo.Checksum = checksum.ComputeChecksum(fs);

                // Reset filestream position
                fs.Position = 0;

                // Fetch metadata directories using MetadataExctractor and parse metadata to the Photo object
                var metadataDirectories = ImageMetadataReader.ReadMetadata(fs);
                ParseMetadata.Parse(photo, metadataDirectories);

                // Rename and sort photos
                _sortService.SortPhoto(photo);

                // Add photo to database context if it does not exist already
                if (!(_context is null) && !await _context.Photos.AnyAsync(p => p.Name == photo.Name))
                {
                    await _context.Photos.AddAsync(photo);
                }

                photoCounter++;
            }

            if (!(_context is null))
            {
                // Save all additions to the database
                await _context.SaveChangesAsync();
            }

            _logger.LogInformation($"End organizing. Organized { photoCounter } photos.");
        }
Пример #8
0
 public Logic(TokenMagic tokenMagic, VkApi vkApi, VkApiUtils vkApiUtils, BackgroundDownloader downloader, FilesystemTools filesystemTools, DownloadQueueProvider queueProvider, WallHandler wallHandler, AudioHandler audioHandler, PhotoHandler photoHandler, IOptionsSnapshot <Settings> settings)
 {
     this.settings        = settings.Value;
     this.tokenMagic      = tokenMagic;
     this.vkApi           = vkApi;
     this.vkApiUtils      = vkApiUtils;
     this.downloader      = downloader;
     this.filesystemTools = filesystemTools;
     this.queueProvider   = queueProvider;
     this.wallHandler     = wallHandler;
     this.audioHandler    = audioHandler;
     this.photoHandler    = photoHandler;
 }
Пример #9
0
        public async Task FindPhotosAsync_MultiLevelDirectory_MultipleFiles_JpegFormatAsync()
        {
            // Create temporary directory
            var tempDirectory = PathHelper.GetTemporaryDirectory();

            // Find expected paths when creating files
            var expectedPaths = new HashSet <string>();

            for (var i = 0; i < 10; i++)
            {
                // Creates list of directories used for creating path with max depth
                var directoryList = new List <string> {
                    tempDirectory
                };
                var rand = new Random().Next(0, MAXDEPTH);
                for (var k = 0; k < rand; k++)
                {
                    directoryList.Add(Path.GetRandomFileName());
                }

                // Combine the directory list and create path
                var tempPath = Path.Combine(directoryList.ToArray());
                Directory.CreateDirectory(tempPath);

                // Create file inside the generated directory
                var tempFileName = PathHelper.CreateImageFile(tempPath, ImageFormat.Jpeg);

                // Adds path to expectedPaths
                var expectedPath = Path.Combine(tempPath, tempFileName);
                expectedPaths.Add(expectedPath);
            }

            // Find actual paths
            var photoList = new List <Photo>();

            await foreach (var p in PhotoHandler.FindPhotosAsync(tempDirectory))
            {
                photoList.Add(p);
            }

            var actualPaths = new HashSet <string>();

            foreach (var photo in photoList)
            {
                actualPaths.Add(photo.FilePath);
            }

            // Assert the two sets are equal
            Assert.Subset(expectedPaths, actualPaths);
            Assert.Superset(expectedPaths, actualPaths);
        }
Пример #10
0
        public async Task FindPhotosAsync_FlatDirectory_SingleFile_UnknownFormatAsync()
        {
            var tempDirectory = PathHelper.GetTemporaryDirectory();

            PathHelper.CreateTmpFile(tempDirectory); // create tmp file with unsupported filetype

            var photoList = new List <Photo>();

            await foreach (var photo in PhotoHandler.FindPhotosAsync(tempDirectory))
            {
                photoList.Add(photo);
            }

            Assert.Empty(photoList);
        }
Пример #11
0
        public OptionsWindow()
        {
            InitializeComponent();
            Application.Current.MainWindow.Closing += new CancelEventHandler(MainWindow_Closing);
            var image = UserRepo.fetchPhotoByUsername(Globals.currentUserId);

            if (image != null)
            {
                profile_image.Source = PhotoHandler.ToImage(UserRepo.fetchPhotoByUsername(Globals.currentUserId));
            }
            else
            {
                profile_image.Source = new BitmapImage(new Uri(AppDomain.CurrentDomain.BaseDirectory + @"../../Img/user.png"));
            }
        }
Пример #12
0
        public async Task FindPhotosAsync_FlatDirectory_SingleFile_JpegFormatAsync()
        {
            var tempDirectory = PathHelper.GetTemporaryDirectory();
            var tempPath      = PathHelper.CreateImageFile(tempDirectory, ImageFormat.Jpeg);
            var expectedPath  = Path.Combine(tempDirectory, tempPath);

            var photoList = new List <Photo>();

            await foreach (var p in PhotoHandler.FindPhotosAsync(tempDirectory))
            {
                photoList.Add(p);
            }

            var photo      = photoList.FirstOrDefault();
            var actualPath = photo.FilePath;

            Assert.Equal(expectedPath, actualPath);
        }
Пример #13
0
        static async void Handle(object sender, MessageEventArgs args)
        {
            FindPair a = new FindPair(_applicationUsers);

            if (args.Message.Text == "/find")
            {
                FindPair.ShowButton(_botClient, args);
            }
            if (args.Message.Text == "Next")
            {
                a.NextAction(_botClient, args);
            }
            if (args.Message.Type == MessageType.Photo)
            {
                var test = new PhotoHandler();
                test.HandlePhoto(_botClient, args, _applicationUsers.GetById(args.Message.From.Id));
            }
            var text = args.Message.Text;

            if (args.Message.Type == MessageType.Text && !string.IsNullOrEmpty(text))
            {
                var messageHandler = new MessageHandler(_botClient, _applicationUsers);
                var parseMessage   = messageHandler.TryParseMessage(text);
                if (parseMessage.isParsed)
                {
                    var handler = parseMessage.handler;
                    handler.Handle(_botClient, args);
                }

                else
                {
                    await _botClient.SendTextMessageAsync(args.Message.Chat, parseMessage.responseMessage);
                }
            }

            else if (_applicationUsers.GetById(args.Message.From.Id) == null)
            {
                await _botClient.SendTextMessageAsync(args.Message.Chat, "Заполните анкету!");
            }
        }
Пример #14
0
    /// <summary>
    /// This function handles user input.
    /// </summary>
    private void HandleUserInput()
    {
        if (Input.GetKeyDown(KeyCode.Space))
        {
            // Call static function from PhotoHandler script, which is responsible for taking pictures.
            PhotoHandler.TakePicture_Static(Screen.width, Screen.height);
        }

        if (Input.GetKeyDown(KeyCode.R))         // Rotate.
        {
            currentMode = Mode.rotation;
        }

        if (Input.GetKeyDown(KeyCode.T))         // Translate.
        {
            currentMode = Mode.translation;
        }

        if (Input.GetKeyDown(KeyCode.N))         // Load next model.
        {
            LoadNextModel();
        }

        if (Input.GetKeyDown(KeyCode.P))         // Load previous model.
        {
            LoadPreviousModel();
        }

        if (Input.GetKeyDown(KeyCode.H))         // Display help panel.
        {
            DisplayHelpPanel(true);
        }

        if (Input.GetKeyDown(KeyCode.U))         // Reset rotation.
        {
            models[currentModelIndex].ResetModelRotation();
        }
    }
Пример #15
0
        /// <summary>
        /// .post发送消息
        /// </summary>
        /// <param name="collection"></param>
        /// <returns></returns>
        public JsonResult SendMsg(FormCollection collection)
        {
            if (collection == null)
            {
                return(Json(new { result = 0, code = 11, message = "" }));
            }
            string userToken = _convert.ObjectConvert.ChangeType <string>(Request.Headers["usertoken"] ?? collection["usertoken"]);

            if (string.IsNullOrEmpty(userToken))
            {
                return(Json(new { result = 0, code = 11, message = "" }));
            }
            long roomId = _convert.ObjectConvert.ChangeType <long>(collection["roomId"]);

            if (roomId <= 0)
            {
                return(Json(new { result = 0, code = 11, message = "" }));
            }
            string content     = _convert.ObjectConvert.ChangeType <string>(collection["content"] ?? null);
            string sourceMsgId = _convert.ObjectConvert.ChangeType <string>(collection["sourceMsgId"]);
            string msgtype     = _convert.ObjectConvert.ChangeType <string>(collection["msgtype"] ?? null);
            int    isRobot     = _convert.ObjectConvert.ChangeType <int>(collection["isRobot"] == null ? 0 : Convert.ToInt32(collection["isRobot"]));
            int    _roleId     = _convert.ObjectConvert.ChangeType <int>(collection["roleId"] ?? collection["roleId"], 0);
            string userIp      = Niu.Cabinet.Web.ExtensionMethods.RequestExtensions.ClientIp(Request);
            string returnExt   = string.Empty;
            long   userID      = 0;

            Niu.Live.User.IModel.TokenManager.TokenUserInfo userInfo;
            Niu.Live.User.Provider.TokenManager.TokenManager.ValidateUserToken(userToken, out userInfo);
            if (userInfo == null)
            {
                return(Json(new { result = 1, code = 13, message = "token error" }));
            }
            userID = userInfo.userId;
            if (Niu.Live.Chat.Core.Access.Chatroom.QueryBlock(new { roomId = roomId, target = userID }))
            {
                return(Json(new { result = 1, code = 15, message = "您当前不能发言" }));
            }
            string attach = string.Empty; //消息主体
            string ext    = string.Empty; //消息扩展字段

            #region 图片内容
            MsgContent msgcontent = new MsgContent()
            {
                userId   = userInfo.userId,
                ismanger = userInfo.isManage.ToString(),
                name     = userInfo.nickName,
                roleId   = _roleId == 0 ? userInfo.roleId : _roleId
            };
            int[] arry = new int[] { 5, 6, 7, 13, 14 };                         //管理员id列表
            if (arry.Contains(userInfo.roleId) || isRobot == 1 || isRobot == 2) //isRobot ==2为礼物
            {
                msgcontent.isAudit = 1;
            }
            if (isRobot == 1)
            {
                msgcontent.roleId = _roleId;
            }
            msgcontent.ext = new Ext();
            var resultdata = PhotoHandler.Upload(userID, Request.Files);
            if (resultdata != null && resultdata.data != null && resultdata.data.Count > 0)
            {
                ext    = Newtonsoft.Json.JsonConvert.SerializeObject(new { w = resultdata.data[0].width, h = resultdata.data[0].height });
                attach = resultdata.data[0].url;
                msgcontent.ext.width  = resultdata.data[0].width;
                msgcontent.ext.height = resultdata.data[0].height;
                msgcontent.ext.mstype = 2;
                msgcontent.ext.url    = attach;                           //原图地址
                msgcontent.attach     = string.Format("{0}/200", attach); //为啥要标注200不知道
            }
            #endregion
            else
            {
                #region 文本内容
                if (resultdata == null || resultdata.data == null || resultdata.data.Count == 0)
                {
                    ////发送彩条时候,重写消息体
                    if (string.IsNullOrEmpty(content) || content.Length <= 0 || content.Length > 300)
                    {
                        return(Json(new { result = 0, code = 31, message = "内容过长度不匹配" }));
                    }
                    msgcontent.attach     = attach = content;
                    msgcontent.ext.mstype = 1;
                    if (!string.IsNullOrEmpty(msgtype))
                    {
                        msgcontent.ext.mstype = int.Parse(msgtype);
                        //彩条信息
                        switch (msgcontent.ext.mstype)
                        {
                        case 13:
                            msgcontent.ext.url = "https://live.fxtrade888.com/chatroom/images/dingyige.gif";   //顶
                            msgcontent.attach  = "https://live.fxtrade888.com/chatroom/images/dingyige.gif";   //顶
                            break;

                        case 12:
                            msgcontent.ext.url = "https://live.fxtrade888.com/chatroom/images/zanyige.gif";   //赞
                            msgcontent.attach  = "https://live.fxtrade888.com/chatroom/images/zanyige.gif";   //赞
                            break;

                        case 11:
                            msgcontent.ext.url = "https://live.fxtrade888.com/chatroom/images/zhangsheng.gif";   //掌
                            msgcontent.attach  = "https://live.fxtrade888.com/chatroom/images/zhangsheng.gif";   //掌
                            break;

                        case 14:
                            msgcontent.ext.url = "https://live.fxtrade888.com/chatroom/images/xianhua.gif";   //花
                            msgcontent.attach  = "https://live.fxtrade888.com/chatroom/images/xianhua.gif";   //花
                            break;

                        case 5:
                            msgcontent.ext.url = "https://live.fxtrade888.com/chatroom/images/kanzhang.gif";   //看涨
                            msgcontent.attach  = "https://live.fxtrade888.com/chatroom/images/kanzhang.gif";   //看涨
                            break;

                        case 6:
                            msgcontent.ext.url = "https://live.fxtrade888.com/chatroom/images/kandie.gif";   //看跌
                            msgcontent.attach  = "https://live.fxtrade888.com/chatroom/images/kandie.gif";   //看跌
                            break;

                        case 7:
                            msgcontent.ext.url = "https://live.fxtrade888.com/chatroom/images/zhendang.gif";   //震荡
                            msgcontent.attach  = "https://live.fxtrade888.com/chatroom/images/zhendang.gif";   //震荡
                            break;
                        }
                        msgcontent.isAudit = 1;
                    }
                }
                #endregion
            }

            long   sourceId       = 0;
            string sourceUserName = string.Empty;
            string sourceContent  = string.Empty;
            #region 引用数据

            if (!string.IsNullOrEmpty(sourceMsgId))
            {
                Niu.Live.Chat.Core.Model.Im_Chatroom_Msg sourceMsg = Niu.Live.Chat.Core.Access.Chatroom.ChatroomGetMsg(sourceMsgId);
                if (sourceMsg != null && !string.IsNullOrEmpty(sourceMsg.attach))
                {
                    var fromuserinfo = Niu.Live.Chat.Core.Access.User.UserQuery(sourceMsg.fromAccId);
                    var touserinof   = Niu.Live.Chat.Core.Access.User.QueryImUserByUserId(userInfo.userId);

                    msgcontent.ext.other  = new { from = userInfo.nickName, to = fromuserinfo.name, content = sourceMsg.attach };
                    msgcontent.attach     = content;
                    msgcontent.ext.mstype = 3;
                    sourceId      = sourceMsg.id;
                    sourceContent = sourceMsg.attach;
                }
            }
            #endregion

            #region 发送请求

            string jsonext = string.Empty;
            string msgId   = Niu.Live.Chat.Core.Utils.UniqueValue.GenerateGuid();
            msgcontent.msgId   = msgId;
            msgcontent.addtime = Cabinet.Time.TimeStmap.DateTimeToUnixTimeStmap(DateTime.Now);
            Im_User imUser = new Im_User();
            if (isRobot == 1)
            {
                imUser.accid         = Guid.NewGuid().ToString().Substring(0, 31);
                imUser.name          = _convert.ObjectConvert.ChangeType <string>(collection["Robotname"] ?? "");
                msgcontent.isRobot   = 1;
                msgcontent.Robotname = imUser.name;
                Niu.Live.Chat.Core.Provider.User.NeteaseIm_CreateRobot(imUser.accid, imUser.name);
            }
            else
            {
                imUser = Niu.Live.Chat.Core.Provider.User.NeteaseIm_Create(userID.ToString(), userInfo.nickName, "");
            }

            //#if DEBUG
            //            roomId = 9884735;
            //#endif
            #endregion
            var temp = Niu.Live.Chat.Core.Provider.Chatroom.NeteaseIm_SendMsg(msgId, Niu.Live.Chat.Core.Provider.ChatroomMessageType.Custom, roomId, imUser.accid, 0, attach, Newtonsoft.Json.JsonConvert.SerializeObject(msgcontent), msgcontent.isAudit, userInfo.isManage, 1, _roleId == 0 ? userInfo.roleId : _roleId);
            return(Json(new { result = 0, code = temp.code, msg = temp.desc }));
        }
Пример #16
0
 public void Initialize()
 {
     _handler = new PhotoHandler();
 }
Пример #17
0
    private bool takePictureOnNextFrame = false;     // If yes take a picture

    private void Awake()
    {
        // Set the instance.
        Insatnce         = this;
        screenshotCamera = GetComponent <Camera>();
    }
Пример #18
0
        public async Task HandleAsync(IUpdateContext context, UpdateDelegate next, CancellationToken cancellationToken)
        {
            long chatId = context?.Update?.Message?.Chat?.Id ?? -1;

            RecyclingCodeFromPhotoHandler.ChatIdsAwaitingForPhoto.Remove(chatId);

            bool canProcessMessage = _codeRecognitionModelController?.CanProcessImage ?? false;

            if (!canProcessMessage)
            {
                await context.Bot.Client.SendTextMessageAsync(
                    chatId : context.Update.Message.Chat.Id,
                    text : "Can't process photos"
                    );

                return;
            }

            using (PhotoHandler photoHandler = await PhotoHandler.FromMessage(context, context?.Update?.Message))
            {
                if (photoHandler == null)
                {
                    await context.Bot.Client.SendTextMessageAsync(
                        chatId : context.Update.Message.Chat.Id,
                        text : "Can't download photo"
                        );

                    return;
                }

                ImageData imageData = new ImageData
                {
                    ImagePath = photoHandler.FilePath
                };

                CodeRecognitionResult codeRecognitionResult = _codeRecognitionModelController.Recognize(imageData);
                if (codeRecognitionResult == null || !codeRecognitionResult.SuccessfullyProcessedImage)
                {
                    await context.Bot.Client.SendTextMessageAsync(
                        chatId : context.Update.Message.Chat.Id,
                        text : "Failed code recognition"
                        );

                    return;
                }

                IRecyclingCodeInfo recyclingCodeInfo;
                if (!RecyclingCodeInfoWiki.LabelToFractionInfo.TryGetValue(codeRecognitionResult.PredictedLabel, out recyclingCodeInfo))
                {
                    await context.Bot.Client.SendTextMessageAsync(
                        chatId : context.Update.Message.Chat.Id,
                        text : "Unknown recycling code recognized"
                        );

                    return;
                }

                foreach (string recyclingCodeInfoItem in RecyclingCodeRecognitionHandler.FormatRecyclingCodeInfo(recyclingCodeInfo))
                {
                    await context.Bot.Client.SendTextMessageAsync(
                        chatId : chatId,
                        text : recyclingCodeInfoItem
                        );
                }
            }
        }
Пример #19
0
 //Default listener
 void Awake()
 {
     PhotoSelectFinishHandler += delefunTest;
 }