Ejemplo n.º 1
0
        /// <summary>
        /// 检测服务器上Dir信息.
        /// </summary>
        /// <returns><c>true</c>, 成功, <c>false</c> 失败.</returns>
        /// <param name="iServer">服务器信息.</param>
        /// <param name="iParentUrl">上一层Url.</param>
        /// <param name="iCheckDir">欲检测的文件夹的相对路径.</param>
        /// <param name="iCreatedDir">已创建的相对目录.</param>
        private bool CheckDirOnServer(
            UploadServerInfo iServer, string iParentUrl,
            string iCheckDir, ref string iCreatedDir)
        {
            if (string.IsNullOrEmpty(iCreatedDir) == true)
            {
                iCreatedDir = iCheckDir;
            }
            else
            {
                iCreatedDir = string.Format("{0}/{1}", iCreatedDir, iCheckDir);
            }

            // 已经在服务器上创建
            if (ServersConf.GetInstance().isDirCreatedOnServerByLocal(iServer.ID, iCreatedDir) == true)
            {
                return(true);
            }

            // 检测目录
            if (this.CheckDirOnServer(iServer, iParentUrl, iCheckDir) == true)
            {
                ServersConf.GetInstance().AddCreatedDir(iServer.ID, iCreatedDir);
            }
            else
            {
                this._State = TRunState.CheckDirFailed;
                return(false);
            }
            return(true);
        }
Ejemplo n.º 2
0
        private VkNet.Model.Attachments.Photo UploadAttachmentPhoto(string имяФайла)
        {
            UploadServerInfo serverInfo   = Api.Photo.GetMessagesUploadServer();
            string           ответСервера = UploadPhoto(serverInfo.UploadUrl, имяФайла);
            var хуй = Api.Photo.SaveMessagesPhoto(ответСервера);

            return(хуй.First());
        }
Ejemplo n.º 3
0
        public void GetProfileUploadServer_NormalCase()
        {
            const string url  = "https://api.vk.com/method/photos.getProfileUploadServer?v=5.9&access_token=token";
            const string json =
                @"{
                    'response': {
                      'upload_url': 'http://cs618026.vk.com/upload.php?_query=eyJhY3QiOiJvd25lcl9waG90byIsInNh'
                    }
                  }";

            UploadServerInfo info = GetMockedPhotosCategory(url, json).GetProfileUploadServer();

            info.UploadUrl.ShouldEqual("http://cs618026.vk.com/upload.php?_query=eyJhY3QiOiJvd25lcl9waG90byIsInNh");
        }
Ejemplo n.º 4
0
        public override void Execute()
        {
            try
            {
                using (WebClient client = new WebClient())
                {
                    UploadServerInfo uploadServer = Api.Photo.GetMessagesUploadServer(PersonID);

                    string response = Encoding.ASCII.GetString(
                        client.UploadFile(uploadServer.UploadUrl,
                                          GetPathToMeme(ChangeSymbols(requestMessage, ' ', '_'))));

                    var photo = Api.Photo.SaveMessagesPhoto(response);

                    Api.Messages.Send(new MessagesSendParams()
                    {
                        UserId      = UserID,
                        Attachments = new List <MediaAttachment>()
                        {
                            photo.FirstOrDefault()
                        },
                        RandomId = GetRandomNullableInt()
                    });
                }
            }
            catch (HasNotFoundException ex)
            {
                string similars = GetSimilarMemes(ex.ToFindMeme, MemesBot.Memes);

                if (similars == "")
                {
                    Api.Messages.Send(new MessagesSendParams()
                    {
                        UserId   = UserID,
                        Message  = "Не нашел такой мем",
                        RandomId = GetRandomNullableInt()
                    });
                }
                else
                {
                    Api.Messages.Send(new MessagesSendParams()
                    {
                        UserId   = UserID,
                        Message  = $"Не нашел такой мем, но есть похожие: {similars}",
                        RandomId = GetRandomNullableInt()
                    });
                }
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// 检测服务器上Dir信息.
        /// </summary>
        /// <returns><c>true</c>, 成功, <c>false</c> 失败.</returns>
        /// <param name="iServer">服务器信息.</param>
        /// <param name="iParentUrl">上一层Url.</param>
        /// <param name="iCheckDir">检测.</param>
        private bool CheckDirOnServer(UploadServerInfo iServer, string iParentUrl, string iCheckDir)
        {
            if (string.IsNullOrEmpty(iParentUrl) == true)
            {
                return(false);
            }
            if (string.IsNullOrEmpty(iCheckDir) == true)
            {
                return(false);
            }

            TDirState state = TDirState.None;

            // FTP
            if (TUploadWay.Ftp == this._uploadWay)
            {
                state = this.GetDirStateOnFtpServer(
                    string.Format("{0}/", iParentUrl),
                    iCheckDir, iServer.AccountId, iServer.Pwd);
            }
            switch (state)
            {
            case TDirState.Exist:
            {
                return(true);
            }
            break;

            case TDirState.NotExist:
            {
                string createUrl = string.Format("{0}/{1}", iParentUrl, iCheckDir);
                if (TUploadWay.Ftp == this._uploadWay)
                {
                    state = this.CreateDirOnFtpServer(createUrl, iServer.AccountId, iServer.Pwd);
                    if (TDirState.Created == state)
                    {
                        return(true);
                    }
                }
            }
            break;

            default:
                break;
            }
            return(false);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// 上传.
        /// </summary>
        private IEnumerator UploadFiles(TUploadWay iUploadWay = TUploadWay.Default)
        {
            UploadServerInfo server = ServersConf.GetInstance().GetUploadServerInfo();

            if (server == null)
            {
                yield return(null);
            }
            while (this.UploadQueue.Count > 0)
            {
                if (this.UploaderCount >= this.UploaderMaxCount)
                {
                    yield return(new WaitForSeconds(1.0f));
                }

                // 上传出错则停止
                if (TRunState.OK != this._State)
                {
                    UtilsLog.Error("UploadFiles", "Failed!!! State:{0} Detail:{1}",
                                   this._State.ToString(), this._errors.ToString());
                    // 取消现有上传线程
                    isCanceled = true;
                    break;
                }

                Uploader uploader = this.UploadQueue.Dequeue();
                if (uploader == null)
                {
                    continue;
                }
                yield return(uploader.UploadFile());

                yield return(new WaitForEndOfFrame());

                // 上传出错则停止
                if (TRunState.OK != this._State)
                {
                    UtilsLog.Error("UploadFiles", "Failed!!! State:{0} Detail:{1}",
                                   this._State.ToString(), this._errors.ToString());
                    // 取消现有上传线程
                    isCanceled = true;
                    break;
                }
            }

            yield return(null);
        }
Ejemplo n.º 7
0
        public override async Task Post(Post post)
        {
            try {
                var vkClient = new VkApi();
                vkClient.Authorize(new ApiAuthParams {
                    ApplicationId = _appId,
                    AccessToken   = _accessToken,
                    Login         = _login,
                    Password      = _password,
                    Settings      = Settings.FromJsonString("wall,photos")
                });

                UploadServerInfo uploadServerInfo = await vkClient.Photo.GetWallUploadServerAsync();

                string uploadedFileJson = "";
                using (var client = new HttpClient()) {
                    var    requestContent = new MultipartFormDataContent();
                    byte[] data           = File.ReadAllBytes(post.PathToImageToAttach);
                    var    content        = new ByteArrayContent(data);
                    content.Headers.ContentType = MediaTypeHeaderValue.Parse("multipart/form-data");
                    requestContent.Add(content, "file", $"file.{Path.GetExtension(post.PathToImageToAttach)}");

                    var response = await client.PostAsync(uploadServerInfo.UploadUrl, requestContent);

                    Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);                     // https://stackoverflow.com/questions/33579661/encoding-getencoding-cant-work-in-uwp-app
                    uploadedFileJson = await response.Content.ReadAsStringAsync();
                }

                Photo[] image = vkClient.Photo.SaveWallPhoto(uploadedFileJson, (ulong)uploadServerInfo.UserId).ToArray();

                var wallPost = new WallPostParams();
                wallPost.Message = post.MultilineText
                                   + Environment.NewLine
                                   + "#"
                                   + string.Join(" #", post.Hashtags)
                                   + Environment.NewLine;
                wallPost.Attachments = image;

                vkClient.Wall.Post(wallPost);

                vkClient.Dispose();
            } catch (Exception ex) {
                Console.WriteLine($"vk> {ex.ToString()}");
                ;
            }
        }
Ejemplo n.º 8
0
        private async Task <MediaAttachment> _uploadPhoto(FileAttachment ph, UploadServerInfo server)
        {
            try
            {
                var file = await _uploadFile(ph, server);

                var photo = await ApiClient.Photo.SaveMessagesPhotoAsync(file);

                return(photo[0]);
            }
            catch (Exception e)
            {
                Logger.LogError(e, "Failed to upload photo to vk server");
            }

            return(null);
        }
Ejemplo n.º 9
0
        public void GetMessagesUploadServer_NormalCase()
        {
            const string url  = "https://api.vk.com/method/photos.getMessagesUploadServer?v=5.9&access_token=token";
            const string json =
                @"{
                    'response': {
                      'upload_url': 'http://cs618026.vk.com/upload.php?act=do_add&mid=234695118&aid=-3&gid=0&hash=de2523dd173af592a5dcea351a0ea9e7&rhash=71534021af2730c5b88c05d9ca7c9ed3&swfupload=1&api=1&mailphoto=1',
                      'album_id': -3,
                      'user_id': 234618
                    }
                  }";

            UploadServerInfo info = GetMockedPhotosCategory(url, json).GetMessagesUploadServer();

            info.UploadUrl.ShouldEqual("http://cs618026.vk.com/upload.php?act=do_add&mid=234695118&aid=-3&gid=0&hash=de2523dd173af592a5dcea351a0ea9e7&rhash=71534021af2730c5b88c05d9ca7c9ed3&swfupload=1&api=1&mailphoto=1");
            info.AlbumId.ShouldEqual(-3);
            info.UserId.ShouldEqual(234618);
        }
Ejemplo n.º 10
0
        private async Task <MediaAttachment> _uploadDocument(FileAttachment at, UploadServerInfo server,
                                                             string overrideFileName = null, string overrideMimeType = null)
        {
            try
            {
                var file = await _uploadFile(at, server, overrideFileName, overrideMimeType);

                var document = await ApiClient.Docs.SaveAsync(file, at.FileName, null);

                return(document[0].Instance);
            }
            catch (Exception e)
            {
                Logger.LogError(e, "Failed to upload document to vk server");
            }

            return(null);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// 初始化.
        /// </summary>
        /// <param name="iTarget">上传目标.</param>
        /// <param name="iOnStart">开始上传委托.</param>
        /// <param name="iOnFailed">上传失败委托.</param>
        /// <param name="iOnSuccessed">上传成功委托.</param>
        /// <param name="iUploadWay">上传方式.</param>
        private void Init(
            UploadItem iTarget,
            OnStart iOnStart,
            OnFailed iOnFailed,
            OnSuccessed iOnSuccessed,
            TUploadWay iUploadWay = TUploadWay.Ftp)
        {
            this._target      = iTarget;
            this._onStart     = iOnStart;
            this._onFailed    = iOnFailed;
            this._onSuccessed = iOnSuccessed;
            this._uploadWay   = iUploadWay;
            this.Retries      = ServersConf.GetInstance().NetRetries;

            if (this._server == null)
            {
                this._server = ServersConf.GetInstance().UploadServer;
            }
            this.UploadBaseUrl = ServersConf.GetBundleUploadBaseURL(this._server, this._target);
            this.FileName      = UploadList.GetLocalBundleFileName(this._target.ID, this._target.FileType);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// 向服务器更新最新状态.
        /// </summary>
        private IEnumerator UpdateInfoToServer()
        {
            UploadServerInfo server = ServersConf.GetInstance().UploadServer;

            // 备份本地文件
            if (true == ServersConf.GetInstance().AssetBundlesBackUp)
            {
                this.BackUpBundleFiles();
            }
            yield return(new WaitForEndOfFrame());

            // 开始上传Bunlde包依赖信息文件(Json文件)
            string bundlesMapFilePath = this.UploadBundlesMapFile(server);

            yield return(new WaitForEndOfFrame());

            // 备份文件
            this.BackupFile(bundlesMapFilePath);
            yield return(new WaitForEndOfFrame());

            // 开始上传Bundles列表信息(Json文件)
            string uploadListFilePath = this.UploadUploadListFile(server);

            yield return(new WaitForEndOfFrame());

            // 备份文件
            this.BackupFile(uploadListFilePath);
            yield return(new WaitForEndOfFrame());

            // 清空本地文件
            AssetBundles.Common.ClearStreamingAssets();
            yield return(new WaitForEndOfFrame());

            if ((this._uploadEvents != null) && (this._uploadEvents.OnCompletedNotification != null))
            {
                this._uploadEvents.OnCompletedNotification.Invoke();
            }
            yield return(null);
        }
Ejemplo n.º 13
0
        /// <summary>
        /// 上传上传列表列表信息.
        /// </summary>
        /// <param name="iServerInfo">服务器信息.</param>
        private string UploadUploadListFile(UploadServerInfo iServerInfo)
        {
            // 导出Json文件,保存至(Resources/Conf)
            string inputFilePath = UploadList.GetInstance().ExportToJsonFile();

            UtilsLog.Info("UploadUploadListFile", "ExportToJsonFile(Path:{0})", inputFilePath);

            // 打包信息URL
            string uploadUrl = ServersConf.GetUploadListBaseUrl(iServerInfo);

            if (File.Exists(inputFilePath) == true)
            {
                int    lastIndex = inputFilePath.LastIndexOf("/");
                string fileName  = inputFilePath.Substring(lastIndex + 1);
                uploadUrl = string.Format("{0}/{1}", uploadUrl, fileName);

                // 上传Bundles列表信息文件
                this._State = UpLoadFileToFtpServer(
                    uploadUrl, inputFilePath, iServerInfo.AccountId, iServerInfo.Pwd);

                if (TRunState.OK != this._State)
                {
                    UtilsLog.Error("UploadUploadListFile", "Upload Failed!!! \n {0} -> {1}", inputFilePath, uploadUrl);
                    return(null);
                }
                else
                {
                    this._uploadState = string.Format("[Upload] {0}", fileName);
                    return(inputFilePath);
                }
            }
            else
            {
                UtilsLog.Error("UploadUploadListFile", "Upload Failed!!! \n Upload file is not exist!!!(Path:{0})", inputFilePath);
                return(null);
            }
        }
Ejemplo n.º 14
0
        //Загрузка на стену и добавление во вложенные
        public static IReadOnlyCollection <Document> SendOnServer(string filename, string extension)
        {
            VkApi api = new VkApi();

            //Авторизация
            api.Authorize(new ApiAuthParams
            {
                AccessToken = mytoken
            });

            Console.WriteLine("Авторизировались");
            UploadServerInfo getWallUploadServer = api.Docs.GetWallUploadServer(group_id);
            string           uploadurl           = getWallUploadServer.UploadUrl;
            //long? userid = getWallUploadServer.UserId;
            //long? albumid = getWallUploadServer.AlbumId;
            string responseFile = null;
            IReadOnlyCollection <Document> doclist = null;

            // Загрузить фотографию.
            try
            {
                WebClient wc = new WebClient();
                //string responseImg = null;

                responseFile = Encoding.ASCII.GetString(wc.UploadFile(uploadurl, filename));
                responseFile.GetHashCode();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
            }
            return(doclist);
        }
Ejemplo n.º 15
0
        private async Task <string> _uploadFile(FileAttachment at, UploadServerInfo server,
                                                string overrideFileName = null, string overrideMimeType = null)
        {
            var file = await _downloadFile(at.Url);

            if (at.MimeType.StartsWith("image/") && at.MimeType != "image/png" && at.MimeType != "image/jpeg" &&
                at.MimeType != "image/gif")
            {
                var image = SKImage.FromBitmap(SKBitmap.Decode(file));
                using (var p = image.Encode(SKEncodedImageFormat.Png, 100))
                    using (MemoryStream ms = new MemoryStream())
                    {
                        p.AsStream().CopyTo(ms);
                        file             = ms.ToArray();
                        overrideMimeType = "image/png";
                        overrideFileName = "image.png";
                    }
            }

            var postParameters = new Dictionary <string, object>
            {
                {
                    "file",
                    new FormUpload.FileParameter(file, overrideFileName ?? at.FileName, overrideMimeType ?? at.MimeType)
                }
            };

            using (var webResponse =
                       FormUpload.MultipartFormDataPost(server?.UploadUrl, "MeBridgeBot/2", postParameters))
            {
                var responseReader = new StreamReader(webResponse.GetResponseStream() ??
                                                      throw new NullReferenceException("Response stream is null"));
                var fullResponse = responseReader.ReadToEnd();
                return(fullResponse);
            }
        }
Ejemplo n.º 16
0
        public override async Task SendMessage(Conversation conversation, Message message)
        {
            Logger.LogTrace("Send message to conversation {0}", conversation.OriginId);
            var peerId = Convert.ToInt32(conversation.OriginId);

            #region Get forwarded and attachments

            var fwd         = FlattenForwardedMessages(message);
            var attachments = GetAllAttachments(message, fwd);

            #endregion

            #region Send message

            var sender = "";
            if (message.OriginSender != null)
            {
                sender = FormatSender(message.OriginSender) + "\n";
            }

            var body = FormatMessageBody(message, fwd);
            if (body.Length > 0)
            {
                await ApiClient.Messages.SendAsync(new MessagesSendParams
                {
                    GroupId  = _groupId,
                    PeerId   = peerId,
                    Message  = $"{sender}{body}",
                    RandomId = random.Next()
                });
            }

            #endregion

            if (attachments.Any())
            {
                Logger.LogTrace("Sending message with attachments");
                try
                {
                    #region Get upload server urls

                    UploadServerInfo photoUploadServer = null;
                    UploadServerInfo docsUploadServer  = null;
                    UploadServerInfo voiceUploadServer = null;
                    await Task.WhenAll(Task.Run(async() =>
                    {
                        if (attachments.Any(at => (at is PhotoAttachment || at is StickerAttachment)))
                        {
                            photoUploadServer = await ApiClient.Photo.GetMessagesUploadServerAsync(peerId);
                        }
                    }), Task.Run(async() =>
                    {
                        if (attachments.Any(at => !(at is VoiceAttachment || at is PhotoAttachment)))
                        {
                            docsUploadServer =
                                await ApiClient.Docs.GetMessagesUploadServerAsync(peerId, DocMessageType.Doc);
                        }
                    }), Task.Run(async() =>
                    {
                        if (attachments.Any(at => at is VoiceAttachment))
                        {
                            voiceUploadServer =
                                await ApiClient.Docs.GetMessagesUploadServerAsync(peerId, DocMessageType.AudioMessage);
                        }
                    }));

                    #endregion

                    #region Get vk attachments

                    var groupableAttachments = attachments.Where(at => !(at is IVkSpecialAttachment));

                    Func <Attachment, Task <MediaAttachment> > GroupableAttachmentSelector()
                    {
                        return(async at =>
                        {
                            switch (at)
                            {
                            case AnimationAttachment animation:
                                return await _uploadDocument(animation, docsUploadServer);

                            case StickerAttachment sticker:
                                return await _uploadPhoto(sticker, photoUploadServer);

                            case PhotoAttachment albumPhoto:
                                return await _uploadPhoto(albumPhoto, photoUploadServer);

                            case VideoAttachment albumVideo:
                                return await _uploadDocument(albumVideo, docsUploadServer);

                            case VoiceAttachment voice:
                                return await _uploadDocument(voice, voiceUploadServer);

                            case AudioAttachment audio:
                                return await _uploadDocument(audio, docsUploadServer, $"{audio.ToString()}.mp3.txt",
                                                             "audio/mp3");

                            case FileAttachment file:
                                return await _uploadDocument(file, docsUploadServer);

                            default:
                                return null;
                            }
                        });
                    }

                    #endregion

                    #region Send vk attachments by chunks

                    var chunks = groupableAttachments
                                 .Select((val, i) => (val, i))
                                 .GroupBy(tuple => tuple.i / 10);

                    foreach (var chunk in chunks)
                    {
                        var vkAttachments =
                            await Task.WhenAll(chunk.Select(x => x.val)
                                               .Select(GroupableAttachmentSelector()));

                        await ApiClient.Messages.SendAsync(new MessagesSendParams
                        {
                            GroupId     = _groupId,
                            PeerId      = peerId,
                            Attachments = vkAttachments.Where(a => a != null),
                            RandomId    = random.Next(),
                            Message     = $"{sender}{string.Join(" ", vkAttachments.Where(a => a == null).Select(a => "[Unsupported attachment]").ToArray())}"
                        });
                    }

                    #endregion

                    #region Send special attachments (contacts/urls/places)

                    foreach (var at in attachments)
                    {
                        switch (at)
                        {
                        case ContactAttachment contact:
                            await ApiClient.Messages.SendAsync(new MessagesSendParams
                            {
                                GroupId     = _groupId,
                                PeerId      = peerId,
                                Attachments = new[] { await _uploadDocument(contact, docsUploadServer) },
                                Message     = $"{sender}{contact.ToString()}",
                                RandomId    = random.Next()
                            });

                            break;

                        case LinkAttachment link:
                            await ApiClient.Messages.SendAsync(new MessagesSendParams
                            {
                                GroupId  = _groupId,
                                PeerId   = peerId,
                                Message  = $"{sender}{link.ToString()}",
                                RandomId = random.Next()
                            });

                            break;

                        case PlaceAttachment place:
                            await ApiClient.Messages.SendAsync(new MessagesSendParams
                            {
                                GroupId   = _groupId,
                                PeerId    = peerId,
                                Lat       = place.Latitude,
                                Longitude = place.Longitude,     // typo in lib
                                Message   = $"{sender}{place.ToString()}",
                                RandomId  = random.Next()
                            });

                            break;
                        }
                    }

                    #endregion
                }
                catch (Exception e)
                {
                    Logger.LogError("Attachments upload failed {0}", e);
                }
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        /// 检测服务器上得各个路径.
        /// </summary>
        /// <returns><c>true</c>, OK, <c>false</c> NG.</returns>
        private IEnumerator CheckDirsOnServer()
        {
            string buildName = BuildInfo.GetInstance().BuildName;

            // 上传服务器信息
            UploadServerInfo server = ServersConf.GetInstance().UploadServer;

            if (server == null)
            {
                this._State = TRunState.GetServerInfoFailed;
                yield return(null);
            }

            // 取得上传URL
            string uploadBaseUrl = ServersConf.GetUploadBaseURL(server);

            int    startIndex = uploadBaseUrl.IndexOf(buildName);
            string dirsInfo   = uploadBaseUrl.Substring(startIndex);

            string[] dirNames = dirsInfo.Split('/');

            string curUrl     = uploadBaseUrl.Substring(0, startIndex - 1);
            string createdDir = null;

            for (int i = 0; i < dirNames.Length; ++i)
            {
                if (this.CheckDirOnServer(server, curUrl, dirNames [i], ref createdDir) == true)
                {
                    curUrl = string.Format("{0}/{1}", curUrl, dirNames [i]);
                    yield return(new WaitForEndOfFrame());
                }
                else
                {
                    this._State = TRunState.CheckDirFailed;
                    yield return(null);
                }
            }

            // 检测目录
            // Url:<ParentUrl>/bundles
            if (this.CheckDirOnServer(server, curUrl, "bundles", ref createdDir) == true)
            {
                curUrl = string.Format("{0}/{1}", curUrl, "bundles");
                yield return(new WaitForEndOfFrame());
            }
            else
            {
                this._State = TRunState.CheckDirFailed;
                yield return(null);
            }

            // Url:<ParentUrl>/<BuildTarget>
            string buildTarget = UploadList.GetInstance().BuildTarget;

            if (this.CheckDirOnServer(server, curUrl, buildTarget, ref createdDir) == true)
            {
                curUrl = string.Format("{0}/{1}", curUrl, buildTarget);
                yield return(new WaitForEndOfFrame());
            }
            else
            {
                this._State = TRunState.CheckDirFailed;
                yield return(null);
            }

            // Url:<ParentUrl>/<AppVersion>
            string appVersion = UploadList.GetInstance().AppVersion;

            if (this.CheckDirOnServer(server, curUrl, appVersion, ref createdDir) == true)
            {
                curUrl = string.Format("{0}/{1}", curUrl, appVersion);
                yield return(new WaitForEndOfFrame());
            }
            else
            {
                this._State = TRunState.CheckDirFailed;
                yield return(null);
            }

            // Url:<ParentUrl>/Normal
            string subUrlTmp        = curUrl;
            string subCreatedDirTmp = createdDir;

            if (this.CheckDirOnServer(server, subUrlTmp,
                                      UploadList.AssetBundleDirNameOfNormal, ref subCreatedDirTmp) == true)
            {
                subUrlTmp = string.Format("{0}/{1}", subUrlTmp, UploadList.AssetBundleDirNameOfNormal);
                yield return(new WaitForEndOfFrame());
            }
            else
            {
                this._State = TRunState.CheckDirFailed;
                yield return(null);
            }

            // Url:<ParentUrl>/Scene
            subUrlTmp        = curUrl;
            subCreatedDirTmp = createdDir;
            if (this.CheckDirOnServer(server, subUrlTmp,
                                      UploadList.AssetBundleDirNameOfScenes, ref subCreatedDirTmp) == true)
            {
                subUrlTmp = string.Format("{0}/{1}", subUrlTmp, UploadList.AssetBundleDirNameOfScenes);
                yield return(new WaitForEndOfFrame());
            }
            else
            {
                this._State = TRunState.CheckDirFailed;
                yield return(null);
            }

            yield return(null);
        }
Ejemplo n.º 18
0
        static void CreateUploadShell()
        {
            const string funcBlock = "AssetBundlesBuild.CreateUploadShell()";

            BuildLogger.OpenBlock(funcBlock);

            string filePath = string.Format("{0}/../Shell/Upload.sh", Application.dataPath);

            if (File.Exists(filePath) == true)
            {
                File.Delete(filePath);
            }
            FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write);

            if (null == fs)
            {
                return;
            }
            StreamWriter sw = new StreamWriter(fs);

            if (null == sw)
            {
                if (null != fs)
                {
                    fs.Flush();
                    fs.Close();
                    fs.Dispose();
                }
                return;
            }

            // 写入文件头
            sw.WriteLine("#!/bin/bash");
            sw.Flush();

            sw.WriteLine("");
            sw.Flush();

            // 设定变量
            sw.WriteLine("# 上传根目录");
            sw.WriteLine("ROOT_DIR=bundles");
            sw.Flush();
            sw.WriteLine("# 本地上传路径");
            sw.WriteLine(string.Format("UPLOAD_FROM_ROOT_DIR={0}/StreamingAssets", Application.dataPath));
            sw.WriteLine("");
            sw.Flush();
            sw.WriteLine("# 上传目标平台");
            sw.WriteLine(string.Format("BUILD_TARGET={0}", UploadList.GetInstance().BuildTarget));
            sw.Flush();
            sw.WriteLine("# App Version");
            sw.WriteLine(string.Format("APP_VERSION={0}", UploadList.GetInstance().AppVersion));
            sw.Flush();
            sw.WriteLine("# Center Version");
            sw.WriteLine(string.Format("CENTER_VERSION={0}", UploadList.GetInstance().CenterVersion));
            sw.WriteLine("");
            sw.Flush();

            UploadServerInfo uploadServer = ServersConf.GetInstance().UploadServer;

            sw.WriteLine("# 检测上传目录");
            sw.WriteLine("# $1 上传目录");
            sw.WriteLine("checkUploadDir()");
            sw.WriteLine("{");
            sw.WriteLine("ftp -n<<!");
            sw.WriteLine(string.Format("open {0} {1}", uploadServer.IpAddresss, uploadServer.PortNo));
            sw.WriteLine(string.Format("user {0} {1}", uploadServer.AccountId, uploadServer.Pwd));
            sw.WriteLine("binary");
            sw.WriteLine("pwd");
            sw.WriteLine("if [ ! -d \"$1\" ]; then");
            sw.WriteLine("  mkdir \"$1\"");
            sw.WriteLine("fi");
            sw.WriteLine("prompt");
//			sw.WriteLine("ls -l");
            sw.WriteLine("close");
            sw.WriteLine("bye");
            sw.WriteLine("!");
            sw.WriteLine("}");
            sw.WriteLine("");
            sw.Flush();

            sw.WriteLine("# 文件上传函数");
            sw.WriteLine("# $1 本地上传目录");
            sw.WriteLine("# $2 上传目标目录");
            sw.WriteLine("# $3 上传目标文件");
            sw.WriteLine("upload()");
            sw.WriteLine("{");
            sw.WriteLine("ftp -n<<!");
            sw.WriteLine(string.Format("open {0} {1}", uploadServer.IpAddresss, uploadServer.PortNo));
            sw.WriteLine(string.Format("user {0} {1}", uploadServer.AccountId, uploadServer.Pwd));
            sw.WriteLine("binary");
            sw.WriteLine("cd \"$2\"");
            sw.WriteLine("lcd \"$1\"");
            sw.WriteLine("pwd");
            sw.WriteLine("prompt");
            sw.WriteLine("put \"$3\"");
//			sw.WriteLine("ls -l");
            sw.WriteLine("close");
            sw.WriteLine("bye");
            sw.WriteLine("!");
            sw.WriteLine("}");
            sw.WriteLine("");
            sw.Flush();


            sw.WriteLine("# 检测目录");
            sw.WriteLine("checkUploadDir $ROOT_DIR");
            sw.WriteLine("checkUploadDir $ROOT_DIR/$BUILD_TARGET");
            sw.WriteLine("checkUploadDir $ROOT_DIR/$BUILD_TARGET/$APP_VERSION");
            sw.WriteLine("");
            sw.Flush();

            sw.WriteLine("# 上传资源文件");
            List <UploadItem> Targets = UploadList.GetInstance().Targets;

            UploadItem[] _normals = Targets
                                    .Where(o => (TBundleType.Normal == o.BundleType))
                                    .OrderBy(o => o.No)
                                    .ToArray();
            if (0 < _normals.Length)
            {
                sw.WriteLine("# 检测一般文件目录");
                sw.WriteLine(string.Format("checkUploadDir $ROOT_DIR/$BUILD_TARGET/$APP_VERSION/{0}", TBundleType.Normal.ToString()));

                sw.WriteLine("# 一般文件");
                foreach (UploadItem loop in _normals)
                {
                    string fileName = UploadList.GetLocalBundleFileName(loop.ID, loop.FileType);
                    sw.WriteLine(string.Format("upload $UPLOAD_FROM_ROOT_DIR/{0} $ROOT_DIR/$BUILD_TARGET/$APP_VERSION/{0} {1}",
                                               TBundleType.Normal.ToString(), fileName));
                }
                sw.WriteLine("");
                sw.Flush();
            }

            UploadItem[] _scenes = Targets
                                   .Where(o => (TBundleType.Scene == o.BundleType))
                                   .OrderBy(o => o.No)
                                   .ToArray();
            if (0 < _scenes.Length)
            {
                sw.WriteLine("# 检测场景文件目录");
                sw.WriteLine(string.Format("checkUploadDir $ROOT_DIR/$BUILD_TARGET/$APP_VERSION/{0}", TBundleType.Scene.ToString()));
                sw.WriteLine("# 场景文件");
                foreach (UploadItem loop in _scenes)
                {
                    string fileName = UploadList.GetLocalBundleFileName(loop.ID, loop.FileType);
                    sw.WriteLine(string.Format("upload $UPLOAD_FROM_ROOT_DIR/{0} $ROOT_DIR/$BUILD_TARGET/$APP_VERSION/{0} {1}",
                                               TBundleType.Scene.ToString(), fileName));
                }
                sw.WriteLine("");
                sw.Flush();
            }

            // 导出依赖文件
            BundlesMap.GetInstance().ExportToJsonFile(string.Format("{0}/StreamingAssets", Application.dataPath));
            sw.WriteLine("# 上传依赖文件");
            sw.WriteLine("upload $UPLOAD_FROM_ROOT_DIR $ROOT_DIR/$BUILD_TARGET/$APP_VERSION BundlesMapData.json");

            // 导出上传列表文件
            UploadList.GetInstance().ExportToJsonFile(string.Format("{0}/StreamingAssets", Application.dataPath));
            sw.WriteLine("# 上传上传列表文件");
            sw.WriteLine("upload $UPLOAD_FROM_ROOT_DIR $ROOT_DIR/$BUILD_TARGET/$APP_VERSION UploadListData.json");

            if (0 < Targets.Count)
            {
                sw.WriteLine("# 清空上传文件");
                sw.WriteLine(string.Format("rm -rfv $UPLOAD_FROM_ROOT_DIR", TBundleType.Normal.ToString()));
                sw.WriteLine("");
                sw.Flush();
            }

            sw.WriteLine("");
            sw.Flush();

            if (null != fs)
            {
                fs.Flush();
                fs.Close();
                fs.Dispose();
            }

            if (null != sw)
            {
                sw.Flush();
                sw.Close();
                sw.Dispose();
            }

            BuildLogger.CloseBlock();
        }
Ejemplo n.º 19
0
        private void Send_Message(VkApi api, long idsob, string fullmessage)
        {
            Random random  = new Random();
            int    randid  = random.Next(999999);
            string pattern = "<Image>";
            string message = "";
            string date    = DateTime.Now.ToString();

            Regex regex = new Regex(pattern);

            Match match = Regex.Match(fullmessage, pattern);

            if (match.Length > 0)
            {
                message = fullmessage.Substring(0, match.Index);
            }
            else
            {
                message = fullmessage;
            }
            message += "<VkMKDateMes>" + date;
            string crmessage = Utils.SimCrypto.Encryption(message);
            string attachmentstr = "", crattachments = "";
            string ImageFilePath = Environment.CurrentDirectory;

            if (match.Length > 0)
            {
                attachmentstr = fullmessage.Substring(match.Index);
                crattachments = Utils.SimCrypto.Encryption(attachmentstr);
                File.WriteAllText(Path.Combine(ImageFilePath, "Images.txt"), string.Empty);
                File.WriteAllText(Path.Combine(ImageFilePath, "Images.txt"), CompressString(crattachments));

                UploadServerInfo uploadServer = MainWindow.api.Docs.GetUploadServer();
                // Загрузить файл.
                WebClient wc           = new WebClient();
                string    responseFile = Encoding.ASCII.GetString(wc.UploadFile(uploadServer.UploadUrl, Path.Combine(ImageFilePath, "Images.txt")));
                // Сохранить загруженный файл
                var attachments = MainWindow.api.Docs.Save(responseFile, "doc").Select(x => x.Instance);


                try
                {
                    api.Messages.Send(new MessagesSendParams
                    {
                        UserId      = idsob,
                        RandomId    = randid,
                        Message     = crmessage,
                        Attachments = attachments
                    });
                }
                catch
                {
                    try
                    {
                        api.Messages.Send(new MessagesSendParams
                        {
                            UserId      = idsob,
                            RandomId    = randid,
                            Message     = crmessage,
                            Attachments = attachments
                        });
                    }
                    catch
                    {
                        try
                        {
                            api.Messages.Send(new MessagesSendParams
                            {
                                UserId      = idsob,
                                RandomId    = randid,
                                Message     = crmessage,
                                Attachments = attachments
                            });
                        }
                        catch
                        {
                            try
                            {
                                api.Messages.Send(new MessagesSendParams
                                {
                                    UserId      = idsob,
                                    RandomId    = randid,
                                    Message     = crmessage,
                                    Attachments = attachments
                                });
                            }
                            catch (Exception e) { MessageBox.Show(e.ToString()); }
                        }
                    }
                }
            }
            else
            {
                try
                {
                    api.Messages.Send(new MessagesSendParams
                    {
                        UserId   = idsob,
                        RandomId = randid,
                        Message  = crmessage
                    });
                }
                catch
                {
                    try
                    {
                        api.Messages.Send(new MessagesSendParams
                        {
                            UserId   = idsob,
                            RandomId = randid,
                            Message  = crmessage
                        });
                    }
                    catch
                    {
                        try
                        {
                            api.Messages.Send(new MessagesSendParams
                            {
                                UserId   = idsob,
                                RandomId = randid,
                                Message  = crmessage
                            });
                        }
                        catch
                        {
                            try
                            {
                                api.Messages.Send(new MessagesSendParams
                                {
                                    UserId   = idsob,
                                    RandomId = randid,
                                    Message  = crmessage
                                });
                            }
                            catch (Exception e) { MessageBox.Show(e.ToString()); }
                        }
                    }
                }
            }
        }