Exemple #1
0
const bool Message::Create(const long localidentityid, const long boardid, const std::string &subject, const std::string &body, const std::vector<std::string> &references)
{
	Initialize();

	Poco::UUIDGenerator uuidgen;
	Poco::UUID uuid;

	// get header info
	// date is always set to now regardless of what message has
	m_datetime=Poco::Timestamp();

	// messageuuid is always a unique id we generate regardless of message message-id
	try
	{
		uuid=uuidgen.createRandom();
		m_messageuuid=uuid.toString();
		StringFunctions::UpperCase(m_messageuuid,m_messageuuid);
	}
	catch(...)
	{
		m_log->fatal("Message::ParseNNTPMessage could not create UUID");
	}
	
	// get from
	SQLite3DB::Statement st=m_db->Prepare("SELECT Name FROM tblLocalIdentity WHERE LocalIdentityID=?;");
	st.Bind(0,localidentityid);
	st.Step();
	if(st.RowReturned())
	{
		st.ResultText(0,m_fromname);
	}

	// get boards posted to
	std::string boardname="";
	SQLite3DB::Statement boardst=m_db->Prepare("SELECT BoardName FROM tblBoard WHERE BoardID=?;");
	boardst.Bind(0,boardid);
	boardst.Step();
	if(boardst.RowReturned())
	{
		boardst.ResultText(0,boardname);
	}

	m_boards.push_back(boardname);
	m_replyboardname=boardname;

	m_subject=subject;

	m_body=body;

	long currentref=0;
	for(std::vector<std::string>::const_iterator i=references.begin(); i!=references.end(); i++, currentref++)
	{
		m_inreplyto[currentref]=(*i);
	}

	return true;
}
const std::string createOrGetUuid() {
    std::string uuid;
    bool getUuid = read_pref<std::string>("Uuid", uuid);
    if (!getUuid) {
        Poco::UUID pocoUuid = Poco::UUIDGenerator().create();
        uuid = pocoUuid.toString();
        bool setUuid = write_pref("Uuid", uuid);
    }
    return uuid;
}
Exemple #3
0
void testApp::saveFloatBuffer(vector < float > & audioData, int sampleRate, int note, string fileName, chromaRecordingStats stats){
    
    
    Poco::UUID uuid;
    uuid = Poco::UUIDGenerator::defaultGenerator().createRandom();
    vector < string > uuidSplit = ofSplitString(uuid.toString(), "-");
    string uniqueFileName = uuidSplit[0];

    string tempFileName = "temp/" + uniqueName + "-" + uniqueFileName + ".mp3";
    
    
    //cout << "start of save float" << endl;
    
    
    
    int read, write;
    
    
    vector < string >  split = ofSplitString(radioLine, "///", true);
    
//    string url = "";
//    if (split[1].find("||") != string::npos){
//        vector < string > urls = ofSplitString(split[1], "||");
//        url = urls[ (int)ofRandom(0,urls.size() + 100) % urls.size() ];
//    } else {
//        url = split[1];
//    }
    
    
    FILE *mp3 = fopen( ofToDataPath(tempFileName).c_str(), "wb");
    
    const int PCM_SIZE = 8192;
    const int MP3_SIZE = 8192;
    
    float pcm_buffer[PCM_SIZE];
    unsigned char mp3_buffer[MP3_SIZE];
    
    lame_t lame = lame_init();
    
    
    lame_set_in_samplerate(lame, sampleRate);
    lame_set_VBR(lame, vbr_default);
    
    string albumbName = ofToString(stats.myStrength) + "," + ofToString(stats.theirStrength) + "," + ofToString(stats.duration);
    
    
    id3tag_add_v2(lame);
    
    
    
	//id3tag_set_title(lame, "TITLE: any TItle");
	//id3tag_set_artist(lame, "who is the author?");
    
    
    string title =split[4] + "||" + split[5];
    
    id3tag_set_title(lame, title.c_str());
    id3tag_set_artist(lame, radioLine.c_str());
    id3tag_set_album(lame, albumbName.c_str());
	id3tag_set_comment(lame, ofGetTimestampString().c_str());
    
    
    
    
    
    lame_init_params(lame);

    int nChuncks = ceil(audioData.size() / PCM_SIZE) + 1;
    int pos = 0;
    
    
    for (int i = 0; i < nChuncks; i++){
        
        read = 0;
        
        for (int j = pos; j < pos + PCM_SIZE; j++){
            
            if (j >= audioData.size()){
                pcm_buffer[j-pos] = 0;
                read = 0;
            } else {
                pcm_buffer[j-pos] = audioData[j];
                read++;
            }
            
        }
        
        
        if (read == 0)
            write = lame_encode_flush_nogap(lame, mp3_buffer, MP3_SIZE);
        else{
            write = lame_encode_buffer_ieee_float(lame, pcm_buffer, pcm_buffer, read, mp3_buffer, MP3_SIZE);
            
            //cout << write << endl;
        }
        fwrite(mp3_buffer, write, 1, mp3);
        
        pos+=PCM_SIZE;
    }
    
    //lame_mp3_tags_fid(lame, mp3);
    lame_close(lame);
    fclose(mp3);
    
    
    cout << "mid of save float" << endl;
    
    // TODO:
    
    // SOX for octave splits...
    // SOX normalize  (MP3)  or use RMS and raw data...
    
    
    int octave = getMedianSpectralCentroid(tempFileName);
    
    
    //if (octave < 0) return; // ?
    
    
    // add note and octave to filename
    
    fileName = "normalized/" + fileName;
    
    
    // put some info in (Content group description) : id3v2 --TIT1
    
    char moreTageMessage[512];
    string noteInfo = ofToString(note) + "," + ofToString(octave);
    
    
#ifdef TARGET_OSX
    sprintf(moreTageMessage, "/usr/local/bin/id3v2 --TIT2 %s %s", noteInfo.c_str(), ofToDataPath(tempFileName).c_str());
    
#else
    sprintf(moreTageMessage, "/usr/bin/id3v2 --TIT2 %s %s", noteInfo.c_str(),  ofToDataPath(tempFileName).c_str());
#endif

    system(moreTageMessage);
    
    char soxMessage[512];
    
    

#ifdef TARGET_OSX
    sprintf(soxMessage, "/usr/local/bin/sox \"%s\" \"%s\" compand 0,0.1 -80.1,-inf,-80,-160,-48,-24,-24,-6,-12,-1.5,-6,-0.3 -1 -6 loudness",
            ofToDataPath(tempFileName).c_str(), ofToDataPath(fileName).c_str());
#else
    sprintf(soxMessage, "/usr/bin/sox \"%s\" \"%s\" compand 0,0.1 -80.1,-inf,-80,-160,-48,-24,-24,-6,-12,-1.5,-6,-0.3 -1 -6 loudness",
            ofToDataPath(tempFileName).c_str(), ofToDataPath(fileName).c_str());
#endif
    
    system(soxMessage);
    
    char id3cpMessage[512];
    
#ifdef TARGET_OSX
    sprintf(id3cpMessage, "/usr/local/bin/id3cp \"%s\" \"%s\"",
            ofToDataPath(tempFileName).c_str(), ofToDataPath(fileName).c_str());
#else
    sprintf(id3cpMessage, "/usr/bin/id3cp \"%s\" \"%s\"",
            ofToDataPath(tempFileName).c_str(), ofToDataPath(fileName).c_str());
#endif    
    system(id3cpMessage);


    string deleteCommand = "rm " + ofToDataPath(tempFileName);
    //system(deleteCommand.c_str());
    
    ofLog(OF_LOG_NOTICE) << "saved " << fileName <<  " " << tempFileName;
    
    
    //sox "$original_file" "$temp_file" compand 0,0.1 -80.1,-inf,-80,-160,-48,-24,-24,-6,-12,-1.5,-6,-0.3 -1 -6 loudness
    //id3cp "$original_file" "$temp_file"
    //mv "$temp_file" "$original_file"
    
    
    // unix version of this?
    
    string command = "/usr/local/share/google/google-cloud-sdk/platform/gsutil cp " + ofToDataPath(fileName) + " gs://devart_storage & ";
    cout << command << endl;
    system(command.c_str());
    
    
    
    //string mvCommand = "mv " + ofToDataPath(tempFileName) + " " + ofToDataPath(fileName);
    //system(mvCommand.c_str());
    
    //cout << mvCommand << endl;
    
    
    //cout << "save " << fileName << endl;
    
    return;
    
    
    
    
    
    
}
Exemple #4
0
void testApp::initSystem(){
    
    
    loadSettings();
    
    /// ? plugin->reset();
    
    samples.clear();
    chromaDatas.clear();
    values.clear();
    
    
    Poco::UUID uuid;
    uuid = Poco::UUIDGenerator::defaultGenerator().createRandom();
    vector < string > uuidSplit = ofSplitString(uuid.toString(), "-");
    uniqueName = uuidSplit[0];
    
    
    restartRate = ofRandom(5,10);
    
    
    ofBuffer radioStationsBuffer = ofBufferFromFile("newRadio2.txt");
    
    ofLogToFile("logs/" + uniqueName + ".log.txt");
    
    vector < string > radios;
    
    while (true){
        string line = radioStationsBuffer.getNextLine();
        radios.push_back(line);
        if (radioStationsBuffer.isLastLine()) break;
    }
    
    string url = "";
    
    while (true){
        
//        
//        class radioStation{
//            
//        public:
//            
//            float longitude;    // EW       -180-180
//            float latitude;     // NS       -90-90
        float randomLon = ofRandom(-180,180); //arc4random_uniform(361) - 180;
        float randomLat = ofRandom(-90,90); //arc4random_uniform(181) - 90;
        

        while (true){
            
            ofPoint pt = projection(randomLat, randomLon, ofRectangle(0,0, img.getWidth(), img.getHeight()));
            int alpha = img.getColor(pt.x, pt.y).a;
            if (alpha > 127){
                break;
            } else {
                randomLon = ofRandom(-180,180); //arc4random_uniform(361) - 180;
                randomLat = ofRandom(-90,90); //arc4random_uniform(181) - 90;

            }
            
        }
        
        float minDistance = 10000000000;
        int minIndex = -1;
        
        for (int i = 0; i < stations.size(); i++){
            float latR = stations[i].latitude + ofRandom(-0.4, 0.4);
            float lonR = stations[i].longitude + ofRandom(-0.4, 0.4);
            float dist = earthDistance(randomLon, randomLat, lonR, latR);
            
            if (dist < minDistance ){
                minDistance = dist;
                minIndex = i;
            }
        }
        
        if (minIndex != -1){
            
            cout << minIndex << endl;
            cout << stations[minIndex].radioStationString << endl;
            
            radioLine = stations[minIndex].radioStationString;
            
            //radios[ (int)ofRandom(0,radios.size()) % radios.size()];
            
            ofLog(OF_LOG_NOTICE) << radioLine;
            
            cout << radioLine << endl;
            vector < string >  split = ofSplitString(radioLine, "///", true);
            
            if (split[1].find("||") != string::npos){
                vector < string > urls = ofSplitString(split[1], "||");
                url = urls[ (int)ofRandom(0,urls.size() + 100) % urls.size() ];
            } else {
                url = split[1];
            }
            string fileName = ofToDataPath("curl/" + uniqueName + "_curlTest.mp3");
            string command = "curl -sS -o " + fileName + " -m 1 " + url;
            system(command.c_str());
            ofFile file (fileName);
            
            if (file.exists()){
                cout << "file size " << file.getSize()  << endl;
                if (file.getSize() > 1000){
                    file.remove();
                    break;
                } else {
                    file.remove();
                    cout << fileName << " too small " << endl;
                    
                    //std::exit(0);
                }
            } else {
                cout << fileName << " doesn't exist " << endl;
                //std::exit(0);
            }

            
            
            
        } else {
            //continue;
        }
        
        
        
        
               //ofSleepMillis(500);
        
    }
    
    
    
    ofSetVerticalSync(false);


    startRecordTime = ofGetElapsedTimeMillis();;
    
    MP3Stream.start(url);
    
    
}
Exemple #5
0
const bool Message::ParseNNTPMessage(const std::string &nntpmessage)
{

	Initialize();

	Poco::UUIDGenerator uuidgen;
	Poco::UUID uuid;
	CMimeMessage mime;
	mime.Load(nntpmessage.c_str(),nntpmessage.size());

	// get header info
	// date is always set to now regardless of what message has
	m_datetime=Poco::Timestamp();

	// messageuuid is always a unique id we generate regardless of message message-id
	try
	{
		uuid=uuidgen.createRandom();
		m_messageuuid=uuid.toString();
		StringFunctions::UpperCase(m_messageuuid,m_messageuuid);
	}
	catch(...)
	{
		m_log->fatal("Message::ParseNNTPMessage could not create UUID");
	}
	
	// get from
	if(mime.GetFieldValue("From"))
	{
		m_fromname=mime.GetFieldValue("From");
		// remove any path folding
		m_fromname=StringFunctions::Replace(m_fromname,"\r\n","");
		m_fromname=StringFunctions::Replace(m_fromname,"\t","");
		// strip off everything between () and <> and any whitespace
		std::string::size_type startpos=m_fromname.find('(');
		std::string::size_type endpos;
		if(startpos!=std::string::npos)
		{
			endpos=m_fromname.find(')',startpos);
			if(endpos!=std::string::npos)
			{
				m_fromname.erase(startpos,(endpos-startpos)+1);
			}
		}
		startpos=m_fromname.find('<');
		if(startpos!=std::string::npos)
		{
			endpos=m_fromname.find('>',startpos);
			if(endpos!=std::string::npos)
			{
				m_fromname.erase(startpos,(endpos-startpos)+1);
			}
		}
		m_fromname=StringFunctions::TrimWhitespace(m_fromname);

		// trim off " from beginning and end
		if(m_fromname.size()>0 && m_fromname[0]=='\"')
		{
			m_fromname.erase(0,1);
		}
		if(m_fromname.size()>0 && m_fromname[m_fromname.size()-1]=='\"')
		{
			m_fromname.erase(m_fromname.size()-1,1);
		}

		m_fromname=StringFunctions::TrimWhitespace(m_fromname);
	}
	else
	{
		m_fromname="Anonymous";
	}
	// get boards posted to
	if(mime.GetFieldValue("Newsgroups"))
	{
		std::string temp=mime.GetFieldValue("Newsgroups");
		// remove any path folding
		temp=StringFunctions::Replace(temp,"\r\n","");
		temp=StringFunctions::Replace(temp,"\t","");
		std::vector<std::string> parts;
		StringFunctions::SplitMultiple(temp,", \t",parts);
		for(std::vector<std::string>::iterator i=parts.begin(); i!=parts.end(); i++)
		{
			(*i)=StringFunctions::Replace((*i),"<","");
			(*i)=StringFunctions::Replace((*i),">","");
			(*i)=StringFunctions::TrimWhitespace((*i));
			if((*i)!="")
			{
				m_boards.push_back((*i));
			}
		}
	}
	// followup-to board - must be done after board vector populated
	if(mime.GetFieldValue("Followup-To"))
	{
		m_replyboardname=mime.GetFieldValue("Followup-To");
		// remove any path folding
		m_replyboardname=StringFunctions::Replace(m_replyboardname,"\r\n","");
		m_replyboardname=StringFunctions::Replace(m_replyboardname,"\t","");
		std::vector<std::string> parts;
		StringFunctions::Split(m_replyboardname,",",parts);
		if(parts.size()>1)
		{
			m_replyboardname=parts[0];
		}
	}
	else
	{
		if(m_boards.size()>0)
		{
			m_replyboardname=m_boards[0];
		}
	}
	// subject
	if(mime.GetFieldValue("Subject"))
	{
		m_subject=mime.GetFieldValue("Subject");
		// remove any path folding
		m_subject=StringFunctions::Replace(m_subject,"\r\n","");
		m_subject=StringFunctions::Replace(m_subject,"\t","");
#if DO_CHARSET_CONVERSION
		if(mime.GetFieldCharset("Subject"))
		{
			std::string charset=mime.GetFieldCharset("Subject");
			CharsetConverter ccv;
			if(charset!="" && charset!="UTF-8" && ccv.SetConversion(charset,"UTF-8"))
			{
				std::string output="";
				ccv.Convert(m_subject,output);
				m_subject=output;
			}
		}
#endif
	}
	else
	{
		m_subject="No Subject";
	}
	// references
	if(mime.GetFieldValue("References"))
	{
		std::string temp=mime.GetFieldValue("References");
		// remove any path folding
		temp=StringFunctions::Replace(temp,"\r\n","");
		temp=StringFunctions::Replace(temp,"\t"," ");
		std::vector<std::string> parts;
		int count=0;
		StringFunctions::SplitMultiple(temp,", \t",parts);
		for(std::vector<std::string>::reverse_iterator i=parts.rbegin(); i!=parts.rend(); i++)
		{
			if((*i).size()>2)
			{
				// get rid of < and > and any whitespace
				(*i)=StringFunctions::Replace((*i),"<","");
				(*i)=StringFunctions::Replace((*i),">","");
				(*i)=StringFunctions::TrimWhitespace((*i));
				/*
				// erase @ and everything after
				if((*i).find('@')!=std::string::npos)
				{
					(*i).erase((*i).find('@'));
				}
				*/
				// only erase after @ if message is old type with @freenetproject.org
				if((*i).find("@freenetproject.org")!=std::string::npos)
				{
					(*i).erase((*i).find('@'));
				}
				if((*i)!="")
				{
					m_inreplyto[count++]=(*i);
				}
			}
		}
	}

	CMimeBody::CBodyList mbl;
	mime.GetBodyPartList(mbl);

	// append all text parts of nntp message to body
	for(CMimeBody::CBodyList::iterator i=mbl.begin(); i!=mbl.end(); i++)
	{
		if((*i)->IsText() && (*i)->GetContent())
		{
			std::string bodypart=(char *)(*i)->GetContent();
#ifdef DO_CHARSET_CONVERSION
			std::string charset=(*i)->GetCharset();
			if(charset!="" && charset!="UTF-8")
			{
				CharsetConverter ccv;
				if(ccv.SetConversion(charset,"UTF-8"))
				{
					std::string output="";
					ccv.Convert(bodypart,output);
					bodypart=output;
				}
			}
#endif
			m_body+=bodypart;
		}
		// add a binary file attachment
		else if(((*i)->GetName()!="" || (*i)->GetFilename()!="") && (*i)->GetLength()>0 && (*i)->GetContent())
		{
			std::string filename="";
			std::string contenttype="";
			std::vector<unsigned char> data((*i)->GetContent(),(*i)->GetContent()+(*i)->GetContentLength());
			if((*i)->GetContentType())
			{
				contenttype=(*i)->GetContentType();
				// find first ; tab cr or lf and erase it and everything after it
				std::string::size_type endpos=contenttype.find_first_of(";\t\r\n ");
				if(endpos!=std::string::npos)
				{
					contenttype.erase(endpos);
				}
			}
			filename=(*i)->GetFilename();
			if(filename=="")
			{
				filename=(*i)->GetName();
			}
			m_insertfileattachments.push_back(insertfileattachment(filename,contenttype,data));
		}
	}

	return true;
}
Exemple #6
0
void Message::HandleAdministrationMessage()
{
	// only continue if this message was actually a reply to another message
	if(m_inreplyto.size()>0)
	{
		int localidentityid=-1;
		int boardid=0;
		std::string boardname="";
		std::string identityname="";
		int identityid;
		int changemessagetrust=0;
		int changetrustlisttrust=0;
		int origmessagetrust=0;
		int origtrustlisttrust=0;
		SQLite3DB::Statement st=m_db->Prepare("SELECT tblBoard.BoardID,BoardName,ModifyLocalMessageTrust,ModifyLocalTrustListTrust FROM tblBoard INNER JOIN tblAdministrationBoard ON tblBoard.BoardID=tblAdministrationBoard.BoardID;");
		st.Step();

		localidentityid=FindLocalIdentityID(m_fromname);

		while(st.RowReturned() && localidentityid!=-1)
		{
			st.ResultInt(0,boardid);
			st.ResultText(1,boardname);
			st.ResultInt(2,changemessagetrust);
			st.ResultInt(3,changetrustlisttrust);

			if(std::find(m_boards.begin(),m_boards.end(),boardname)!=m_boards.end())
			{
				SQLite3DB::Statement origmess=m_db->Prepare("SELECT tblIdentity.IdentityID,tblIdentity.Name,tblIdentityTrust.LocalMessageTrust,tblIdentityTrust.LocalTrustListTrust FROM tblIdentity INNER JOIN tblMessage ON tblIdentity.IdentityID=tblMessage.IdentityID LEFT JOIN (SELECT IdentityID,LocalMessageTrust,LocalTrustListTrust FROM tblIdentityTrust WHERE LocalIdentityID=?) AS 'tblIdentityTrust' ON tblIdentity.IdentityID=tblIdentityTrust.IdentityID WHERE tblMessage.MessageUUID=?;");
				origmess.Bind(0,localidentityid);
				origmess.Bind(1,m_inreplyto[0]);
				origmess.Step();

				if(origmess.RowReturned())
				{
					origmess.ResultInt(0,identityid);
					origmess.ResultText(1,identityname);
					if(origmess.ResultNull(2)==false)
					{
						origmess.ResultInt(2,origmessagetrust);
					}
					else
					{
						//origmessagetrust=m_minlocalmessagetrust;
						origmessagetrust=50;
					}
					if(origmess.ResultNull(3)==false)
					{
						origmess.ResultInt(3,origtrustlisttrust);
					}
					else
					{
						//origtrustlisttrust=m_minlocaltrustlisttrust;
						origtrustlisttrust=50;
					}

					origmessagetrust+=changemessagetrust;
					origtrustlisttrust+=changetrustlisttrust;

					origmessagetrust<0 ? origmessagetrust=0 : false;
					origmessagetrust>100 ? origmessagetrust=100 : false;
					origtrustlisttrust<0 ? origtrustlisttrust=0 : false;
					origtrustlisttrust>100 ? origtrustlisttrust=100 : false;

					// make sure we have a record in tblIdentityTrust
					SQLite3DB::Statement ins=m_db->Prepare("INSERT OR IGNORE INTO tblIdentityTrust(LocalIdentityID,IdentityID) VALUES(?,?);");
					ins.Bind(0,localidentityid);
					ins.Bind(1,identityid);
					ins.Step();

					// update new trust levels
					SQLite3DB::Statement update=m_db->Prepare("UPDATE tblIdentityTrust SET LocalMessageTrust=?, LocalTrustListTrust=? WHERE IdentityID=? AND LocalIdentityID=?;");
					update.Bind(0,origmessagetrust);
					update.Bind(1,origtrustlisttrust);
					update.Bind(2,identityid);
					update.Bind(3,localidentityid);
					update.Step();

					// insert message to show what id was changed and what current levels are
					int lastid=0;
					std::string messagebody;
					std::string messagetruststr="";
					std::string trustlisttruststr="";

					Poco::UUIDGenerator uuidgen;
					Poco::UUID uuid;

					try
					{
						uuid=uuidgen.createRandom();
					}
					catch(...)
					{
						m_log->fatal("Message::HandleAdministrationMessage could not generate a UUID");
					}

					Poco::DateTime now;
					StringFunctions::Convert(origmessagetrust,messagetruststr);
					StringFunctions::Convert(origtrustlisttrust,trustlisttruststr);
					messagebody="Trust List of "+m_fromname+"\r\n";
					messagebody="Trust Changed for "+identityname+"\r\n";
					messagebody+="Local Message Trust : "+messagetruststr+"\r\n";
					messagebody+="Local Trust List Trust : "+trustlisttruststr+"\r\n";
					SQLite3DB::Statement insert=m_db->Prepare("INSERT INTO tblMessage(FromName,MessageDate,MessageTime,Subject,MessageUUID,ReplyBoardID,Body,BodyLineMaxBytes,MessageSource) VALUES('FMS',?,?,?,?,?,?,?,?);");
					insert.Bind(0,Poco::DateTimeFormatter::format(now,"%Y-%m-%d"));
					insert.Bind(1,Poco::DateTimeFormatter::format(now,"%H:%M:%S"));
					insert.Bind(2,identityname+" Trust Changed");
					std::string uuidstr=uuid.toString();
					StringFunctions::UpperCase(uuidstr,uuidstr);
					int linemaxbytes=LineMaxBytes(messagebody);
					insert.Bind(3,uuidstr);
					insert.Bind(4,boardid);
					insert.Bind(5,messagebody);
					insert.Bind(6,linemaxbytes);
					insert.Bind(7,SOURCE_AUTOMATED);
					insert.Step(true);
					lastid=insert.GetLastInsertRowID();

					insert=m_db->Prepare("INSERT INTO tblMessageBoard(MessageID,BoardID) VALUES(?,?);");
					insert.Bind(0,lastid);
					insert.Bind(1,boardid);
					insert.Step();

					m_log->debug("Message::HandleAdministrationMessage updated "+identityname+" to "+messagetruststr+" , "+trustlisttruststr);

				}
			}

			st.Step();
		}
	}

}
		// Adapted from Bjarne Stroustrup, "A Tour of C++"
		std::size_t operator()(const Poco::UUID& key) const
		{
			return hash<std::string>()(key.toString());
		}
const bool IntroductionPuzzleInserter::StartInsert(const long &localidentityid)
{
	Poco::DateTime now;
	std::string idstring="";
	int index=0;
	std::string indexstr="";
	Poco::UUIDGenerator uuidgen;
	Poco::UUID uuid;
	std::string messagebase="";
	IntroductionPuzzleXML xml;
	std::string encodedpuzzle="";
	std::string solutionstring="";
	FCPv2::Message message;
	std::string xmldata="";
	std::string xmldatasizestr="";
	std::string privatekey="";
	std::string publickey="";
	std::string keypart="";
	std::string captchatype="";
	std::string mimetype="";
	std::string requestedtype="";

	StringFunctions::Convert(localidentityid,idstring);
	SQLite3DB::Statement st=m_db->Prepare("SELECT MAX(InsertIndex)+1 FROM tblIntroductionPuzzleInserts WHERE Day=? AND LocalIdentityID=?");
	st.Bind(0,Poco::DateTimeFormatter::format(now,"%Y-%m-%d"));
	st.Bind(1,localidentityid);
	st.Step();

	if(st.RowReturned())
	{
		st.ResultInt(0, index); // NULL converted to 0
		st.Reset();
	}
	else
	{
		index=0;
	}
	StringFunctions::Convert(index,indexstr);

	if(index<m_maxpuzzleinserts)
	{
		SQLite3DB::Statement st2=m_db->Prepare("SELECT PrivateKey,PublicKey,IntroductionPuzzleType FROM tblLocalIdentity WHERE LocalIdentityID=?");
		st2.Bind(0, localidentityid);
		st2.Step();
		if(st2.RowReturned())
		{
			st2.ResultText(0, privatekey);
			st2.ResultText(1, publickey);
			if(publickey.size()>=50)
			{
				// remove - and ~
				keypart=StringFunctions::Replace(StringFunctions::Replace(publickey.substr(4,43),"-",""),"~","");
			}
			st2.ResultText(2, requestedtype);
			st2.Reset();
		}

		Option option(m_db);
		option.Get("MessageBase",messagebase);

		GenerateCaptcha(encodedpuzzle,solutionstring,requestedtype,captchatype,mimetype);
		if(encodedpuzzle.size()==0)
		{
			m_log->fatal("IntroductionPuzzleInserter::StartInsert could not create introduction puzzle");
			return false;
		}

		try
		{
			uuid=uuidgen.createRandom();
		}
		catch(...)
		{
			m_log->fatal("IntroductionPuzzleInserter::StartInsert could not create UUID");
		}

		xml.SetType(captchatype);
		std::string uuidstr=uuid.toString();
		StringFunctions::UpperCase(uuidstr,uuidstr);
		xml.SetUUID(uuidstr+"@"+keypart);
		xml.SetPuzzleData(encodedpuzzle);
		xml.SetMimeType(mimetype);

		xmldata=xml.GetXML();
		StringFunctions::Convert(xmldata.size(),xmldatasizestr);

		message.SetName("ClientPut");
		message["URI"]=privatekey+messagebase+"|"+Poco::DateTimeFormatter::format(now,"%Y-%m-%d")+"|IntroductionPuzzle|"+indexstr+".xml";
		message["Identifier"]=m_fcpuniquename+"|"+idstring+"|"+indexstr+"|"+xml.GetUUID()+"|"+message["URI"];
		message["IgnoreUSKDatehints"]="true"; // per-day key, DATEHINTs useless
		message["PriorityClass"]=m_defaultinsertpriorityclassstr;
		message["UploadFrom"]="direct";
		message["DataLength"]=xmldatasizestr;
		message["Metadata.ContentType"]="";
		m_fcp->Send(message);
		m_fcp->Send(std::vector<char>(xmldata.begin(),xmldata.end()));

		// insert to USK - not used, but don't remove code yet
		/*
		message.Clear();
		message.SetName("ClientPutComplexDir");
		message["URI"]="USK"+privatekey.substr(3)+messagebase+"|"+Poco::DateTimeFormatter::format(now,"%Y.%m.%d")+"|IntroductionPuzzle/0/";
		message["Identifier"]=m_fcpuniquename+"USK|"+message["URI"];
		message["DefaultName"]="IntroductionPuzzle.xml";
		message["Files.0.Name"]="IntroductionPuzzle.xml";
		message["Files.0.UplaodFrom"]="direct";
		message["Files.0.DataLength"]=xmldatasizestr;
		m_fcp->Send(message);
		m_fcp->Send(std::vector<char>(xmldata.begin(),xmldata.end()));
		*/

		SQLite3DB::Statement ins=m_db->Prepare("INSERT INTO tblIntroductionPuzzleInserts(UUID,Type,MimeType,LocalIdentityID,PuzzleData,PuzzleSolution) VALUES(?, ?, ?, ?, ?, ?)");
		ins.Bind(0, xml.GetUUID());
		ins.Bind(1, captchatype);
		ins.Bind(2, mimetype);
		ins.Bind(3, localidentityid);
		ins.Bind(4, encodedpuzzle);
		ins.Bind(5, solutionstring);
		ins.Step();

		m_inserting.push_back(localidentityid);

		m_log->debug("IntroductionPuzzleInserter::StartInsert started insert for id "+idstring);
	}
	else
	{
		m_log->warning("IntroductionPuzzleInserter::StartInsert already inserted max puzzles for "+idstring);
	}

	return true;

}