summaryrefslogtreecommitdiff
path: root/spedytor/Form1.cs
blob: 4448d8e10bf4788bfb21297ccacca8590f3e7536 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using MySql.Data.MySqlClient;
using System.IO;
using System.Threading;

namespace spedytor
{
    public partial class Form1 : Form
    {
        const string LOG_FILENAME = "spedytor.log";
        private List<string> selectedDBs = new List<string>();
        private dbWindow dbSelectionWindow = new dbWindow();
        private int runningDumps = 0;
        private string lastDumpDB = null;
        private DateTime lastDumpTime;
        private string lastSendDB = null;
        private DateTime lastSendTime;

        public Form1()
        {
            InitializeComponent();
            this.dbSelectionWindow.setParent(this);
        }

        private void bExit_Click(object sender, EventArgs e)
        {
            if (this.selectedDBs.Count > 0)
            {
                if (MessageBox.Show("Czy chcesz zrzucić/wysłać bazy przed zakończeniem działania programu?", "Spedytor - wyjście", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    tInterval_Tick(null, null);
                }
            }
            this.tLogger.Enabled = false;
            Logger.getLogger(this.tbLog, LOG_FILENAME).cleanup();
            this.saveSettings();
            this.Dispose();
        }

        private void Form1_Shown(object sender, EventArgs e)
        {
            if (!MySQL.getConfigured())
            {
                (new MysqlSettings()).ShowDialog();
            }
            if (!MySQL.getConfigured())
            {
                this.Dispose();
                return;
            }
            this.restoreSettings();
            this.refreshDatabaseList();
            this.checkS3Options();
        }

        private void checkS3Options()
        {
            cSend.Enabled = (Properties.S3Settings.Default.AWS_ACCESS_KEY.Length > 0
                && Properties.S3Settings.Default.AWS_SECRET_KEY.Length > 0
                && Properties.S3Settings.Default.AWS_BUCKET_ID.Length > 0);
            if (!cSend.Enabled)
            {
                cSend.Checked = false;
            }
        }

        private void bSettings_Click(object sender, EventArgs e)
        {
            (new MysqlSettings()).ShowDialog();
            this.refreshDatabaseList();
            this.checkS3Options();
        }

        internal void refreshDatabaseList()
        {
            this.dbSelectionWindow.lbDatabases.Items.Clear();
            MySQL c = new MySQL("");
            MySqlDataReader dbs = c.select("SELECT TABLE_SCHEMA FROM information_schema.COLUMNS GROUP BY TABLE_SCHEMA;");
            int index = 0;
            List<string> dbNames = new List<string>();
            while (dbs.Read())
            {
                string dbName = dbs.GetString(0);
                dbNames.Add(dbName);
                this.dbSelectionWindow.lbDatabases.Items.Add(dbName);
                if (this.selectedDBs.IndexOf(dbName) > -1)
                {
                    this.dbSelectionWindow.lbDatabases.SelectedIndices.Add(index);
                }
                index++;
            }
            dbs.Close();
            this.setSelectedDBs(this.selectedDBs.Intersect(dbNames).ToList());
        }

        private string getBucketID()
        {
            if (this.cSend.Checked && spedytor.Properties.S3Settings.Default.AWS_BUCKET_ID.Length > 0)
            {
                return spedytor.Properties.S3Settings.Default.AWS_BUCKET_ID;
            }
            return null;
        }

        private Thread invokeSave(string filePath, string dbName, bool enableControls = false, bool updateStats = true)
        {
            Thread t = new Thread(() => this.saveFile(filePath, dbName, this.getBucketID(), enableControls, updateStats));
            t.IsBackground = true;
            t.Start();
            return t;
        }

        private string getDirectory()
        {
            String directory = spedytor.Properties.Settings.Default.DIRECTORY;
            if (!Directory.Exists(directory))
            {
                directory = "";
                spedytor.Properties.Settings.Default.DIRECTORY = "";
            }
            if (directory.Length == 0)
            {
                FolderBrowserDialog fd = new FolderBrowserDialog();
                if (fd.ShowDialog() == DialogResult.OK)
                {
                    directory = fd.SelectedPath;
                }
            }
            return directory;
        }

        private void bSave_Click(object sender, EventArgs e)
        {
            string directory = this.getDirectory();
            if (directory.Length > 0)
            {
                foreach (string dbName in this.selectedDBs)
                {
                    string filePath = Path.Combine(directory, dbName + DateTime.Now.ToString("-yyyyMMdd-HHmmss") + ".sql");
                    this.invokeSave(filePath, dbName, true);
                }
            }
        }

        private void saveFile(string filePath, string dbName, string s3Bucket = null, bool enableControls = false, bool updateStats = true)
        {
            if (enableControls && this.runningDumps == 0)
            {
                this.Invoke(new setStateDelegate(setControlState), new object[] { false, null });
            }
            this.runningDumps++;
            try
            {
                MySQL c = new MySQL(dbName);
                c.backup(filePath);
                c.close();
                if (updateStats)
                {
                    this.lastDumpDB = dbName;
                    this.lastDumpTime = DateTime.Now;
                    this.refreshLastRunStats();
                }
                Logger.getLogger(this.tbLog, LOG_FILENAME).log("Wyeksportowano pomyślnie do pliku: " + filePath);
                if (s3Bucket != null)
                {
                    S3 s3Client = new S3();
                    s3Client.send(s3Bucket, filePath, dbName + ".sql");
                    Logger.getLogger(this.tbLog, LOG_FILENAME).log("Wysłano bazę danych: " + dbName + "!");
                    if (updateStats)
                    {
                        this.lastSendDB = dbName;
                        this.lastSendTime = DateTime.Now;
                        this.refreshLastRunStats();
                    }
                }
            }
            catch (Exception ex)
            {
                Logger.getLogger(this.tbLog, LOG_FILENAME).log("ERROR: " + ex.Message);
            }
            finally
            {
                this.runningDumps--;
                if (enableControls && this.runningDumps == 0)
                {
                    this.Invoke(new setStateDelegate(setControlState), new object[] { true, null });
                }
            }
        }

        private delegate void setStateDelegate(bool state, Control sender);

        private void setControlState(bool state, Control sender)
        {
            foreach (Control control in this.Controls)
            {
                if (control != sender && control != this.tbLog && control != this.bToggleLog && control != this.lSendStats && control != this.lDumpStats)
                {
                    control.Enabled = state;
                }
            }
        }

        private void bTimer_Click(object sender, EventArgs e)
        {
            tInterval.Interval = Convert.ToInt32(nInterval.Value) * 60000;
            tInterval.Enabled = !tInterval.Enabled;
            if (tInterval.Enabled)
            {
                bTimer.Image = spedytor.Properties.Resources.stop;
                bTimer.Text = "Zatrzymaj";
                this.setControlState(false, bTimer);
                tInterval_Tick(this.bTimer, null);
            }
            else
            {
                bTimer.Image = spedytor.Properties.Resources.refresh;
                bTimer.Text = "Zapisz co...";
                this.Enabled = true;
                this.setControlState(true, bTimer);
                this.repeatFilePath = null;
            }
        }

        private string repeatFilePath = null;

        private void tInterval_Tick(object sender, EventArgs e)
        {
            if (this.repeatFilePath == null)
            {
                this.repeatFilePath = this.getDirectory();
            }
            if (this.repeatFilePath.Length > 0)
            {
                List<Thread> threadList = new List<Thread>();
                foreach (string dbName in this.selectedDBs)
                {
                    string filePath = Path.Combine(this.repeatFilePath, dbName + DateTime.Now.ToString("-yyyyMMdd-HHmmss") + ".sql");
                    threadList.Add(this.invokeSave(filePath, dbName, false, sender != null));
                }
                if (sender == null) // programmatic invoke, not actual button click
                {
                    foreach (Thread t in threadList)
                    {
                        t.Join();
                    }
                }
            }
            else
            {
                bTimer_Click(null, null);
                return;
            }
        }

        private int prevHeight;

        private void bToggleLog_Click(object sender, EventArgs e)
        {
            this.prevHeight = this.Height;
            if (bToggleLog.Text.Equals("▼"))
            {
                bToggleLog.Text = "▲";
                this.Height = this.prevHeight * 2;
                this.prevHeight = this.Height;
            }
            else
            {
                bToggleLog.Text = "▼";
                this.Height = this.prevHeight / 2;
                this.prevHeight = this.Height;
            }
        }

        private void tLogger_Tick(object sender, EventArgs e)
        {
            Logger.getLogger(this.tbLog, LOG_FILENAME).tick();
        }

        private void notifyIcon1_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            this.Show();
            this.WindowState = FormWindowState.Normal;
            this.notifyIcon.Visible = false;
        }

        private void minimizeToTray()
        {
            this.Hide();
            this.notifyIcon.Visible = true;
            this.notifyIcon.ShowBalloonTip(1000, "Spedytor", "Spedytor będzie działać w tle", ToolTipIcon.Info);
        }

        private delegate void setStatsText(Label label, String text);

        private void setLabelText(Label label, String text)
        {
            label.Text = text;
        }

        private void refreshLastRunStats()
        {
            StringBuilder sb = new StringBuilder("Spedytor\n");
            if (this.lastDumpDB != null)
            {
                sb.Append("↓ ");
                sb.Append(this.lastDumpTime.ToShortTimeString());
                sb.Append(" ");
                sb.Append(this.lastDumpDB.Substring(0, Math.Min(20, this.lastDumpDB.Length)));
                sb.Append("\n");
                this.Invoke(new setStatsText(setLabelText), new object[] { this.lDumpStats, "Ostatni zrzut: " + this.lastDumpDB + " (" + this.lastDumpTime.ToString() + ")" });
            }
            else
            {
                this.Invoke(new setStatsText(setLabelText), new object[] { this.lDumpStats, "" });
            }
            if (this.lastSendDB != null)
            {
                sb.Append("↑ ");
                sb.Append(this.lastSendTime.ToShortTimeString());
                sb.Append(" ");
                sb.Append(this.lastSendDB.Substring(0, Math.Min(20, this.lastSendDB.Length)));
                sb.Append("\n");
                this.Invoke(new setStatsText(setLabelText), new object[] { this.lSendStats, "Ostatnia wysyłka: " + this.lastSendDB + " (" + this.lastSendTime.ToString() + ")" });
            }
            else
            {
                this.Invoke(new setStatsText(setLabelText), new object[] { this.lSendStats, "" });
            }
            this.notifyIcon.Text = sb.ToString().Trim();
        }

        private void Form1_Resize(object sender, EventArgs e)
        {
            if (this.WindowState == FormWindowState.Minimized)
            {
                this.minimizeToTray();
            }
        }

        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            e.Cancel = true;
            if (this.tInterval.Enabled)
            {
                DialogResult dr = MessageBox.Show("Spedytor jest w trybie pracy ciągłej.\nCzy chcesz zakończyć działanie programu?", "Spedytor - wyjście", MessageBoxButtons.YesNoCancel);
                switch (dr)
                {
                    case DialogResult.Yes:
                        this.bExit_Click(null, null);
                        break;
                    case DialogResult.No:
                        this.minimizeToTray();
                        break;
                }
            }
            else
            {
                this.bExit_Click(null, null);
            }
        }

        private void closeMenuItem_Click(object sender, EventArgs e)
        {
            this.bExit_Click(null, null);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            this.refreshDatabaseList();
            this.dbSelectionWindow.ShowDialog();
        }

        internal void setSelectedDBs(List<string> selected)
        {
            this.selectedDBs = selected;
            this.bSave.Enabled = this.bTimer.Enabled = (this.selectedDBs.Count > 0);
            if (this.selectedDBs.Count == 0)
            {
                this.bSelectDBs.Text = "[nie wybrano]";
            }
            else
            {
                this.bSelectDBs.Text = String.Format("[wybrano: {0}]", this.selectedDBs.Count);
            }
        }

        private void restoreSettings()
        {
            if (Properties.OptionSettings.Default.DB_NAMES != null)
            {
                this.setSelectedDBs(Properties.OptionSettings.Default.DB_NAMES.Cast<string>().ToList());
            }
            this.cSend.Checked = Properties.OptionSettings.Default.SEND_FLAG;
            this.nInterval.Value = Properties.OptionSettings.Default.RUN_INTERVAL;
        }

        private void saveSettings()
        {
            Properties.OptionSettings.Default.SEND_FLAG = this.cSend.Checked;
            if (Properties.OptionSettings.Default.DB_NAMES == null)
            {
                Properties.OptionSettings.Default.DB_NAMES = new System.Collections.Specialized.StringCollection();
            }
            Properties.OptionSettings.Default.DB_NAMES.Clear();
            Properties.OptionSettings.Default.DB_NAMES.AddRange(this.selectedDBs.ToArray());
            Properties.OptionSettings.Default.RUN_INTERVAL = this.nInterval.Value;
            Properties.OptionSettings.Default.Save();
        }

    }
}