source: extensions/Picasa2Piwigo/PicasaMyPhotos/Form1.cs @ 31334

Last change on this file since 31334 was 31334, checked in by kenl, 8 years ago
File size: 52.7 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.ComponentModel;
4using System.Data;
5using System.Drawing;
6using System.Linq;
7using System.Text;
8using System.Windows.Forms;
9using System.Diagnostics;
10using System.Drawing.Imaging;
11using System.IO;
12using MySql.Data.MySqlClient;
13
14namespace PicasaFindMyPhotos
15{   
16    public partial class Form1 : Form
17    {
18
19        const int MAX_DUPLICATE_FILENAMES = 10000;
20        const int MAX_NUMBER_OF_CONTACTS = 512;
21
22
23        bool formhasbeenclosed;
24        public struct PersonIDStruct
25        {
26            public string name;
27            public int index;           
28        }
29        public struct UniqueIDStruct
30        {
31            public string unique_id;
32            public int index;
33        }
34
35        bool ContactPathSet, RootPathSet, OutputPathSet;
36        string ContactPathStr, RootPathStr, OutputPathStr;
37        public Form1()
38        {
39            InitializeComponent();
40            ContactPathSet = false;
41            RootPathSet = false;
42            OutputPathSet = false; 
43        }
44
45        private void SetContactPathBtn_Click(object sender, EventArgs e)
46        {
47            OpenFileDialog openFile1 = new OpenFileDialog();
48            openFile1.Filter = "XML Files|*.xml";
49            if (openFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
50            {
51                FormSettings.Default.PicasaContactsFileSetting = openFile1.FileName;
52                FormSettings.Default.Save();
53                ContactPathSet = true;
54                ContactPathStr = openFile1.FileName;
55                PicasaContactsFileTextBox.Text = ContactPathStr;
56                if (ContactPathSet && RootPathSet && OutputPathSet)
57                {                   
58                    ExecuteBtn.Enabled = true;
59                }
60            }
61        }
62
63        private void ExecuteBtn_Click(object sender, EventArgs e)
64        {
65            string filedata, unique_id, person_str, piwigo_album_name, piwigo_photo_name,
66                PiwigoDBVersion;
67            int k, l, i, person_count, unique_id_count, face_tag_id, piwigo_category_id,
68                piwigo_photo_filename_count, piwigo_unique_image_id, face_tags_moved, 
69                processing_loop_count, already_tagged_count;
70            int[] piwigo_image_id = new int[MAX_DUPLICATE_FILENAMES];
71            int[] piwigo_person_tag_count = new int[MAX_NUMBER_OF_CONTACTS];
72            PersonIDStruct[] contact_array = new PersonIDStruct[MAX_NUMBER_OF_CONTACTS];
73            UniqueIDStruct[] picasa_unique_id_arrary = new UniqueIDStruct[MAX_NUMBER_OF_CONTACTS];
74            bool[] found_contact_in_photo_array = new bool[MAX_NUMBER_OF_CONTACTS];
75            bool person_exists, already_tagged;
76            DBConnect PiwigoDBConn = new DBConnect();
77            DialogResult dlgresult;
78
79            formhasbeenclosed = false;
80            ExecuteBtn.Enabled = false;
81            StatusTextBox.Text = "";
82            this.Refresh();
83            this.StatusTextBox.Update();
84            Application.DoEvents();
85
86            //read contacts and create an output file for each
87            System.IO.StreamReader file = new System.IO.StreamReader(ContactPathStr);
88            System.IO.StreamWriter[] outfile = new System.IO.StreamWriter[MAX_NUMBER_OF_CONTACTS];
89
90            for (i = 0; i < MAX_NUMBER_OF_CONTACTS; i++)
91            {
92                piwigo_person_tag_count[i] = 0;
93            }
94            if (SetTagsInPiwigoCheckBox.Checked)
95            {
96                WriteStatusText("Checking Database Connection...");               
97                PiwigoDBConn.InitializeDBConnection(ServerNameTextBox.Text, 
98                    PiwigoDatabaseTextBox.Text, PiwigoDBUserNameTextBox.Text,
99                    PiwigoDBPwdTextBox.Text);
100                i = PiwigoDBConn.OpenDBConnection();
101                if (i == -1)
102                {
103                    WriteStatusText("Database connection ok.");                   
104                }
105                else
106                {
107                    WriteStatusText("Database connection failed.");
108                    switch (i)
109                    {
110                        case 0:
111                            WriteStatusText("Error - Cannot connect to server.");
112                        break;
113                        case 1045:
114                        WriteStatusText("Error - Invalid username/password");
115                        break;
116                        default:
117                        WriteStatusText("Error - unknown error - " + i.ToString());
118                        break;
119                    }
120                    ExecuteBtn.Enabled = true;
121                    return;
122                }
123
124                //validate database version
125                WriteStatusText("Validating Database Version...");
126                PiwigoDBVersion = GetPiwigoDBVersion(PiwigoDBConn, PwigoDBPrefixTextBox.Text);
127                PiwigoDBConn.CloseConnection();
128                if (PiwigoDBVersion != "2.4")
129                {
130                    dlgresult = MessageBox.Show("The Piwigo database vesrsion is " + PiwigoDBVersion +
131                        ".  This does not match the expected version (2.4).  This application was only tested with version 2.4.  Do you want to continue?",
132                        "DB Version Warning", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
133                    if (dlgresult == DialogResult.No)
134                    {
135                        ExecuteBtn.Enabled = true;
136                        return;
137                    }
138                }
139                else
140                {
141                    WriteStatusText("Database version ok.");
142                }
143            }
144
145            person_count = 0;
146            unique_id_count =0;
147            while ((filedata = file.ReadLine()) != null)
148            {
149                //parse name and unique id
150                k = filedata.IndexOf("contact id=");
151                if (k != -1)
152                {                   
153                    unique_id = filedata.Substring(k + 12,  16);
154                    k = filedata.IndexOf("name=");
155                    l = filedata.IndexOf("\"",k+6);
156                    person_str = filedata.Substring(k + 6,  (l - k-6));
157                    Debug.WriteLine("Person: " + person_str + " ID: " + unique_id);
158                    //does this person already exist
159                    person_exists = false;
160                    for (i = 0; i < person_count; i++)
161                    {
162                        if (person_str == contact_array[i].name)
163                        {
164                            person_exists = true;
165                            break;
166                        }
167                    }
168
169                    if (!person_exists)
170                    {
171                        contact_array[person_count].name = person_str;
172                        contact_array[person_count].index = person_count;
173                        picasa_unique_id_arrary[unique_id_count].unique_id = unique_id;
174                        picasa_unique_id_arrary[unique_id_count].index = person_count;
175                        outfile[person_count] = new System.IO.StreamWriter(OutputPathStr + "\\" + person_str + ".txt");
176                        person_count++;
177                    }
178                    else
179                    {
180                        picasa_unique_id_arrary[unique_id_count].unique_id = unique_id;
181                        picasa_unique_id_arrary[unique_id_count].index = i;
182                    }                   
183                    unique_id_count++;
184                }
185                Debug.WriteLine("Number of contacts: " + person_count.ToString());
186            }
187
188            //start traversing directories
189            Stack<string> dirs = new Stack<string>(5000);
190
191            if (!System.IO.Directory.Exists(RootPathStr))
192            {
193                throw new ArgumentException();
194            }
195            dirs.Push(RootPathStr);
196
197            processing_loop_count = 0;
198            while (dirs.Count > 0)
199            {
200                string currentDir = dirs.Pop();
201                string[] subDirs;
202                string inidata, ini_unique_id, photo_file_name, photo_path_filename;               
203                bool[] first_mention_in_dir = new bool[MAX_NUMBER_OF_CONTACTS];
204                bool found_person, finished_faces;
205                int m;
206
207                subDirs = System.IO.Directory.GetDirectories(currentDir);
208               
209                WriteStatusText("Processing Directory:  " + currentDir);
210                this.StatusTextBox.Update();
211                Application.DoEvents();
212                if (formhasbeenclosed)
213                {
214                    return;
215                }
216                if (currentDir.IndexOf(".picasaoriginals") != -1)
217                {
218                    WriteStatusTextAppend(" (ignored)");
219                }
220                if (currentDir.IndexOf(".picasaoriginals") == -1)
221                {
222                    string[] files = null;
223                    files = System.IO.Directory.GetFiles(currentDir);
224                    foreach (string fileindir in files)
225                    {
226                        if (fileindir.IndexOf(".picasa.ini") != -1)
227                        {
228                            for (k = 0; k < person_count; k++)
229                            {
230                                first_mention_in_dir[k] = false;
231                            }
232                            System.IO.StreamReader inifile = new System.IO.StreamReader(fileindir);               
233                            k = 0;
234                            photo_file_name = "";
235                            while ((inidata = inifile.ReadLine()) != null)
236                            {
237                                processing_loop_count++;
238                                if (processing_loop_count >= 10)
239                                {
240                                    WriteStatusTextAppend(" .");
241                                    processing_loop_count = 0;
242                                }
243                                if (inidata.Length > 4)
244                                {
245                                    if (inidata.Substring(0, 1) == "[")
246                                    {
247                                        k = inidata.IndexOf("]");
248                                        if (k != -1)
249                                        {
250                                            photo_file_name = inidata.Substring(1, k - 1);
251                                        }
252                                        if (photo_file_name.IndexOf(".jpg", StringComparison.OrdinalIgnoreCase) != -1 ||
253                                            photo_file_name.IndexOf(".gif", StringComparison.OrdinalIgnoreCase) != -1 ||
254                                            photo_file_name.IndexOf(".png", StringComparison.OrdinalIgnoreCase) != -1 ||
255                                            photo_file_name.IndexOf(".tga", StringComparison.OrdinalIgnoreCase) != -1 ||
256                                            photo_file_name.IndexOf(".tif", StringComparison.OrdinalIgnoreCase) != -1 ||
257                                            photo_file_name.IndexOf(".tiff", StringComparison.OrdinalIgnoreCase) != -1 ||
258                                            photo_file_name.IndexOf(".psd", StringComparison.OrdinalIgnoreCase) != -1)
259                                        {
260                                            for (k = 0; k < person_count; k++)
261                                            {
262                                                found_contact_in_photo_array[k] = false;
263                                            }
264                                            k = fileindir.LastIndexOf("\\");
265                                            photo_path_filename = fileindir.Substring(0, k);
266                                            photo_path_filename += "\\" + photo_file_name;
267                                            Application.DoEvents();
268                                            if (formhasbeenclosed)
269                                            {
270                                                return;
271                                            }
272                                            SearchForNamesInExif(ref found_contact_in_photo_array, contact_array, photo_path_filename, person_count);
273                                            for (k = 0; k < person_count; k++)
274                                            {
275                                                if (found_contact_in_photo_array[k])
276                                                {
277                                                    if (photo_file_name.Length > 3)
278                                                    {
279                                                        if (!first_mention_in_dir[k])
280                                                        {
281                                                            m = currentDir.IndexOf(':');
282                                                            if (m != -1)
283                                                            {
284                                                                //regular path
285                                                                m = currentDir.IndexOf('\\');
286                                                                first_mention_in_dir[k] = true;
287                                                                if (m == -1)
288                                                                {
289                                                                    m = 0;
290                                                                }
291                                                                outfile[k].WriteLine(currentDir.Substring(m + 1));
292                                                            }
293                                                            else
294                                                            {
295                                                                //unc path
296                                                                m = currentDir.IndexOf('\\',2);
297                                                                first_mention_in_dir[k] = true;
298                                                                if (m == -1)
299                                                                {
300                                                                    m = 0;
301                                                                }
302                                                                outfile[k].WriteLine(currentDir.Substring(m + 1));
303                                                            }
304                                                        }
305                                                        outfile[k].WriteLine("\t" + photo_file_name);
306                                                    }
307                                                }
308                                            }
309                                        }
310                                    }
311                                    else if (inidata.Substring(0, 6) == "faces=")
312                                    {
313                                        finished_faces = false;
314                                        k = 0;
315                                        do
316                                        {
317                                            k = inidata.IndexOf("),", k);
318                                            if (k != -1)
319                                            {
320                                                l = inidata.IndexOf(";", k);
321                                                if (l == -1)
322                                                {
323                                                    l = inidata.Length;
324                                                }
325                                                if (l != -1)
326                                                {
327                                                    ini_unique_id = inidata.Substring(k + 2, l - k - 2);
328
329                                                    //found face in a picture, but who?
330                                                    l = 0;
331                                                    found_person = false;
332                                                    do
333                                                    {
334                                                        if (picasa_unique_id_arrary[l].unique_id == ini_unique_id)
335                                                        {
336                                                            //did we already find this person?
337                                                            if (found_contact_in_photo_array[l] == false)
338                                                            {
339                                                                found_person = true;
340                                                                break;
341                                                            }                                                           
342                                                        }
343                                                        l++;
344                                                    } while (l < unique_id_count);
345
346                                                    //found person
347                                                    if (found_person)
348                                                    {
349                                                        if (photo_file_name.Length > 3)
350                                                        {
351                                                            if (!first_mention_in_dir[picasa_unique_id_arrary[l].index])
352                                                            {
353                                                                m = currentDir.IndexOf("\\photo\\");
354                                                                first_mention_in_dir[picasa_unique_id_arrary[l].index] = true;
355                                                                outfile[picasa_unique_id_arrary[l].index].WriteLine(currentDir.Substring(m + 7));
356                                                            }
357                                                            outfile[picasa_unique_id_arrary[l].index].WriteLine("\t" + photo_file_name);
358                                                        }
359                                                    }
360                                                }
361                                                k++;
362                                            }
363                                            else
364                                            {
365                                                finished_faces = true;
366                                            }
367                                        } while (!finished_faces);
368                                    }
369                                }
370                            }
371                            inifile.Close();
372                        }
373                    }
374
375                }
376                // Push the subdirectories onto the stack for traversal.
377                // This could also be done before handing the files.
378                foreach (string str in subDirs)
379                    dirs.Push(str);
380            }
381
382            file.Close();
383            for (k = 0; k < person_count; k++)
384            {
385                outfile[k].Close();
386            }
387
388
389            //generate html
390            string html_filepath;
391            if (GenerateHTMLCheckBox.Checked)
392            {
393                string pathtoexe = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location);
394                WriteStatusText("Generating html");
395                for (k = 0; k < person_count; k++)
396                {                   
397                    System.IO.StreamReader htmlinfile = new System.IO.StreamReader(OutputPathStr + "\\" + contact_array[k].name + ".txt");
398                    System.IO.StreamWriter htmloutfile = new System.IO.StreamWriter(OutputPathStr + "\\" + contact_array[k].name + ".html");
399                    System.IO.StreamReader htmlprotostart = new System.IO.StreamReader(pathtoexe + "\\" + "html_file_start.txt");
400                    System.IO.StreamReader htmlprotoend = new System.IO.StreamReader(pathtoexe + "\\" + "html_file_end.txt");
401                   
402                    //write start of html
403                    while ((filedata = htmlprotostart.ReadLine()) != null)
404                    {
405                        htmloutfile.WriteLine(filedata); 
406                    }
407                    htmlprotostart.Close();
408
409                    htmloutfile.WriteLine("<h3>Photos of:  " + contact_array[k].name + "</h3>");
410
411                    html_filepath = "";
412                    while ((filedata = htmlinfile.ReadLine()) != null)
413                    {
414                        if (filedata.Length != 0)
415                        {
416                            if (filedata.Substring(0,1) != "\t")
417                            {
418                                html_filepath = BaseURLTextBox.Text + filedata.Trim();
419                                html_filepath = html_filepath.Replace("\\", "/");
420                                htmloutfile.WriteLine("<br><b>" + filedata.Trim() + "</b><br>");
421                            }
422                            else
423                            {
424                                filedata = filedata.Substring(1);
425                                filedata.Trim();
426                                string htmlphotofile = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;" +
427                                    "<a href=" + "\"" + html_filepath + "/" + filedata + "\"" + ">" + filedata + "</a><br>";
428                                htmlphotofile = htmlphotofile.Replace("\\", "/");
429                                htmloutfile.WriteLine(htmlphotofile);
430                            }
431                        }
432                    }
433
434                    //write end of html
435                    while ((filedata = htmlprotoend.ReadLine()) != null)
436                    {
437                        htmloutfile.WriteLine(filedata);
438                    }
439                    htmlprotoend.Close();
440                    htmloutfile.Close();
441                    htmlinfile.Close();
442                }
443            }
444
445            face_tags_moved = 0;
446            //update piwigo database
447            piwigo_photo_name = "";
448            piwigo_album_name = "";
449            already_tagged_count = 0;
450            if (SetTagsInPiwigoCheckBox.Checked)
451            {               
452                //clear out existing face tags
453                if (ClearPiwigoTagsCheckbox.Checked)
454                {
455                    WriteStatusText("Clearing existing face tags...");
456                    PiwigoDBConn.InitializeDBConnection(ServerNameTextBox.Text,
457                        PiwigoDatabaseTextBox.Text, PiwigoDBUserNameTextBox.Text,
458                        PiwigoDBPwdTextBox.Text);                   
459                    ClearPiwigoTags(person_count, contact_array,
460                        PiwigoDBConn, PwigoDBPrefixTextBox.Text);                   
461                }
462                //now add new tags
463                WriteStatusText("Adding face tags to Piwigo...");
464                if (PiwigoDBConn.OpenDBConnection() != -1)
465                {
466                    WriteStatusText("Error opening database.");
467                }
468                else
469                {                   
470                    for (k = 0; k < person_count; k++)
471                    {
472                        WriteStatusText("Processing " + contact_array[k].name + " ");
473                        this.Refresh();
474                        this.StatusTextBox.Update();
475                        Application.DoEvents();
476                        if (formhasbeenclosed)
477                        {
478                            return;
479                        }
480
481                        System.IO.StreamReader taginfile = new
482                            System.IO.StreamReader(OutputPathStr + "\\" +
483                            contact_array[k].name + ".txt");                       
484                        while ((filedata = taginfile.ReadLine()) != null)
485                        {
486                            this.Refresh();
487                            this.StatusTextBox.Update();
488                            Application.DoEvents();
489                            if (formhasbeenclosed)
490                            {
491                                return;
492                            }
493
494                            //is this an album or a file name
495                            if (filedata.Substring(0, 1) == "\t")
496                            {
497                                //it's a file
498                                piwigo_photo_name = filedata.Trim();
499                            }
500                            else
501                            {
502                                //it's an album
503                                //find last '\'
504                                piwigo_album_name = filedata.Trim();
505                                int index_last_slash = filedata.LastIndexOf('\\');
506                                if (index_last_slash != -1)
507                                {
508                                    piwigo_album_name = filedata.Substring(index_last_slash + 1);
509                                    piwigo_album_name = piwigo_album_name.Trim();
510                                }
511                                continue;
512                            }
513                            //add new tag to db
514                            face_tag_id = -1;
515                            //add a tag for the person
516                            SetPiwigoTag(contact_array[k].name, PiwigoDBConn,
517                                PwigoDBPrefixTextBox.Text, ref face_tag_id);
518                            if (face_tag_id == -1)
519                            {
520                                continue;
521                            }
522
523                            //face tag has been entered in tag list
524                            //now assign tags to photos
525
526                            //correlate the album to a particular category in piwigo
527                            piwigo_category_id = -1;
528                            GetPiwigoCategoryID(piwigo_album_name, PiwigoDBConn,
529                                PwigoDBPrefixTextBox.Text, ref piwigo_category_id);
530                            if (piwigo_category_id == -1)
531                            {
532                                continue;
533                            }
534
535                            //get the image id from the name of the photo.
536                            //it's possible that filenames can be re-used so
537                            //look for possible matches
538                            for (i = 0; i < MAX_DUPLICATE_FILENAMES; i++)
539                            {
540                                piwigo_image_id[i] = -1;
541                            }
542                            piwigo_photo_filename_count = 0;
543                            GetPiwigoImageID(piwigo_photo_name, PiwigoDBConn,
544                                PwigoDBPrefixTextBox.Text, ref piwigo_image_id,
545                                ref piwigo_photo_filename_count);
546
547                            if (piwigo_photo_filename_count == 0)
548                            {
549                                continue;
550                            }
551
552                            //now there's potential photos but let's see if we can
553                            //track the photo id to the appropriate album id
554                            piwigo_unique_image_id = -1;
555                            GetPiwigoUniqueImageID(piwigo_image_id, piwigo_photo_filename_count,
556                                piwigo_category_id, PiwigoDBConn, PwigoDBPrefixTextBox.Text, ref piwigo_unique_image_id);
557
558                            if (piwigo_unique_image_id == -1)
559                            {
560                                continue;
561                            }
562
563                            //now we have photo id and album id and face tag id
564                            //we can finally add it to the database
565                            already_tagged = false;
566                            SetPiwigoPhotoTag(piwigo_unique_image_id, face_tag_id,
567                                PiwigoDBConn, PwigoDBPrefixTextBox.Text, ref already_tagged);
568                            face_tags_moved++;
569                            piwigo_person_tag_count[k]++;
570                            if ((face_tags_moved % 10) == 0)
571                            {
572                                WriteStatusTextAppend(" .");
573                            }
574                            if (already_tagged)
575                            {
576                                already_tagged_count++;
577                            }
578                        }
579                        taginfile.Close();
580                    }
581                    PiwigoDBConn.CloseConnection();
582                }
583            }
584           
585            if (SetTagsInPiwigoCheckBox.Checked)
586            {
587                WriteStatusText("Piwigo Face Tag Summary:");
588                for (i = 0; i < person_count; i++)
589                {
590                   WriteStatusText("     " + contact_array[i].name + " " + 
591                       piwigo_person_tag_count[i].ToString());                   
592                }
593                WriteStatusText("Number of face tags found that were already in Piwigo: " + 
594                    already_tagged_count.ToString());
595                WriteStatusText("Total number of face tags found:  " + face_tags_moved.ToString());
596            }
597            ExecuteBtn.Enabled = true;
598            WriteStatusText("Finished");         
599            this.Refresh();
600            this.StatusTextBox.Update();
601            Application.DoEvents();
602        }
603
604        public void WriteStatusText(string status_to_write)
605        {
606            StatusTextBox.Text = StatusTextBox.Text + Environment.NewLine + status_to_write; 
607            StatusTextBox.SelectionStart = StatusTextBox.Text.Length - status_to_write.Length - Environment.NewLine.Length;
608            StatusTextBox.ScrollToCaret();
609        }
610        public void WriteStatusTextAppend(string status_to_append)
611        {
612            StatusTextBox.Text = StatusTextBox.Text +  status_to_append;
613            StatusTextBox.SelectionStart = StatusTextBox.Text.Length - status_to_append.Length - Environment.NewLine.Length;
614            StatusTextBox.ScrollToCaret();
615        }
616
617        private void SetPhotoPathBtn_Click(object sender, EventArgs e)
618        {
619            FolderBrowserDialog openFile2 = new FolderBrowserDialog();           
620            if (openFile2.ShowDialog() == System.Windows.Forms.DialogResult.OK)
621            {
622                FormSettings.Default.PicasaPhotoPathSetting = openFile2.SelectedPath;
623                FormSettings.Default.Save();
624                PicasaRootPhotoPathTextBox.Text = openFile2.SelectedPath;
625                RootPathSet = true;
626                RootPathStr = openFile2.SelectedPath;
627                if (ContactPathSet && RootPathSet && OutputPathSet)
628                {
629                    ExecuteBtn.Enabled = true;
630                }
631            }
632        }
633
634        private void SetOutputPathBtn_Click(object sender, EventArgs e)
635        {
636            FolderBrowserDialog openFile3 = new FolderBrowserDialog();
637            if (openFile3.ShowDialog() == System.Windows.Forms.DialogResult.OK)
638            {
639                FormSettings.Default.OutputPathSetting = openFile3.SelectedPath;
640                FormSettings.Default.Save();
641                PicasaOutputPathTextBox.Text = openFile3.SelectedPath;
642                OutputPathSet = true;
643                OutputPathStr = openFile3.SelectedPath;
644                if (ContactPathSet && RootPathSet && OutputPathSet)
645                {
646                    ExecuteBtn.Enabled = true;
647                }
648            }
649
650        }
651        public void SearchForNamesInExif(ref bool[] found_contact_in_photo_array, PersonIDStruct[] contact_array, string filename, int person_count)
652        {
653            byte[] filedata = new byte[100*1024];
654            byte[] name_sig = new byte[] {0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 
655                0x70, 0x74, 0x69, 0x6F, 0x6E, 0x20, 0x6D, 0x77, 0x67, 0x2D, 0x72, 0x73, 0x3A, 
656                0x4E, 0x61, 0x6D, 0x65, 0x3D, 0x22 };
657            int temp1, temp2, k, i;
658            UInt16 signature, exif_length;
659            string name_from_photo, tempstr;
660            byte[] temp_array = new byte[1];
661
662            try
663            {
664                BinaryReader b = new BinaryReader(File.Open(filename, FileMode.Open));
665
666                signature = b.ReadUInt16();
667                if (signature != 0xD8FF)
668                {
669                    b.Close();
670                    return;
671                }
672                signature = b.ReadUInt16();
673                if (signature != 0xE1FF && signature != 0xE0FF)
674                {
675                    b.Close();
676                    return;
677                }
678                for (i = 0; i < 2; i++)
679                {
680                    //get length
681                    temp1 = b.ReadByte();
682                    temp2 = b.ReadByte();
683                    exif_length = (UInt16)((temp1 << 8) + temp2);
684                    filedata = b.ReadBytes(exif_length - 1);
685                    k = 0;
686                    do
687                    {
688                        k = SearchForNameXML(filedata, name_sig, k, exif_length);
689                        if (k != -1)
690                        {
691                            name_from_photo = "";
692                            do
693                            {
694                                //found a name
695                                temp_array[0] = filedata[k];
696                                tempstr = Encoding.Default.GetString(temp_array);
697                                if (tempstr != "\"")
698                                {
699                                    name_from_photo += tempstr;
700                                }
701                                else
702                                {
703                                    if (name_from_photo.Substring(0, 1) == "0")
704                                    {
705                                        name_from_photo = name_from_photo.Substring(1);
706                                    }
707                                    //have name, search for it in array
708                                    for (i = 0; i < person_count; i++)
709                                    {
710                                        if (name_from_photo == contact_array[i].name)
711                                        {
712                                            found_contact_in_photo_array[i] = true;
713                                            break;
714                                        }
715                                    }
716                                    break;
717                                }
718                                k++;
719                            } while (tempstr != "\"");
720                        }
721                        k++;
722                    } while (k != 0);
723                    Array.Clear(filedata, 0, exif_length - 1);
724                }
725
726
727                b.Close();
728            }
729            catch (IOException e)
730            {
731                e.ToString();
732                return;
733            }
734            catch (Exception e)
735            {
736                e.ToString();
737                return;
738            }
739        }
740        public int SearchForNameXML(byte[] filedata, byte[] name_sig, int k, int exif_length)
741        {
742
743            byte firstByte = name_sig[0];
744            int index = -1;
745            int n, match_count;
746
747            n = k;           
748            do
749            {
750                match_count = 0;
751                if ((index = Array.IndexOf(filedata, firstByte, n)) >= 0)
752                {
753                    for (int i = 0; i < name_sig.Length; i++)
754                    {
755                        if (index + i > exif_length - 2)
756                        {
757                            break;
758                        }
759                        if (name_sig[i] != filedata[index + i])
760                        {
761                            break;
762                        }
763                        else
764                        {
765                            match_count++;
766                        }
767                    }
768                    if (match_count == name_sig.Length)
769                    {
770                        //found a person
771                        return index + name_sig.Length;                       
772                    }
773                }
774                n = index + 1;
775            }  while (index != -1);
776            return index;
777        }
778
779        private void GenerateHTMLCheckBox_CheckedChanged(object sender, EventArgs e)
780        {
781            if (GenerateHTMLCheckBox.Checked)
782            {
783                BaseURLTextBox.Enabled = true;
784            }
785            else
786            {
787                BaseURLTextBox.Enabled = false;               
788            }
789            FormSettings.Default.GeneratHTMLSetting = GenerateHTMLCheckBox.Checked;
790            FormSettings.Default.Save();
791        }
792
793        private void SetTagsInPiwigoCheckBox_CheckedChanged(object sender, EventArgs e)
794        {
795            if (SetTagsInPiwigoCheckBox.Checked)
796            {
797                ServerNameTextBox.Enabled = true;
798                PiwigoDatabaseTextBox.Enabled = true;
799                PiwigoDBUserNameTextBox.Enabled = true;
800                PiwigoDBPwdTextBox.Enabled = true;
801                ClearPiwigoTagsCheckbox.Enabled = true;
802                PwigoDBPrefixTextBox.Enabled = true;
803            }
804            else
805            {
806                ServerNameTextBox.Enabled = false;
807                PiwigoDatabaseTextBox.Enabled = false;
808                PiwigoDBUserNameTextBox.Enabled = false;
809                PiwigoDBPwdTextBox.Enabled = false;
810                ClearPiwigoTagsCheckbox.Enabled = false;
811                PwigoDBPrefixTextBox.Enabled = false;
812            }
813            FormSettings.Default.SetPiwigoTagSetting = SetTagsInPiwigoCheckBox.Checked;
814            FormSettings.Default.Save();
815        }
816        public bool ClearPiwigoTags(int person_count, PersonIDStruct[] contact_array,
817            DBConnect PiwigoDBConn, string piwigo_table_prefix)
818        {
819            int i;
820            string del_query, sel_query, tag_id;
821
822            //connect to database
823            if (PiwigoDBConn.OpenDBConnection() != -1)
824            {
825                return false;
826            }
827
828            for (i = 0; i < person_count; i++)
829            {
830                //get tag id, for later removal from photos listed in db
831                sel_query = "SELECT * FROM " + piwigo_table_prefix + "_tags WHERE name='" + contact_array[i].name.Replace("'","''") + "'";
832                MySqlCommand cmd_sel = new MySqlCommand(sel_query, PiwigoDBConn.connection);
833                MySqlDataReader dataReader = cmd_sel.ExecuteReader();
834                while (dataReader.Read())
835                {
836                    tag_id = dataReader["id"] + "";
837                    dataReader.Close();
838                    //have tag id from list of tags
839                    //now, delete that tag from list of photos with tags
840                    del_query = "DELETE FROM " + piwigo_table_prefix + "_image_tag WHERE tag_id=" + tag_id.ToString() ;
841                    MySqlCommand deltagcmd = new MySqlCommand(del_query, PiwigoDBConn.connection);
842                    deltagcmd.ExecuteNonQuery();
843                    break;
844                }
845                if (!dataReader.IsClosed)
846                {
847                    dataReader.Close();
848                }
849
850                //finally, delete tag from list of tags
851                del_query = "DELETE FROM " + piwigo_table_prefix + "_tags WHERE name='" + contact_array[i].name.Replace("'", "''") + "'";
852                MySqlCommand cmd = new MySqlCommand(del_query, PiwigoDBConn.connection);
853                cmd.ExecuteNonQuery();
854            }
855
856            PiwigoDBConn.CloseConnection();
857            return true;
858        }
859
860        public void SetPiwigoTag(string tag_string, DBConnect PiwigoDBConn, 
861            string piwigo_table_prefix, ref int face_tag_id)
862        {
863            string sel_query, tag_id_string, ins_query;
864
865            //see if face tag already exists
866            tag_id_string = "";
867            ins_query = "";
868            sel_query = "SELECT * FROM " + piwigo_table_prefix + "_tags WHERE name='" + tag_string.Replace("'", "''") + "'";
869            MySqlCommand cmd_sel = new MySqlCommand(sel_query, PiwigoDBConn.connection);
870            MySqlDataReader dataReader = cmd_sel.ExecuteReader();
871            while (dataReader.Read())
872            {
873                tag_id_string = dataReader["id"] + "";
874            }
875            dataReader.Close();
876            if (tag_id_string.Length != 0)
877            {
878                face_tag_id = Convert.ToInt32(tag_id_string);
879            }           
880            else
881            {
882                //face tag does not exist, so add it
883                ins_query = "INSERT INTO " + piwigo_table_prefix +
884                    "_tags (name, url_name) VALUES('" + tag_string.Replace("'", "''") + "', '" +
885                    tag_string.Replace("'", "''") + "')";
886                MySqlCommand ins_cmd = new MySqlCommand(ins_query, PiwigoDBConn.connection);
887                ins_cmd.ExecuteNonQuery();
888
889                //now get the face tag id back
890                sel_query = "SELECT * FROM " + piwigo_table_prefix + "_tags WHERE name='" + tag_string.Replace("'", "''") + "'";
891                cmd_sel = new MySqlCommand(sel_query, PiwigoDBConn.connection);
892                dataReader = cmd_sel.ExecuteReader();
893                while (dataReader.Read())
894                {
895                    tag_id_string = dataReader["id"] + "";
896                }
897                dataReader.Close();
898                if (tag_id_string.Length != 0)
899                {
900                    face_tag_id = Convert.ToInt32(tag_id_string);
901                }
902                else
903                {
904                    face_tag_id = -1;
905                }
906            }
907        }
908
909        public void GetPiwigoCategoryID(string piwigo_album_name, DBConnect PiwigoDBConn,
910            string piwigo_table_prefix, ref int piwigo_category_id)
911        {
912            string category_id_string, sel_query;
913
914            category_id_string = "";
915            sel_query = "SELECT * FROM " + piwigo_table_prefix + "_categories WHERE name='" + piwigo_album_name.Replace("'", "''") + "'";
916            MySqlCommand cmd_sel = new MySqlCommand(sel_query, PiwigoDBConn.connection);
917            MySqlDataReader dataReader = cmd_sel.ExecuteReader();
918            while (dataReader.Read())
919            {
920                category_id_string = dataReader["id"] + "";
921            }
922            dataReader.Close();
923            if (category_id_string.Length != 0)
924            {
925                piwigo_category_id = Convert.ToInt32(category_id_string);
926            }
927            else
928            {
929                piwigo_category_id = -1;
930            }                           
931        }
932
933        public void GetPiwigoImageID(string photo_name, DBConnect PiwigoDBConn,
934            string piwigo_table_prefix, ref int[] piwigo_image_id, ref int photo_count)
935        {
936            string sel_query, photo_id_string;           
937
938            photo_id_string = "";
939            photo_count = 0;
940            sel_query = "SELECT * FROM " + piwigo_table_prefix + "_images WHERE file='" + photo_name.Replace("'", "''") + "'";
941            MySqlCommand cmd_sel = new MySqlCommand(sel_query, PiwigoDBConn.connection);
942            MySqlDataReader dataReader = cmd_sel.ExecuteReader();
943            while (dataReader.Read())
944            {
945                photo_id_string = dataReader["id"] + "";
946                piwigo_image_id[photo_count] = Convert.ToInt32(photo_id_string);
947                photo_count++;
948                if (photo_count >= MAX_DUPLICATE_FILENAMES)
949                {
950                    break;
951                }
952            }
953            dataReader.Close();
954        }
955        public string GetPiwigoDBVersion(DBConnect PiwigoDBConn, string piwigo_table_prefix)
956        {
957            string dbversion, sel_query;
958           
959            dbversion = "";
960            sel_query = "SELECT value FROM " + piwigo_table_prefix + "_config WHERE param = 'piwigo_db_version'";
961            MySqlCommand cmd_sel = new MySqlCommand(sel_query, PiwigoDBConn.connection);
962            MySqlDataReader dataReader = cmd_sel.ExecuteReader();
963            dataReader.Read();
964            dbversion = dataReader["value"] + "";
965            dataReader.Close();
966            return dbversion;
967        }
968
969        public void GetPiwigoUniqueImageID(int[] piwigo_image_id, int piwigo_photo_filename_count,
970            int piwigo_category_id, DBConnect PiwigoDBConn, string piwigo_table_prefix, ref int piwigo_unique_image_id)
971        {
972            int i;
973            string sel_query;
974
975            piwigo_unique_image_id = -1;
976            for (i = 0; i < MAX_DUPLICATE_FILENAMES; i++)
977            {
978                if (piwigo_image_id[i] == -1)
979                {
980                    break;
981                }
982                sel_query = "SELECT * FROM " + piwigo_table_prefix + "_image_category WHERE category_id=" + piwigo_category_id +
983                    " AND image_id=" + piwigo_image_id[i];
984                MySqlCommand cmd_sel = new MySqlCommand(sel_query, PiwigoDBConn.connection);
985                MySqlDataReader dataReader = cmd_sel.ExecuteReader();
986                while (dataReader.Read())
987                {
988                    piwigo_unique_image_id = piwigo_image_id[i];
989                    break;
990                }
991                if (piwigo_unique_image_id != -1)
992                {
993                    dataReader.Close();
994                    break;
995                }
996                dataReader.Close();
997            }           
998        }
999        public void SetPiwigoPhotoTag(int piwigo_unique_image_id, int face_tag_id,
1000            DBConnect PiwigoDBConn, string piwigo_table_prefix, ref bool already_tagged)
1001        {
1002            string sel_query, ins_query;
1003
1004            already_tagged = false;
1005
1006            //let's see if the tag is already in the database
1007            sel_query = "SELECT * FROM " + piwigo_table_prefix + "_image_tag WHERE image_id=" + piwigo_unique_image_id +
1008                " AND tag_id=" + face_tag_id;
1009            MySqlCommand cmd_sel = new MySqlCommand(sel_query, PiwigoDBConn.connection);
1010            MySqlDataReader dataReader = cmd_sel.ExecuteReader();
1011            while (dataReader.Read())
1012            {
1013                already_tagged = true;
1014                dataReader.Close();
1015                return;
1016            }
1017            dataReader.Close();
1018
1019            //add tag to photo
1020            ins_query = "INSERT INTO " + piwigo_table_prefix +
1021                "_image_tag (image_id, tag_id) VALUES(" + piwigo_unique_image_id + ", " +
1022                face_tag_id + ")";
1023            MySqlCommand ins_cmd = new MySqlCommand(ins_query, PiwigoDBConn.connection);
1024            ins_cmd.ExecuteNonQuery();
1025        }
1026
1027        private void Form1_Load(object sender, EventArgs e)
1028        {
1029            BaseURLTextBox.Text = FormSettings.Default.BaseURLSetting;
1030            GenerateHTMLCheckBox.Checked = FormSettings.Default.GeneratHTMLSetting;
1031            SetTagsInPiwigoCheckBox.Checked = FormSettings.Default.SetPiwigoTagSetting;
1032            ServerNameTextBox.Text = FormSettings.Default.ServerNameSetting;
1033            PiwigoDatabaseTextBox.Text = FormSettings.Default.DBNameSetting;
1034            PiwigoDBUserNameTextBox.Text = FormSettings.Default.DBUserNameSetting;
1035            PiwigoDBPwdTextBox.Text = FormSettings.Default.DBPasswordSetting;
1036            PwigoDBPrefixTextBox.Text = FormSettings.Default.DBTablePrefixSetting;
1037            ClearPiwigoTagsCheckbox.Checked = FormSettings.Default.ClearFaceTagSetting;
1038            PicasaContactsFileTextBox.Text = FormSettings.Default.PicasaContactsFileSetting;
1039            PicasaOutputPathTextBox.Text = FormSettings.Default.OutputPathSetting;
1040            PicasaRootPhotoPathTextBox.Text = FormSettings.Default.PicasaPhotoPathSetting;
1041
1042            if (PicasaContactsFileTextBox.Text.Length > 3)
1043            {
1044                ContactPathSet = true;
1045            }
1046
1047            if (PicasaOutputPathTextBox.Text.Length > 3)
1048            {
1049                OutputPathSet = true;
1050            }
1051
1052            if (PicasaRootPhotoPathTextBox.Text.Length > 3)
1053            {
1054                RootPathSet = true;
1055            }
1056            if (ContactPathSet && OutputPathSet && RootPathSet)
1057            {
1058                ExecuteBtn.Enabled = true;
1059            }
1060            ContactPathStr = PicasaContactsFileTextBox.Text;
1061            OutputPathStr = PicasaOutputPathTextBox.Text;
1062            RootPathStr = PicasaRootPhotoPathTextBox.Text;
1063        }
1064
1065        private void BaseURLTextBox_TextChanged(object sender, EventArgs e)
1066        {
1067            FormSettings.Default.BaseURLSetting = BaseURLTextBox.Text;
1068            FormSettings.Default.Save();
1069        }
1070
1071        private void ServerNameTextBox_TextChanged(object sender, EventArgs e)
1072        {
1073            FormSettings.Default.ServerNameSetting = ServerNameTextBox.Text;
1074            FormSettings.Default.Save();
1075
1076        }
1077
1078        private void PiwigoDatabaseTextBox_TextChanged(object sender, EventArgs e)
1079        {
1080            FormSettings.Default.DBNameSetting = PiwigoDatabaseTextBox.Text;
1081            FormSettings.Default.Save();
1082        }
1083
1084        private void PiwigoDBUserNameTextBox_TextChanged(object sender, EventArgs e)
1085        {
1086            FormSettings.Default.DBUserNameSetting = PiwigoDBUserNameTextBox.Text;
1087            FormSettings.Default.Save();
1088        }
1089
1090        private void PiwigoDBPwdTextBox_TextChanged(object sender, EventArgs e)
1091        {
1092            FormSettings.Default.DBPasswordSetting = PiwigoDBPwdTextBox.Text;
1093            FormSettings.Default.Save();
1094        }
1095
1096        private void PwigoDBPrefixTextBox_TextChanged(object sender, EventArgs e)
1097        {
1098            FormSettings.Default.DBTablePrefixSetting = PwigoDBPrefixTextBox.Text;
1099            FormSettings.Default.Save();
1100        }
1101
1102        private void ClearPiwigoTagsCheckbox_CheckedChanged(object sender, EventArgs e)
1103        {
1104            FormSettings.Default.ClearFaceTagSetting = ClearPiwigoTagsCheckbox.Checked;
1105            FormSettings.Default.Save();
1106        }
1107
1108        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
1109        {
1110            formhasbeenclosed = true;
1111        }
1112
1113
1114    }
1115    public class DBConnect
1116    {
1117        public MySqlConnection connection;
1118        private string server;
1119        private string database;
1120        private string uid;
1121        private string password;
1122
1123        //Initialize values
1124        public void InitializeDBConnection(string servername, string database_name,
1125            string database_username, string database_password)
1126        {
1127            server = servername;
1128            database = database_name;
1129            uid = database_username;
1130            password = database_password;
1131            string connectionString;
1132            connectionString = "SERVER=" + server + ";" + "DATABASE=" +
1133            database + ";" + "UID=" + uid + ";" + "PASSWORD=" + password + ";port=3306;";
1134
1135            connection = new MySqlConnection(connectionString);
1136        }
1137
1138        //open connection to database
1139        public int OpenDBConnection()
1140        {
1141            try
1142            {
1143                connection.Open();
1144                return -1;
1145            }
1146            catch (MySqlException ex)
1147            {
1148                //When handling errors, you can your application's response based
1149                //on the error number.
1150                //The two most common error numbers when connecting are as follows:
1151                //0: Cannot connect to server.
1152                //1045: Invalid user name and/or password.
1153                return ex.Number;
1154            }
1155        }
1156
1157        //Close connection
1158        public int CloseConnection()
1159        {
1160            try
1161            {
1162                connection.Close();
1163                return -1;
1164            }
1165            catch (MySqlException ex)
1166            {
1167                return ex.Number;
1168            }
1169        }
1170    }
1171}
Note: See TracBrowser for help on using the repository browser.