Skip to content

Commit

Permalink
Implemented method Create new
Browse files Browse the repository at this point in the history
  • Loading branch information
gasparez15 committed Aug 26, 2024
1 parent 29ee954 commit 67ba73e
Show file tree
Hide file tree
Showing 8 changed files with 181 additions and 70 deletions.
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.logicaldoc.onlyoffice.controllers;

import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
Expand All @@ -20,10 +21,10 @@
import com.logicaldoc.gui.common.client.InvalidSessionServerException;
import com.logicaldoc.onlyoffice.entities.User;
import com.logicaldoc.onlyoffice.helpers.ConfigManager;
import com.logicaldoc.onlyoffice.helpers.DocumentManager;
import com.logicaldoc.onlyoffice.helpers.OODocumentManager;
import com.logicaldoc.onlyoffice.helpers.FileUtility;
import com.logicaldoc.onlyoffice.helpers.Users;
import com.logicaldoc.onlyoffice.manager.DocumentManagerImpl;
import com.logicaldoc.onlyoffice.manager.OODocumentManagerImpl;
import com.logicaldoc.onlyoffice.manager.SettingsManagerImpl;
import com.logicaldoc.onlyoffice.manager.UrlMangerImpl;
import com.logicaldoc.onlyoffice.model.LDOOUSer;
Expand Down Expand Up @@ -62,11 +63,12 @@ protected void service(HttpServletRequest request, HttpServletResponse response)
try {
Session session = OnlyOfficeEditor.validateSession(request);

DocumentManager.init(request, response);
OODocumentManager.init(request, response);

String sid = session.getSid();
String docId = request.getParameter("docId");
String fileName = request.getParameter("fileName");
String fileExt = request.getParameter("fileExt");

Boolean isEnableDirectUrl = true;
try {
Expand All @@ -78,13 +80,33 @@ protected void service(HttpServletRequest request, HttpServletResponse response)

User user = Users.getUser("uid-1");

if (fileExt != null) {
System.out.println("fileExt: " +fileExt);
try {
//fileName = DocumentManager.createDemo(fileExt, false, user);

// Create New demo document into LogicalDOC
// get the folderId from the previous docId
com.logicaldoc.core.document.Document ldDocument = OODocumentManager.createDemoLD(session.getUser(), fileExt, docId, false);
fileName = ldDocument.getFileName();
System.out.println("created fileName: " +fileName);

// redirect the request
response.sendRedirect(request.getContextPath() +"/onlyoffice/editor?fileName=" + URLEncoder.encode(fileName, "UTF-8") +"&sid" +sid +"&docId=" +ldDocument.getId());
return;
} catch (Exception ex) {
response.getWriter().write("Error: " + ex.getMessage());
}
}

settingsManager = new SettingsManagerImpl(ConfigManager.getProperty("files.docservice.url.site"), ConfigManager.getProperty("files.docservice.secret"));
DocumentManagerImpl dm = new DocumentManagerImpl(settingsManager);
OODocumentManagerImpl dm = new OODocumentManagerImpl(settingsManager);
UrlMangerImpl um = new UrlMangerImpl(settingsManager, request, sid);
JwtManager jwtManager = this.jwtManager(settingsManager);
configService = new ConfigServiceImpl(dm, um, jwtManager, settingsManager);
Config config = configService.createConfig(docId, Mode.EDIT, Type.DESKTOP);

System.out.println("fileName: " +fileName);
dm.setFileName(fileName);

config.setDocumentType(dm.getDocumentType(fileName));
Expand All @@ -94,7 +116,7 @@ protected void service(HttpServletRequest request, HttpServletResponse response)
Document myDoc = config.getDocument();
myDoc.setFileType(dm.getExtension(fileName));
myDoc.setTitle(fileName);
myDoc.setUrl(DocumentManager.getDownloadUrl02(fileName, docId, sid, true));
myDoc.setUrl(OODocumentManager.getDownloadUrl02(fileName, docId, sid, true));
//myDoc.setKey(docId);

// Set the key to something unique
Expand All @@ -103,7 +125,7 @@ protected void service(HttpServletRequest request, HttpServletResponse response)
// String xxx = docId +"-" +dldDoc.getVersion();
myDoc.setKey(docId +"-" + System.currentTimeMillis());

config.getEditorConfig().setCallbackUrl(DocumentManager.getCallback02(fileName, docId, sid));
config.getEditorConfig().setCallbackUrl(OODocumentManager.getCallback02(fileName, docId, sid));
// disable all customizations
//config.getEditorConfig().setCustomization(null);

Expand All @@ -126,8 +148,8 @@ protected void service(HttpServletRequest request, HttpServletResponse response)
config.getEditorConfig().setUser(edUser);

// Setup createUrl to enable save as
String createUrl = DocumentManager.getCreateUrl(FileUtility.getFileType(fileName));
createUrl += "?sid=" + sid;
String createUrl = OODocumentManager.getCreateUrl(FileUtility.getFileType(fileName));
createUrl += "&sid=" + sid +"&docId=" +docId;
config.getEditorConfig().setCreateUrl(!user.getId().equals("uid-0") ? createUrl : null);

// rebuild the verification token
Expand All @@ -148,28 +170,28 @@ protected void service(HttpServletRequest request, HttpServletResponse response)
// an image that will be inserted into the document
Map<String, Object> dataInsertImage = new HashMap<>();
dataInsertImage.put("fileType", "png");
dataInsertImage.put("url", DocumentManager.getServerUrl(true) + "/css/img/logo.png");
dataInsertImage.put("url", OODocumentManager.getServerUrl(true) + "/css/img/logo.png");
if (isEnableDirectUrl) {
dataInsertImage.put("directUrl", DocumentManager.getServerUrl(false) + "/css/img/logo.png");
dataInsertImage.put("directUrl", OODocumentManager.getServerUrl(false) + "/css/img/logo.png");
}

// a document that will be compared with the current document
Map<String, Object> dataDocument = new HashMap<>();
dataDocument.put("fileType", "docx");
dataDocument.put("url", DocumentManager.getServerUrl(true) + "/onlyoffice/IndexServlet?type=assets&"
dataDocument.put("url", OODocumentManager.getServerUrl(true) + "/onlyoffice/IndexServlet?type=assets&"
+ "name=sample.docx");
if (isEnableDirectUrl) {
dataDocument.put("directUrl", DocumentManager.getServerUrl(false) + "/onlyoffice/IndexServlet?"
dataDocument.put("directUrl", OODocumentManager.getServerUrl(false) + "/onlyoffice/IndexServlet?"
+ "type=assets&name=sample.docx");
}

// recipients data for mail merging
Map<String, Object> dataSpreadsheet = new HashMap<>();
dataSpreadsheet.put("fileType", "csv");
dataSpreadsheet.put("url", DocumentManager.getServerUrl(true) + "/onlyoffice/IndexServlet?"
dataSpreadsheet.put("url", OODocumentManager.getServerUrl(true) + "/onlyoffice/IndexServlet?"
+ "type=csv");
if (isEnableDirectUrl) {
dataSpreadsheet.put("directUrl", DocumentManager.getServerUrl(false)
dataSpreadsheet.put("directUrl", OODocumentManager.getServerUrl(false)
+ "/onlyoffice/IndexServlet?type=csv");
}

Expand All @@ -193,6 +215,8 @@ protected void service(HttpServletRequest request, HttpServletResponse response)
request.getRequestDispatcher("/onlyoffice/editor.jsp").forward(request, response);

} catch (Exception e) {
e.printStackTrace();
System.err.println(e);
handleError(response, e);
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@
import com.logicaldoc.gui.common.client.InvalidSessionServerException;
import com.logicaldoc.onlyoffice.helpers.ConfigManager;
import com.logicaldoc.onlyoffice.helpers.CookieManager;
import com.logicaldoc.onlyoffice.helpers.DocumentManager;
import com.logicaldoc.onlyoffice.helpers.OODocumentManager;
import com.logicaldoc.onlyoffice.helpers.FileUtility;
import com.logicaldoc.onlyoffice.helpers.TrackManager;
import com.logicaldoc.onlyoffice.helpers.Users;
Expand Down Expand Up @@ -176,8 +176,10 @@ private static void saveAs(final HttpServletRequest request,
JSONParser parser = new JSONParser();
JSONObject body = (JSONObject) parser.parse(bodyString);

/*
CookieManager cm = new CookieManager(request);
com.logicaldoc.onlyoffice.entities.User user = Users.getUser(cm.getCookie("uid"));
*/

String title = (String) body.get("title");
String saveAsFileUrl = (String) body.get("url");
Expand Down Expand Up @@ -249,7 +251,7 @@ private static void saveAs(final HttpServletRequest request,
history.setSessionId(sid);

// creates a new document into the same folder
com.logicaldoc.core.document.DocumentManager dmi = (com.logicaldoc.core.document.DocumentManager) Context.get().getBean(DocumentManager.class);
com.logicaldoc.core.document.DocumentManager dmi = (com.logicaldoc.core.document.DocumentManager) Context.get().getBean("documentManager");
dmi.create(stream, cloned, history);

writer.write("{\"file\": \"" + fileName + "\"}");
Expand Down Expand Up @@ -630,12 +632,12 @@ private static void download(final HttpServletRequest request,
try {
// enable the verification of the document token before allowing the download of the document.

String fileName = FileUtility.getFileName(request.getParameter("fileName"));
//String fileName = FileUtility.getFileName(request.getParameter("fileName"));
String userAddress = request.getParameter("userAddress");
String isEmbedded = request.getParameter("dmode");

if (DocumentManager.tokenEnabled() && isEmbedded == null && userAddress != null
&& DocumentManager.tokenUseForRequest()) {
if (OODocumentManager.tokenEnabled() && isEmbedded == null && userAddress != null
&& OODocumentManager.tokenUseForRequest()) {

String documentJwtHeader = ConfigManager.getProperty("Authorization");

Expand All @@ -647,8 +649,8 @@ private static void download(final HttpServletRequest request,
token = header.startsWith(bearerPrefix) ? header.substring(bearerPrefix.length()) : header;
}
try {
Verifier verifier = HMACVerifier.newVerifier(DocumentManager.getTokenSecret());
JWT jwt = JWT.getDecoder().decode(token, verifier);
Verifier verifier = HMACVerifier.newVerifier(OODocumentManager.getTokenSecret());
JWT.getDecoder().decode(token, verifier);
} catch (Exception e) {
response.sendError(HttpServletResponse.SC_FORBIDDEN, "JWT validation failed");
return;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -54,16 +54,27 @@
import org.primeframework.jwt.domain.JWT;
import org.primeframework.jwt.hmac.HMACSigner;
import org.primeframework.jwt.hmac.HMACVerifier;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.logicaldoc.core.PersistenceException;
import com.logicaldoc.core.document.DocumentDAO;
import com.logicaldoc.core.document.DocumentHistory;
import com.logicaldoc.core.folder.Folder;
import com.logicaldoc.core.folder.FolderDAO;
import com.logicaldoc.onlyoffice.entities.FileType;
import com.logicaldoc.onlyoffice.entities.User;
import com.logicaldoc.onlyoffice.format.FormatManager;
import com.logicaldoc.util.Context;

public final class DocumentManager {
public final class OODocumentManager {

private static Logger log = LoggerFactory.getLogger(OODocumentManager.class);

private static HttpServletRequest request;
private static FormatManager formatManager = new FormatManager();

private DocumentManager() { }
private OODocumentManager() { }

public static void init(final HttpServletRequest req, final HttpServletResponse resp) {
request = req;
Expand All @@ -84,26 +95,26 @@ public static long getMaxFileSize() {

// get all the supported file extensions
public static List<String> getFileExts() {
return DocumentManager.formatManager.allExtensions();
return OODocumentManager.formatManager.allExtensions();
}

public static List<String> getFillExts() {
return DocumentManager.formatManager.fillableExtensions();
return OODocumentManager.formatManager.fillableExtensions();
}

// get file extensions that can be viewed
public static List<String> getViewedExts() {
return DocumentManager.formatManager.viewableExtensions();
return OODocumentManager.formatManager.viewableExtensions();
}

// get file extensions that can be edited
public static List<String> getEditedExts() {
return DocumentManager.formatManager.editableExtensions();
return OODocumentManager.formatManager.editableExtensions();
}

// get file extensions that can be converted
public static List<String> getConvertExts() {
return DocumentManager.formatManager.autoConvertExtensions();
return OODocumentManager.formatManager.autoConvertExtensions();
}

// get current user host address
Expand Down Expand Up @@ -649,4 +660,84 @@ public static String readFileToEnd(final File file) {
} catch (Exception e) { }
return output;
}

// create demo document
public static String createDemo(final String fileExt, final Boolean sample, final User user) throws Exception {
// create sample or new template file with the necessary extension
String demoName = (sample ? "sample." : "new.") + fileExt;

// get the path to the sample document
String demoPath = "assets"
+ File.separator
+ "document-templates"
+ File.separator
+ (sample ? "sample" : "new")
+ File.separator;

// get a file name with an index if the file with such a name already exists
String fileName = getCorrectName(demoName, null);

// get the input file stream
InputStream stream = Thread.currentThread()
.getContextClassLoader()
.getResourceAsStream(demoPath + demoName);

createFile(Paths.get(storagePath(fileName, null)), stream);

// create meta information of the demo file
createMeta(fileName, user.getId(), user.getName(), null);

return fileName;
}

public static com.logicaldoc.core.document.Document createDemoLD(com.logicaldoc.core.security.user.User user, String fileExt, String docId, final Boolean sample) throws PersistenceException {
// create sample or new template file with the necessary extension
String demoName = (sample ? "sample." : "new.") + fileExt;

// get the path to the sample document
String demoPath = "assets"
+ File.separator
+ "document-templates"
+ File.separator
+ (sample ? "sample" : "new")
+ File.separator;

// get a file name with an index if the file with such a name already exists
//String fileName = getCorrectName(demoName, null);
String fileName = demoName;

// get the input file stream
InputStream stream = Thread.currentThread()
.getContextClassLoader()
.getResourceAsStream(demoPath + demoName);

return createDocumentLD(user, fileName, docId, stream);
}

private static com.logicaldoc.core.document.Document createDocumentLD(com.logicaldoc.core.security.user.User user, String fileName, String docId, InputStream stream) throws PersistenceException {

com.logicaldoc.core.document.DocumentManager dmi = (com.logicaldoc.core.document.DocumentManager) Context.get().getBean("documentManager");

DocumentDAO documentDao = (DocumentDAO) Context.get().getBean(DocumentDAO.class);

Folder saveFolder = null;
try {
com.logicaldoc.core.document.Document fDoc = documentDao.findDocument(Long.parseLong(docId));
saveFolder = fDoc.getFolder();
} catch (PersistenceException e) {
log.error(e.getMessage(), e);
}

com.logicaldoc.core.document.Document docVo = new com.logicaldoc.core.document.Document();
docVo.setFileName(fileName);
docVo.setFolder(saveFolder);

DocumentHistory transact = new DocumentHistory();
transact.setDocument(docVo);
transact.setDate(new Date());
transact.setUser(user);

return dmi.create(stream, docVo, transact);
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -171,7 +171,7 @@ public static Map<String, String> getConvertedData(final String documentUri, fin
}

String headerToken = "";
if (DocumentManager.tokenEnabled() && DocumentManager.tokenUseForRequest()) {
if (OODocumentManager.tokenEnabled() && OODocumentManager.tokenUseForRequest()) {
HashMap<String, Object> map = new HashMap<String, Object>();
map.put("region", lang);
map.put("url", body.getUrl());
Expand All @@ -185,12 +185,12 @@ public static Map<String, String> getConvertedData(final String documentUri, fin
}

// add token to the body if it is enabled
String token = DocumentManager.createToken(map);
String token = OODocumentManager.createToken(map);
body.setToken(token);

Map<String, Object> payloadMap = new HashMap<String, Object>();
payloadMap.put("payload", map); // create payload object
headerToken = DocumentManager.createToken(payloadMap); // create header token
headerToken = OODocumentManager.createToken(payloadMap); // create header token
}

Gson gson = new Gson();
Expand All @@ -209,7 +209,7 @@ public static Map<String, String> getConvertedData(final String documentUri, fin
connection.setConnectTimeout(convertTimeout);

// write header token to the request
if (DocumentManager.tokenEnabled()) {
if (OODocumentManager.tokenEnabled()) {
connection.setRequestProperty(DOCUMENT_JWT_HEADER.equals("")
? "Authorization" : DOCUMENT_JWT_HEADER, "Bearer " + headerToken);
}
Expand Down
Loading

0 comments on commit 67ba73e

Please sign in to comment.