Exemple #1
0
        public void InsertUploadLog(UploadLog uploadLog)
        {
            using (IDbConnection dbConnection = this.GetOpenDbConnection())
                using (IDbCommand dbCommand = dbConnection.CreateCommand())
                {
                    dbCommand.CommandText = "INSERT INTO UploadLogs " +
                                            "(delete_datetime, delete_reason, id, post_fullname, reply_deleted, reply_fullname, requestor_username, upload_datetime, upload_deleted, upload_delete_key, upload_destination, upload_path) " +
                                            "VALUES " +
                                            "(@delete_datetime, @delete_reason, @id, @post_fullname, @reply_deleted, @reply_fullname, @requestor_username, @upload_datetime, @upload_deleted, @upload_delete_key, @upload_destination, @upload_path)";

                    dbCommand.AddParameter("@delete_datetime", (object)uploadLog.DeleteDatetime ?? DBNull.Value);
                    dbCommand.AddParameter("@delete_reason", (object)uploadLog.DeleteReason ?? DBNull.Value);
                    dbCommand.AddParameter("@id", uploadLog.Id);
                    dbCommand.AddParameter("@post_fullname", uploadLog.PostFullname);
                    dbCommand.AddParameter("@reply_deleted", uploadLog.ReplyDeleted);
                    dbCommand.AddParameter("@reply_fullname", uploadLog.ReplyFullname);
                    dbCommand.AddParameter("@requestor_username", uploadLog.RequestorUsername);
                    dbCommand.AddParameter("@upload_datetime", uploadLog.UploadDatetime);
                    dbCommand.AddParameter("@upload_deleted", uploadLog.UploadDeleted);
                    dbCommand.AddParameter("@upload_delete_key", uploadLog.UploadDeleteKey);
                    dbCommand.AddParameter("@upload_destination", uploadLog.UploadDestination);
                    dbCommand.AddParameter("@upload_path", uploadLog.UploadPath);

                    dbCommand.ExecuteNonQuery();
                }
        }
Exemple #2
0
        public async Task <ApiResponse <string> > CreateUploadLog(PanePostRequest request)
        {
            var hashedPassword = string.Empty;

            if (!string.IsNullOrEmpty(request.Password))
            {
                hashedPassword = await _panPasswordHasher.HashPassword(request.Password);
            }
            var uploadlog = new UploadLog()
            {
                Description    = request.Description,
                DataKey        = request.DataKey,
                HashedPassword = hashedPassword,
                AlipayFileKey  = request.AlipayKey,
                WxpayFileKey   = request.WxpayKey,
            };

            using (var scope = GlobalServices.Container.BeginLifetimeScope())
            {
                var repository = scope.Resolve <IFilPanRepository>();
                await repository.CreateUploadLog(uploadlog);

                if (!await repository.HasFileCid(request.DataKey))
                {
                    var fileCid = new FileCid()
                    {
                        Id = request.DataKey
                    };
                    await repository.CreateFileCid(fileCid);
                }
                await repository.Commit();
            }
            return(ApiResponse.Ok(uploadlog.Id));
        }
Exemple #3
0
 public string Create(UploadLog instance)
 {
     if (instance == null)
     {
         throw new ArgumentNullException();
     }
     return(this._repository.Create(instance));
 }
Exemple #4
0
 public void Update(UploadLog instance)
 {
     if (instance == null)
     {
         throw new ArgumentNullException();
     }
     this._repository.Update(instance);
 }
Exemple #5
0
        /// <summary>
        /// insert uploadlog
        /// </summary>
        /// <param name="loginID"></param>
        /// <param name="fileSavePath"></param>
        /// <param name="tableName">PosData</param>
        /// <returns></returns>
        private string insertUploadLog(int loginID, string fileSavePath, string tableName, bool success, string serverFileName)
        {
            UploadLog _UploadLog = new UploadLog();

            _UploadLog.FK_LoginId     = loginID;
            _UploadLog.FileName       = Path.GetFileName(fileSavePath);
            _UploadLog.TableName      = tableName;
            _UploadLog.UpdateTime     = DateTime.Now.ToString("yyyy/MM/dd hh:mm:ss");
            _UploadLog.Success        = success;
            _UploadLog.ServerFileName = serverFileName;
            return(this._uploadLogService.Create(_UploadLog));
        }
        public async Task <GenericResponse> WriteToBucket(string filePath, string bucketName, string folderPath)
        {
            GenericResponse result = new GenericResponse();

            try
            {
                FileInfo file = new FileInfo(filePath);
                //string path = "my-folder/sub-folder/test.txt";

                PutObjectRequest request = new PutObjectRequest()
                {
                    InputStream = file.OpenRead(),
                    BucketName  = bucketName,
                    Key         = folderPath.ToUpper()
                };

                PutObjectResponse response = await _client.PutObjectAsync(request);

                result.Value = response.ResponseMetadata.RequestId;

                char[] separator = { '/' };
                //save to db
                var uploadLog       = new UploadLog();
                var folderPathArray = folderPath.Split(separator);

                uploadLog.BookValue        = folderPathArray[0];
                uploadLog.UploadedFileName = file.Name;
                uploadLog.LogId            = result.Value;
                uploadLog.IsCurrent        = true;
                uploadLog.Path             = folderPath;
                uploadLog.CreatedDate      = DateTime.UtcNow;
                uploadLog.Version          = Int32.Parse(folderPathArray[1]);

                repoUpload.Insert(uploadLog);
                var persist = uow.Save("David");
                if (persist > 0)
                {
                    result.Status = "OK";
                }
            }
            catch (AmazonS3Exception awsEx)
            {
                var errorMessage = awsEx.ErrorCode;
            }
            catch (Exception ex)
            {
                var errorMessage = ex.Message;
            }

            return(result);
        }
Exemple #7
0
 public UploadLogVM(UploadLog log)
 {
     if (log != null)
     {
         Id              = log.Id;
         UploadedBy      = log.User?.FullName;
         UploadedTime    = log.CreationTime?.ToString();
         UploadStatus    = GetUploadStatus(log.UploadStatus.GetValueOrDefault());
         SavedRecordNum  = log.SavedRecordNum.GetValueOrDefault();
         FailedRecordNum = log.FailedRecordNum.GetValueOrDefault();
         NumberOfEntries = log.NumberOfEntries.GetValueOrDefault();
         ErrorLogPath    = log.ErrorLogPath;
         FailureMsg      = log.FailureMsg;
         FileName        = log.OriginalFileName;
     }
 }
        private void LblUploaded_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                if (UploadLogForm == null)
                {
                    UploadLogForm = new UploadLog(this);
                }

                UploadLogForm.ShowDialog();
            }
            catch
            {
                UploadLogForm = new UploadLog(this);
                UploadLogForm.ShowDialog();
            }
        }
Exemple #9
0
        public UploadLog GetUploadLog(Guid uploadLogId)
        {
            using (IDbConnection dbConnection = this.GetOpenDbConnection())
                using (IDbCommand dbCommand = dbConnection.CreateCommand())
                {
                    dbCommand.CommandText = "SELECT delete_datetime, delete_reason, id, post_fullname, reply_deleted, reply_fullname, requestor_username, upload_datetime, upload_deleted, upload_delete_key, upload_destination, upload_path FROM UploadLogs WHERE id = @id";

                    dbCommand.AddParameter("@id", uploadLogId);

                    using (IDataReader dataReader = dbCommand.ExecuteReader())
                    {
                        if (dataReader.Read())
                        {
                            int       col       = 0;
                            UploadLog uploadLog = new UploadLog();
                            if (!dataReader.IsDBNull(col++))
                            {
                                uploadLog.DeleteDatetime = dataReader.GetDateTime(col - 1);
                            }
                            if (!dataReader.IsDBNull(col++))
                            {
                                uploadLog.DeleteReason = dataReader.GetString(col - 1);
                            }
                            uploadLog.Id                = dataReader.GetGuid(col++);
                            uploadLog.PostFullname      = dataReader.GetString(col++);
                            uploadLog.ReplyDeleted      = dataReader.GetBoolean(col++);
                            uploadLog.ReplyFullname     = dataReader.GetString(col++);
                            uploadLog.RequestorUsername = dataReader.GetString(col++);
                            uploadLog.UploadDatetime    = dataReader.GetDateTime(col++);
                            uploadLog.UploadDeleted     = dataReader.GetBoolean(col++);
                            uploadLog.UploadDeleteKey   = dataReader.GetString(col++);
                            uploadLog.UploadDestination = dataReader.GetString(col++);
                            uploadLog.UploadPath        = dataReader.GetString(col++);

                            return(uploadLog);
                        }
                    }
                }

            return(null);
        }
Exemple #10
0
        public List <UploadLog> GetAllUploadLogs()
        {
            using (IDbConnection dbConnection = this.GetOpenDbConnection())
                using (IDbCommand dbCommand = dbConnection.CreateCommand())
                {
                    dbCommand.CommandText = "SELECT delete_datetime, delete_reason, id, post_fullname, reply_deleted, reply_fullname, requestor_username, upload_datetime, upload_deleted, upload_delete_key, upload_destination, upload_path FROM UploadLogs";

                    using (IDataReader dataReader = dbCommand.ExecuteReader())
                    {
                        List <UploadLog> uploadLogs = new List <UploadLog>();

                        while (dataReader.Read())
                        {
                            int       col       = 0;
                            UploadLog uploadLog = new UploadLog();
                            if (!dataReader.IsDBNull(col++))
                            {
                                uploadLog.DeleteDatetime = dataReader.GetDateTime(col - 1);
                            }
                            if (!dataReader.IsDBNull(col++))
                            {
                                uploadLog.DeleteReason = dataReader.GetString(col - 1);
                            }
                            uploadLog.Id                = dataReader.GetGuid(col++);
                            uploadLog.PostFullname      = dataReader.GetString(col++);
                            uploadLog.ReplyDeleted      = dataReader.GetBoolean(col++);
                            uploadLog.ReplyFullname     = dataReader.GetString(col++);
                            uploadLog.RequestorUsername = dataReader.GetString(col++);
                            uploadLog.UploadDatetime    = dataReader.GetDateTime(col++);
                            uploadLog.UploadDeleted     = dataReader.GetBoolean(col++);
                            uploadLog.UploadDeleteKey   = dataReader.GetString(col++);
                            uploadLog.UploadDestination = dataReader.GetString(col++);
                            uploadLog.UploadPath        = dataReader.GetString(col++);

                            uploadLogs.Add(uploadLog);
                        }

                        return(uploadLogs);
                    }
                }
        }
Exemple #11
0
        public async Task DeleteUpload(UploadLog uploadLog, string reason)
        {
            Log.Information($"Deleting UploadLog with ID '{uploadLog.Id}' (reply '{uploadLog.ReplyFullname}')");

            if (!uploadLog.UploadDeleted)
            {
                switch (uploadLog.UploadDestination.ToLower())
                {
                case "imgur":
                    uploadLog.UploadDeleted = await imgurClient.Delete(uploadLog.UploadDeleteKey);

                    break;

                case "gfycat":
                    uploadLog.UploadDeleted = await gfycatClient.Delete(uploadLog.UploadDeleteKey);

                    break;

                default:
                    throw new NotImplementedException($"Unimplemented delete from upload destination '{uploadLog.UploadDestination}'.");
                }
            }

            if (!uploadLog.ReplyDeleted)
            {
                await redditClient.DeletePost(uploadLog.ReplyFullname);

                uploadLog.ReplyDeleted = true;
            }

            if (uploadLog.DeleteDatetime == null)
            {
                uploadLog.DeleteDatetime = DateTime.UtcNow;
                uploadLog.DeleteReason   = reason;
            }

            databaseAccessor.UpdateUploadLog(uploadLog);

            Log.Information($"Deleted post '{uploadLog.ReplyFullname}'.");
        }
Exemple #12
0
        /// <summary>
        /// 1. upload file (excel)
        /// 2. parse excel column value
        /// 3. batch insert posdata
        /// 4. insert uploadlog
        /// 5. copy file to success directory
        /// </summary>
        /// <returns></returns>
        public List <string> UploadFile()
        {
            List <string> _ListError  = new List <string>();
            string        _FilePath   = this._commonFileService.Upload();
            UploadLog     _ReportFile = this._uploadLogService.GetByName(Path.GetFileName(_FilePath));

            if (_ReportFile != null)
            {
                throw new Exception(" don't upload duplicate file  ");
            }
            IQueryable <Edi_Pos> _Edi_PosData = parse(_FilePath);

            if (checkData(_Edi_PosData))
            {
                int _LoginID = HttpContext.Current.Request["LoginID"].ToString() != "" ? Convert.ToInt32(HttpContext.Current.Request["LoginID"].ToString()) : 0;
                _ListError = _edi_PosService.MiltiCreate(_Edi_PosData, _LoginID);
                bool   _Success        = _ListError.Count > 1 ? false : true;
                string _ServerFileName = this._commonFileService.SaveToSuccess(_LoginID, _FilePath, "Edi_Pos");
                string _UploadLogError = insertUploadLog(_LoginID, _FilePath, "Edi_Pos", _Success, _ServerFileName);
                if (_UploadLogError != "")
                {
                    _ListError.Add(_UploadLogError);
                }
                if (_ListError.Count > 1)
                {
                    _ListError[_ListError.Count - 2] = _ListError[_ListError.Count - 2] + "ms";
                    string _Error = string.Join("\r\n", _ListError.ToArray());
                    throw new Exception(_Error);
                }
                else
                {
                    _ListError[0] = _ListError[0] + "ms";
                }
            }
            else
            {
                throw new Exception(" please confirm your file format ");
            }
            return(_ListError);
        }
        protected int SaveNewUploadLog(string path, int lastRowNum, string uploadedFileName)
        {
            UploadLog uploadLog = new UploadLog()
            {
                FilePath         = path,
                CreationTime     = DateTime.Now,
                UserId           = LoggedUserId,
                NumberOfEntries  = lastRowNum,
                UploadStatus     = (int)UploadStatusEnum.Uploaded,
                OriginalFileName = uploadedFileName
            };

            unitOfWork.UploadLogBL.Add(uploadLog);
            if (unitOfWork.Complete() > 0)
            {
                return(uploadLog.Id);
            }
            else
            {
                return(-1);
            }
        }
Exemple #14
0
        public void UpdateUploadLog(UploadLog uploadLog)
        {
            using (IDbConnection dbConnection = this.GetOpenDbConnection())
                using (IDbCommand dbCommand = dbConnection.CreateCommand())
                {
                    dbCommand.CommandText = "UPDATE UploadLogs SET delete_datetime = @delete_datetime, delete_reason = @delete_reason, post_fullname = @post_fullname, reply_deleted = @reply_deleted, reply_fullname = @reply_fullname, requestor_username = @requestor_username, upload_datetime = @upload_datetime, upload_deleted = @upload_deleted, upload_delete_key = @upload_delete_key, upload_destination = @upload_destination, upload_path = @upload_path WHERE id = @id";

                    dbCommand.AddParameter("@delete_datetime", (object)uploadLog.DeleteDatetime ?? DBNull.Value);
                    dbCommand.AddParameter("@delete_reason", (object)uploadLog.DeleteReason ?? DBNull.Value);
                    dbCommand.AddParameter("@id", uploadLog.Id);
                    dbCommand.AddParameter("@post_fullname", uploadLog.PostFullname);
                    dbCommand.AddParameter("@reply_deleted", uploadLog.ReplyDeleted);
                    dbCommand.AddParameter("@reply_fullname", uploadLog.ReplyFullname);
                    dbCommand.AddParameter("@requestor_username", uploadLog.RequestorUsername);
                    dbCommand.AddParameter("@upload_datetime", uploadLog.UploadDatetime);
                    dbCommand.AddParameter("@upload_deleted", uploadLog.UploadDeleted);
                    dbCommand.AddParameter("@upload_delete_key", uploadLog.UploadDeleteKey);
                    dbCommand.AddParameter("@upload_destination", uploadLog.UploadDestination);
                    dbCommand.AddParameter("@upload_path", uploadLog.UploadPath);

                    dbCommand.ExecuteNonQuery();
                }
        }
Exemple #15
0
 public async Task CreateUploadLog(UploadLog entity)
 {
     await DbContext.UploadLogs.AddAsync(entity);
 }
        /// <summary>
        /// 1. upload file (excel)
        /// 2. get file version data to judge you got approved
        /// 3. parse excel column value
        /// 4. batch insert  data
        /// 5. copy file to success directory
        /// 6. insert uploadlog
        /// 7. insert update FileVersionBudget
        /// </summary>
        /// <returns></returns>
        public List <string> UploadFile()
        {
            string _ItemId            = HttpContext.Current.Request["ItemId"].ToString();
            string _ItemId_CostCommon = "";
            //  string _ItemId = "00000000";
            string                   _DepartmentId             = HttpContext.Current.Request["DepartmentId"].ToString();
            string                   _Factory                  = HttpContext.Current.Request["Factory"].ToString();
            string                   _Account                  = HttpContext.Current.Request["Account"].ToString();
            List <string>            _ListError                = new List <string>();
            string                   _FilePath                 = this._commonFileService.Upload();
            int                      _LoginID                  = HttpContext.Current.Request["LoginID"].ToString() != "" ? Convert.ToInt32(HttpContext.Current.Request["LoginID"].ToString()) : 0;
            string                   _TableName                = "";
            Budget_FileVersionBudget _Budget_FileVersionBudget = new Budget_FileVersionBudget();

            if (this._itemCatalogService.GetByItemIdInClassName(_ItemId, "CostCommon") != null)
            {
                _Budget_FileVersionBudget = this._budget_FileVersionBudgetService.GetLastVersion(_ItemId, (DateTime.Now.Year + 1).ToString(), _Factory);
                _ItemId_CostCommon        = _ItemId;
                _ItemId = "CostCommon";
            }
            else if (_ItemId == "PartTime")
            {
                _Budget_FileVersionBudget = this._budget_FileVersionBudgetService.GetLastVersion(_ItemId, (DateTime.Now.Year + 1).ToString(), _Factory);
            }
            else
            {
                _Budget_FileVersionBudget = this._budget_FileVersionBudgetService.GetLastVersion(_ItemId, _DepartmentId, _Factory, (DateTime.Now.Year + 1).ToString());
            }
            if ((_Budget_FileVersionBudget != null) && (!Convert.ToBoolean(_Budget_FileVersionBudget.Approve)))
            {
                throw new Exception("please inform Iris(#6802) to approve you duplicate upload ");
            }
            string _Version = _Budget_FileVersionBudget != null?Convert.ToString(Convert.ToInt32(_Budget_FileVersionBudget.Version) + 1).PadLeft(4, '0') : "0001";

            Budget _Budget = parse(_FilePath, _ItemId, _DepartmentId, _Factory, _Version, _ItemId_CostCommon);

            _ListError = miltiCreate(_ItemId, _Budget, out _TableName);
            bool      _Success        = _ListError.Count > 1 ? false : true;
            string    _ServerFileName = this._commonFileService.SaveToSuccess(_LoginID, _FilePath, _TableName);
            string    _UploadLogError = this._commonFileService.InsertUploadLog(_LoginID, _FilePath, _TableName, _Success, _ServerFileName);
            UploadLog _UploadLog      = this._uploadLogService.GetAll().Where(x => x.FK_LoginId == _LoginID).OrderByDescending(x => x.Id).First();
            Budget_FileVersionBudget _SetBudget_FileVersionBudget = setBudget_FileVersionBudget(_Budget_FileVersionBudget, _Account, _ItemId, _DepartmentId, _Factory, _UploadLog.Id, _ItemId_CostCommon);

            if (_Budget_FileVersionBudget != null)
            {
                this._budget_FileVersionBudgetService.Update(_SetBudget_FileVersionBudget);
            }
            else
            {
                this._budget_FileVersionBudgetService.Create(_SetBudget_FileVersionBudget);
            }
            if (_UploadLogError != "")
            {
                _ListError.Add(_UploadLogError);
            }
            if (_ListError.Count > 0)
            {
                _ListError[0] = _ListError[0] + "ms";
            }
            return(_ListError);
        }
Exemple #17
0
        /// <summary>
        /// 製作上傳圖片的縮圖
        /// </summary>
        /// <returns></returns>
        public ActionResult GetPhotoInfo()
        {
            string[] rtn = new string[] { "", "", "" };

            if (Request.HttpMethod == "POST")
            {
                var uaParser = JsonConvert.DeserializeObject <UAParserModel>(Request["UAParser"]);
                var files    = Request.Files;
                var fileLen  = files.AllKeys.Count();

                if (fileLen == 0)
                {
                    rtn[0] = "無任何上傳檔案 !";
                    return(this.ToJsonNet(rtn));
                }

                var now       = DateTime.Now;
                var t         = new PhotoInfoModel();
                var sw        = new Stopwatch();
                var photoList = new List <int>();
                sw.Start();
                for (var i = 0; i < fileLen; i++)
                {
                    using (var scope = new TransactionScope()) {
                        using (var db = new SqlConnection(this.SettingsContext.GetValue("Test"))) {
                            var file = files[i];
                            t.FileExt  = Path.GetExtension(file.FileName);
                            t.FileName = Path.GetFileNameWithoutExtension(file.FileName);

                            Stream fs          = file.InputStream;
                            Image  img         = null;
                            var    guid        = Guid.NewGuid();
                            var    maxPix      = AppConfig.ThumbnailPixel;
                            var    path        = Server.MapPath($"~/Temp/{guid}.jpg");
                            var    thbPath     = Server.MapPath($"~/Temp/{guid}_{maxPix}.jpg");
                            var    thb1920Path = Server.MapPath($"~/Temp/{guid}_1920.jpg");

                            try {
                                using (Stream stream = new FileStream(path, FileMode.Create)) {
                                    if (t.FileExt.ToLower() == ".heic")
                                    {
                                        // heic to jpg
                                        using (MagickImage mag = new MagickImage(fs)) {
                                            mag.Write(stream, MagickFormat.Jpg);
                                        }
                                        img = Image.FromStream(stream, true, true);
                                    }
                                    else
                                    {
                                        img = Image.FromStream(fs, true, true);
                                    }

                                    PhotoUtility.PhotoExif(ref img, ref t);
                                    // Origin
                                    img.Save(stream, ImageFormat.Jpeg);
                                    // Thumbnail
                                    PhotoUtility.MakeThumbnail(stream, thbPath, maxPix.FixInt());
                                    // Thumbnail
                                    PhotoUtility.MakeThumbnail(stream, thb1920Path, 1920);
                                }

                                // 主檔
                                var p = new PhotoModel();
                                p.CreateDateTime    = now;
                                p.FileDesc          = "";
                                p.FileExt           = t.FileExt;
                                p.FileName          = t.FileName;
                                p.OrgCreateDateTime = t.OrgCreatDateTime;
                                p.OrgModifyDateTime = t.OrgModifyDateTime;
                                p.ModifyDateTime    = t.OrgModifyDateTime;
                                p.Orientation       = t.Orientation;
                                p.Location          = t.Location;
                                p.Width             = t.Width;
                                p.Height            = t.Height;
                                p.Person            = "";
                                p.CreateDateTime    = now;
                                p.ModifyDateTime    = now;
                                db.Insert(p);

                                // 原圖
                                var orgPhoto = new PhotoDetailModel();
                                orgPhoto.PhotoDetailSN  = p.PhotoSN;
                                orgPhoto.CreateDateTime = now;
                                orgPhoto.Photo          = Files.ReadBinaryFile(path);
                                orgPhoto.Type           = "Origin";
                                db.Insert(orgPhoto);
                                Files.RenameFile(path, path.Replace(guid.ToString(), p.PhotoSN.ToString()));
                                path = path.Replace(guid.ToString(), p.PhotoSN.ToString());

                                // 縮圖
                                var thumbPhoto = new PhotoDetailModel();
                                thumbPhoto.PhotoDetailSN  = p.PhotoSN;
                                thumbPhoto.CreateDateTime = now;
                                thumbPhoto.Photo          = Files.ReadBinaryFile(thbPath);
                                thumbPhoto.Type           = "Thumbnail";
                                db.Insert(thumbPhoto);
                                Files.RenameFile(thbPath, thbPath.Replace(guid.ToString(), p.PhotoSN.ToString()));
                                thbPath = thbPath.Replace(guid.ToString(), p.PhotoSN.ToString());

                                // 縮圖 1920
                                var thumbPhoto1920 = new PhotoDetailModel();
                                thumbPhoto1920.PhotoDetailSN  = p.PhotoSN;
                                thumbPhoto1920.CreateDateTime = now;
                                thumbPhoto1920.Photo          = Files.ReadBinaryFile(thb1920Path);
                                thumbPhoto1920.Type           = "Thumbnail";
                                db.Insert(thumbPhoto1920);
                                Files.RenameFile(thb1920Path, thb1920Path.Replace(guid.ToString(), p.PhotoSN.ToString()));
                                thb1920Path = thb1920Path.Replace(guid.ToString(), p.PhotoSN.ToString());

                                //t.Url = "data:image/" + t.FileExt.Replace(".", "") + ";base64," + Convert.ToBase64String(Files.ReadBinaryFile(path));
                                t.Thumbnail = "data:image/" + t.FileExt.Replace(".", "") + ";base64," + Convert.ToBase64String(thumbPhoto1920.Photo);

                                var percent = ((double)(i + 1) / (double)fileLen * 100);
                                percent = percent > 99 ? 99 : percent;
                                ProgressHub.SendMessage(Request["Selector"], percent, "", Request["ConnId"], i, t.Thumbnail);

                                photoList.Add(p.PhotoSN);
                            } catch (Exception e) {
                                this.LogContext.LogRepoistory.SysLog(e);
                                rtn[0] += $"{t.FileName} - {e.Message} <br>";
                                Files.DelBulkFiles(new string[] { path, thbPath, thb1920Path });
                                ProgressHub.SendMessage(Request["Selector"], 0, e.Message, Request["ConnId"], i, "");
                                continue;
                            } finally {
                                if (img != null)
                                {
                                    img.Dispose();
                                }
                                img = null;
                            }
                        }
                        scope.Complete();
                    }
                }

                if (rtn[0] == "")
                {
                    // 上傳記錄
                    var log = new UploadLog();
                    log.Browser        = $"{uaParser.BrowserName}  {uaParser.BrowserVersion}";
                    log.Device         = $"{uaParser.DeviceType}  {uaParser.DeviceVendor}";
                    log.OS             = $"{uaParser.OsName}  {uaParser.OsVersion}";
                    log.LocalIP        = "";
                    log.TotalNum       = fileLen;
                    log.Type           = "Photo";
                    log.CompletedTime  = sw.Elapsed.ToString("mm\\:ss\\.ff");
                    log.CreateDateTime = now;
                    log.PhotoSNList    = photoList.ToArray().Join(",");

                    using (var db = new SqlConnection(this.SettingsContext.GetValue("Test"))) {
                        db.Insert(log);
                    }
                }

                ProgressHub.SendMessage(Request["Selector"], 100, "", Request["ConnId"], fileLen, "");
            }

            return(this.ToJsonNet(rtn));
        }
Exemple #18
0
        private async Task ProcessCommands(List <RedditThing> commands)
        {
            foreach (RedditThing command in commands)
            {
                await redditClient.MarkMessagesAsRead(new List <string> {
                    command.Name
                });

                List <string> splitCommandText = command.Body.Trim().Split().ToList();

                if (splitCommandText.Count < 1 || string.IsNullOrEmpty(splitCommandText[0]))
                {
                    continue;
                }

                switch (splitCommandText[0].ToLower())
                {
                case "ban":
                case "blacklist":
                    if (!settings.Administrators.Contains(command.Author))
                    {
                        break;
                    }

                    StringBuilder replyText = new StringBuilder();
                    for (int i = 1; i < splitCommandText.Count; i++)
                    {
                        if (Regex.IsMatch(splitCommandText[i], @"^/?r/\w+"))
                        {
                            string subreddit = splitCommandText[i].Substring(splitCommandText[1].LastIndexOf("/") + 1);
                            if (databaseAccessor.GetBlacklistedSubreddit(subreddit) == null)
                            {
                                databaseAccessor.InsertBlacklistedSubreddit(subreddit, command.Author);
                                replyText.Append($"/r/{subreddit} has been blacklisted.  \n");
                            }
                            else
                            {
                                replyText.Append($"/r/{subreddit} is already blacklisted.  \n");
                            }
                        }
                        else if (Regex.IsMatch(splitCommandText[i], @"^/?u/\w+"))
                        {
                            string username = splitCommandText[i].Substring(splitCommandText[1].LastIndexOf("/") + 1);
                            if (databaseAccessor.GetBlacklistedUser(username) == null)
                            {
                                databaseAccessor.InsertBlacklistedUser(username, command.Author);
                                await redditClient.BlockUser(username);

                                replyText.Append($"/u/{username} has been blacklisted.  \n");
                            }
                            else
                            {
                                replyText.Append($"/u/{username} is already blacklisted.  \n");
                            }
                        }
                    }

                    if (!string.IsNullOrEmpty(replyText.ToString()))
                    {
                        await redditClient.PostComment(command.Name, replyText.ToString());
                    }

                    break;

                case "delete":
                    if (splitCommandText.Count < 2)
                    {
                        break;
                    }

                    UploadLog uploadLog = databaseAccessor.GetUploadLog(new Guid(splitCommandText[1]));
                    if (uploadLog == null)
                    {
                        break;
                    }

                    if (settings.Administrators.Contains(command.Author) || uploadLog.RequestorUsername == command.Author)
                    {
                        await cleanupManager.DeleteUpload(uploadLog, $"Requested by /u/{command.Author}");
                    }

                    break;
                }
            }
        }