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 System.Diagnostics; using System.IO; using System.Net; using System.Xml; using System.Resources; using System.Globalization; using System.Threading; using Picasa2PiwigoConstants; namespace Picasa2Piwigo { using Picasa2PiwigoConstants; using Picasa2PiwigoCommonFunctions; public partial class StatusForm : Form { bool stop_button_pressed = false; int command_to_run; string[] local_command_line_args; int[] piwigo_person_tag_count = new int[constants.MAX_NUMBER_OF_CONTACTS]; CookieContainer cookiesjar = new CookieContainer(); public StatusForm(int command, string[] command_line_args) { CultureInfo ci; ci = new CultureInfo(Thread.CurrentThread.CurrentCulture.Name); Thread.CurrentThread.CurrentUICulture = ci; Thread.CurrentThread.CurrentCulture = ci; if (Picasa2PiwigoConstants.constants.DEBUG_LOCALE) { #pragma warning disable 0162 Thread.CurrentThread.CurrentUICulture = new CultureInfo(Picasa2PiwigoConstants.constants.SET_LOCALE); #pragma warning restore 0162 } InitializeComponent(); command_to_run = command; local_command_line_args = command_line_args; } private void StatusForm_Load(object sender, EventArgs e) { bool step_passed; XmlDocument TagList = new XmlDocument(); XmlDocument AlbumList = new XmlDocument(); int NewPiwigoAlbumId; string PiwigoVersionNumber; this.button1.Text = WinFormStrings.SFbutton1StrRes; this.Text = WinFormStrings.SFCaptionsStrRes; this.label1.Text = WinFormStrings.SFlabel1StrRes; LabelAdjust AdjustLabelClass = new LabelAdjust(); AdjustLabelClass.AdjustLabelSize(label1); AdjustLabelClass.AdjustButtonSize(button1); DialogResult = DialogResult.Yes; this.Show(); StatusRefresh(); //4. Retrieve tags //SetStatus("Retrieving tags..."); //step_passed = UpdateStatus(SyncPiwigoGetTags(ref TagList)); //if (!step_passed) // { // return; //} switch (command_to_run) { case constants.COMMAND_START_UP: WriteLog("Start up"); //1. Reading Picasa contacts SetStatus(WinFormStrings.ReadContactsFileStrRes); step_passed = UpdateStatus((SyncPiwigoReadPicasaContacts())); if (stop_button_pressed) { return; } if (!step_passed) { return; } //2. Validate that server can be reached SetStatus(WinFormStrings.CheckServerConnStrRes); step_passed = UpdateStatus((SyncPiwigoCheckServerStatus())); if (!step_passed) { return; } if (stop_button_pressed) { return; } //3. Login SetStatus(WinFormStrings.LogInStrRes); step_passed = UpdateStatus(SyncPiwigoLogIn()); if (!step_passed) { return; } if (stop_button_pressed) { return; } //4. Get Piwigo Version PiwigoVersionNumber = ""; SetStatus(WinFormStrings.GetPiwigoVersionStrRes); step_passed = UpdateStatus(SyncPiwigoGetVersion(ref PiwigoVersionNumber)); if (stop_button_pressed) { return; } GlobalClass.PiwigoVersionNumber = PiwigoVersionNumber; //5. Get list of albums SetStatus(WinFormStrings.RetrieveAlbumListStRes); step_passed = UpdateStatus(SyncPiwigoGetAlbums(ref AlbumList)); if (step_passed) { GlobalClass.AlbumList = AlbumList; return; } if (stop_button_pressed) { return; } break; case constants.COMMAND_ADD_TO_ALBUM: WriteLog("Add to Album"); //1. Validate that server can be reached SetStatus(WinFormStrings.CheckServerConnStrRes); step_passed = UpdateStatus((SyncPiwigoCheckServerStatus())); if (!step_passed) { return; } if (stop_button_pressed) { return; } //2. Login SetStatus(WinFormStrings.LogInStrRes); step_passed = UpdateStatus(SyncPiwigoLogIn()); if (!step_passed) { return; } if (stop_button_pressed) { return; } //3. upload photos NewPiwigoAlbumId = GlobalClass.AddAlbumCategoryID; SetStatus(WinFormStrings.UploadPhotosStrRes); step_passed = UpdateStatus(SyncPiwigoAddPhoto(NewPiwigoAlbumId)); if (!step_passed) { return; } if (stop_button_pressed) { return; } break; case constants.COMMAND_NEW_ALBUM: WriteLog("New Album"); //1. Validate that server can be reached SetStatus(WinFormStrings.CheckServerConnStrRes); step_passed = UpdateStatus((SyncPiwigoCheckServerStatus())); if (!step_passed) { return; } if (stop_button_pressed) { return; } //2. Login SetStatus(WinFormStrings.LogInStrRes); step_passed = UpdateStatus(SyncPiwigoLogIn()); if (!step_passed) { return; } if (stop_button_pressed) { return; } //3. Create new album SetStatus(WinFormStrings.CreateNewAlbumRes); NewPiwigoAlbumId = -1; step_passed = UpdateStatus(SyncPiwigoCreateAlbum(ref NewPiwigoAlbumId)); if (!step_passed) { return; } if (stop_button_pressed) { return; } //4. upload photos SetStatus(WinFormStrings.UploadPhotosStrRes); step_passed = UpdateStatus(SyncPiwigoAddPhoto(NewPiwigoAlbumId)); if (!step_passed) { return; } if (stop_button_pressed) { return; } break; } } public int SearchForNameXML(byte[] filedata, byte[] name_sig, int k, int exif_length) { byte firstByte = name_sig[0]; int index = -1; int n, match_count; n = k; do { match_count = 0; if ((index = Array.IndexOf(filedata, firstByte, n)) >= 0) { for (int i = 0; i < name_sig.Length; i++) { if (index + i > exif_length - 2) { break; } if (name_sig[i] != filedata[index + i]) { break; } else { match_count++; } } if (match_count == name_sig.Length) { //found a person return index + name_sig.Length; } } n = index + 1; } while (index != -1); return index; } private static int ByteSearch(byte[] searchIn, byte[] searchBytes, int start) { int found = -1; bool matched = false; //only look at this if we have a populated search array and search bytes with a sensible start if (searchIn.Length > 0 && searchBytes.Length > 0 && start <= (searchIn.Length - searchBytes.Length) && searchIn.Length >= searchBytes.Length) { //iterate through the array to be searched for (int i = start; i <= searchIn.Length - searchBytes.Length; i++) { //if the start bytes match we will start comparing all other bytes if (searchIn[i] == searchBytes[0]) { if (searchIn.Length > 1) { //multiple bytes to be searched we have to compare byte by byte matched = true; for (int y = 1; y <= searchBytes.Length - 1; y++) { if (searchIn[i + y] != searchBytes[y]) { matched = false; break; } } //everything matched up if (matched) { found = i; break; } } else { //search byte is only one bit nothing else to do found = i; break; //stop the loop } } } } return found; } public string GetCommentListFromXml(string xmlstring) { string tag_list, s; int j, k, l, m, n; tag_list = ""; k = xmlstring.IndexOf(""); if (k != -1) { l = xmlstring.IndexOf("/dc:description", k); if (l != -1) { j = k; do { j = xmlstring.IndexOf("", j); if (n != -1 && n < l) { m = xmlstring.IndexOf("", j); if (m != -1 && m < l) { s = xmlstring.Substring(n + 1, m - n - 1); tag_list += RemoveCommaFromContract(s); tag_list += ","; } } } } while (j != -1); } } if (tag_list.Length > 1) { tag_list = tag_list.Substring(0, tag_list.Length - 1); } return tag_list; } public string GetTagListFromXml(string xmlstring) { string tag_list, s; int j, k, l, m; tag_list = ""; k = xmlstring.IndexOf(""); if (k != -1) { l = xmlstring.IndexOf("",k); if (l != -1) { j = k; do { j = xmlstring.IndexOf("", j+1); if (j != -1 && j < l) { m = xmlstring.IndexOf("", j); if (m != -1 && m < l) { s = xmlstring.Substring(j + 8, m - j - 8); tag_list += RemoveCommaFromContract(s); tag_list += ","; } } } while (j != -1); } } if (tag_list.Length > 1) { tag_list = tag_list.Substring(0, tag_list.Length - 1); } return tag_list; } public void SyncPiwigoGetTagsandComments(ref string tag_list, ref string comment_list, string filename) { byte[] filedata = new byte[100 * 1024]; byte[] name_sig = new byte[] {0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6F, 0x6E, 0x20, 0x6D, 0x77, 0x67, 0x2D, 0x72, 0x73, 0x3A, 0x4E, 0x61, 0x6D, 0x65, 0x3D, 0x22 }; int temp1, temp2, k, i, l, m; UInt16 signature, exif_length; byte[] temp_array = new byte[1]; byte[] xml_start = { 0x3C, 0x78, 0x3A, 0x78, 0x6D, 0x70, 0x6D, 0x65, 0x74, 0x61 }; byte[] xml_end = { 0x3C, 0x2F, 0x78, 0x3A, 0x78, 0x6D, 0x70, 0x6D, 0x65, 0x74, 0x61, 0x3E }; string xml_content; XmlDocument xmldoc = new XmlDocument(); try { BinaryReader b = new BinaryReader(File.Open(filename, FileMode.Open)); signature = b.ReadUInt16(); if (signature != 0xD8FF) { b.Close(); return; } signature = b.ReadUInt16(); if (signature != 0xE1FF && signature != 0xE0FF) { b.Close(); return; } for (i = 0; i < 2; i++) { //get length temp1 = b.ReadByte(); temp2 = b.ReadByte(); exif_length = (UInt16)((temp1 << 8) + temp2); filedata = b.ReadBytes(exif_length - 1); //search file data for xml l = -1; k = ByteSearch(filedata, xml_start, 0); if (k != -1) { l = ByteSearch(filedata, xml_end, k); } if (k != -1 && l != -1) { xml_content = System.Text.Encoding.UTF8.GetString(filedata, k, l - k + xml_end.Length); tag_list = GetTagListFromXml(xml_content); comment_list = GetCommentListFromXml(xml_content); break; } m = exif_length; if (m > filedata.Length) { m = filedata.Length + 1; } Array.Clear(filedata, 0, m - 1); } b.Close(); } catch (IOException e) { e.ToString(); return; } catch (Exception e) { e.ToString(); return; } } public void SearchForNamesInExif(ref bool[] found_contact_in_photo_array, constants.PersonIDStruct[] contact_array, string filename, int person_count) { byte[] filedata = new byte[100 * 1024]; byte[] name_sig = new byte[] {0x44, 0x65, 0x73, 0x63, 0x72, 0x69, 0x70, 0x74, 0x69, 0x6F, 0x6E, 0x20, 0x6D, 0x77, 0x67, 0x2D, 0x72, 0x73, 0x3A, 0x4E, 0x61, 0x6D, 0x65, 0x3D, 0x22 }; int temp1, temp2, k, i, m; UInt16 signature, exif_length; string name_from_photo, tempstr; byte[] temp_array = new byte[1]; try { BinaryReader b = new BinaryReader(File.Open(filename, FileMode.Open)); signature = b.ReadUInt16(); if (signature != 0xD8FF) { b.Close(); return; } signature = b.ReadUInt16(); if (signature != 0xE1FF && signature != 0xE0FF) { b.Close(); return; } for (i = 0; i < 2; i++) { //get length temp1 = b.ReadByte(); temp2 = b.ReadByte(); exif_length = (UInt16)((temp1 << 8) + temp2); filedata = b.ReadBytes(exif_length - 1); k = 0; do { k = SearchForNameXML(filedata, name_sig, k, exif_length); if (k != -1) { name_from_photo = ""; do { //found a name temp_array[0] = filedata[k]; tempstr = Encoding.Default.GetString(temp_array); if (tempstr != "\"") { name_from_photo += tempstr; } else { if (name_from_photo.Substring(0, 1) == "0") { name_from_photo = name_from_photo.Substring(1); } //have name, search for it in array for (i = 0; i < person_count; i++) { if (name_from_photo == contact_array[i].name) { found_contact_in_photo_array[i] = true; break; } } break; } k++; } while (tempstr != "\""); } k++; } while (k != 0); m = exif_length; if (m > filedata.Length) { m = filedata.Length + 1; } Array.Clear(filedata, 0, m - 1); } b.Close(); } catch (IOException e) { e.ToString(); return; } catch (Exception e) { e.ToString(); return; } } public string RemoveCommaFromContract(string contact) { string cleaned_name, s, t; int k; cleaned_name = contact; //do we have to remove commma if (HaveToRemoveComma()) { do { k = cleaned_name.IndexOf(","); if (k != -1) { s = cleaned_name.Substring(0, k); t = cleaned_name.Substring(k + 1); cleaned_name = s + t; } } while (k != -1); } else { //commas are ok, so escape them cleaned_name = cleaned_name.Replace(",", "/,"); } return cleaned_name; } public string SyncPiwigoGetFaceTags(string filename) { int k, l; string filepath, inidata, photofilename, photo_file_name, ini_unique_id; string face_tag_list; bool[] found_contact_in_photo_array = new bool[256]; bool found_photo; bool finished_faces, found_person; System.IO.StreamReader inifile; face_tag_list = ""; k = filename.LastIndexOf("\\"); filepath = filename.Substring(0, k); photofilename = filename.Substring(k + 1); photo_file_name = ""; //if it's a video file then skip it if (photofilename.ToLower().IndexOf(".jpg", StringComparison.OrdinalIgnoreCase) == -1 && photofilename.ToLower().IndexOf(".gif", StringComparison.OrdinalIgnoreCase) == -1 && photofilename.ToLower().IndexOf(".png", StringComparison.OrdinalIgnoreCase) == -1 && photofilename.ToLower().IndexOf(".tga", StringComparison.OrdinalIgnoreCase) == -1 && photofilename.ToLower().IndexOf(".tif", StringComparison.OrdinalIgnoreCase) == -1 && photofilename.ToLower().IndexOf(".tiff", StringComparison.OrdinalIgnoreCase) == -1 && photofilename.ToLower().IndexOf(".psd", StringComparison.OrdinalIgnoreCase) == -1) { return face_tag_list; } //parse photo for (k = 0; k < GlobalClass.person_count; k++) { found_contact_in_photo_array[k] = false; } SearchForNamesInExif(ref found_contact_in_photo_array, GlobalClass.contact_array, filename, GlobalClass.person_count); for (k = 0; k < GlobalClass.person_count; k++) { if (found_contact_in_photo_array[k]) { face_tag_list += RemoveCommaFromContract(GlobalClass.contact_array[k].name) + ","; } } inifile = null; if (File.Exists(filepath + "\\.picasa.ini")) { try { inifile = new System.IO.StreamReader(filepath + "\\.picasa.ini"); } catch { if (face_tag_list.Length > 1) { face_tag_list = face_tag_list.Substring(0, face_tag_list.Length - 1); } return face_tag_list; } } else if (File.Exists(filepath + "\\Picasa.ini")) { try { inifile = new System.IO.StreamReader(filepath + "\\Picasa.ini"); } catch { if (face_tag_list.Length > 1) { face_tag_list = face_tag_list.Substring(0, face_tag_list.Length - 1); } return face_tag_list; } } k = 0; found_photo = false; if (inifile != null) { while ((inidata = inifile.ReadLine()) != null) { if (inidata.Length > 4) { if (inidata.Substring(0, 1) == "[") { found_photo = false; k = inidata.IndexOf("]"); if (k != -1) { photo_file_name = inidata.Substring(1, k - 1); } if (photo_file_name.ToUpper() != photofilename.ToUpper()) { continue; } if (photo_file_name.ToLower().IndexOf(".jpg", StringComparison.OrdinalIgnoreCase) != -1 || photo_file_name.ToLower().IndexOf(".gif", StringComparison.OrdinalIgnoreCase) != -1 || photo_file_name.ToLower().IndexOf(".png", StringComparison.OrdinalIgnoreCase) != -1 || photo_file_name.ToLower().IndexOf(".tga", StringComparison.OrdinalIgnoreCase) != -1 || photo_file_name.ToLower().IndexOf(".tif", StringComparison.OrdinalIgnoreCase) != -1 || photo_file_name.ToLower().IndexOf(".tiff", StringComparison.OrdinalIgnoreCase) != -1 || photo_file_name.ToLower().IndexOf(".psd", StringComparison.OrdinalIgnoreCase) != -1) { found_photo = true; } } else if (inidata.Substring(0, 6) == "faces=" && found_photo) { finished_faces = false; k = 0; do { k = inidata.IndexOf("),", k); if (k != -1) { l = inidata.IndexOf(";", k); if (l == -1) { l = inidata.Length; } if (l != -1) { ini_unique_id = inidata.Substring(k + 2, l - k - 2); //found face in a picture, but who? l = 0; found_person = false; do { if (GlobalClass.picasa_unique_id_arrary[l].unique_id == ini_unique_id) { //did we already find this person? if (found_contact_in_photo_array[l] == false) { found_person = true; break; } } l++; } while (l < GlobalClass.unique_id_count); //found person if (found_person) { if (photo_file_name.Length > 3) { face_tag_list += GlobalClass.contact_array[l].name + ","; } } } k++; } else { finished_faces = true; } } while (!finished_faces); } } } } //remove last comma if (face_tag_list.Length > 1) { face_tag_list = face_tag_list.Substring(0, face_tag_list.Length - 1); } return face_tag_list; } public bool SyncPiwigoReadPicasaContacts() { int i, k, l; string filedata, person_str, unique_id; bool person_exists; System.IO.StreamReader file; try { file = new System.IO.StreamReader(FormSettings.Default.PicasaContactsLocation); } catch (Exception e) { GlobalClass.StatusDialogErrorMessage = WinFormStrings.UnableToOpenContactsStrRes + " " + e.Message; return false; } for (i = 0; i < constants.MAX_NUMBER_OF_CONTACTS; i++) { piwigo_person_tag_count[i] = 0; } GlobalClass.person_count = 0; GlobalClass.unique_id_count = 0; while ((filedata = file.ReadLine()) != null) { //parse name and unique id k = filedata.IndexOf("contact id="); if (k != -1) { unique_id = filedata.Substring(k + 12, 16); k = filedata.IndexOf("name="); l = filedata.IndexOf("\"", k + 6); person_str = filedata.Substring(k + 6, (l - k - 6)); Debug.WriteLine("Person: " + person_str + " ID: " + unique_id); //does this person already exist person_exists = false; for (i = 0; i < GlobalClass.person_count; i++) { if (person_str == GlobalClass.contact_array[i].name) { person_exists = true; break; } } if (!person_exists) { GlobalClass.contact_array[GlobalClass.person_count].name = person_str; GlobalClass.contact_array[GlobalClass.person_count].index = GlobalClass.person_count; GlobalClass.picasa_unique_id_arrary[GlobalClass.unique_id_count].unique_id = unique_id; GlobalClass.picasa_unique_id_arrary[GlobalClass.unique_id_count].index = GlobalClass.person_count; GlobalClass.person_count++; } else { GlobalClass.picasa_unique_id_arrary[GlobalClass.unique_id_count].unique_id = unique_id; GlobalClass.picasa_unique_id_arrary[GlobalClass.unique_id_count].index = i; } GlobalClass.unique_id_count++; } Debug.WriteLine("Number of contacts: " + GlobalClass.person_count.ToString()); } return true; } public bool SyncPiwigoCheckServerStatus() { string WebResponse, WebRequest, xmlResponse; WebRequest = FormSettings.Default.PiwigoUrlSetting + "/ws.php?method=pwg.session.getStatus"; WriteLog(WebRequest); WebResponse = SendWebGet(WebRequest); WriteLog(WebResponse); if (WebResponse.IndexOf("An error occurred:") != -1) { GlobalClass.StatusDialogErrorMessage = WebResponse; return false; } xmlResponse = XmlGetAttribute(FilterForXML(WebResponse), "stat"); if (xmlResponse == "ok") { return true; } GlobalClass.StatusDialogErrorMessage = WinFormStrings.UnableToContactServerStrRes; return false; } public bool SyncPiwigoLogIn() { string WebResponse, WebRequest, xmlResponse, PostData; byte[] dummy_data = new byte[1]; bool response; dummy_data[0] = 0; WebRequest = FormSettings.Default.PiwigoUrlSetting + "/ws.php?method=pwg.session.login"; PostData = "username=" + FormSettings.Default.PiwigoUserName + "&password=" + FormSettings.Default.PiwigoPassword; WriteLog(WebRequest); WriteLog(PostData); response = SendWebPost(WebRequest, PostData, "application/x-www-form-urlencoded"); if (!response) { WriteLog("Log In Post Fail."); return false; } WebRequest = FormSettings.Default.PiwigoUrlSetting + "/ws.php?method=pwg.session.getStatus"; WriteLog(WebRequest); WebResponse = SendWebGet(WebRequest); WriteLog(WebResponse); if (WebResponse.IndexOf("An error occurred:") != -1) { GlobalClass.StatusDialogErrorMessage = WebResponse; return false; } xmlResponse = XmlGetElement(FilterForXML(WebResponse), "username"); if (xmlResponse == FormSettings.Default.PiwigoUserName) { return true; } GlobalClass.StatusDialogErrorMessage = WinFormStrings.UnableToLogInStrRes; return false; } public bool SyncPiwigoGetVersion(ref string PiwigoVersionNumber) { string WebResponse, WebRequest, xmlResponse; WebRequest = FormSettings.Default.PiwigoUrlSetting + "/ws.php?method=pwg.getVersion"; WriteLog(WebRequest); WebResponse = SendWebGet(WebRequest); WriteLog(WebResponse); PiwigoVersionNumber = ""; if (WebResponse.IndexOf("An error occurred:") != -1) { GlobalClass.StatusDialogErrorMessage = WebResponse; return false; } xmlResponse = XmlGetAttribute(FilterForXML(WebResponse), "stat"); if (xmlResponse != "ok") { GlobalClass.StatusDialogErrorMessage = WinFormStrings.UnableToGetVersionStrRes; return false; } PiwigoVersionNumber = XmlGetElement(FilterForXML(WebResponse), "rsp"); PiwigoVersionNumber = PiwigoVersionNumber.Substring(1); PiwigoVersionNumber = PiwigoVersionNumber.Substring(0,PiwigoVersionNumber.Length -1); return true; } public bool SyncPiwigoGetAlbums(ref XmlDocument AlbumList) { string WebResponse, WebRequest, xmlResponse; int piwigo_minor_version; piwigo_minor_version = Convert.ToInt32(GlobalClass.PiwigoVersionNumber.Substring(2, 1)); if (piwigo_minor_version >= 6) { WebRequest = FormSettings.Default.PiwigoUrlSetting + "/ws.php?method=pwg.categories.getList&fullname=true&recursive=true"; } else { WebRequest = FormSettings.Default.PiwigoUrlSetting + "/ws.php?method=pwg.categories.getList&fullname=\"true\"&recursive=\"false\""; } WriteLog(WebRequest); WebResponse = SendWebGet(WebRequest); WriteLog(WebResponse); if (WebResponse.IndexOf("An error occurred:") != -1) { GlobalClass.StatusDialogErrorMessage = WebResponse; return false; } xmlResponse = XmlGetAttribute(FilterForXML(WebResponse), "stat"); if (xmlResponse == "ok") { AlbumList.LoadXml(FilterForXML(WebResponse)); return true; } GlobalClass.StatusDialogErrorMessage = WinFormStrings.UnableToRetreiveAlbumStrRes; return false; } public bool SyncPiwigoGetTags(ref XmlDocument TagList) { string WebResponse, WebRequest, xmlResponse; WebRequest = FormSettings.Default.PiwigoUrlSetting + "/ws.php?method=pwg.tags.getList"; WriteLog(WebRequest); WebResponse = SendWebGet(WebRequest); WriteLog(WebResponse); if (WebResponse.IndexOf("An error occurred:") != -1) { GlobalClass.StatusDialogErrorMessage = WebResponse; return false; } xmlResponse = XmlGetAttribute(FilterForXML(WebResponse), "stat"); if (xmlResponse == "ok") { TagList.LoadXml(FilterForXML(WebResponse)); return true; } GlobalClass.StatusDialogErrorMessage = WinFormStrings.UnableToRetreiveTagsStrRes; return false; } public bool SyncPiwigoCreateAlbum(ref int NewPiwigoAlbumID) { string WebResponse, WebRequest, xmlResponse, tempstr; NewPiwigoAlbumID = -1; WebRequest = FormSettings.Default.PiwigoUrlSetting + "/ws.php?method=pwg.categories.add&name=" + GlobalClass.NewAlbumName; if (Form1Settings.Default.AccessValue == WinFormStrings.PublicStrRes) { tempstr = "public"; } else { tempstr = "private"; } WebRequest += "&status=" + tempstr; if (GlobalClass.NewAlbumNameParentID != -1) { WebRequest += "&parent=" + GlobalClass.NewAlbumNameParentID.ToString(); } if (GlobalClass.NewAlbumDescription.Length != 0) { WebRequest += "&comment=" + GlobalClass.NewAlbumDescription; } WriteLog(WebRequest); WebResponse = SendWebGet(WebRequest); WriteLog(WebResponse); if (WebResponse.IndexOf("An error occurred:") != -1) { GlobalClass.StatusDialogErrorMessage = WebResponse; return false; } xmlResponse = XmlGetAttribute(FilterForXML(WebResponse), "stat"); if (xmlResponse == "ok") { NewPiwigoAlbumID = Convert.ToInt32(XmlGetElement(FilterForXML(WebResponse), "id")); return true; } GlobalClass.StatusDialogErrorMessage = WinFormStrings.UnableToCreateAlbumStrRes; return false; } public bool SyncPiwigoAddPhoto(int NewPiwigoAlbumId) { int i,k, di; string WebResponse, WebRequest, xmlResponse, filename; byte[] PhotoFileContents; string [] file_to_send = {local_command_line_args[0]}; string[,] post_array = new string[10,2]; string image_id; bool upload_failed, response; string face_tag_list, tag_list, comment_list, all_tags; upload_failed = false; for (i = 0; i < local_command_line_args.Length; i++) { if (stop_button_pressed) { return false; } SetStatus(WinFormStrings.UploadingPHotoStrRes + " " + (i + 1).ToString() + " " + WinFormStrings.ofStrREf + " " + local_command_line_args.Length.ToString() + "..."); face_tag_list = SyncPiwigoGetFaceTags(local_command_line_args[i]); tag_list = ""; comment_list = ""; all_tags = ""; SyncPiwigoGetTagsandComments(ref tag_list, ref comment_list, local_command_line_args[i]); if (face_tag_list.Length != 0) { all_tags = face_tag_list; } if (tag_list.Length != 0) { if (all_tags.Length != 0) { all_tags += ","; } all_tags += tag_list; } k = local_command_line_args[i].LastIndexOf("\\"); filename = local_command_line_args[i].Substring(k + 1); PhotoFileContents = FileToByteArray(local_command_line_args[i]); WebRequest = FormSettings.Default.PiwigoUrlSetting + "/ws.php?method=pwg.images.addSimple"; WebResponse = ""; local_command_line_args[i] = local_command_line_args[i].Replace("\\","\\\\"); post_array[0, 0] = "name=\"category\""; post_array[0, 1] = NewPiwigoAlbumId.ToString(); post_array[1, 0] = "name=\"name\"" ; post_array[1, 1] = filename; k = 2; if (all_tags.Length != 0) { post_array[k, 0] = "name=\"tags\""; post_array[k, 1] = all_tags; k++; } if (comment_list.Length != 0) { post_array[k, 0] = "name=\"comment\""; post_array[k, 1] = "\"" + comment_list + "\""; k++; } post_array[k, 0] = "name=\"image\"" + ";filename=" + "\"" + local_command_line_args[i] + "\""; WriteLog(WebRequest); for (di = 0; di < k; di++) { WriteLog(post_array[k, 0] + post_array[k, 1]); } response = SendWebPostMultipart(WebRequest, post_array, "multipart/form-data", PhotoFileContents, ref WebResponse); WriteLog(WebResponse); if (!response) { return false; } xmlResponse = XmlGetAttribute(FilterForXML(WebResponse), "stat"); if (xmlResponse == "ok") { image_id = XmlGetElement(FilterForXML(WebResponse), "image_id"); } else { upload_failed = true; } } return !upload_failed; } public string SendWebGet(string webrequest) { string webresponse; webresponse = ""; try { ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(webrequest); request.CookieContainer = cookiesjar; request.Proxy = null; request.Timeout = 60000; request.Credentials = CredentialCache.DefaultCredentials; HttpWebResponse response = (HttpWebResponse)request.GetResponse(); Stream dataStream = response.GetResponseStream(); StreamReader reader = new StreamReader(dataStream); // Read the content. webresponse = reader.ReadToEnd(); reader.Close(); dataStream.Close(); response.Close(); } catch (Exception e) { webresponse = WinFormStrings.ErrorOcurredStrRes + " " + e.Message; } return webresponse; } public bool SendWebPost(string webrequest, string post_data, string content_type) { try { HttpWebRequest request = (HttpWebRequest)WebRequest.Create(webrequest); ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3; request.CookieContainer = cookiesjar; request.Proxy = null; request.Timeout = 60000; request.Method = "POST"; request.Credentials = CredentialCache.DefaultCredentials; // Create POST data and convert it to a byte array. string postData = post_data; byte[] byteArray = Encoding.UTF8.GetBytes(postData); // Set the ContentType property of the WebRequest. request.ContentType = content_type; // Set the ContentLength property of the WebRequest. request.ContentLength = byteArray.Length; // Get the request stream. Stream dataStream = request.GetRequestStream(); // Write the data to the request stream. dataStream.Write(byteArray, 0, byteArray.Length); WebResponse response = request.GetResponse(); // Display the status. Console.WriteLine(((HttpWebResponse)response).StatusDescription); // Get the stream containing content returned by the server. dataStream = response.GetResponseStream(); // Open the stream using a StreamReader for easy access. StreamReader reader = new StreamReader(dataStream); // Read the content. string responseFromServer = reader.ReadToEnd(); // Display the content. // Close the Stream object. dataStream.Close(); } catch (Exception e) { GlobalClass.StatusDialogErrorMessage = WinFormStrings.ErrorOcurredStrRes + " " + e.Message; return false; } return true; } public string XmlGetAttribute(string xmlstring, string element) { string foundattribute; foundattribute = ""; XmlDocument StatusResponse = new XmlDocument(); StatusResponse.LoadXml(xmlstring); XmlElement ResponseElem = StatusResponse.DocumentElement; if (ResponseElem.HasAttribute(element)) { foundattribute = ResponseElem.GetAttribute(element); } return foundattribute; } public string XmlGetElement(string xmlstring, string element) { XmlDocument StatusResponse = new XmlDocument(); StatusResponse.LoadXml(xmlstring); XmlNodeList nodelist = StatusResponse.GetElementsByTagName(element); foreach (XmlNode anode in nodelist) { return anode.ChildNodes[0].Value; } return ""; } public bool UpdateStatus(bool result) { if (result) { this.StatusTextBox.Text += WinFormStrings.OKStrRes; } else { this.StatusTextBox.Text += WinFormStrings.FailedStrRes; DialogResult = DialogResult.No; } StatusRefresh(); return result; } public void SetStatus(string status) { this.StatusTextBox.Text = status; StatusRefresh(); } public void StatusRefresh() { this.Refresh(); this.StatusTextBox.Update(); Application.DoEvents(); } public byte[] FileToByteArray(string _FileName) { byte[] _Buffer = null; try { // Open file for reading System.IO.FileStream _FileStream = new System.IO.FileStream(_FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read); // attach filestream to binary reader System.IO.BinaryReader _BinaryReader = new System.IO.BinaryReader(_FileStream); // get total byte length of the file long _TotalBytes = new System.IO.FileInfo(_FileName).Length; // read entire file into buffer _Buffer = _BinaryReader.ReadBytes((Int32)_TotalBytes); // close file reader _FileStream.Close(); _FileStream.Dispose(); _BinaryReader.Close(); } catch (Exception _Exception) { // Error Console.WriteLine("File Read Error: ", _Exception.ToString()); } return _Buffer; } public bool SendWebPostMultipart(string webrequest, string[,] post_data, string content_type, byte[] binary_content, ref string response_from_server) { int i; ServicePointManager.ServerCertificateValidationCallback = delegate { return true; }; ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3; HttpWebRequest request = (HttpWebRequest)WebRequest.Create(webrequest); request.CookieContainer = cookiesjar; string boundary, formdataTemplate; Stream dataStream; byte[] byteArray; Stream memStream = new System.IO.MemoryStream(); request.Proxy = null; request.Timeout = 10 * 60 * 1000; request.Method = "POST"; request.Credentials = CredentialCache.DefaultCredentials; request.KeepAlive = true; try { // Create POST data and convert it to a byte array. boundary = "----------------------------" + DateTime.Now.Ticks.ToString("x"); content_type = "multipart/form-data; boundary=" + boundary; // Set the ContentType property of the WebRequest. request.ContentType = content_type; byte[] boundarybytes = System.Text.Encoding.ASCII.GetBytes("\r\n--" + boundary + "\r\n"); memStream.Write(boundarybytes, 0, boundarybytes.Length); byteArray = Encoding.UTF8.GetBytes(""); for (i = 0; i < 10; i++) { if (post_data[i, 0] != null) { formdataTemplate = "Content-Disposition: form-data; " + post_data[i, 0] + "\r\n"; if (post_data[i, 1] != null) { formdataTemplate += "\r\n"; formdataTemplate += post_data[i, 1]; } if (post_data[i + 1, 0] != null) { formdataTemplate += "\r\n--" + boundary + "\r\n"; } byte[] byteArray2 = Encoding.UTF8.GetBytes(formdataTemplate); // Set the ContentLength property of the WebRequest. //request.ContentLength = byteArray.Length; memStream.Write(byteArray2, 0, byteArray2.Length); } else { break; } } formdataTemplate = "Content-Type: image/jpeg\r\n\r\n"; byte[] byteArray3 = Encoding.UTF8.GetBytes(formdataTemplate); memStream.Write(byteArray3, 0, byteArray3.Length); memStream.Write(binary_content, 0, binary_content.Length); formdataTemplate = "\r\n--" + boundary + "--\r\n"; byte[] byteArray4 = Encoding.UTF8.GetBytes(formdataTemplate); memStream.Write(byteArray4, 0, byteArray4.Length); memStream.Position = 0; byte[] tempBuffer = new byte[memStream.Length]; memStream.Read(tempBuffer, 0, tempBuffer.Length); memStream.Close(); request.ContentLength = tempBuffer.Length; dataStream = request.GetRequestStream(); dataStream.Write(tempBuffer, 0, tempBuffer.Length); dataStream.Close(); WebResponse response = request.GetResponse(); // Display the status. Console.WriteLine(((HttpWebResponse)response).StatusDescription); // Get the stream containing content returned by the server. dataStream = response.GetResponseStream(); // Open the stream using a StreamReader for easy access. StreamReader reader = new StreamReader(dataStream); // Read the content. response_from_server = reader.ReadToEnd(); // Display the content. // Close the Stream object. dataStream.Close(); } catch (Exception e) { GlobalClass.StatusDialogErrorMessage = WinFormStrings.ErrorOcurredStrRes + " " + e.Message; return false; } return true; } private void button1_Click(object sender, EventArgs e) { GlobalClass.StatusDialogErrorMessage = WinFormStrings.StopButtonStrRes; DialogResult = DialogResult.No; stop_button_pressed = true; } public bool HaveToRemoveComma() { int k,l; int major_version, sub_version, minor_version; k = GlobalClass.PiwigoVersionNumber.IndexOf("."); if (k == -1) { return true; } l = 0; if (GlobalClass.PiwigoVersionNumber.Length >= k + 1) { l = GlobalClass.PiwigoVersionNumber.IndexOf(".", k + 1); if (l == -1) { return true; } } major_version = Convert.ToInt32(GlobalClass.PiwigoVersionNumber.Substring(0, k)); sub_version = Convert.ToInt32(GlobalClass.PiwigoVersionNumber.Substring(k+1, l-k-1)); minor_version = Convert.ToInt32(GlobalClass.PiwigoVersionNumber.Substring(l+1)); return true; } public string FilterForXML(string input_xml) { int k; string xml_only_str; xml_only_str = ""; k = input_xml.IndexOf("