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