btobexprofiles/obexserviceman/utils/src/obexutilsmessagehandler.cpp
branchRCL_3
changeset 56 9386f31cc85b
parent 55 613943a21004
child 61 269724087bed
equal deleted inserted replaced
55:613943a21004 56:9386f31cc85b
     1 /*
       
     2 * Copyright (c) 2002,2010 Nokia Corporation and/or its subsidiary(-ies).
       
     3 * All rights reserved.
       
     4 * This component and the accompanying materials are made available
       
     5 * under the terms of "Eclipse Public License v1.0"
       
     6 * which accompanies this distribution, and is available
       
     7 * at the URL "http://www.eclipse.org/legal/epl-v10.html".
       
     8 *
       
     9 * Initial Contributors:
       
    10 * Nokia Corporation - initial contribution.
       
    11 *
       
    12 * Contributors:
       
    13 *
       
    14 * Description: 
       
    15 *
       
    16 */
       
    17 
       
    18 
       
    19 // INCLUDE FILES
       
    20 #include "obexutilsmessagehandler.h"
       
    21 #include "obexutilsdebug.h"
       
    22 #include "obexutilsentryhandler.h"
       
    23 
       
    24 #include <msvids.h>
       
    25 #include <msvuids.h>
       
    26 #include <apgcli.h>
       
    27 #include <txtrich.h>
       
    28 
       
    29 #include <biouids.h>
       
    30 #include <bautils.h>
       
    31 
       
    32 #include <e32property.h>
       
    33 #include <UikonInternalPSKeys.h>
       
    34 
       
    35 #include <mmsvattachmentmanagersync.h>
       
    36 #include <mmsvattachmentmanager.h>
       
    37 
       
    38 #include <centralrepository.h>
       
    39 #include <btengdomaincrkeys.h>
       
    40 #include "updatemusiccollection.h"
       
    41 
       
    42 #include <pathinfo.h>          // provides interface for quering system paths 
       
    43 
       
    44 #ifdef __BT_SAP
       
    45  #include "vMessageHandler.h"
       
    46 #endif // __BT_SAP
       
    47 
       
    48 // CONSTANT
       
    49 const TInt KFFSBelowCritical = -2;
       
    50 const TInt KRenameOffSet = 4 ;
       
    51 
       
    52 // todo @ QT migration: take official definition from Messaging at app layer (btmsgtypeuid.h)
       
    53 const TUid KUidMsgTypeBt = {0x10009ED5};
       
    54 
       
    55 const TInt KObexUtilsMaxCharToFromField = 256;
       
    56 
       
    57 const TInt32 KUidMsgTypeBtTInt32 = 0x10009ED5;
       
    58 
       
    59 // ============================= LOCAL FUNCTIONS ===============================
       
    60 
       
    61 // -----------------------------------------------------------------------------
       
    62 // RemoveObexBuffer  Removes Obex buffer object.
       
    63 // -----------------------------------------------------------------------------
       
    64 //
       
    65 void TObexUtilsMessageHandler::RemoveObexBuffer(CObexBufObject* &aBufObject)
       
    66     {
       
    67     if (aBufObject)
       
    68         {
       
    69         delete aBufObject;
       
    70         aBufObject = NULL;
       
    71         }
       
    72     }
       
    73 
       
    74 // -----------------------------------------------------------------------------
       
    75 // CreateMsvSessionLC  Creates MSV session
       
    76 // -----------------------------------------------------------------------------
       
    77 //
       
    78 void TObexUtilsMessageHandler::CreateMsvSessionLC(
       
    79     CDummySessionObserver* &aSessionObs,
       
    80     CMsvSession* &aMsvSession)
       
    81     {
       
    82     aSessionObs = new( ELeave )CDummySessionObserver;
       
    83     CleanupStack::PushL( aSessionObs );  //1st push
       
    84     aMsvSession = CMsvSession::OpenSyncL( *aSessionObs );
       
    85     CleanupStack::PushL( aMsvSession );  //2nd push
       
    86     }
       
    87 
       
    88 // -----------------------------------------------------------------------------
       
    89 // CreateMsvSessionLC  Creates MSV session to selected destination
       
    90 // -----------------------------------------------------------------------------
       
    91 //
       
    92 void TObexUtilsMessageHandler::CreateMsvSessionLC(
       
    93     CDummySessionObserver* &aSessionObs,
       
    94     CMsvSession* &aMsvSession,
       
    95     CMsvEntry* &aDestination,
       
    96     TMsvId aMsvId)
       
    97     {
       
    98     CreateMsvSessionLC(aSessionObs, aMsvSession);
       
    99     aDestination = aMsvSession->GetEntryL( aMsvId );
       
   100     CleanupStack::PushL( aDestination );  //3rd push
       
   101     }
       
   102 
       
   103 // -----------------------------------------------------------------------------
       
   104 // GetCenRepKeyIntValueL Gets integer repository value
       
   105 // Returns: Error
       
   106 // -----------------------------------------------------------------------------
       
   107 //
       
   108 EXPORT_C TInt TObexUtilsMessageHandler::GetCenRepKeyIntValueL(
       
   109     TUid aRepositoryUid,  // aRepositoryUid Central repository's UID value
       
   110     TUint32 aId,          // Central repository's ID value
       
   111     TInt& aVal)           // Returned integer value
       
   112     {
       
   113     CRepository* storage = CRepository::NewLC( aRepositoryUid );
       
   114     TInt retval = storage->Get( aId, aVal );
       
   115     if (retval != KErrNone)
       
   116         {
       
   117         FLOG(_L("[OBEXUTILS]\t GetCenRepKeyIntValueL() Get failed"));
       
   118         }
       
   119     CleanupStack::PopAndDestroy( storage );
       
   120     return retval;
       
   121     }
       
   122 
       
   123 // -----------------------------------------------------------------------------
       
   124 // GetCurrentTime Gets current time
       
   125 // Returns: Current time
       
   126 // -----------------------------------------------------------------------------
       
   127 //
       
   128 TTime TObexUtilsMessageHandler::GetCurrentTime()
       
   129     {
       
   130     TTime time;
       
   131     time.UniversalTime();
       
   132     return time;
       
   133     }
       
   134 
       
   135 // -----------------------------------------------------------------------------
       
   136 // StoreAsRichTextL Change message content to Richtext
       
   137 // Returns: None.
       
   138 // -----------------------------------------------------------------------------
       
   139 //
       
   140 void TObexUtilsMessageHandler::StoreAsRichTextL( 
       
   141     CMsvEntry* aParentEntry,  // A pointer to new message server entry.
       
   142     RFile& aFile)             // New file to store
       
   143     {
       
   144     FLOG(_L("[OBEXUTILS]\t StoreAsRichTextL()"));
       
   145 
       
   146     TInt fileLength = 0;
       
   147     User::LeaveIfError( aFile.Size( fileLength ) );
       
   148 
       
   149     // Calculate the number of blocks to read
       
   150     const TInt blockSize = 128 * 1024;
       
   151     TInt fullBlockCnt = fileLength / blockSize;
       
   152     if (fileLength % blockSize > 0)
       
   153         {
       
   154         fullBlockCnt++;
       
   155         }
       
   156 
       
   157     CRichText* richText = ConstructRichTextLC(); // 1st, 2nd, 3rd push
       
   158 
       
   159     RBuf8 buffer8;
       
   160     CleanupClosePushL(buffer8);  // 4th push
       
   161     buffer8.CreateL( blockSize );
       
   162     RBuf buffer16;
       
   163     CleanupClosePushL(buffer16); // 5th push
       
   164     buffer16.CreateL(blockSize);
       
   165     
       
   166     // Read the file into buffer in small chunks  
       
   167     TInt readBytes = 0;
       
   168     for (TInt i = 0; i < fullBlockCnt; ++i)
       
   169         {
       
   170         User::LeaveIfError( aFile.Read( buffer8 ) );
       
   171     
       
   172         // In order for Bio to understand 8-bit binary data, 
       
   173         // it needs to be stored in wide rich text object
       
   174         // in the low byte of each word with the upper byte as 0.
       
   175         // Do not use UTF8, just convert 8-bit to 16-bit.  
       
   176         buffer16.Copy( buffer8 );
       
   177         
       
   178         richText->InsertL(readBytes, buffer16);
       
   179         readBytes += buffer8.Length();
       
   180         }
       
   181     CleanupStack::PopAndDestroy(2, &buffer8);
       
   182     // -2 pop: free unused memory before StoreBodyTextL()
       
   183 
       
   184     CMsvStore* parentStore = aParentEntry->EditStoreL();
       
   185     CleanupStack::PushL(parentStore);   // 4th push
       
   186     parentStore->StoreBodyTextL(*richText);
       
   187     parentStore->CommitL();
       
   188 
       
   189     CleanupStack::PopAndDestroy(4);  // parentStore, richText, richParaFormatLayer,
       
   190                                      // richCharFormatLayer
       
   191 
       
   192     FLOG(_L("[OBEXUTILS]\t StoreAsRichTextL() completed"));
       
   193     }
       
   194 
       
   195 // -----------------------------------------------------------------------------
       
   196 // UpdateAttachmentInformationL Add the obex object as a file attachment.
       
   197 // Returns: None.
       
   198 // -----------------------------------------------------------------------------
       
   199 //
       
   200 void TObexUtilsMessageHandler::UpdateAttachmentInformationL(
       
   201     TReceivedData& aRecData,      // The obex received data
       
   202     CMsvEntry* aAttachEntry,      // Attachment entry
       
   203     CMsvAttachment* aAttachInfo,  // Attachment information
       
   204     CMsvStore* aStore)            // Message store (attachment)
       
   205     {
       
   206     FLOG(_L("[OBEXUTILS]\t UpdateAttachmentInformationL()"));
       
   207 
       
   208     TMsvEntry attachTEntry = aAttachEntry->Entry();
       
   209 
       
   210     SetDetailsLC(attachTEntry.iDescription, aAttachInfo->MimeType());
       
   211     attachTEntry.iSize = aRecData.bytesReceived;
       
   212     attachTEntry.iDate = aRecData.recTime;
       
   213     aAttachEntry->ChangeL(attachTEntry);  // Save properties.
       
   214     CleanupStack::PopAndDestroy(); // unicode in SetDetailsLC
       
   215 
       
   216     aAttachInfo->SetSize(aRecData.bytesReceived);
       
   217     aAttachInfo->SetAttachmentNameL(aRecData.msgName);
       
   218     aAttachInfo->SetComplete(ETrue);
       
   219 
       
   220     aStore->AttachmentManagerExtensionsL().ModifyAttachmentInfoL(aAttachInfo);
       
   221     
       
   222     FLOG(_L("[OBEXUTILS]\t UpdateAttachmentInformation() completed"));
       
   223     }
       
   224 
       
   225 // -----------------------------------------------------------------------------
       
   226 // FinaliseMessageL Save the size of all the attachments and make visible.
       
   227 // Returns: None.
       
   228 // -----------------------------------------------------------------------------
       
   229 //
       
   230 void TObexUtilsMessageHandler::FinaliseMessageL(
       
   231     CMsvEntry* aParentEntry,  // Parent entry
       
   232     TReceivedData& aRecData,  // The obex received data
       
   233     CMsvStore* aStore,        // Attachment's store
       
   234     TBool aIsBioMsg)          // Is BIO message?
       
   235     {
       
   236     FLOG(_L("[OBEXUTILS]\t FinaliseMessageL()"));
       
   237     // Save the size of all the attachment & make visible.   
       
   238     TMsvEntry parentTEntry = aParentEntry->Entry();
       
   239     parentTEntry.iDate = GetCurrentTime();
       
   240     parentTEntry.iSize = aRecData.bytesReceived;
       
   241     parentTEntry.SetUnread(ETrue);
       
   242     
       
   243     // Saved OK. Make the entry visible and flag it as complete.
       
   244     parentTEntry.SetVisible(ETrue);                   // visible
       
   245     parentTEntry.SetInPreparation(EFalse);            // complete
       
   246     if (!aIsBioMsg)
       
   247         {
       
   248         parentTEntry.iDescription.Set(aRecData.msgName);  // "Subject"
       
   249         }
       
   250     aParentEntry->ChangeL(parentTEntry);              // commit changes
       
   251 
       
   252     aStore->CommitL();
       
   253     
       
   254     FLOG(_L("[OBEXUTILS]\t FinaliseMessageL() completed"));
       
   255     }
       
   256 
       
   257 // -----------------------------------------------------------------------------
       
   258 // FinaliseMessageL Save the size of all the attachments and make visible.
       
   259 // for Saving file received via BT/IR directly to file system.
       
   260 // Returns: None.
       
   261 // -----------------------------------------------------------------------------
       
   262 //
       
   263 void TObexUtilsMessageHandler::FinaliseMessageL(
       
   264     CMsvEntry* aParentEntry,
       
   265     CMsvStore* aStore,
       
   266     TEntry& aFileEntry,
       
   267     TParse& aFileNameParser)
       
   268     {
       
   269     FLOG(_L("[OBEXUTILS]\t FinaliseMessageL() new "));
       
   270     
       
   271     // Save the size of all the attachment & make visible.
       
   272     TMsvEntry parentTEntry = aParentEntry->Entry();
       
   273     parentTEntry.iDate = GetCurrentTime();
       
   274     parentTEntry.iSize = aFileEntry.iSize;  
       
   275     // Saved OK. Make the entry visible and flag it as complete.
       
   276     parentTEntry.SetVisible(ETrue);                   // visible
       
   277     parentTEntry.SetUnread(ETrue);
       
   278     parentTEntry.SetInPreparation(EFalse);            // complete
       
   279     parentTEntry.iDescription.Set(aFileNameParser.FullName());        // "Subject" 
       
   280     aParentEntry->ChangeL(parentTEntry);              // commit changes
       
   281     aStore->CommitL();
       
   282     
       
   283     FLOG(_L("[OBEXUTILS]\t FinaliseMessageL() new completed "));
       
   284     }
       
   285 
       
   286 // -----------------------------------------------------------------------------
       
   287 // StoreAndUpdateBioMessageL Stores and updates a BIO message
       
   288 // Returns: None.
       
   289 // -----------------------------------------------------------------------------
       
   290 //
       
   291 void TObexUtilsMessageHandler::StoreAndUpdateBioMessageL(
       
   292     CBIODatabase* aBioDB,     // Bio database
       
   293     TUid aBioMsgId,           // Bio message ID
       
   294     CMsvEntry* parentEntry,   // Parent message entry
       
   295     RFile& aFile)             // File to attachment
       
   296     {
       
   297     FLOG(_L("[OBEXUTILS]\t StoreAndUpdateBioMessageL()"));
       
   298     
       
   299     TInt index;
       
   300     aBioDB->GetBioIndexWithMsgIDL(aBioMsgId, index);
       
   301     
       
   302     StoreAsRichTextL( parentEntry, aFile );
       
   303     
       
   304     TMsvEntry parentTEntry = parentEntry->Entry();
       
   305     parentTEntry.iMtm = KUidBIOMessageTypeMtm;
       
   306     parentTEntry.iServiceId = KMsvLocalServiceIndexEntryId;  
       
   307     parentTEntry.iBioType = aBioMsgId.iUid;
       
   308     parentTEntry.iMtmData1 = KUidMsgTypeBtTInt32;
       
   309     parentTEntry.iDescription.Set(aBioDB->BifReader(index).Description());
       
   310     parentEntry->ChangeL(parentTEntry);
       
   311     
       
   312     FLOG(_L("[OBEXUTILS]\t StoreAndUpdateBioMessageL() completed"));
       
   313     }
       
   314 
       
   315 // -----------------------------------------------------------------------------
       
   316 // RecogniseObjectsL Recognised objects if no type field has been given.
       
   317 // Returns: None.
       
   318 // -----------------------------------------------------------------------------
       
   319 //
       
   320 void TObexUtilsMessageHandler::RecogniseObjectsL(
       
   321     TFileName& aFileName,
       
   322     CMsvAttachment* aAttachInfo)  // Attachment information
       
   323     {
       
   324     FLOG(_L("[OBEXUTILS]\t RecogniseObjectsL()"));
       
   325 
       
   326     TPtrC8 mimeType;
       
   327     RApaLsSession lsSess;
       
   328     User::LeaveIfError( lsSess.Connect() );
       
   329     CleanupClosePushL(lsSess);
       
   330     TDataType appDataType;
       
   331     TUid appUid;
       
   332     if (lsSess.AppForDocument(aFileName, appUid, appDataType) == KErrNone)
       
   333         {
       
   334         mimeType.Set(appDataType.Des8());
       
   335         }
       
   336     else
       
   337         {
       
   338         // Don't trust on sender's MIME type here. Just set to empty.
       
   339         mimeType.Set(KNullDesC8);
       
   340         FLOG(_L("[OBEXUTILS]\t RecogniseObjectsL() MIME check failed"));
       
   341         }
       
   342     CleanupStack::PopAndDestroy();  // lsSess
       
   343     HBufC* buf16 = HBufC::NewLC(mimeType.Length());
       
   344     buf16->Des().Copy(mimeType);
       
   345     TPtrC mimeType16(buf16->Des());
       
   346     CleanupStack::PopAndDestroy();   //   buf16
       
   347     
       
   348     CUpdateMusicCollection* updateMusicCollection = CUpdateMusicCollection::NewL();
       
   349     CleanupStack::PushL(updateMusicCollection);    
       
   350     if (updateMusicCollection->isSupported(mimeType16))
       
   351         {
       
   352         updateMusicCollection->addToCollectionL(aFileName);
       
   353         }
       
   354     CleanupStack::PopAndDestroy();  // updateMusicCollection
       
   355     
       
   356     aAttachInfo->SetMimeTypeL( mimeType );
       
   357     
       
   358     FLOG(_L("[OBEXUTILS]\t RecogniseObjectsL() completed"));
       
   359     }
       
   360 
       
   361 // -----------------------------------------------------------------------------
       
   362 // SaveMimeAndGetBioLC Saves MIME type and gets BIO database for that MIME
       
   363 // Returns: BIO database if BIO message
       
   364 // -----------------------------------------------------------------------------
       
   365 //
       
   366 CBIODatabase* TObexUtilsMessageHandler::SaveMimeAndGetBioLC(
       
   367     TFileName& aFileName,
       
   368     RFs& aFsSess,                 // File session
       
   369     CMsvAttachment* aAttachInfo,  // Attachment information
       
   370     TUid &aBioMsgId)              // BIO message ID for data
       
   371     {
       
   372     FLOG(_L("[OBEXUTILS]\t TObexUtilsMessageHandler::SaveMimeAndGetBioLC()"));
       
   373     
       
   374     RecogniseObjectsL( aFileName, aAttachInfo );
       
   375 
       
   376     // For attachments / BIO check.
       
   377     CBIODatabase* bioDB = CBIODatabase::NewLC( aFsSess );  // 1st push
       
   378     
       
   379     // Run through the data objects, seeing if they can be accepted by BIO.
       
   380     // Check if they are bio objects
       
   381 
       
   382     TBioMsgIdText bioMessageIdText;
       
   383     SetBioDataTextL( bioMessageIdText, aAttachInfo->MimeType() );
       
   384 
       
   385     // Remove any zero termination on mime type
       
   386     //
       
   387     TInt zeroTermination = bioMessageIdText.Locate( TChar(0) ); 
       
   388     
       
   389     if ( zeroTermination != KErrNotFound )
       
   390         {
       
   391         bioMessageIdText.SetLength( zeroTermination );
       
   392         }
       
   393 
       
   394     TInt bioMsgErr = bioDB->IsBioMessageL( EBioMsgIdIana, bioMessageIdText, NULL, aBioMsgId );
       
   395     FLOG(_L("[OBEXUTILS]\t TObexUtilsMessageHandler::SaveMimeAndGetBioLC() completed"));
       
   396     if (bioMsgErr != KErrNone)
       
   397         {
       
   398         return NULL;
       
   399         }
       
   400     return bioDB;
       
   401     }
       
   402 
       
   403 // ============================ MEMBER FUNCTIONS ===============================
       
   404 
       
   405 // -----------------------------------------------------------------------------
       
   406 // CreateInboxAttachmentL Creates inbox entry and attachment for it
       
   407 // If this leaves, it means the entry and obex object have already been deleted.
       
   408 // In this case aMsvIdParent has been set to zero.
       
   409 // Returns: None.
       
   410 // -----------------------------------------------------------------------------
       
   411 //
       
   412 EXPORT_C void TObexUtilsMessageHandler::CreateInboxAttachmentL(
       
   413     CObexBufObject* &aBufObject,  // Obex object
       
   414     const TUid aMtmId,            // Mtm ID of the message
       
   415     TMsvId &aMsvIdParent,         // Message ID of the parent message entry
       
   416     RFile &aFile)                 // File to the attachment
       
   417     {
       
   418     TMsvId msvId = 0;
       
   419     TRAPD(retTrap, DoCreateInboxAttachmentL(aMtmId, msvId, aFile,KNullDesC))
       
   420     if (retTrap != KErrNone)
       
   421         {
       
   422         aMsvIdParent = 0;
       
   423         if (msvId)
       
   424             {
       
   425             RemoveInboxEntriesL(aBufObject, msvId);
       
   426             }
       
   427         User::Leave(retTrap);
       
   428         }
       
   429     aMsvIdParent = msvId;
       
   430     }
       
   431 
       
   432 // -----------------------------------------------------------------------------
       
   433 // CreateInboxAttachmentL Creates inbox entry and attachment for it
       
   434 // If this leaves, it means the entry and obex object have already been deleted.
       
   435 // In this case aMsvIdParent has been set to zero.
       
   436 // Returns: None.
       
   437 // -----------------------------------------------------------------------------
       
   438 //
       
   439 EXPORT_C void TObexUtilsMessageHandler::CreateInboxAttachmentL(
       
   440     CObexBufObject* &aBufObject,  // Obex object
       
   441     const TUid aMtmId,            // Mtm ID of the message
       
   442     TMsvId &aMsvIdParent,         // Message ID of the parent message entry
       
   443     RFile &aFile,                 // File to the attachment
       
   444     const TDesC& aRemoteBluetoothName)  // bluetooth name of remote device
       
   445     {
       
   446     TMsvId msvId = 0;
       
   447     TRAPD(retTrap, DoCreateInboxAttachmentL(aMtmId, msvId, aFile,aRemoteBluetoothName))
       
   448     if (retTrap != KErrNone)
       
   449         {
       
   450         aMsvIdParent = 0;
       
   451         if (msvId)
       
   452             {
       
   453             RemoveInboxEntriesL(aBufObject, msvId);
       
   454             }
       
   455         User::Leave(retTrap);
       
   456         }
       
   457     aMsvIdParent = msvId;
       
   458     }
       
   459 
       
   460 // -----------------------------------------------------------------------------
       
   461 // DoCreateInboxAttachmentL Creates inbox entry and attachment for it (private)
       
   462 // Returns: None.
       
   463 // -----------------------------------------------------------------------------
       
   464 //
       
   465 void TObexUtilsMessageHandler::DoCreateInboxAttachmentL(
       
   466     const TUid aMtmId,     // Mtm ID of the message
       
   467     TMsvId &aMsvIdParent,  // Message ID of the parent message entry
       
   468     RFile &aFile,          // File to the attachment
       
   469     const TDesC& aRemoteBluetoothName)  // bluetooth name of remote device
       
   470     {
       
   471     FLOG(_L("[OBEXUTILS]\t TObexUtilsMessageHandler::CreateInboxAttachmentL()"));
       
   472     
       
   473     CDummySessionObserver* sessionObs;
       
   474     CMsvSession* msvSession;
       
   475     CMsvEntry* inbox;
       
   476     CreateMsvSessionLC(sessionObs, msvSession, inbox, KMsvGlobalInBoxIndexEntryId);
       
   477     // 1st, 2nd, 3rd push
       
   478 
       
   479     TBuf<KObexUtilsMaxCharToFromField> toFrom;
       
   480 
       
   481     // todo @ QT migration: load from string id for localization
       
   482     if (aMtmId == KUidMsgTypeBt)
       
   483         {
       
   484         _LIT(KBluetoothMsg, "Bluetooth message");
       
   485         toFrom.Copy(KBluetoothMsg);
       
   486         }
       
   487     else
       
   488         {
       
   489         _LIT(KInfraredMsg, "Infrared message");
       
   490         toFrom.Copy(KInfraredMsg);    
       
   491         }
       
   492     
       
   493     TMsvEntry parentTEntry;
       
   494     parentTEntry.iMtm = aMtmId;
       
   495     parentTEntry.SetVisible(EFalse); // Make invisible..
       
   496     parentTEntry.SetUnread(ETrue);
       
   497     
       
   498     // ...and in preparation to make sure it gets cleaned up on errors.
       
   499     //
       
   500     parentTEntry.SetInPreparation(ETrue); 
       
   501     parentTEntry.iType = KUidMsvMessageEntry;
       
   502     parentTEntry.iServiceId = KMsvUnknownServiceIndexEntryId;
       
   503     // iDate & iSize will be set later
       
   504     if ( aRemoteBluetoothName.Length() > 0 )
       
   505         {
       
   506         parentTEntry.iDetails.Set(aRemoteBluetoothName);
       
   507         }
       
   508     else
       
   509         {
       
   510         parentTEntry.iDetails.Set(toFrom);
       
   511         }
       
   512     inbox->CreateL(parentTEntry);
       
   513     
       
   514     aMsvIdParent = parentTEntry.Id();
       
   515     
       
   516     // Create attachment for the inbox entry
       
   517     
       
   518     TMsvEntry attachTEntry;
       
   519     attachTEntry.iType      = KUidMsvAttachmentEntry;
       
   520     attachTEntry.iServiceId = KMsvUnknownServiceIndexEntryId;   
       
   521     attachTEntry.iMtm       = aMtmId;
       
   522     
       
   523     CMsvEntry* parentEntry = msvSession->GetEntryL(aMsvIdParent);
       
   524     CleanupStack::PushL(parentEntry);  // 4th push
       
   525     parentEntry->CreateL(attachTEntry);  // create attachment as child of parent
       
   526     
       
   527     // create the v2 attachment, save RFile
       
   528     
       
   529     CMsvEntry* attachEntry = msvSession->GetEntryL(attachTEntry.Id());
       
   530     CleanupStack::PushL(attachEntry);  // 5th push
       
   531     
       
   532     CMsvStore* store = attachEntry->EditStoreL();
       
   533     CleanupStack::PushL(store);  // 6th push
       
   534     CMsvAttachment* attachment = CMsvAttachment::NewL(CMsvAttachment::EMsvFile);
       
   535     CleanupStack::PushL(attachment);  // 7th push
       
   536      
       
   537     store->AttachmentManagerExtensionsL().CreateAttachmentL(_L("Unnamed"), aFile, attachment);
       
   538     CleanupStack::Pop(attachment);
       
   539     store->CommitL();
       
   540     // CommitL() required here otherwise EditStoreL() will fail in SaveObjToInbox()
       
   541     
       
   542     CleanupStack::PopAndDestroy(6);
       
   543     // store, attachEntry, parentEntry, inbox, msvSession, sessionObs
       
   544 
       
   545     FLOG(_L("[OBEXUTILS]\t TObexUtilsMessageHandler::CreateInboxAttachmentL() completed"));
       
   546     }
       
   547 
       
   548 // -----------------------------------------------------------------------------
       
   549 // CObexUtilsMessageHandler::RemoveInboxEntriesL
       
   550 // -----------------------------------------------------------------------------
       
   551 EXPORT_C void TObexUtilsMessageHandler::RemoveInboxEntriesL(
       
   552     CObexBufObject* &aBufObject, // Obex object
       
   553     TMsvId aMsvIdParent)         // Message ID of the parent message entry
       
   554     {
       
   555     FLOG(_L("[OBEXUTILS]\t TObexUtilsMessageHandler::RemoveInboxEntriesL()"));
       
   556     
       
   557     CDummySessionObserver* sessionObs;
       
   558     CMsvSession* msvSession;
       
   559     CMsvEntry* inbox;
       
   560     CreateMsvSessionLC(sessionObs, msvSession, inbox, KMsvGlobalInBoxIndexEntryId);
       
   561     // 1st, 2nd, 3rd push
       
   562     
       
   563     // Close file
       
   564     
       
   565     RemoveObexBuffer(aBufObject);
       
   566     
       
   567     // Delete parent and descendants
       
   568     if ( aMsvIdParent )
       
   569         {
       
   570         inbox->DeleteL(aMsvIdParent);
       
   571         }
       
   572     
       
   573     CleanupStack::PopAndDestroy(3);
       
   574     
       
   575     FLOG(_L("[OBEXUTILS]\t TObexUtilsMessageHandler::RemoveInboxEntriesL() completed"));
       
   576     }
       
   577 
       
   578 // -----------------------------------------------------------------------------
       
   579 // CObexUtilsMessageHandler::SaveObjToInboxL
       
   580 // -----------------------------------------------------------------------------
       
   581 //
       
   582 EXPORT_C void TObexUtilsMessageHandler::SaveObjToInboxL( 
       
   583     CObexBufObject* /*aReceivedObject*/, const TDesC16& /*aPath*/, const TUid /*aMtmID*/ )
       
   584     {
       
   585     }
       
   586 
       
   587 // -----------------------------------------------------------------------------
       
   588 // CObexUtilsMessageHandler::SaveObjToInboxL
       
   589 // -----------------------------------------------------------------------------
       
   590 //
       
   591 EXPORT_C void TObexUtilsMessageHandler::SaveObjToInboxL(
       
   592     CObexBufObject* &aReceivedObject, // Obex object
       
   593     RFile  &aFile,         
       
   594     TMsvId aMsvIdParent)              // Message ID of the parent message entry
       
   595     {
       
   596     FLOG(_L("[OBEXUTILS]\t TObexUtilsMessageHandler::SaveObjToInboxL()"));
       
   597 
       
   598     // Open session. 
       
   599     CDummySessionObserver* sessionObs;
       
   600     CMsvSession* msvSession;
       
   601     CreateMsvSessionLC(sessionObs, msvSession);  // 1st, 2nd push
       
   602 
       
   603     CMsvEntry* parentEntry = msvSession->GetEntryL(aMsvIdParent);
       
   604     CleanupStack::PushL( parentEntry );  // 3rd push
       
   605 
       
   606 #ifdef __BT_SAP
       
   607     if(CSapVMessageParser::HandleMessageL(aReceivedObject, parentEntry->Entry().iMtm,
       
   608         aFile, msvSession, GetCurrentTime()))
       
   609         {
       
   610         RemoveObexBuffer(aReceivedObject);
       
   611         CMsvEntry* inbox = msvSession->GetEntryL( KMsvGlobalInBoxIndexEntryId );
       
   612         CleanupStack::PushL( inbox );         //4th push
       
   613         inbox->DeleteL(aMsvIdParent);
       
   614         // Close session etc.
       
   615         CleanupStack::PopAndDestroy(4, sessionObs);  // inbox, parentEntry, session, sessionObs
       
   616         FLOG(_L("[OBEXUTILS]\t TObexUtilsMessageHandler::SaveObjToInboxL() completed"));
       
   617         return;
       
   618         }
       
   619 #endif // __BT_SAP
       
   620     CMsvEntry* attachEntry = msvSession->GetEntryL(((*parentEntry)[0]).Id());
       
   621     CleanupStack::PushL(attachEntry); // 4th push
       
   622 
       
   623     CMsvStore* store = attachEntry->EditStoreL();
       
   624     CleanupStack::PushL( store );  // 5th push
       
   625 
       
   626     // Collect obex received data before obex buffer deletion
       
   627 
       
   628     TReceivedData receivedData;
       
   629     receivedData.bytesReceived = aReceivedObject->BytesReceived();
       
   630     receivedData.recTime = aReceivedObject->Time();
       
   631 
       
   632     RFs& fsSess = msvSession->FileSession();
       
   633     receivedData.msgName = aReceivedObject->Name();
       
   634     MakeValidFileName(fsSess, receivedData.msgName);
       
   635 
       
   636     // Rename attachment for MIME type checking
       
   637     
       
   638     RemoveObexBuffer(aReceivedObject);
       
   639     store->AttachmentManagerExtensionsL().RenameAttachmentL(0, receivedData.msgName);
       
   640     RFile newFile = store->AttachmentManagerL().GetAttachmentFileL(0);
       
   641     CleanupClosePushL(newFile);  // 6th push
       
   642     
       
   643     // RenameAttachmentL() modified attachment info, so read it now
       
   644     
       
   645     CMsvAttachment* attachInfo = store->AttachmentManagerL().GetAttachmentInfoL(0);
       
   646     CleanupStack::PushL( attachInfo ); // 7th push
       
   647 
       
   648     TUid bioMsgId;  // SaveMimeAndGetBioLC modifies this
       
   649     TFileName fileName;
       
   650     newFile.FullName(fileName);
       
   651     CBIODatabase* bioDB = SaveMimeAndGetBioLC( fileName, fsSess, attachInfo, bioMsgId );
       
   652     // 8th push
       
   653     if (bioDB)  // bio message
       
   654         {
       
   655         FLOG(_L("[OBEXUTILS]\t TObexUtilsMessageHandler::SaveObjToInboxL() BIO"));
       
   656         StoreAndUpdateBioMessageL( bioDB, bioMsgId, parentEntry, newFile );
       
   657         FinaliseMessageL(parentEntry, receivedData, store, ETrue);
       
   658         TMsvId attachId = attachEntry->EntryId();
       
   659         CleanupStack::PopAndDestroy(5);  // bioDB, attachInfo, newFile (close),
       
   660                                          // store, attachEntry
       
   661         // PopAndDestroying here because open store locks the entry,
       
   662         // it can be deleted only after destroying the store pointer
       
   663         parentEntry->DeleteL(attachId);  // invalidate unused attachment
       
   664         CleanupStack::PopAndDestroy(3);  // parentEntry, msvSession, sessionObs
       
   665         FLOG(_L("[OBEXUTILS]\t TObexUtilsMessageHandler::SaveObjToInboxL() BIO completed"));
       
   666         }
       
   667     else  // attachment message
       
   668         {
       
   669         FLOG(_L("[OBEXUTILS]\t TObexUtilsMessageHandler::SaveObjToInboxL() Attachment"));
       
   670         CleanupStack::PopAndDestroy();   // bioDB
       
   671         UpdateAttachmentInformationL(receivedData, attachEntry, attachInfo, store);
       
   672         CleanupStack::Pop(attachInfo);   // ownership taken by ModifyAttachmentInfoL()
       
   673         FinaliseMessageL(parentEntry, receivedData, store, EFalse);
       
   674         CleanupStack::PopAndDestroy(6);  // newFile (close), store, attachEntry,
       
   675                                          // parentEntry, msvSession, sessionObs
       
   676         FLOG(_L("[OBEXUTILS]\t TObexUtilsMessageHandler::SaveObjToInboxL() Attachment completed"));
       
   677         }
       
   678 
       
   679     FLOG(_L("[OBEXUTILS]\t TObexUtilsMessageHandler::SaveObjToInboxL() completed"));
       
   680     }
       
   681 
       
   682 
       
   683 // -----------------------------------------------------------------------------
       
   684 // GetCenRepKeyStringValueL Gets integer repository value
       
   685 // Returns: Error
       
   686 // -----------------------------------------------------------------------------
       
   687 //
       
   688 EXPORT_C TInt TObexUtilsMessageHandler::GetCenRepKeyStringValueL(
       
   689     TUid aRepositoryUid,  // aRepositoryUid Central repository's UID value
       
   690     TUint32 aId,          // Central repository's ID value
       
   691     TDes& aVal)           // Returned String
       
   692     {
       
   693     CRepository* storage = CRepository::NewLC( aRepositoryUid );
       
   694     TInt retval = storage->Get( aId, aVal );
       
   695     if (retval != KErrNone)
       
   696         {
       
   697         FLOG(_L("[OBEXUTILS]\t GetCenRepKeyStringValueL() Get failed"));
       
   698         }
       
   699     CleanupStack::PopAndDestroy( storage );
       
   700     return retval;
       
   701     }
       
   702 
       
   703 // -----------------------------------------------------------------------------
       
   704 // CreateReceiveBufferL Creates an Obex receive buffer object and RFile object.
       
   705 // Returns: Symbian error code
       
   706 // -----------------------------------------------------------------------------
       
   707 //
       
   708 
       
   709 EXPORT_C TInt TObexUtilsMessageHandler::CreateReceiveBufferAndRFileL(
       
   710     RFile& aFile,
       
   711     const TDesC& aPath,
       
   712     TFileName& aFullName, 
       
   713     CBufFlat* &aReceiveObject, 
       
   714     const TInt aBufSize )  
       
   715     {
       
   716     
       
   717     FLOG(_L("[OBEXUTILS]\t TObexUtilsMessageHandler::CreateReceiveBufferAndRFileL()"));
       
   718     
       
   719     aReceiveObject = CBufFlat::NewL(aBufSize); 
       
   720     aReceiveObject->ResizeL(aBufSize);
       
   721     
       
   722     
       
   723     RFs rfs;
       
   724     User::LeaveIfError( rfs.Connect() );
       
   725     if ( !BaflUtils::FolderExists( rfs, aPath ) )
       
   726         {
       
   727         User::LeaveIfError(rfs.MkDirAll(aPath));
       
   728         }
       
   729     User::LeaveIfError( aFile.Temp( rfs, aPath, aFullName, EFileWrite) );
       
   730     // Set temp file  hidden file.
       
   731     //
       
   732     TUint setAttMask(0);
       
   733     TUint clearAttMask(0);
       
   734     aFile.SetAtt(setAttMask | KEntryAttHidden, clearAttMask);
       
   735     aFile.Flush();
       
   736     aFile.Close();
       
   737     
       
   738     RFile logFile;
       
   739     TFileName logFilePath;
       
   740     TFileName cenRepFolder;
       
   741     GetCenRepKeyStringValueL(KCRUidBluetoothEngine, KLCReceiveFolder,cenRepFolder);
       
   742     
       
   743     logFilePath.Zero();
       
   744     logFilePath.Append(PathInfo::PhoneMemoryRootPath());
       
   745     logFilePath.Append(cenRepFolder);
       
   746     
       
   747     if ( !BaflUtils::FolderExists(rfs , logFilePath) )
       
   748         {
       
   749         User::LeaveIfError(rfs.MkDirAll(logFilePath));
       
   750         }
       
   751     logFilePath.Append(_L("log.txt"));
       
   752     if ( !BaflUtils::FileExists( rfs, logFilePath ))
       
   753         {
       
   754         logFile.Create(rfs, logFilePath, EFileWrite);
       
   755         }
       
   756     else
       
   757         {
       
   758         User::LeaveIfError(logFile.Open(rfs, logFilePath, EFileWrite));
       
   759         }
       
   760     
       
   761     FLOG(_L("[OBEXUTILS]\t TObexUtilsMessageHandler::CreateReceiveBufferAndRFileL()    log.txt is created"));
       
   762     TFileText ft;              
       
   763     ft.Set(logFile);
       
   764     ft.Write(aFullName);    // restore tempfilename in logfile
       
   765 
       
   766     // Set log file 
       
   767     logFile.SetAtt(setAttMask | KEntryAttHidden, clearAttMask);
       
   768     logFile.Flush();
       
   769     logFile.Close();
       
   770     rfs.Close();
       
   771     
       
   772     FLOG(_L("[OBEXUTILS]\t TObexUtilsMessageHandler::CreateReceiveBufferAndRFileL() completed"));
       
   773     
       
   774     return KErrNone;
       
   775     }
       
   776 
       
   777 // -----------------------------------------------------------------------------
       
   778 // CObexUtilsMessageHandler::RemoveTemporaryRFileL
       
   779 // -----------------------------------------------------------------------------
       
   780 //
       
   781 EXPORT_C void TObexUtilsMessageHandler::RemoveTemporaryRFileL ( const TFileName& aFullName )
       
   782     {
       
   783     FLOG(_L("[OBEXUTILS]\t TObexUtilsMessageHandler::RemoveTemporaryRFileL()"));
       
   784     RFs rfs;
       
   785     User::LeaveIfError(rfs.Connect());
       
   786     
       
   787     TParse fileNameParser;
       
   788     User::LeaveIfError(fileNameParser.Set(aFullName, NULL, NULL));
       
   789     
       
   790     TFileName logFilePath;
       
   791     TFileName cenRepFolder;
       
   792     GetCenRepKeyStringValueL(KCRUidBluetoothEngine, KLCReceiveFolder,cenRepFolder);
       
   793     logFilePath.Zero();
       
   794     logFilePath.Append(PathInfo::PhoneMemoryRootPath());
       
   795     logFilePath.Append(cenRepFolder);
       
   796     logFilePath.Append(_L("log.txt"));
       
   797             
       
   798     if ( fileNameParser.Ext().Compare(_L(".$$$")) == 0  )                                                                           
       
   799         {
       
   800         // aFullName is a temp file name, we need to remove it.        
       
   801         rfs.Delete( aFullName );
       
   802         FLOG(_L("[OBEXUTILS]\t TObexUtilsMessageHandler::RemoveTemporaryRFileL() temp file is removed (bt off)"));
       
   803         }
       
   804     else if ( (aFullName.Length() == 0) && BaflUtils::FileExists(rfs, logFilePath))
       
   805         {
       
   806         RFile logFile;
       
   807         User::LeaveIfError(logFile.Open(rfs, logFilePath, EFileRead));
       
   808         TFileText ft;
       
   809         ft.Set(logFile);
       
   810         TFileName tempFileName;
       
   811         ft.Read(tempFileName);  // read tempfile name stored in logfile.
       
   812         
       
   813         if ( tempFileName.Length() > 0 )
       
   814             {
       
   815             rfs.Delete(tempFileName);
       
   816             }
       
   817         logFile.Close();   
       
   818         FLOG(_L("[OBEXUTILS]\t TObexUtilsMessageHandler::RemoveTemporaryRFileL() temp files are removed (reboot)"));
       
   819         }              
       
   820     rfs.Delete( logFilePath );
       
   821     rfs.Close();
       
   822     FLOG(_L("[OBEXUTILS]\t TObexUtilsMessageHandler::RemoveTemporaryRFileL() completed"));
       
   823     }
       
   824 // -----------------------------------------------------------------------------
       
   825 // CObexUtilsMessageHandler::SaveFileToFileSystemL
       
   826 // -----------------------------------------------------------------------------
       
   827 //
       
   828 EXPORT_C void TObexUtilsMessageHandler::SaveFileToFileSystemL(
       
   829     CObexBufObject* &aReceivedObject,
       
   830     const TUid aMtmId,
       
   831     TMsvId& aMsvIdParent,
       
   832     TFileName& aFullName, 
       
   833     RFile& aFile,
       
   834     const TDesC& aSenderBluetoothName)
       
   835     {
       
   836    
       
   837     FLOG(_L("[OBEXUTILS]\t TObexUtilsMessageHandler::SaveFileToFileSystemL()"));
       
   838     // Create inbox entry ( this was done in CreateAttachment() before )
       
   839     //
       
   840     CDummySessionObserver* sessionObs;
       
   841     CMsvSession* msvSession;
       
   842     CMsvEntry* inbox;
       
   843     CreateMsvSessionLC(sessionObs, msvSession, inbox, KMsvGlobalInBoxIndexEntryId);
       
   844     // 1st, 2nd, 3rd push
       
   845 
       
   846     TBuf<KObexUtilsMaxCharToFromField> toFrom;
       
   847 
       
   848     // todo @ QT migration: load from string id for localization
       
   849     if (aMtmId == KUidMsgTypeBt)
       
   850         {
       
   851         _LIT(KBluetoothMsg, "Bluetooth message");
       
   852         toFrom.Copy(KBluetoothMsg);
       
   853         }
       
   854     else
       
   855         {
       
   856         _LIT(KInfraredMsg, "Infrared message");
       
   857         toFrom.Copy(KInfraredMsg);    
       
   858         }
       
   859     
       
   860     // NOTE: toFrom will be updated to Bluetooth sender's bt name in the future.
       
   861 
       
   862     TMsvEntry parentTEntry;   
       
   863     parentTEntry.iMtm = aMtmId;
       
   864     parentTEntry.SetVisible(EFalse); // Make invisible..
       
   865     parentTEntry.SetUnread(ETrue);  //  Set msg to Unread
       
   866         
       
   867     // ...and in preparation to make sure it gets cleaned up on errors.
       
   868     //
       
   869     parentTEntry.SetInPreparation(ETrue); 
       
   870     parentTEntry.iType = KUidMsvMessageEntry;
       
   871     parentTEntry.iServiceId = KMsvUnknownServiceIndexEntryId;
       
   872     // iDate & iSize will be set later
       
   873     if ( aSenderBluetoothName.Length() > 0 )
       
   874         {
       
   875         parentTEntry.iDetails.Set(aSenderBluetoothName);
       
   876         }
       
   877     else
       
   878         {
       
   879         parentTEntry.iDetails.Set(toFrom);
       
   880         }
       
   881     inbox->CreateL(parentTEntry);
       
   882         
       
   883     aMsvIdParent = parentTEntry.Id();
       
   884         
       
   885     // Create attachment for the inbox entry
       
   886     
       
   887     TMsvEntry attachTEntry;
       
   888     attachTEntry.iType      = KUidMsvAttachmentEntry;
       
   889     attachTEntry.iServiceId = KMsvUnknownServiceIndexEntryId;   
       
   890     attachTEntry.iMtm       = aMtmId;
       
   891      
       
   892     CMsvEntry* parentEntry = msvSession->GetEntryL(aMsvIdParent);
       
   893     CleanupStack::PushL(parentEntry);  // 4th push
       
   894     parentEntry->CreateL(attachTEntry);  // create attachment as child of parent
       
   895   
       
   896     // Check if message is sap message
       
   897     // If we delete parent entry in sap, we have to delete the RFile object ourself as well )
       
   898     //
       
   899     RFs& fsSess = msvSession->FileSession();
       
   900     TFileName tempFullName;
       
   901     aFile.FullName(tempFullName);
       
   902     
       
   903 #ifdef __BT_SAP   
       
   904     if(CSapVMessageParser::HandleMessageL(aReceivedObject, parentEntry->Entry().iMtm,
       
   905             aFile, msvSession, GetCurrentTime()))
       
   906         {
       
   907         RemoveObexBuffer(aReceivedObject);
       
   908         CMsvEntry* inbox = msvSession->GetEntryL( KMsvGlobalInBoxIndexEntryId );
       
   909         CleanupStack::PushL( inbox );         //5th push
       
   910         inbox->DeleteL(aMsvIdParent);
       
   911         fsSess.Delete(tempFullName);  // we have to use fullname to delete the file object in file system 
       
   912         // Close session etc.
       
   913         CleanupStack::PopAndDestroy(5, sessionObs);  // inbox, parentEntry, session, sessionObs
       
   914         FLOG(_L("[OBEXUTILS]\t TObexUtilsMessageHandler::SaveFileToFileSystemL() completed"));
       
   915         return;
       
   916         }
       
   917 #endif // __BT_SAP
       
   918 
       
   919     // Collect obex received data before obex buffer deletion
       
   920     TReceivedData receivedData;
       
   921     receivedData.bytesReceived = aReceivedObject->BytesReceived();
       
   922     receivedData.recTime = aReceivedObject->Time();
       
   923     receivedData.msgName = aReceivedObject->Name();
       
   924     
       
   925     TFileName filename;
       
   926     TParse parse;
       
   927     parse.Set(aFullName, NULL, NULL);
       
   928     filename.Copy(receivedData.msgName);
       
   929     FixExtremeLongFileName(filename, parse.DriveAndPath());
       
   930     MakeValidFileName( fsSess, filename);     
       
   931     RemoveObexBuffer(aReceivedObject);
       
   932 
       
   933     // We set file to visible before renaming 
       
   934     // so that photo/music app can scan the media files we recevie. 
       
   935     //
       
   936     // Set file back to visible
       
   937     //
       
   938     TUint setAttMask(0);
       
   939     TUint clearAttMask(0);
       
   940     User::LeaveIfError(aFile.Open(fsSess,tempFullName,EFileWrite));
       
   941     User::LeaveIfError(aFile.SetAtt(setAttMask , clearAttMask | KEntryAttHidden));
       
   942     aFile.Close();
       
   943     
       
   944     
       
   945     // Move file to the actual drive and directory
       
   946     // as well rename the file with the correct file name instead of temporary name 
       
   947     // tempFullName will be updated in RenameFileL()    
       
   948     TInt error = RenameFileL(tempFullName, filename, parse.DriveAndPath(), fsSess);
       
   949     
       
   950     if ( error != KErrNone )
       
   951         {
       
   952         fsSess.Delete(tempFullName);   // If rename fails, we remove the temp RFile object.
       
   953         }
       
   954     aFullName = tempFullName; // assign new full Name back to aFullName,which goes back to caller
       
   955     
       
   956     CleanupStack::PopAndDestroy(4);         // parentEntry, inbox, msvSession, sessionObs
       
   957      
       
   958     FLOG(_L("[OBEXUTILS]\t TObexUtilsMessageHandler::SaveFileToFileSystemL() completed"));
       
   959     }
       
   960 
       
   961 // -----------------------------------------------------------------------------
       
   962 // CObexUtilsMessageHandler::AddEntryToInboxL
       
   963 // -----------------------------------------------------------------------------
       
   964 //
       
   965 EXPORT_C void TObexUtilsMessageHandler::AddEntryToInboxL( 
       
   966     TMsvId& aMsvIdParent,
       
   967     TFileName& aFullName)
       
   968     {
       
   969     FLOG(_L("[OBEXUTILS]\t TObexUtilsMessageHandler::AddEntryToInboxL() "));
       
   970         
       
   971     CDummySessionObserver* sessionObs;
       
   972     CMsvSession* msvSession;
       
   973     CreateMsvSessionLC(sessionObs, msvSession);
       
   974     // 1st, 2nd push
       
   975         
       
   976     CMsvEntry* parentEntry = msvSession->GetEntryL(aMsvIdParent);
       
   977     CleanupStack::PushL(parentEntry);  // 3th push
       
   978     
       
   979     CMsvEntry* attachEntry = msvSession->GetEntryL(((*parentEntry)[0]).Id());
       
   980     CleanupStack::PushL(attachEntry); // 4th push
       
   981             
       
   982     CMsvStore* store = attachEntry->EditStoreL();
       
   983     CleanupStack::PushL( store );  // 5th push
       
   984         
       
   985     CObexutilsEntryhandler* entryHandler = CObexutilsEntryhandler::NewL();
       
   986     CleanupStack::PushL(entryHandler);  // 6th push  
       
   987                 
       
   988     CMsvAttachment* attachInfo = CMsvAttachment::NewL(CMsvAttachment::EMsvLinkedFile);
       
   989     CleanupStack::PushL(attachInfo);  // 7th push
       
   990            
       
   991     // Create attachment Info
       
   992     //
       
   993     RFs& fsSess = msvSession->FileSession();
       
   994         
       
   995     TParse fileNameParser;
       
   996     User::LeaveIfError(fileNameParser.Set(aFullName, NULL, NULL));
       
   997     attachInfo->SetAttachmentNameL( fileNameParser.FullName());
       
   998                  
       
   999     TEntry fileEntry;
       
  1000     User::LeaveIfError(fsSess.Entry( fileNameParser.FullName(), fileEntry) );
       
  1001     attachInfo->SetSize(fileEntry.iSize);
       
  1002             
       
  1003     // check if it's the bio message
       
  1004            
       
  1005     TUid bioMsgId;  // SaveMimeAndGetBioLC modifies this
       
  1006     CBIODatabase* bioDB = SaveMimeAndGetBioLC( aFullName, fsSess, attachInfo, bioMsgId );
       
  1007     // 8th push
       
  1008     if (bioDB)  // bio message
       
  1009         {
       
  1010         FLOG(_L("[OBEXUTILS]\t TObexUtilsMessageHandler::AddEntryToInboxL() BIO"));
       
  1011     
       
  1012         RFile file;
       
  1013         User::LeaveIfError(file.Open(fsSess,aFullName,EFileShareReadersOnly));
       
  1014         TReceivedData receivedData;
       
  1015         receivedData.bytesReceived = fileEntry.iSize;
       
  1016         receivedData.recTime = fileEntry.iModified;
       
  1017         receivedData.msgName = fileNameParser.Name();     
       
  1018                     
       
  1019         StoreAndUpdateBioMessageL( bioDB, bioMsgId, parentEntry, file );
       
  1020         FinaliseMessageL(parentEntry, receivedData, store, ETrue);
       
  1021         TMsvId attachId = attachEntry->EntryId();
       
  1022         file.Close();
       
  1023         fsSess.Delete(aFullName);
       
  1024         CleanupStack::PopAndDestroy(5);  // bioDB, attachInfo, linkHandler,
       
  1025                                              // store, attachEntry
       
  1026             
       
  1027         // PopAndDestroying here because open store locks the entry,
       
  1028         // it can be deleted only after destroying the store pointer
       
  1029         parentEntry->DeleteL(attachId);  // invalidate unused attachment
       
  1030         CleanupStack::PopAndDestroy(3);  // parentEntry, msvSession, sessionObs
       
  1031         FLOG(_L("[OBEXUTILS]\t TObexUtilsMessageHandler::AddEntryToInboxL() BIO completed"));
       
  1032         }
       
  1033     else
       
  1034         {
       
  1035 
       
  1036         CleanupStack::PopAndDestroy();  // bioDB
       
  1037         // Add entry to Inbox
       
  1038         entryHandler->AddEntryAttachment(aFullName, attachInfo, store);
       
  1039         CleanupStack::Pop(attachInfo);   // attachInfo, Pass ownership to store
       
  1040         CleanupStack::PopAndDestroy(entryHandler);  // entryHandler
       
  1041         FinaliseMessageL(parentEntry, store,fileEntry, fileNameParser);
       
  1042         CleanupStack::PopAndDestroy(5);         // linkHandler, attachInfo, store, attachEntry,
       
  1043                                                     // parentEntry, msvSession, sessionObs                            
       
  1044         FLOG(_L("[OBEXUTILS]\t TObexUtilsMessageHandler::AddEntryToInboxL() completed "));
       
  1045         }
       
  1046     }
       
  1047 
       
  1048 // -----------------------------------------------------------------------------
       
  1049 // CObexUtilsMessageHandler::AddEntryToInboxL
       
  1050 // -----------------------------------------------------------------------------
       
  1051 //
       
  1052 EXPORT_C void TObexUtilsMessageHandler::AddEntryToInboxL( 
       
  1053     TMsvId& aMsvIdParent,
       
  1054     TFileName& aFullName,
       
  1055     RArray<TMsvId>* aMsvIdArray)
       
  1056     {
       
  1057     AddEntryToInboxL(aMsvIdParent, aFullName);
       
  1058     aMsvIdArray->Append(aMsvIdParent);
       
  1059     }
       
  1060 
       
  1061 // -----------------------------------------------------------------------------
       
  1062 // CObexUtilsMessageHandler::UpdateEntryAttachmentL
       
  1063 // -----------------------------------------------------------------------------
       
  1064 //
       
  1065 EXPORT_C void TObexUtilsMessageHandler::UpdateEntryAttachmentL ( 
       
  1066     TFileName& aFullName,
       
  1067     CMsvEntry* aParentEntry)
       
  1068     {
       
  1069     FLOG(_L("[OBEXUTILS]\t TObexUtilsMessageHandler::UpdateEntryAttachmentL() "));
       
  1070     CDummySessionObserver* sessionObs;
       
  1071     CMsvSession* msvSession;
       
  1072     CreateMsvSessionLC(sessionObs, msvSession);
       
  1073     // 1st, 2nd push
       
  1074       
       
  1075     CMsvEntry* attachEntry = msvSession->GetEntryL(((*aParentEntry)[0]).Id());
       
  1076     CleanupStack::PushL(attachEntry); // 3th push
       
  1077             
       
  1078     CMsvStore* store = attachEntry->EditStoreL();
       
  1079     CleanupStack::PushL( store );  // 4th push
       
  1080   
       
  1081     CObexutilsEntryhandler* entryHandler = CObexutilsEntryhandler::NewL();
       
  1082     CleanupStack::PushL(entryHandler);  // 5th push  
       
  1083     
       
  1084     // Note:
       
  1085     // Because setFilePath() in CMsvAttachment is not implementated by Symbian yet, 
       
  1086     // we have to delete the original attachment and add another new one to fix the broken link.
       
  1087     //
       
  1088     
       
  1089     // remove the old attachment first.
       
  1090     //
       
  1091     store->AttachmentManagerExtensionsL().RemoveAttachmentL(0);
       
  1092     // Create a new attachment.
       
  1093     //
       
  1094     CMsvAttachment* attachInfo = CMsvAttachment::NewL(CMsvAttachment::EMsvLinkedFile);
       
  1095     CleanupStack::PushL(attachInfo);  // 6th  push
       
  1096     
       
  1097     // Get mime type
       
  1098     //
       
  1099     RecogniseObjectsL(aFullName, attachInfo);
       
  1100     RFs& fsSess = msvSession->FileSession();
       
  1101     
       
  1102     TParse fileNameParser;
       
  1103     User::LeaveIfError(fileNameParser.Set(aFullName, NULL, NULL));
       
  1104     attachInfo->SetAttachmentNameL(fileNameParser.NameAndExt());
       
  1105     TEntry fileEntry;
       
  1106     User::LeaveIfError(fsSess.Entry( fileNameParser.FullName(), fileEntry) );
       
  1107     attachInfo->SetSize(fileEntry.iSize);
       
  1108 
       
  1109     entryHandler->AddEntryAttachment(aFullName,attachInfo, store);
       
  1110     CleanupStack::Pop(attachInfo);   // attachInfo, Pass ownership to store
       
  1111     CleanupStack::PopAndDestroy(entryHandler);  // entryHandler
       
  1112     FinaliseMessageL(aParentEntry, store,fileEntry, fileNameParser);
       
  1113     CleanupStack::PopAndDestroy(4);   // store, 
       
  1114                                       // attachEntry, msvSession, sessionObs
       
  1115     FLOG(_L("[OBEXUTILS]\t TObexUtilsMessageHandler::UpdateEntryAttachmentL() completed "));
       
  1116     }
       
  1117 
       
  1118 
       
  1119 // Common methods
       
  1120 
       
  1121 // -----------------------------------------------------------------------------
       
  1122 // ConstructRichTextLC Handles rich text initialisation.
       
  1123 // Returns: CRichText* A pointer to the rich text.
       
  1124 // -----------------------------------------------------------------------------
       
  1125 //
       
  1126 CRichText* TObexUtilsMessageHandler::ConstructRichTextLC()
       
  1127     {
       
  1128     FLOG(_L("[OBEXUTILS]\t ConstructRichTextLC()"));
       
  1129 
       
  1130     CParaFormatLayer* richParaFormatLayer = CParaFormatLayer::NewL();
       
  1131     CleanupStack::PushL( richParaFormatLayer );
       
  1132 
       
  1133     CCharFormatLayer* richCharFormatLayer = CCharFormatLayer::NewL(); 
       
  1134     CleanupStack::PushL( richCharFormatLayer );
       
  1135     CRichText* richText = CRichText::NewL( richParaFormatLayer, 
       
  1136                                            richCharFormatLayer );
       
  1137     CleanupStack::PushL(richText);
       
  1138 
       
  1139     FLOG(_L("[OBEXUTILS]\t ConstructRichTextLC() completed"));
       
  1140 
       
  1141     return richText;
       
  1142     }
       
  1143 
       
  1144 // -----------------------------------------------------------------------------
       
  1145 // MakeValidFileName Rename the given filename to a valid filename.
       
  1146 // Removes invalid characters from a filename; if no characters left, filename
       
  1147 // is set to R_NAME_FOR_INVALID_FILE
       
  1148 // Returns: None.
       
  1149 // -----------------------------------------------------------------------------
       
  1150 //
       
  1151 void TObexUtilsMessageHandler::MakeValidFileName( 
       
  1152     RFs& aFileSession, // A reference to file server session.
       
  1153     TDes& aFileName )  // The filename to modify.
       
  1154     {
       
  1155     FLOG(_L("[OBEXUTILS]\t MakeValidFileName()"));
       
  1156 
       
  1157     TParse fileParse;
       
  1158     fileParse.Set(aFileName, NULL, NULL);
       
  1159     
       
  1160     if (fileParse.NameOrExtPresent())
       
  1161         {        
       
  1162         aFileName = fileParse.NameAndExt();
       
  1163         TText badChar;    
       
  1164         TInt nameLength = aFileName.Length();
       
  1165     
       
  1166         while ( !aFileSession.IsValidName(aFileName, badChar) )
       
  1167             {
       
  1168             // Locate and delete all instances of the bad char
       
  1169             FOREVER
       
  1170                 {
       
  1171                 TInt index = aFileName.Locate(TChar(badChar)); 
       
  1172                 nameLength--;
       
  1173                 if (index == KErrNotFound)
       
  1174                     {
       
  1175                     break;
       
  1176                     }             
       
  1177                 aFileName.Delete(index,1);               
       
  1178                 }
       
  1179                 if ( nameLength <= 0 )
       
  1180                     {
       
  1181                     break;
       
  1182                     }
       
  1183             }    
       
  1184         }    
       
  1185     FLOG(_L("[OBEXUTILS]\t MakeValidFileName() completed"));
       
  1186     }
       
  1187 
       
  1188 // -----------------------------------------------------------------------------
       
  1189 // TObexUtilsMessageHandler::CreateOutboxEntryL
       
  1190 // -----------------------------------------------------------------------------
       
  1191 //
       
  1192 EXPORT_C TMsvId TObexUtilsMessageHandler::CreateOutboxEntryL(
       
  1193     const TUid& aMtm,          // Message type id
       
  1194     //todo need to check whether to use the textmap id or send as a string here
       
  1195     const TInt& /*aResourceID*/ )  // Resource id for the message entry text
       
  1196     {
       
  1197     FLOG(_L("[OBEXUTILS]\t TObexUtilsMessageHandler::CreateOutboxEntryL()"));
       
  1198 
       
  1199     CDummySessionObserver* sessionObs;
       
  1200     CMsvSession* msvSession;
       
  1201     CMsvEntry* outBoxEntry;
       
  1202     CreateMsvSessionLC(sessionObs, msvSession, outBoxEntry, KMsvGlobalOutBoxIndexEntryId);
       
  1203     // 1st, 2nd, 3rd push
       
  1204 
       
  1205     TBuf<KObexUtilsMaxCharToFromField> toFrom;
       
  1206  //   TObexUtilsUiLayer::ReadResourceL( toFrom, aResourceID );
       
  1207     //todo need to change the string constant to orbit localisation file
       
  1208     toFrom.Copy(_L("Bluetooth message"));
       
  1209 
       
  1210     // Message entry fields
       
  1211     TMsvEntry newTEntry;
       
  1212     newTEntry.SetVisible( ETrue );          // Make visible
       
  1213     newTEntry.SetInPreparation( ETrue );    // and in preparation to make sure gets cleaned up on errors.
       
  1214     newTEntry.iDetails.Set( toFrom );       // To/From field on Outbox
       
  1215     newTEntry.SetSendingState( KMsvSendStateSending );
       
  1216     newTEntry.iType = KUidMsvMessageEntry;      
       
  1217     newTEntry.iMtm = aMtm;                  // message type id 
       
  1218     newTEntry.iServiceId = KMsvGlobalOutBoxIndexEntryId;
       
  1219     outBoxEntry->CreateL( newTEntry );
       
  1220     
       
  1221     CleanupStack::PopAndDestroy(3);         //outBoxEntry, msvSession, sessionObs
       
  1222     return newTEntry.Id();
       
  1223     }
       
  1224 
       
  1225 // -----------------------------------------------------------------------------
       
  1226 // TObexUtilsMessageHandler::DeleteOutboxEntryL
       
  1227 // -----------------------------------------------------------------------------
       
  1228 //
       
  1229 EXPORT_C void TObexUtilsMessageHandler::DeleteOutboxEntryL( const TMsvId& aMessageServerIndex )
       
  1230     {
       
  1231     FLOG(_L("[OBEXUTILS]\t TObexUtilsMessageHandler::DeleteOutboxEntryL()"));
       
  1232 
       
  1233     CDummySessionObserver* sessionObs;
       
  1234     CMsvSession* msvSession;
       
  1235     CMsvEntry* outBoxEntry;
       
  1236     CreateMsvSessionLC(sessionObs, msvSession, outBoxEntry, KMsvGlobalOutBoxIndexEntryId);
       
  1237     // 1st, 2nd, 3rd push
       
  1238 
       
  1239     outBoxEntry->DeleteL( aMessageServerIndex );
       
  1240 
       
  1241     CleanupStack::PopAndDestroy(3);         //outBoxEntry, msvSession, sessionObs
       
  1242     }
       
  1243 
       
  1244 // -----------------------------------------------------------------------------
       
  1245 // TObexUtilsMessageHandler::GetFileSystemStatus
       
  1246 // -----------------------------------------------------------------------------
       
  1247 //
       
  1248 EXPORT_C TInt TObexUtilsMessageHandler::GetFileSystemStatus()
       
  1249     {
       
  1250     FLOG(_L("[OBEXUTILS]\t TObexUtilsMessageHandler::GetFileSystemStatus()"));
       
  1251 
       
  1252     /**
       
  1253     *  Free space level of FFS file system (drive C:)
       
  1254     *  The integer value may be:
       
  1255     *       0: Free space OK
       
  1256     *      -1: Free space at or below warning level
       
  1257     *      -2: Free space at or below critical level
       
  1258     */
       
  1259     
       
  1260     TInt status = KErrNone;
       
  1261     TInt retVal = KErrNone;
       
  1262     
       
  1263     retVal = GetPubSubKeyIntValue(KPSUidUikon, KUikFFSFreeLevel, status);
       
  1264     if ( ( retVal == KErrNone ) && ( status == KFFSBelowCritical ) )
       
  1265         {
       
  1266         retVal = KErrDiskFull;
       
  1267         }
       
  1268      
       
  1269     FTRACE(FPrint(_L("[OBEXUTILS]\t TObexUtilsMessageHandler::GetFileSystemStatus completed with %d."), retVal));
       
  1270     return retVal;
       
  1271     }
       
  1272 
       
  1273 // -----------------------------------------------------------------------------
       
  1274 // TObexUtilsMessageHandler::GetMmcFileSystemStatus
       
  1275 // -----------------------------------------------------------------------------
       
  1276 //
       
  1277 EXPORT_C TInt TObexUtilsMessageHandler::GetMmcFileSystemStatus()
       
  1278     {
       
  1279     FLOG(_L("[OBEXUTILS]\t TObexUtilsMessageHandler::GetMmcFileSystemStatus()"));
       
  1280 
       
  1281     /**
       
  1282     *  Free space level of FFS file system (MMC)
       
  1283     *  The integer value may be:
       
  1284     *       0: Free space OK
       
  1285     *      -1: Free space at or below warning level
       
  1286     *      -2: Free space at or below critical level
       
  1287     */
       
  1288    
       
  1289     TInt retVal = KErrNone;
       
  1290     TInt status = KErrNone;
       
  1291     
       
  1292     retVal = GetPubSubKeyIntValue(KPSUidUikon, KUikMmcFFSFreeLevel, status);
       
  1293     if ( ( retVal == KErrNone ) && ( status == KFFSBelowCritical ) )
       
  1294         {
       
  1295         retVal = KErrDiskFull;
       
  1296         }
       
  1297     
       
  1298     FTRACE(FPrint(_L("[OBEXUTILS]\t TObexUtilsMessageHandler::GetMmcFileSystemStatus completed with %d."), retVal));
       
  1299     return retVal;
       
  1300     }
       
  1301 
       
  1302 // -----------------------------------------------------------------------------
       
  1303 // TObexUtilsMessageHandler::GetMessageCentreDriveL
       
  1304 // -----------------------------------------------------------------------------
       
  1305 //
       
  1306 EXPORT_C TInt TObexUtilsMessageHandler::GetMessageCentreDriveL()
       
  1307     {
       
  1308     FLOG(_L("[OBEXUTILS]\t TObexUtilsMessageHandler::GetMessageCentreDriveL()"));
       
  1309     
       
  1310     CDummySessionObserver* sessionObs;
       
  1311     CMsvSession* msvSession;
       
  1312     CreateMsvSessionLC(sessionObs, msvSession);  // 1st, 2nd push
       
  1313     
       
  1314     TDriveUnit driveUnit = msvSession->CurrentDriveL();
       
  1315     CleanupStack::PopAndDestroy(2);  // msvSession, sessionObs
       
  1316     
       
  1317     FLOG(_L("[OBEXUTILS]\t TObexUtilsMessageHandler::GetMessageCentreDriveL() Completed"));
       
  1318     return driveUnit;
       
  1319     }
       
  1320 
       
  1321 // -----------------------------------------------------------------------------
       
  1322 // TObexUtilsMessageHandler::CreateDefaultMtmServiceL
       
  1323 // -----------------------------------------------------------------------------
       
  1324 //
       
  1325 EXPORT_C void TObexUtilsMessageHandler::CreateDefaultMtmServiceL(TUid aMtm)
       
  1326     {
       
  1327     FLOG(_L("[OBEXUTILS]\t TObexUtilsMessageHandler::CreateDefaultMtmServiceL()"));
       
  1328     
       
  1329     CDummySessionObserver* sessionObs;
       
  1330     CMsvSession* msvSession;
       
  1331     CMsvEntry* root;
       
  1332     CreateMsvSessionLC(sessionObs, msvSession, root, KMsvRootIndexEntryId);
       
  1333     // 1st, 2nd, 3rd push
       
  1334     
       
  1335     TMsvSelectionOrdering msvSelectionOrdering = root->SortType();
       
  1336     msvSelectionOrdering.SetShowInvisibleEntries( ETrue );
       
  1337     root->SetSortTypeL( msvSelectionOrdering );
       
  1338     
       
  1339     CMsvEntrySelection* sel = root->ChildrenWithMtmL( aMtm );
       
  1340     CleanupStack::PushL( sel );  // 4th push
       
  1341     if (sel->Count() == 0)
       
  1342         {
       
  1343         TMsvEntry serviceEntry;
       
  1344         serviceEntry.iMtm = aMtm;
       
  1345         serviceEntry.iType = KUidMsvServiceEntry;
       
  1346         serviceEntry.SetVisible(EFalse);
       
  1347         serviceEntry.SetReadOnly(ETrue);
       
  1348         serviceEntry.SetInPreparation(EFalse);
       
  1349         root->CreateL(serviceEntry);
       
  1350         }
       
  1351     CleanupStack::PopAndDestroy(4);  // sel, root, msvSession, sessionObs
       
  1352     
       
  1353     FLOG(_L("[OBEXUTILS]\t TObexUtilsMessageHandler::CreateDefaultMtmServiceL() Completed"));
       
  1354     }
       
  1355 
       
  1356 // -----------------------------------------------------------------------------
       
  1357 // GetCenRepKeyIntValue Gets integer value for a specified CenRep key
       
  1358 // Returns: CenRep key's value
       
  1359 // -----------------------------------------------------------------------------
       
  1360 //
       
  1361 EXPORT_C TInt TObexUtilsMessageHandler::GetPubSubKeyIntValue(
       
  1362     TUid aCategory,  // Category of the key
       
  1363     TUint aKey,      // PUBSUB key
       
  1364     TInt& value)     // Returned value
       
  1365     {
       
  1366     TInt retVal;
       
  1367     RProperty property;
       
  1368     retVal = property.Attach(aCategory, aKey);
       
  1369     if ( retVal == KErrNone )
       
  1370         {
       
  1371         retVal = property.Get(value);
       
  1372         if (retVal != KErrNone)
       
  1373             {
       
  1374             FLOG(_L("[OBEXUTILS]\t GetPubSubKeyIntValue() Get failed for CenRep key"));
       
  1375             }
       
  1376         }
       
  1377     else
       
  1378         {
       
  1379         FLOG(_L("[OBEXUTILS]\t GetPubSubKeyIntValue() Attach failed for CenRep key"));
       
  1380         }
       
  1381     property.Close();
       
  1382     return retVal;
       
  1383     }
       
  1384 
       
  1385 // -----------------------------------------------------------------------------
       
  1386 // SetBioDataTextL Converts message type to bio message id.
       
  1387 // Returns: None.
       
  1388 // -----------------------------------------------------------------------------
       
  1389 //
       
  1390 void TObexUtilsMessageHandler::SetBioDataTextL(
       
  1391     TBioMsgIdText& aText, // A bio message id text.
       
  1392     const TDesC8& aType ) // The type of the content. 
       
  1393     {
       
  1394     FLOG(_L("[OBEXUTILS]\t SetBioDataTextL()"));
       
  1395 
       
  1396     HBufC16* unicode = CnvUtfConverter::ConvertToUnicodeFromUtf8L( aType );
       
  1397     CleanupStack::PushL( unicode );
       
  1398     
       
  1399     if (unicode->Length() > KMaxBioIdText )
       
  1400         {
       
  1401         User::Leave( KErrOverflow );
       
  1402         }
       
  1403     
       
  1404     aText = unicode->Des();
       
  1405     CleanupStack::PopAndDestroy( unicode );
       
  1406     
       
  1407     FLOG(_L("[OBEXUTILS]\t SetBioDataTextL() completed"));
       
  1408     }
       
  1409 
       
  1410 // -----------------------------------------------------------------------------
       
  1411 // SetDetailsLC Converts message type to unicode.
       
  1412 // Returns: None.
       
  1413 // -----------------------------------------------------------------------------
       
  1414 //
       
  1415 void TObexUtilsMessageHandler::SetDetailsLC(
       
  1416     TPtrC& aDetails,      // A message text.
       
  1417     const TDesC8& aType ) // The type of the content.
       
  1418     {
       
  1419     FLOG(_L("[OBEXUTILS]\t SetDetailsLC()"));
       
  1420 
       
  1421     HBufC16* unicode = CnvUtfConverter::ConvertToUnicodeFromUtf8L( aType );
       
  1422     CleanupStack::PushL( unicode );
       
  1423     aDetails.Set(unicode->Des());
       
  1424 
       
  1425     FLOG(_L("[OBEXUTILS]\t SetDetailsLC() completed"));
       
  1426     }
       
  1427 
       
  1428 //-------------------------------------------------------------------------------
       
  1429 // Rename a file and move file if needed 
       
  1430 // Return: None.
       
  1431 //-------------------------------------------------------------------------------
       
  1432 //
       
  1433 TInt TObexUtilsMessageHandler::RenameFileL(
       
  1434     TFileName& aFileName, 
       
  1435     TFileName& aNewFileName,
       
  1436     const TDesC& aNewPath, 
       
  1437     RFs& aFileSession)
       
  1438     {
       
  1439     
       
  1440     // We move the file to the final location
       
  1441     //
       
  1442     CFileMan* fileMan= CFileMan::NewL(aFileSession);
       
  1443     CleanupStack::PushL(fileMan);       
       
  1444     TPtrC tmpNewPath;
       
  1445     TParse fileParse;
       
  1446     fileParse.Set(aFileName, NULL, NULL);
       
  1447     
       
  1448     TInt error = fileMan->Move(aFileName,aNewPath,CFileMan::ERecurse );
       
  1449     
       
  1450     // if error while moving to new location, keep file in old location and change file name
       
  1451     if (error != KErrNone)
       
  1452         {
       
  1453         tmpNewPath.Set (fileParse.DriveAndPath()); 
       
  1454         }
       
  1455     else
       
  1456         {
       
  1457         tmpNewPath.Set (aNewPath);
       
  1458         }
       
  1459     
       
  1460     CleanupStack::PopAndDestroy(fileMan);
       
  1461 
       
  1462     TFileName tempFile;
       
  1463     tempFile.Append(tmpNewPath);
       
  1464     tempFile.Append(fileParse.NameAndExt());
       
  1465     aFileName = tempFile;
       
  1466     
       
  1467     // check the duplicated file name. if so, we renamed in a different way. 
       
  1468     TInt segmentNum = 0;
       
  1469     TBuf<64> segmentString;
       
  1470     
       
  1471     TFileName newFullName;
       
  1472     newFullName.Zero();
       
  1473     newFullName.Append(tmpNewPath);
       
  1474     newFullName.Append(aNewFileName);
       
  1475     
       
  1476     aFileSession.SetSessionPath(tmpNewPath);
       
  1477     
       
  1478     while ( BaflUtils::FileExists(aFileSession, newFullName) )    
       
  1479         {
       
  1480         segmentNum++;
       
  1481         User::LeaveIfError( RenameFileWithSegmentNumL(aNewFileName, segmentNum, segmentString) );
       
  1482         newFullName.Zero();
       
  1483         newFullName.Append(tmpNewPath);
       
  1484         newFullName.Append(aNewFileName);
       
  1485         }
       
  1486     // rename the file.
       
  1487     //
       
  1488     error = aFileSession.Rename(aFileName, newFullName);
       
  1489 
       
  1490     aFileName = newFullName;
       
  1491     
       
  1492     return error;
       
  1493     }
       
  1494 
       
  1495 //-------------------------------------------------------------------------------
       
  1496 // Rename a file by adding a additional segment string
       
  1497 // Return: None.
       
  1498 //-------------------------------------------------------------------------------
       
  1499 //
       
  1500 TInt TObexUtilsMessageHandler::RenameFileWithSegmentNumL(
       
  1501     TDes &aFileName,        // name for the file 
       
  1502     TInt aSegmentNum,       // segment number
       
  1503     TDes &aSegmentString)   // segment String with parenthesis
       
  1504     {
       
  1505     
       
  1506     FLOG(_L("[OBEXUTILS]\t RenameFileWithSegmentNumL()"));
       
  1507 
       
  1508     const char KDot = '.';
       
  1509     const char KLeftParenthesis = '(';
       
  1510     const char KRightParenthesis = ')';
       
  1511     
       
  1512     // Convert Integer to String
       
  1513     // 
       
  1514     TBuf<64> buf;
       
  1515     buf.Zero();
       
  1516     _LIT(KNum, "%d" );
       
  1517     buf.AppendFormat(KNum, aSegmentNum);
       
  1518     
       
  1519     // Rules to modify the duplicated filenames.
       
  1520     // case 1: No extention in filename,  we append aSegmentString directly.
       
  1521     // case 2: Filename with extention, we insert aSegmentString right before dot (.)
       
  1522     // case 3: Filename with aSegmentString is still duplicated, 
       
  1523     //         we remove the old aSegmentString from aFileName and add a new one and add a new aSegmentString.
       
  1524     
       
  1525     TInt posOfDot = aFileName.LocateReverse(KDot);
       
  1526     
       
  1527     if ( aSegmentNum > 1 )   // filename with aSegementString is still duplicated
       
  1528         {
       
  1529         // In case the original file name contains the same string as our aSegmentString
       
  1530         // eg 1 with ext. original filename is file(1).txt, after renaming, it is changed to file(1)(1).txt.
       
  1531         // eg 2 without ext. original filename is file(1), after renaming, it is changed to file(1)(1).
       
  1532         TInt posDeleteStarts = posOfDot == KErrNotFound ? 
       
  1533                                 aFileName.Length() - aSegmentString.Length() :
       
  1534                                 posOfDot - aSegmentString.Length();
       
  1535                                 
       
  1536         aFileName.Delete(posDeleteStarts, aSegmentString.Length());
       
  1537         }
       
  1538     
       
  1539     // Construct (New) aSegmentString
       
  1540     aSegmentString.Zero();
       
  1541     aSegmentString.Append(KLeftParenthesis);
       
  1542     aSegmentString.Append(buf);
       
  1543     aSegmentString.Append(KRightParenthesis);
       
  1544     
       
  1545     // 
       
  1546     // If the length of new filename will be larger than KMaxFileName, we remove few chars from the end of aFilename 
       
  1547     // in order to add aSegmentString without panic.
       
  1548     // 
       
  1549     if ( KMaxFileName < (aFileName.Length() + aSegmentString.Length()))
       
  1550         {
       
  1551         aFileName.Delete(KMaxFileName - aSegmentString.Length(), KMaxFileName - aFileName.Length());
       
  1552         }
       
  1553     
       
  1554     posOfDot = aFileName.LocateReverse(KDot);
       
  1555     if ( posOfDot == KErrNotFound )   
       
  1556         {
       
  1557         // aFileName has no extension
       
  1558         // we append the modification to aFileName
       
  1559         //
       
  1560         aFileName.Append(aSegmentString);
       
  1561         }
       
  1562     else
       
  1563         {
       
  1564         // Dot (.) is found, we insert the modifications before dot.
       
  1565         //
       
  1566         aFileName.Insert(posOfDot,aSegmentString);
       
  1567         
       
  1568         }
       
  1569     
       
  1570     FLOG(_L("[OBEXUTILS]\t RenameFileWithSegmentNumL() completed"));
       
  1571     return KErrNone;
       
  1572     }
       
  1573 
       
  1574 //-------------------------------------------------------------------------------
       
  1575 // Shorten an extreme long file name
       
  1576 // Return: None.
       
  1577 //-------------------------------------------------------------------------------
       
  1578 //
       
  1579 void TObexUtilsMessageHandler::FixExtremeLongFileName(TFileName& aExtremeLongFileName, const TDesC& aDriveAndPath)
       
  1580      {
       
  1581      FLOG( _L( "[OBEXUTILS]\t FixExtremeLongFileName() ") );
       
  1582      const char KDot = '.';
       
  1583      TInt combinedLength = aExtremeLongFileName.Length() + aDriveAndPath.Length();
       
  1584      
       
  1585      if ( combinedLength > aExtremeLongFileName.MaxLength() )
       
  1586         {
       
  1587         FLOG( _L( "[OBEXUTILS]\t FixExtremeLongFileName: combinedLenght > aExtremeLongFileName.MaxLength()\t") );
       
  1588          //KDefaultFileExtensionSeparator
       
  1589          TFileName tempFileName;
       
  1590          TInt dotPos = aExtremeLongFileName.LocateReverse( KDot );    
       
  1591          TInt overLap = combinedLength - aExtremeLongFileName.MaxLength() + KRenameOffSet;  
       
  1592  
       
  1593          if ( dotPos > 0 )
       
  1594              {
       
  1595              tempFileName.Copy( aExtremeLongFileName.Left( dotPos - overLap ) );
       
  1596              tempFileName.Append( aExtremeLongFileName.Right( aExtremeLongFileName.Length() - dotPos ) );  
       
  1597              }
       
  1598          else
       
  1599              {
       
  1600              tempFileName.Copy( aExtremeLongFileName.Left(aExtremeLongFileName.Length() - overLap ) );
       
  1601              }
       
  1602          aExtremeLongFileName.Copy( tempFileName );
       
  1603          }
       
  1604      FLOG( _L( "[OBEXUTILS]\t FixExtremeLongFileName() completed") );
       
  1605      }
       
  1606 
       
  1607 //  End of File  
       
  1608