github.com/cozy/cozy-stack@v0.0.0-20240603063001-31110fa4cae1/model/office/file_by_key.go (about)

     1  package office
     2  
     3  import (
     4  	"bytes"
     5  
     6  	"github.com/cozy/cozy-stack/model/instance"
     7  	"github.com/cozy/cozy-stack/model/vfs"
     8  )
     9  
    10  // EnsureFileForKey returns the file that will be written when OnlyOffice will
    11  // save a document with the given key. The general case is that is the file
    12  // that has been opened. But, it can also be a new file if a conflict has
    13  // happened because a new version has been uploaded for this file (by the
    14  // desktop client for example).
    15  func EnsureFileForKey(inst *instance.Instance, key string) (*vfs.FileDoc, error) {
    16  	detector, err := GetStore().GetDoc(inst, key)
    17  	if err != nil {
    18  		return nil, err
    19  	}
    20  	if detector == nil || detector.ID == "" || detector.Rev == "" {
    21  		return nil, ErrInvalidKey
    22  	}
    23  
    24  	fs := inst.VFS()
    25  	file, err := fs.FileByID(detector.ID)
    26  	if err != nil {
    27  		return nil, err
    28  	}
    29  
    30  	if file.Rev() == detector.Rev || bytes.Equal(file.MD5Sum, detector.MD5Sum) {
    31  		return file, nil
    32  	}
    33  
    34  	// Manage the conflict
    35  	conflictName := vfs.ConflictName(fs, file.DirID, file.DocName, true)
    36  	newfile := vfs.CreateFileDocCopy(file, file.DirID, conflictName)
    37  	newfile.CozyMetadata = vfs.NewCozyMetadata(inst.PageURL("/", nil))
    38  	newfile.CozyMetadata.UpdatedAt = newfile.UpdatedAt
    39  	newfile.CozyMetadata.UploadedAt = &newfile.UpdatedAt
    40  	newfile.CozyMetadata.UploadedBy = &vfs.UploadedByEntry{Slug: OOSlug}
    41  	if err := fs.CopyFile(file, newfile); err != nil {
    42  		return nil, err
    43  	}
    44  
    45  	updated := ConflictDetector{ID: newfile.ID(), Rev: newfile.Rev(), MD5Sum: newfile.MD5Sum}
    46  	_ = GetStore().UpdateSecret(inst, key, file.ID(), newfile.ID())
    47  	_ = GetStore().UpdateDoc(inst, key, updated)
    48  	return newfile, nil
    49  }