Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class VKClient
- {
- private const int RequestDelay = 350;
- private static readonly Random Random = new Random();
- private static readonly HashSet<string> ImageFiles = new HashSet<string>
- {
- ".jpg",
- ".jpeg",
- ".gif",
- ".bmp",
- ".png"
- };
- private static readonly HashSet<string> BlockedExtensions = new HashSet<string>
- {
- ".exe",
- ".jar",
- ".zip",
- ".reg",
- ".ps1",
- ".bat"
- };
- private readonly string _accessToken;
- private readonly Stopwatch _callTimer;
- private string _docsUploadUrl;
- public VKClient(string accessToken)
- {
- _accessToken = accessToken;
- _callTimer = Stopwatch.StartNew();
- }
- public JToken Run(string method, params object[] args)
- {
- var wait = RequestDelay - _callTimer.ElapsedMilliseconds;
- if (wait > 0) Thread.Sleep((int)wait);
- _callTimer.Restart();
- return VK.Run(method, args.Concat(new[] { "access_token", _accessToken }).ToArray());
- }
- public void SendMessage(long id, string message, params Attachment[] attachments)
- {
- Run("messages.send",
- "peer_id", id,
- "random_id", Random.Next(),
- "message", message ?? "...",
- "attachment", string.Join<Attachment>(",", attachments));
- }
- private void GetDocsUploadServer()
- {
- _docsUploadUrl = Run("docs.getUploadServer")?["response"]?["upload_url"]?.AsString;
- }
- public JToken UploadDoc(string file)
- {
- string directory = null;
- if (BlockedExtensions.Contains(Path.GetExtension(file)))
- {
- directory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
- Directory.CreateDirectory(directory);
- var fileCopy = $"{directory}\\{Path.GetFileName(file)}.txt";
- File.Copy(file, fileCopy);
- file = fileCopy;
- }
- string uploadResult = null;
- try
- {
- if (_docsUploadUrl == null)
- GetDocsUploadServer();
- try
- {
- using (var client = new WebClient())
- uploadResult = JToken.Parse(Encoding.UTF8.GetString(client.UploadFile(_docsUploadUrl, file)))?["file"]?.AsString;
- }
- catch (WebException)
- {
- GetDocsUploadServer();
- using (var client = new WebClient())
- uploadResult = JToken.Parse(Encoding.UTF8.GetString(client.UploadFile(_docsUploadUrl, file)))?["file"]?.AsString;
- }
- }
- finally
- {
- if (directory != null && Directory.Exists(directory))
- Directory.Delete(directory, true);
- }
- return Run("docs.save", "file", uploadResult)?["response"]?.AsArray.First();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement