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